]> git.sesse.net Git - stockfish/blob - src/position.cpp
Retire Position::set_castling_rights()
[stockfish] / src / position.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <cassert>
21 #include <cstring>
22 #include <fstream>
23 #include <iostream>
24 #include <sstream>
25
26 #include "bitcount.h"
27 #include "movegen.h"
28 #include "position.h"
29 #include "psqtab.h"
30 #include "rkiss.h"
31 #include "thread.h"
32 #include "tt.h"
33
34 using std::string;
35 using std::cout;
36 using std::endl;
37
38 Key Position::zobrist[2][8][64];
39 Key Position::zobEp[64];
40 Key Position::zobCastle[16];
41 Key Position::zobSideToMove;
42 Key Position::zobExclusion;
43
44 Score Position::pieceSquareTable[16][64];
45
46 // Material values arrays, indexed by Piece
47 const Value PieceValueMidgame[17] = {
48   VALUE_ZERO,
49   PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
50   RookValueMidgame, QueenValueMidgame,
51   VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
52   PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
53   RookValueMidgame, QueenValueMidgame
54 };
55
56 const Value PieceValueEndgame[17] = {
57   VALUE_ZERO,
58   PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
59   RookValueEndgame, QueenValueEndgame,
60   VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
61   PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
62   RookValueEndgame, QueenValueEndgame
63 };
64
65
66 namespace {
67
68   // Bonus for having the side to move (modified by Joona Kiiski)
69   const Score TempoValue = make_score(48, 22);
70
71   // To convert a Piece to and from a FEN char
72   const string PieceToChar(".PNBRQK  pnbrqk  ");
73 }
74
75
76 /// CheckInfo c'tor
77
78 CheckInfo::CheckInfo(const Position& pos) {
79
80   Color them = flip(pos.side_to_move());
81   Square ksq = pos.king_square(them);
82
83   pinned = pos.pinned_pieces();
84   dcCandidates = pos.discovered_check_candidates();
85
86   checkSq[PAWN]   = pos.attacks_from<PAWN>(ksq, them);
87   checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
88   checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
89   checkSq[ROOK]   = pos.attacks_from<ROOK>(ksq);
90   checkSq[QUEEN]  = checkSq[BISHOP] | checkSq[ROOK];
91   checkSq[KING]   = EmptyBoardBB;
92 }
93
94
95 /// Position c'tors. Here we always create a copy of the original position
96 /// or the FEN string, we want the new born Position object do not depend
97 /// on any external data so we detach state pointer from the source one.
98
99 Position::Position(const Position& pos, int th) {
100
101   memcpy(this, &pos, sizeof(Position));
102   threadID = th;
103   nodes = 0;
104
105   assert(pos_is_ok());
106 }
107
108 Position::Position(const string& fen, bool isChess960, int th) {
109
110   from_fen(fen, isChess960);
111   threadID = th;
112 }
113
114
115 /// Position::from_fen() initializes the position object with the given FEN
116 /// string. This function is not very robust - make sure that input FENs are
117 /// correct (this is assumed to be the responsibility of the GUI).
118
119 void Position::from_fen(const string& fenStr, bool isChess960) {
120 /*
121    A FEN string defines a particular position using only the ASCII character set.
122
123    A FEN string contains six fields. The separator between fields is a space. The fields are:
124
125    1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
126       with rank 1; within each rank, the contents of each square are described from file A through file H.
127       Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
128       from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
129       while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
130       of blank squares), and "/" separate ranks.
131
132    2) Active color. "w" means white moves next, "b" means black.
133
134    3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
135       letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
136       kingside), and/or "q" (Black can castle queenside).
137
138    4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
139       If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
140       regardless of whether there is a pawn in position to make an en passant capture.
141
142    5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
143       to determine if a draw can be claimed under the fifty-move rule.
144
145    6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
146 */
147
148   char col, row, token;
149   size_t p;
150   Square sq = SQ_A8;
151   std::istringstream fen(fenStr);
152
153   clear();
154   fen >> std::noskipws;
155
156   // 1. Piece placement
157   while ((fen >> token) && !isspace(token))
158   {
159       if (token == '/')
160           sq -= Square(16); // Jump back of 2 rows
161
162       else if (isdigit(token))
163           sq += Square(token - '0'); // Skip the given number of files
164
165       else if ((p = PieceToChar.find(token)) != string::npos)
166       {
167           put_piece(Piece(p), sq);
168           sq++;
169       }
170   }
171
172   // 2. Active color
173   fen >> token;
174   sideToMove = (token == 'w' ? WHITE : BLACK);
175   fen >> token;
176
177   // 3. Castling availability. Compatible with 3 standards: Normal FEN standard,
178   // Shredder-FEN that uses the letters of the columns on which the rooks began
179   // the game instead of KQkq and also X-FEN standard that, in case of Chess960,
180   // if an inner rook is associated with the castling right, the castling tag is
181   // replaced by the file letter of the involved rook, as for the Shredder-FEN.
182   while ((fen >> token) && !isspace(token))
183   {
184       Square rsq;
185       Color c = islower(token) ? BLACK : WHITE;
186       Piece rook = make_piece(c, ROOK);
187
188       token = char(toupper(token));
189
190       if (token == 'K')
191           for (rsq = relative_square(c, SQ_H1); piece_on(rsq) != rook; rsq--) {}
192
193       else if (token == 'Q')
194           for (rsq = relative_square(c, SQ_A1); piece_on(rsq) != rook; rsq++) {}
195
196       else if (token >= 'A' && token <= 'H')
197           rsq = make_square(File(token - 'A'), relative_rank(c, RANK_1));
198
199       else
200           continue;
201
202       set_castle_right(king_square(c), rsq);
203   }
204
205   // 4. En passant square. Ignore if no pawn capture is possible
206   if (   ((fen >> col) && (col >= 'a' && col <= 'h'))
207       && ((fen >> row) && (row == '3' || row == '6')))
208   {
209       st->epSquare = make_square(File(col - 'a'), Rank(row - '1'));
210
211       if (!(attackers_to(st->epSquare) & pieces(PAWN, sideToMove)))
212           st->epSquare = SQ_NONE;
213   }
214
215   // 5-6. Halfmove clock and fullmove number
216   fen >> std::skipws >> st->rule50 >> startPosPly;
217
218   // Convert from fullmove starting from 1 to ply starting from 0,
219   // handle also common incorrect FEN with fullmove = 0.
220   startPosPly = Max(2 * (startPosPly - 1), 0) + int(sideToMove == BLACK);
221
222   st->key = compute_key();
223   st->pawnKey = compute_pawn_key();
224   st->materialKey = compute_material_key();
225   st->value = compute_value();
226   st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
227   st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
228   st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(flip(sideToMove));
229   chess960 = isChess960;
230
231   assert(pos_is_ok());
232 }
233
234
235 /// Position::set_castle_right() is an helper function used to set castling
236 /// rights given the corresponding king and rook starting squares.
237
238 void Position::set_castle_right(Square ksq, Square rsq) {
239
240   int f = (rsq < ksq ? WHITE_OOO : WHITE_OO) << color_of(piece_on(ksq));
241
242   st->castleRights |= f;
243   castleRightsMask[ksq] ^= f;
244   castleRightsMask[rsq] ^= f;
245   castleRookSquare[f] = rsq;
246 }
247
248
249 /// Position::to_fen() returns a FEN representation of the position. In case
250 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
251
252 const string Position::to_fen() const {
253
254   std::ostringstream fen;
255   Square sq;
256   int emptyCnt;
257
258   for (Rank rank = RANK_8; rank >= RANK_1; rank--)
259   {
260       emptyCnt = 0;
261
262       for (File file = FILE_A; file <= FILE_H; file++)
263       {
264           sq = make_square(file, rank);
265
266           if (!square_is_empty(sq))
267           {
268               if (emptyCnt)
269               {
270                   fen << emptyCnt;
271                   emptyCnt = 0;
272               }
273               fen << PieceToChar[piece_on(sq)];
274           }
275           else
276               emptyCnt++;
277       }
278
279       if (emptyCnt)
280           fen << emptyCnt;
281
282       if (rank > RANK_1)
283           fen << '/';
284   }
285
286   fen << (sideToMove == WHITE ? " w " : " b ");
287
288   if (st->castleRights != CASTLES_NONE)
289   {
290       if (can_castle(WHITE_OO))
291           fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE_OO))))) : 'K');
292
293       if (can_castle(WHITE_OOO))
294           fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE_OOO))))) : 'Q');
295
296       if (can_castle(BLACK_OO))
297           fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK_OO))) : 'k');
298
299       if (can_castle(BLACK_OOO))
300           fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK_OOO))) : 'q');
301   } else
302       fen << '-';
303
304   fen << (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()))
305       << " " << st->rule50 << " " << 1 + (startPosPly - int(sideToMove == BLACK)) / 2;
306
307   return fen.str();
308 }
309
310
311 /// Position::print() prints an ASCII representation of the position to
312 /// the standard output. If a move is given then also the san is printed.
313
314 void Position::print(Move move) const {
315
316   const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
317
318   if (move)
319   {
320       Position p(*this, thread());
321       string dd = (sideToMove == BLACK ? ".." : "");
322       cout << "\nMove is: " << dd << move_to_san(p, move);
323   }
324
325   for (Rank rank = RANK_8; rank >= RANK_1; rank--)
326   {
327       cout << dottedLine << '|';
328       for (File file = FILE_A; file <= FILE_H; file++)
329       {
330           Square sq = make_square(file, rank);
331           Piece piece = piece_on(sq);
332
333           if (piece == PIECE_NONE && color_of(sq) == DARK)
334               piece = PIECE_NONE_DARK_SQ;
335
336           char c = (color_of(piece_on(sq)) == BLACK ? '=' : ' ');
337           cout << c << PieceToChar[piece] << c << '|';
338       }
339   }
340   cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
341 }
342
343
344 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
345 /// king) pieces for the given color. Or, when template parameter FindPinned is
346 /// false, the function return the pieces of the given color candidate for a
347 /// discovery check against the enemy king.
348
349 template<bool FindPinned>
350 Bitboard Position::hidden_checkers() const {
351
352   // Pinned pieces protect our king, dicovery checks attack the enemy king
353   Bitboard b, result = EmptyBoardBB;
354   Bitboard pinners = pieces(FindPinned ? flip(sideToMove) : sideToMove);
355   Square ksq = king_square(FindPinned ? sideToMove : flip(sideToMove));
356
357   // Pinners are sliders, that give check when candidate pinned is removed
358   pinners &=  (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq])
359             | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
360
361   while (pinners)
362   {
363       b = squares_between(ksq, pop_1st_bit(&pinners)) & occupied_squares();
364
365       // Only one bit set and is an our piece?
366       if (b && !(b & (b - 1)) && (b & pieces(sideToMove)))
367           result |= b;
368   }
369   return result;
370 }
371
372
373 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
374 /// king) pieces for the side to move.
375
376 Bitboard Position::pinned_pieces() const {
377
378   return hidden_checkers<true>();
379 }
380
381
382 /// Position:discovered_check_candidates() returns a bitboard containing all
383 /// pieces for the side to move which are candidates for giving a discovered
384 /// check.
385
386 Bitboard Position::discovered_check_candidates() const {
387
388   return hidden_checkers<false>();
389 }
390
391 /// Position::attackers_to() computes a bitboard of all pieces which attacks a
392 /// given square. Slider attacks use occ bitboard as occupancy.
393
394 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
395
396   return  (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
397         | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
398         | (attacks_from<KNIGHT>(s)      & pieces(KNIGHT))
399         | (rook_attacks_bb(s, occ)      & pieces(ROOK, QUEEN))
400         | (bishop_attacks_bb(s, occ)    & pieces(BISHOP, QUEEN))
401         | (attacks_from<KING>(s)        & pieces(KING));
402 }
403
404 /// Position::attacks_from() computes a bitboard of all attacks of a given piece
405 /// put in a given square. Slider attacks use occ bitboard as occupancy.
406
407 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
408
409   assert(square_is_ok(s));
410
411   switch (p)
412   {
413   case WB: case BB: return bishop_attacks_bb(s, occ);
414   case WR: case BR: return rook_attacks_bb(s, occ);
415   case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
416   default: return StepAttacksBB[p][s];
417   }
418 }
419
420
421 /// Position::move_attacks_square() tests whether a move from the current
422 /// position attacks a given square.
423
424 bool Position::move_attacks_square(Move m, Square s) const {
425
426   assert(is_ok(m));
427   assert(square_is_ok(s));
428
429   Bitboard occ, xray;
430   Square f = move_from(m), t = move_to(m);
431
432   assert(!square_is_empty(f));
433
434   if (bit_is_set(attacks_from(piece_on(f), t), s))
435       return true;
436
437   // Move the piece and scan for X-ray attacks behind it
438   occ = occupied_squares();
439   do_move_bb(&occ, make_move_bb(f, t));
440   xray = ( (rook_attacks_bb(s, occ)   & pieces(ROOK, QUEEN))
441           |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
442          & pieces(color_of(piece_on(f)));
443
444   // If we have attacks we need to verify that are caused by our move
445   // and are not already existent ones.
446   return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
447 }
448
449
450 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
451
452 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
453
454   assert(is_ok(m));
455   assert(pinned == pinned_pieces());
456
457   Color us = side_to_move();
458   Square from = move_from(m);
459
460   assert(color_of(piece_on(from)) == us);
461   assert(piece_on(king_square(us)) == make_piece(us, KING));
462
463   // En passant captures are a tricky special case. Because they are rather
464   // uncommon, we do it simply by testing whether the king is attacked after
465   // the move is made.
466   if (is_enpassant(m))
467   {
468       Color them = flip(us);
469       Square to = move_to(m);
470       Square capsq = to + pawn_push(them);
471       Square ksq = king_square(us);
472       Bitboard b = occupied_squares();
473
474       assert(to == ep_square());
475       assert(piece_on(from) == make_piece(us, PAWN));
476       assert(piece_on(capsq) == make_piece(them, PAWN));
477       assert(piece_on(to) == PIECE_NONE);
478
479       clear_bit(&b, from);
480       clear_bit(&b, capsq);
481       set_bit(&b, to);
482
483       return   !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
484             && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
485   }
486
487   // If the moving piece is a king, check whether the destination
488   // square is attacked by the opponent. Castling moves are checked
489   // for legality during move generation.
490   if (type_of(piece_on(from)) == KING)
491       return is_castle(m) || !(attackers_to(move_to(m)) & pieces(flip(us)));
492
493   // A non-king move is legal if and only if it is not pinned or it
494   // is moving along the ray towards or away from the king.
495   return   !pinned
496         || !bit_is_set(pinned, from)
497         ||  squares_aligned(from, move_to(m), king_square(us));
498 }
499
500
501 /// Position::move_is_legal() takes a random move and tests whether the move
502 /// is legal. This version is not very fast and should be used only
503 /// in non time-critical paths.
504
505 bool Position::move_is_legal(const Move m) const {
506
507   for (MoveList<MV_LEGAL> ml(*this); !ml.end(); ++ml)
508       if (ml.move() == m)
509           return true;
510
511   return false;
512 }
513
514
515 /// Position::is_pseudo_legal() takes a random move and tests whether the move
516 /// is pseudo legal. It is used to validate moves from TT that can be corrupted
517 /// due to SMP concurrent access or hash position key aliasing.
518
519 bool Position::is_pseudo_legal(const Move m) const {
520
521   Color us = sideToMove;
522   Color them = flip(sideToMove);
523   Square from = move_from(m);
524   Square to = move_to(m);
525   Piece pc = piece_on(from);
526
527   // Use a slower but simpler function for uncommon cases
528   if (is_special(m))
529       return move_is_legal(m);
530
531   // Is not a promotion, so promotion piece must be empty
532   if (promotion_piece_type(m) - 2 != PIECE_TYPE_NONE)
533       return false;
534
535   // If the from square is not occupied by a piece belonging to the side to
536   // move, the move is obviously not legal.
537   if (pc == PIECE_NONE || color_of(pc) != us)
538       return false;
539
540   // The destination square cannot be occupied by a friendly piece
541   if (color_of(piece_on(to)) == us)
542       return false;
543
544   // Handle the special case of a pawn move
545   if (type_of(pc) == PAWN)
546   {
547       // Move direction must be compatible with pawn color
548       int direction = to - from;
549       if ((us == WHITE) != (direction > 0))
550           return false;
551
552       // We have already handled promotion moves, so destination
553       // cannot be on the 8/1th rank.
554       if (rank_of(to) == RANK_8 || rank_of(to) == RANK_1)
555           return false;
556
557       // Proceed according to the square delta between the origin and
558       // destination squares.
559       switch (direction)
560       {
561       case DELTA_NW:
562       case DELTA_NE:
563       case DELTA_SW:
564       case DELTA_SE:
565       // Capture. The destination square must be occupied by an enemy
566       // piece (en passant captures was handled earlier).
567       if (color_of(piece_on(to)) != them)
568           return false;
569
570       // From and to files must be one file apart, avoids a7h5
571       if (abs(file_of(from) - file_of(to)) != 1)
572           return false;
573       break;
574
575       case DELTA_N:
576       case DELTA_S:
577       // Pawn push. The destination square must be empty.
578       if (!square_is_empty(to))
579           return false;
580       break;
581
582       case DELTA_NN:
583       // Double white pawn push. The destination square must be on the fourth
584       // rank, and both the destination square and the square between the
585       // source and destination squares must be empty.
586       if (   rank_of(to) != RANK_4
587           || !square_is_empty(to)
588           || !square_is_empty(from + DELTA_N))
589           return false;
590       break;
591
592       case DELTA_SS:
593       // Double black pawn push. The destination square must be on the fifth
594       // rank, and both the destination square and the square between the
595       // source and destination squares must be empty.
596       if (   rank_of(to) != RANK_5
597           || !square_is_empty(to)
598           || !square_is_empty(from + DELTA_S))
599           return false;
600       break;
601
602       default:
603           return false;
604       }
605   }
606   else if (!bit_is_set(attacks_from(pc, from), to))
607       return false;
608
609   // Evasions generator already takes care to avoid some kind of illegal moves
610   // and pl_move_is_legal() relies on this. So we have to take care that the
611   // same kind of moves are filtered out here.
612   if (in_check())
613   {
614       // In case of king moves under check we have to remove king so to catch
615       // as invalid moves like b1a1 when opposite queen is on c1.
616       if (type_of(piece_on(from)) == KING)
617       {
618           Bitboard b = occupied_squares();
619           clear_bit(&b, from);
620           if (attackers_to(move_to(m), b) & pieces(flip(us)))
621               return false;
622       }
623       else
624       {
625           Bitboard target = checkers();
626           Square checksq = pop_1st_bit(&target);
627
628           if (target) // double check ? In this case a king move is required
629               return false;
630
631           // Our move must be a blocking evasion or a capture of the checking piece
632           target = squares_between(checksq, king_square(us)) | checkers();
633           if (!bit_is_set(target, move_to(m)))
634               return false;
635       }
636   }
637
638   return true;
639 }
640
641
642 /// Position::move_gives_check() tests whether a pseudo-legal move gives a check
643
644 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
645
646   assert(is_ok(m));
647   assert(ci.dcCandidates == discovered_check_candidates());
648   assert(color_of(piece_on(move_from(m))) == side_to_move());
649
650   Square from = move_from(m);
651   Square to = move_to(m);
652   PieceType pt = type_of(piece_on(from));
653
654   // Direct check ?
655   if (bit_is_set(ci.checkSq[pt], to))
656       return true;
657
658   // Discovery check ?
659   if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
660   {
661       // For pawn and king moves we need to verify also direction
662       if (  (pt != PAWN && pt != KING)
663           || !squares_aligned(from, to, king_square(flip(side_to_move()))))
664           return true;
665   }
666
667   // Can we skip the ugly special cases ?
668   if (!is_special(m))
669       return false;
670
671   Color us = side_to_move();
672   Bitboard b = occupied_squares();
673   Square ksq = king_square(flip(us));
674
675   // Promotion with check ?
676   if (is_promotion(m))
677   {
678       clear_bit(&b, from);
679       return bit_is_set(attacks_from(Piece(promotion_piece_type(m)), to, b), ksq);
680   }
681
682   // En passant capture with check ? We have already handled the case
683   // of direct checks and ordinary discovered check, the only case we
684   // need to handle is the unusual case of a discovered check through
685   // the captured pawn.
686   if (is_enpassant(m))
687   {
688       Square capsq = make_square(file_of(to), rank_of(from));
689       clear_bit(&b, from);
690       clear_bit(&b, capsq);
691       set_bit(&b, to);
692       return  (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
693             ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
694   }
695
696   // Castling with check ?
697   if (is_castle(m))
698   {
699       Square kfrom, kto, rfrom, rto;
700       kfrom = from;
701       rfrom = to;
702
703       if (rfrom > kfrom)
704       {
705           kto = relative_square(us, SQ_G1);
706           rto = relative_square(us, SQ_F1);
707       } else {
708           kto = relative_square(us, SQ_C1);
709           rto = relative_square(us, SQ_D1);
710       }
711       clear_bit(&b, kfrom);
712       clear_bit(&b, rfrom);
713       set_bit(&b, rto);
714       set_bit(&b, kto);
715       return bit_is_set(rook_attacks_bb(rto, b), ksq);
716   }
717
718   return false;
719 }
720
721
722 /// Position::do_move() makes a move, and saves all information necessary
723 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
724 /// moves should be filtered out before this function is called.
725
726 void Position::do_move(Move m, StateInfo& newSt) {
727
728   CheckInfo ci(*this);
729   do_move(m, newSt, ci, move_gives_check(m, ci));
730 }
731
732 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
733
734   assert(is_ok(m));
735   assert(&newSt != st);
736
737   nodes++;
738   Key key = st->key;
739
740   // Copy some fields of old state to our new StateInfo object except the
741   // ones which are recalculated from scratch anyway, then switch our state
742   // pointer to point to the new, ready to be updated, state.
743   struct ReducedStateInfo {
744     Key pawnKey, materialKey;
745     Value npMaterial[2];
746     int castleRights, rule50, pliesFromNull;
747     Score value;
748     Square epSquare;
749   };
750
751   memcpy(&newSt, st, sizeof(ReducedStateInfo));
752
753   newSt.previous = st;
754   st = &newSt;
755
756   // Update side to move
757   key ^= zobSideToMove;
758
759   // Increment the 50 moves rule draw counter. Resetting it to zero in the
760   // case of non-reversible moves is taken care of later.
761   st->rule50++;
762   st->pliesFromNull++;
763
764   if (is_castle(m))
765   {
766       st->key = key;
767       do_castle_move(m);
768       return;
769   }
770
771   Color us = side_to_move();
772   Color them = flip(us);
773   Square from = move_from(m);
774   Square to = move_to(m);
775   bool ep = is_enpassant(m);
776   bool pm = is_promotion(m);
777
778   Piece piece = piece_on(from);
779   PieceType pt = type_of(piece);
780   PieceType capture = ep ? PAWN : type_of(piece_on(to));
781
782   assert(color_of(piece_on(from)) == us);
783   assert(color_of(piece_on(to)) == them || square_is_empty(to));
784   assert(!(ep || pm) || piece == make_piece(us, PAWN));
785   assert(!pm || relative_rank(us, to) == RANK_8);
786
787   if (capture)
788       do_capture_move(key, capture, them, to, ep);
789
790   // Update hash key
791   key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
792
793   // Reset en passant square
794   if (st->epSquare != SQ_NONE)
795   {
796       key ^= zobEp[st->epSquare];
797       st->epSquare = SQ_NONE;
798   }
799
800   // Update castle rights if needed
801   if (    st->castleRights != CASTLES_NONE
802       && (castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
803   {
804       key ^= zobCastle[st->castleRights];
805       st->castleRights &= castleRightsMask[from] & castleRightsMask[to];
806       key ^= zobCastle[st->castleRights];
807   }
808
809   // Prefetch TT access as soon as we know key is updated
810   prefetch((char*)TT.first_entry(key));
811
812   // Move the piece
813   Bitboard move_bb = make_move_bb(from, to);
814   do_move_bb(&byColorBB[us], move_bb);
815   do_move_bb(&byTypeBB[pt], move_bb);
816   do_move_bb(&byTypeBB[0], move_bb); // HACK: byTypeBB[0] == occupied squares
817
818   board[to] = board[from];
819   board[from] = PIECE_NONE;
820
821   // Update piece lists, note that index[from] is not updated and
822   // becomes stale. This works as long as index[] is accessed just
823   // by known occupied squares.
824   index[to] = index[from];
825   pieceList[us][pt][index[to]] = to;
826
827   // If the moving piece was a pawn do some special extra work
828   if (pt == PAWN)
829   {
830       // Reset rule 50 draw counter
831       st->rule50 = 0;
832
833       // Update pawn hash key and prefetch in L1/L2 cache
834       st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
835
836       // Set en passant square, only if moved pawn can be captured
837       if ((to ^ from) == 16)
838       {
839           if (attacks_from<PAWN>(from + pawn_push(us), us) & pieces(PAWN, them))
840           {
841               st->epSquare = Square((int(from) + int(to)) / 2);
842               key ^= zobEp[st->epSquare];
843           }
844       }
845
846       if (pm) // promotion ?
847       {
848           PieceType promotion = promotion_piece_type(m);
849
850           assert(promotion >= KNIGHT && promotion <= QUEEN);
851
852           // Insert promoted piece instead of pawn
853           clear_bit(&byTypeBB[PAWN], to);
854           set_bit(&byTypeBB[promotion], to);
855           board[to] = make_piece(us, promotion);
856
857           // Update piece counts
858           pieceCount[us][promotion]++;
859           pieceCount[us][PAWN]--;
860
861           // Update material key
862           st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
863           st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
864
865           // Update piece lists, move the last pawn at index[to] position
866           // and shrink the list. Add a new promotion piece to the list.
867           Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
868           index[lastPawnSquare] = index[to];
869           pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
870           pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
871           index[to] = pieceCount[us][promotion] - 1;
872           pieceList[us][promotion][index[to]] = to;
873
874           // Partially revert hash keys update
875           key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
876           st->pawnKey ^= zobrist[us][PAWN][to];
877
878           // Partially revert and update incremental scores
879           st->value -= pst(make_piece(us, PAWN), to);
880           st->value += pst(make_piece(us, promotion), to);
881
882           // Update material
883           st->npMaterial[us] += PieceValueMidgame[promotion];
884       }
885   }
886
887   // Prefetch pawn and material hash tables
888   Threads[threadID].pawnTable.prefetch(st->pawnKey);
889   Threads[threadID].materialTable.prefetch(st->materialKey);
890
891   // Update incremental scores
892   st->value += pst_delta(piece, from, to);
893
894   // Set capture piece
895   st->capturedType = capture;
896
897   // Update the key with the final value
898   st->key = key;
899
900   // Update checkers bitboard, piece must be already moved
901   st->checkersBB = EmptyBoardBB;
902
903   if (moveIsCheck)
904   {
905       if (ep | pm)
906           st->checkersBB = attackers_to(king_square(them)) & pieces(us);
907       else
908       {
909           // Direct checks
910           if (bit_is_set(ci.checkSq[pt], to))
911               st->checkersBB = SetMaskBB[to];
912
913           // Discovery checks
914           if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
915           {
916               if (pt != ROOK)
917                   st->checkersBB |= (attacks_from<ROOK>(king_square(them)) & pieces(ROOK, QUEEN, us));
918
919               if (pt != BISHOP)
920                   st->checkersBB |= (attacks_from<BISHOP>(king_square(them)) & pieces(BISHOP, QUEEN, us));
921           }
922       }
923   }
924
925   // Finish
926   sideToMove = flip(sideToMove);
927   st->value += (sideToMove == WHITE ?  TempoValue : -TempoValue);
928
929   assert(pos_is_ok());
930 }
931
932
933 /// Position::do_capture_move() is a private method used to update captured
934 /// piece info. It is called from the main Position::do_move function.
935
936 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
937
938     assert(capture != KING);
939
940     Square capsq = to;
941
942     // If the captured piece was a pawn, update pawn hash key,
943     // otherwise update non-pawn material.
944     if (capture == PAWN)
945     {
946         if (ep) // en passant ?
947         {
948             capsq = to + pawn_push(them);
949
950             assert(to == st->epSquare);
951             assert(relative_rank(flip(them), to) == RANK_6);
952             assert(piece_on(to) == PIECE_NONE);
953             assert(piece_on(capsq) == make_piece(them, PAWN));
954
955             board[capsq] = PIECE_NONE;
956         }
957         st->pawnKey ^= zobrist[them][PAWN][capsq];
958     }
959     else
960         st->npMaterial[them] -= PieceValueMidgame[capture];
961
962     // Remove captured piece
963     clear_bit(&byColorBB[them], capsq);
964     clear_bit(&byTypeBB[capture], capsq);
965     clear_bit(&byTypeBB[0], capsq);
966
967     // Update hash key
968     key ^= zobrist[them][capture][capsq];
969
970     // Update incremental scores
971     st->value -= pst(make_piece(them, capture), capsq);
972
973     // Update piece count
974     pieceCount[them][capture]--;
975
976     // Update material hash key
977     st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
978
979     // Update piece list, move the last piece at index[capsq] position
980     //
981     // WARNING: This is a not perfectly revresible operation. When we
982     // will reinsert the captured piece in undo_move() we will put it
983     // at the end of the list and not in its original place, it means
984     // index[] and pieceList[] are not guaranteed to be invariant to a
985     // do_move() + undo_move() sequence.
986     Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
987     index[lastPieceSquare] = index[capsq];
988     pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
989     pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
990
991     // Reset rule 50 counter
992     st->rule50 = 0;
993 }
994
995
996 /// Position::do_castle_move() is a private method used to make a castling
997 /// move. It is called from the main Position::do_move function. Note that
998 /// castling moves are encoded as "king captures friendly rook" moves, for
999 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1000
1001 void Position::do_castle_move(Move m) {
1002
1003   assert(is_ok(m));
1004   assert(is_castle(m));
1005
1006   Color us = side_to_move();
1007   Color them = flip(us);
1008
1009   // Find source squares for king and rook
1010   Square kfrom = move_from(m);
1011   Square rfrom = move_to(m);
1012   Square kto, rto;
1013
1014   assert(piece_on(kfrom) == make_piece(us, KING));
1015   assert(piece_on(rfrom) == make_piece(us, ROOK));
1016
1017   // Find destination squares for king and rook
1018   if (rfrom > kfrom) // O-O
1019   {
1020       kto = relative_square(us, SQ_G1);
1021       rto = relative_square(us, SQ_F1);
1022   }
1023   else // O-O-O
1024   {
1025       kto = relative_square(us, SQ_C1);
1026       rto = relative_square(us, SQ_D1);
1027   }
1028
1029   // Remove pieces from source squares
1030   clear_bit(&byColorBB[us], kfrom);
1031   clear_bit(&byTypeBB[KING], kfrom);
1032   clear_bit(&byTypeBB[0], kfrom);
1033   clear_bit(&byColorBB[us], rfrom);
1034   clear_bit(&byTypeBB[ROOK], rfrom);
1035   clear_bit(&byTypeBB[0], rfrom);
1036
1037   // Put pieces on destination squares
1038   set_bit(&byColorBB[us], kto);
1039   set_bit(&byTypeBB[KING], kto);
1040   set_bit(&byTypeBB[0], kto);
1041   set_bit(&byColorBB[us], rto);
1042   set_bit(&byTypeBB[ROOK], rto);
1043   set_bit(&byTypeBB[0], rto);
1044
1045   // Update board
1046   Piece king = make_piece(us, KING);
1047   Piece rook = make_piece(us, ROOK);
1048   board[kfrom] = board[rfrom] = PIECE_NONE;
1049   board[kto] = king;
1050   board[rto] = rook;
1051
1052   // Update piece lists
1053   pieceList[us][KING][index[kfrom]] = kto;
1054   pieceList[us][ROOK][index[rfrom]] = rto;
1055   int tmp = index[rfrom]; // In Chess960 could be kto == rfrom
1056   index[kto] = index[kfrom];
1057   index[rto] = tmp;
1058
1059   // Reset capture field
1060   st->capturedType = PIECE_TYPE_NONE;
1061
1062   // Update incremental scores
1063   st->value += pst_delta(king, kfrom, kto);
1064   st->value += pst_delta(rook, rfrom, rto);
1065
1066   // Update hash key
1067   st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1068   st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1069
1070   // Clear en passant square
1071   if (st->epSquare != SQ_NONE)
1072   {
1073       st->key ^= zobEp[st->epSquare];
1074       st->epSquare = SQ_NONE;
1075   }
1076
1077   // Update castling rights
1078   st->key ^= zobCastle[st->castleRights];
1079   st->castleRights &= castleRightsMask[kfrom];
1080   st->key ^= zobCastle[st->castleRights];
1081
1082   // Reset rule 50 counter
1083   st->rule50 = 0;
1084
1085   // Update checkers BB
1086   st->checkersBB = attackers_to(king_square(them)) & pieces(us);
1087
1088   // Finish
1089   sideToMove = flip(sideToMove);
1090   st->value += (sideToMove == WHITE ?  TempoValue : -TempoValue);
1091
1092   assert(pos_is_ok());
1093 }
1094
1095
1096 /// Position::undo_move() unmakes a move. When it returns, the position should
1097 /// be restored to exactly the same state as before the move was made.
1098
1099 void Position::undo_move(Move m) {
1100
1101   assert(is_ok(m));
1102
1103   sideToMove = flip(sideToMove);
1104
1105   if (is_castle(m))
1106   {
1107       undo_castle_move(m);
1108       return;
1109   }
1110
1111   Color us = side_to_move();
1112   Color them = flip(us);
1113   Square from = move_from(m);
1114   Square to = move_to(m);
1115   bool ep = is_enpassant(m);
1116   bool pm = is_promotion(m);
1117
1118   PieceType pt = type_of(piece_on(to));
1119
1120   assert(square_is_empty(from));
1121   assert(color_of(piece_on(to)) == us);
1122   assert(!pm || relative_rank(us, to) == RANK_8);
1123   assert(!ep || to == st->previous->epSquare);
1124   assert(!ep || relative_rank(us, to) == RANK_6);
1125   assert(!ep || piece_on(to) == make_piece(us, PAWN));
1126
1127   if (pm) // promotion ?
1128   {
1129       PieceType promotion = promotion_piece_type(m);
1130       pt = PAWN;
1131
1132       assert(promotion >= KNIGHT && promotion <= QUEEN);
1133       assert(piece_on(to) == make_piece(us, promotion));
1134
1135       // Replace promoted piece with a pawn
1136       clear_bit(&byTypeBB[promotion], to);
1137       set_bit(&byTypeBB[PAWN], to);
1138
1139       // Update piece counts
1140       pieceCount[us][promotion]--;
1141       pieceCount[us][PAWN]++;
1142
1143       // Update piece list replacing promotion piece with a pawn
1144       Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1145       index[lastPromotionSquare] = index[to];
1146       pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1147       pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1148       index[to] = pieceCount[us][PAWN] - 1;
1149       pieceList[us][PAWN][index[to]] = to;
1150   }
1151
1152   // Put the piece back at the source square
1153   Bitboard move_bb = make_move_bb(to, from);
1154   do_move_bb(&byColorBB[us], move_bb);
1155   do_move_bb(&byTypeBB[pt], move_bb);
1156   do_move_bb(&byTypeBB[0], move_bb); // HACK: byTypeBB[0] == occupied squares
1157
1158   board[from] = make_piece(us, pt);
1159   board[to] = PIECE_NONE;
1160
1161   // Update piece list
1162   index[from] = index[to];
1163   pieceList[us][pt][index[from]] = from;
1164
1165   if (st->capturedType)
1166   {
1167       Square capsq = to;
1168
1169       if (ep)
1170           capsq = to - pawn_push(us);
1171
1172       assert(st->capturedType != KING);
1173       assert(!ep || square_is_empty(capsq));
1174
1175       // Restore the captured piece
1176       set_bit(&byColorBB[them], capsq);
1177       set_bit(&byTypeBB[st->capturedType], capsq);
1178       set_bit(&byTypeBB[0], capsq);
1179
1180       board[capsq] = make_piece(them, st->capturedType);
1181
1182       // Update piece count
1183       pieceCount[them][st->capturedType]++;
1184
1185       // Update piece list, add a new captured piece in capsq square
1186       index[capsq] = pieceCount[them][st->capturedType] - 1;
1187       pieceList[them][st->capturedType][index[capsq]] = capsq;
1188   }
1189
1190   // Finally point our state pointer back to the previous state
1191   st = st->previous;
1192
1193   assert(pos_is_ok());
1194 }
1195
1196
1197 /// Position::undo_castle_move() is a private method used to unmake a castling
1198 /// move. It is called from the main Position::undo_move function. Note that
1199 /// castling moves are encoded as "king captures friendly rook" moves, for
1200 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1201
1202 void Position::undo_castle_move(Move m) {
1203
1204   assert(is_ok(m));
1205   assert(is_castle(m));
1206
1207   // When we have arrived here, some work has already been done by
1208   // Position::undo_move. In particular, the side to move has been switched,
1209   // so the code below is correct.
1210   Color us = side_to_move();
1211
1212   // Find source squares for king and rook
1213   Square kfrom = move_from(m);
1214   Square rfrom = move_to(m);
1215   Square kto, rto;
1216
1217   // Find destination squares for king and rook
1218   if (rfrom > kfrom) // O-O
1219   {
1220       kto = relative_square(us, SQ_G1);
1221       rto = relative_square(us, SQ_F1);
1222   }
1223   else // O-O-O
1224   {
1225       kto = relative_square(us, SQ_C1);
1226       rto = relative_square(us, SQ_D1);
1227   }
1228
1229   assert(piece_on(kto) == make_piece(us, KING));
1230   assert(piece_on(rto) == make_piece(us, ROOK));
1231
1232   // Remove pieces from destination squares
1233   clear_bit(&byColorBB[us], kto);
1234   clear_bit(&byTypeBB[KING], kto);
1235   clear_bit(&byTypeBB[0], kto);
1236   clear_bit(&byColorBB[us], rto);
1237   clear_bit(&byTypeBB[ROOK], rto);
1238   clear_bit(&byTypeBB[0], rto);
1239
1240   // Put pieces on source squares
1241   set_bit(&byColorBB[us], kfrom);
1242   set_bit(&byTypeBB[KING], kfrom);
1243   set_bit(&byTypeBB[0], kfrom);
1244   set_bit(&byColorBB[us], rfrom);
1245   set_bit(&byTypeBB[ROOK], rfrom);
1246   set_bit(&byTypeBB[0], rfrom);
1247
1248   // Update board
1249   Piece king = make_piece(us, KING);
1250   Piece rook = make_piece(us, ROOK);
1251   board[kto] = board[rto] = PIECE_NONE;
1252   board[kfrom] = king;
1253   board[rfrom] = rook;
1254
1255   // Update piece lists
1256   pieceList[us][KING][index[kto]] = kfrom;
1257   pieceList[us][ROOK][index[rto]] = rfrom;
1258   int tmp = index[rto];  // In Chess960 could be rto == kfrom
1259   index[kfrom] = index[kto];
1260   index[rfrom] = tmp;
1261
1262   // Finally point our state pointer back to the previous state
1263   st = st->previous;
1264
1265   assert(pos_is_ok());
1266 }
1267
1268
1269 /// Position::do_null_move makes() a "null move": It switches the side to move
1270 /// and updates the hash key without executing any move on the board.
1271
1272 void Position::do_null_move(StateInfo& backupSt) {
1273
1274   assert(!in_check());
1275
1276   // Back up the information necessary to undo the null move to the supplied
1277   // StateInfo object.
1278   // Note that differently from normal case here backupSt is actually used as
1279   // a backup storage not as a new state to be used.
1280   backupSt.key      = st->key;
1281   backupSt.epSquare = st->epSquare;
1282   backupSt.value    = st->value;
1283   backupSt.previous = st->previous;
1284   backupSt.pliesFromNull = st->pliesFromNull;
1285   st->previous = &backupSt;
1286
1287   // Update the necessary information
1288   if (st->epSquare != SQ_NONE)
1289       st->key ^= zobEp[st->epSquare];
1290
1291   st->key ^= zobSideToMove;
1292   prefetch((char*)TT.first_entry(st->key));
1293
1294   sideToMove = flip(sideToMove);
1295   st->epSquare = SQ_NONE;
1296   st->rule50++;
1297   st->pliesFromNull = 0;
1298   st->value += (sideToMove == WHITE) ?  TempoValue : -TempoValue;
1299
1300   assert(pos_is_ok());
1301 }
1302
1303
1304 /// Position::undo_null_move() unmakes a "null move".
1305
1306 void Position::undo_null_move() {
1307
1308   assert(!in_check());
1309
1310   // Restore information from the our backup StateInfo object
1311   StateInfo* backupSt = st->previous;
1312   st->key      = backupSt->key;
1313   st->epSquare = backupSt->epSquare;
1314   st->value    = backupSt->value;
1315   st->previous = backupSt->previous;
1316   st->pliesFromNull = backupSt->pliesFromNull;
1317
1318   // Update the necessary information
1319   sideToMove = flip(sideToMove);
1320   st->rule50--;
1321
1322   assert(pos_is_ok());
1323 }
1324
1325
1326 /// Position::see() is a static exchange evaluator: It tries to estimate the
1327 /// material gain or loss resulting from a move. There are three versions of
1328 /// this function: One which takes a destination square as input, one takes a
1329 /// move, and one which takes a 'from' and a 'to' square. The function does
1330 /// not yet understand promotions captures.
1331
1332 int Position::see_sign(Move m) const {
1333
1334   assert(is_ok(m));
1335
1336   Square from = move_from(m);
1337   Square to = move_to(m);
1338
1339   // Early return if SEE cannot be negative because captured piece value
1340   // is not less then capturing one. Note that king moves always return
1341   // here because king midgame value is set to 0.
1342   if (PieceValueMidgame[piece_on(to)] >= PieceValueMidgame[piece_on(from)])
1343       return 1;
1344
1345   return see(m);
1346 }
1347
1348 int Position::see(Move m) const {
1349
1350   Square from, to;
1351   Bitboard occupied, attackers, stmAttackers, b;
1352   int swapList[32], slIndex = 1;
1353   PieceType capturedType, pt;
1354   Color stm;
1355
1356   assert(is_ok(m));
1357
1358   // As castle moves are implemented as capturing the rook, they have
1359   // SEE == RookValueMidgame most of the times (unless the rook is under
1360   // attack).
1361   if (is_castle(m))
1362       return 0;
1363
1364   from = move_from(m);
1365   to = move_to(m);
1366   capturedType = type_of(piece_on(to));
1367   occupied = occupied_squares();
1368
1369   // Handle en passant moves
1370   if (st->epSquare == to && type_of(piece_on(from)) == PAWN)
1371   {
1372       Square capQq = to - pawn_push(side_to_move());
1373
1374       assert(capturedType == PIECE_TYPE_NONE);
1375       assert(type_of(piece_on(capQq)) == PAWN);
1376
1377       // Remove the captured pawn
1378       clear_bit(&occupied, capQq);
1379       capturedType = PAWN;
1380   }
1381
1382   // Find all attackers to the destination square, with the moving piece
1383   // removed, but possibly an X-ray attacker added behind it.
1384   clear_bit(&occupied, from);
1385   attackers = attackers_to(to, occupied);
1386
1387   // If the opponent has no attackers we are finished
1388   stm = flip(color_of(piece_on(from)));
1389   stmAttackers = attackers & pieces(stm);
1390   if (!stmAttackers)
1391       return PieceValueMidgame[capturedType];
1392
1393   // The destination square is defended, which makes things rather more
1394   // difficult to compute. We proceed by building up a "swap list" containing
1395   // the material gain or loss at each stop in a sequence of captures to the
1396   // destination square, where the sides alternately capture, and always
1397   // capture with the least valuable piece. After each capture, we look for
1398   // new X-ray attacks from behind the capturing piece.
1399   swapList[0] = PieceValueMidgame[capturedType];
1400   capturedType = type_of(piece_on(from));
1401
1402   do {
1403       // Locate the least valuable attacker for the side to move. The loop
1404       // below looks like it is potentially infinite, but it isn't. We know
1405       // that the side to move still has at least one attacker left.
1406       for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1407           assert(pt < KING);
1408
1409       // Remove the attacker we just found from the 'occupied' bitboard,
1410       // and scan for new X-ray attacks behind the attacker.
1411       b = stmAttackers & pieces(pt);
1412       occupied ^= (b & (~b + 1));
1413       attackers |=  (rook_attacks_bb(to, occupied)   & pieces(ROOK, QUEEN))
1414                   | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1415
1416       attackers &= occupied; // Cut out pieces we've already done
1417
1418       // Add the new entry to the swap list
1419       assert(slIndex < 32);
1420       swapList[slIndex] = -swapList[slIndex - 1] + PieceValueMidgame[capturedType];
1421       slIndex++;
1422
1423       // Remember the value of the capturing piece, and change the side to
1424       // move before beginning the next iteration.
1425       capturedType = pt;
1426       stm = flip(stm);
1427       stmAttackers = attackers & pieces(stm);
1428
1429       // Stop before processing a king capture
1430       if (capturedType == KING && stmAttackers)
1431       {
1432           assert(slIndex < 32);
1433           swapList[slIndex++] = QueenValueMidgame*10;
1434           break;
1435       }
1436   } while (stmAttackers);
1437
1438   // Having built the swap list, we negamax through it to find the best
1439   // achievable score from the point of view of the side to move.
1440   while (--slIndex)
1441       swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1442
1443   return swapList[0];
1444 }
1445
1446
1447 /// Position::clear() erases the position object to a pristine state, with an
1448 /// empty board, white to move, and no castling rights.
1449
1450 void Position::clear() {
1451
1452   st = &startState;
1453   memset(st, 0, sizeof(StateInfo));
1454   st->epSquare = SQ_NONE;
1455
1456   memset(byColorBB,  0, sizeof(Bitboard) * 2);
1457   memset(byTypeBB,   0, sizeof(Bitboard) * 8);
1458   memset(pieceCount, 0, sizeof(int) * 2 * 8);
1459   memset(index,      0, sizeof(int) * 64);
1460
1461   for (int i = 0; i < 8; i++)
1462       for (int j = 0; j < 16; j++)
1463           pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1464
1465   for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1466   {
1467       board[sq] = PIECE_NONE;
1468       castleRightsMask[sq] = ALL_CASTLES;
1469   }
1470   sideToMove = WHITE;
1471   nodes = 0;
1472 }
1473
1474
1475 /// Position::put_piece() puts a piece on the given square of the board,
1476 /// updating the board array, pieces list, bitboards, and piece counts.
1477
1478 void Position::put_piece(Piece p, Square s) {
1479
1480   Color c = color_of(p);
1481   PieceType pt = type_of(p);
1482
1483   board[s] = p;
1484   index[s] = pieceCount[c][pt]++;
1485   pieceList[c][pt][index[s]] = s;
1486
1487   set_bit(&byTypeBB[pt], s);
1488   set_bit(&byColorBB[c], s);
1489   set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1490 }
1491
1492
1493 /// Position::compute_key() computes the hash key of the position. The hash
1494 /// key is usually updated incrementally as moves are made and unmade, the
1495 /// compute_key() function is only used when a new position is set up, and
1496 /// to verify the correctness of the hash key when running in debug mode.
1497
1498 Key Position::compute_key() const {
1499
1500   Key result = zobCastle[st->castleRights];
1501
1502   for (Square s = SQ_A1; s <= SQ_H8; s++)
1503       if (!square_is_empty(s))
1504           result ^= zobrist[color_of(piece_on(s))][type_of(piece_on(s))][s];
1505
1506   if (ep_square() != SQ_NONE)
1507       result ^= zobEp[ep_square()];
1508
1509   if (side_to_move() == BLACK)
1510       result ^= zobSideToMove;
1511
1512   return result;
1513 }
1514
1515
1516 /// Position::compute_pawn_key() computes the hash key of the position. The
1517 /// hash key is usually updated incrementally as moves are made and unmade,
1518 /// the compute_pawn_key() function is only used when a new position is set
1519 /// up, and to verify the correctness of the pawn hash key when running in
1520 /// debug mode.
1521
1522 Key Position::compute_pawn_key() const {
1523
1524   Bitboard b;
1525   Key result = 0;
1526
1527   for (Color c = WHITE; c <= BLACK; c++)
1528   {
1529       b = pieces(PAWN, c);
1530       while (b)
1531           result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1532   }
1533   return result;
1534 }
1535
1536
1537 /// Position::compute_material_key() computes the hash key of the position.
1538 /// The hash key is usually updated incrementally as moves are made and unmade,
1539 /// the compute_material_key() function is only used when a new position is set
1540 /// up, and to verify the correctness of the material hash key when running in
1541 /// debug mode.
1542
1543 Key Position::compute_material_key() const {
1544
1545   Key result = 0;
1546
1547   for (Color c = WHITE; c <= BLACK; c++)
1548       for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1549           for (int i = 0; i < piece_count(c, pt); i++)
1550               result ^= zobrist[c][pt][i];
1551
1552   return result;
1553 }
1554
1555
1556 /// Position::compute_value() compute the incremental scores for the middle
1557 /// game and the endgame. These functions are used to initialize the incremental
1558 /// scores when a new position is set up, and to verify that the scores are correctly
1559 /// updated by do_move and undo_move when the program is running in debug mode.
1560 Score Position::compute_value() const {
1561
1562   Bitboard b;
1563   Score result = SCORE_ZERO;
1564
1565   for (Color c = WHITE; c <= BLACK; c++)
1566       for (PieceType pt = PAWN; pt <= KING; pt++)
1567       {
1568           b = pieces(pt, c);
1569           while (b)
1570               result += pst(make_piece(c, pt), pop_1st_bit(&b));
1571       }
1572
1573   result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1574   return result;
1575 }
1576
1577
1578 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1579 /// game material value for the given side. Material values are updated
1580 /// incrementally during the search, this function is only used while
1581 /// initializing a new Position object.
1582
1583 Value Position::compute_non_pawn_material(Color c) const {
1584
1585   Value result = VALUE_ZERO;
1586
1587   for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1588       result += piece_count(c, pt) * PieceValueMidgame[pt];
1589
1590   return result;
1591 }
1592
1593
1594 /// Position::is_draw() tests whether the position is drawn by material,
1595 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1596 /// must be done by the search.
1597 template<bool SkipRepetition>
1598 bool Position::is_draw() const {
1599
1600   // Draw by material?
1601   if (   !pieces(PAWN)
1602       && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1603       return true;
1604
1605   // Draw by the 50 moves rule?
1606   if (st->rule50 > 99 && !is_mate())
1607       return true;
1608
1609   // Draw by repetition?
1610   if (!SkipRepetition)
1611   {
1612       int i = 4, e = Min(st->rule50, st->pliesFromNull);
1613
1614       if (i <= e)
1615       {
1616           StateInfo* stp = st->previous->previous;
1617
1618           do {
1619               stp = stp->previous->previous;
1620
1621               if (stp->key == st->key)
1622                   return true;
1623
1624               i +=2;
1625
1626           } while (i <= e);
1627       }
1628   }
1629
1630   return false;
1631 }
1632
1633 // Explicit template instantiations
1634 template bool Position::is_draw<false>() const;
1635 template bool Position::is_draw<true>() const;
1636
1637
1638 /// Position::is_mate() returns true or false depending on whether the
1639 /// side to move is checkmated.
1640
1641 bool Position::is_mate() const {
1642
1643   return in_check() && !MoveList<MV_LEGAL>(*this).size();
1644 }
1645
1646
1647 /// Position::init() is a static member function which initializes at startup
1648 /// the various arrays used to compute hash keys and the piece square tables.
1649 /// The latter is a two-step operation: First, the white halves of the tables
1650 /// are copied from PSQT[] tables. Second, the black halves of the tables are
1651 /// initialized by flipping and changing the sign of the white scores.
1652
1653 void Position::init() {
1654
1655   RKISS rk;
1656
1657   for (Color c = WHITE; c <= BLACK; c++)
1658       for (PieceType pt = PAWN; pt <= KING; pt++)
1659           for (Square s = SQ_A1; s <= SQ_H8; s++)
1660               zobrist[c][pt][s] = rk.rand<Key>();
1661
1662   for (Square s = SQ_A1; s <= SQ_H8; s++)
1663       zobEp[s] = rk.rand<Key>();
1664
1665   for (int i = 0; i < 16; i++)
1666       zobCastle[i] = rk.rand<Key>();
1667
1668   zobSideToMove = rk.rand<Key>();
1669   zobExclusion  = rk.rand<Key>();
1670
1671   for (Piece p = WP; p <= WK; p++)
1672   {
1673       Score ps = make_score(PieceValueMidgame[p], PieceValueEndgame[p]);
1674
1675       for (Square s = SQ_A1; s <= SQ_H8; s++)
1676       {
1677           pieceSquareTable[p][s] = ps + PSQT[p][s];
1678           pieceSquareTable[p+8][flip(s)] = -pieceSquareTable[p][s];
1679       }
1680   }
1681 }
1682
1683
1684 /// Position::flip_me() flips position with the white and black sides reversed. This
1685 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1686
1687 void Position::flip_me() {
1688
1689   // Make a copy of current position before to start changing
1690   const Position pos(*this, threadID);
1691
1692   clear();
1693   threadID = pos.thread();
1694
1695   // Board
1696   for (Square s = SQ_A1; s <= SQ_H8; s++)
1697       if (!pos.square_is_empty(s))
1698           put_piece(Piece(pos.piece_on(s) ^ 8), flip(s));
1699
1700   // Side to move
1701   sideToMove = flip(pos.side_to_move());
1702
1703   // Castling rights
1704   if (pos.can_castle(WHITE_OO))
1705       set_castle_right(king_square(BLACK), flip(pos.castle_rook_square(WHITE_OO)));
1706   if (pos.can_castle(WHITE_OOO))
1707       set_castle_right(king_square(BLACK), flip(pos.castle_rook_square(WHITE_OOO)));
1708   if (pos.can_castle(BLACK_OO))
1709       set_castle_right(king_square(WHITE), flip(pos.castle_rook_square(BLACK_OO)));
1710   if (pos.can_castle(BLACK_OOO))
1711       set_castle_right(king_square(WHITE), flip(pos.castle_rook_square(BLACK_OOO)));
1712
1713   // En passant square
1714   if (pos.st->epSquare != SQ_NONE)
1715       st->epSquare = flip(pos.st->epSquare);
1716
1717   // Checkers
1718   st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(flip(sideToMove));
1719
1720   // Hash keys
1721   st->key = compute_key();
1722   st->pawnKey = compute_pawn_key();
1723   st->materialKey = compute_material_key();
1724
1725   // Incremental scores
1726   st->value = compute_value();
1727
1728   // Material
1729   st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1730   st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1731
1732   assert(pos_is_ok());
1733 }
1734
1735
1736 /// Position::pos_is_ok() performs some consitency checks for the position object.
1737 /// This is meant to be helpful when debugging.
1738
1739 bool Position::pos_is_ok(int* failedStep) const {
1740
1741   // What features of the position should be verified?
1742   const bool debugAll = false;
1743
1744   const bool debugBitboards       = debugAll || false;
1745   const bool debugKingCount       = debugAll || false;
1746   const bool debugKingCapture     = debugAll || false;
1747   const bool debugCheckerCount    = debugAll || false;
1748   const bool debugKey             = debugAll || false;
1749   const bool debugMaterialKey     = debugAll || false;
1750   const bool debugPawnKey         = debugAll || false;
1751   const bool debugIncrementalEval = debugAll || false;
1752   const bool debugNonPawnMaterial = debugAll || false;
1753   const bool debugPieceCounts     = debugAll || false;
1754   const bool debugPieceList       = debugAll || false;
1755   const bool debugCastleSquares   = debugAll || false;
1756
1757   if (failedStep) *failedStep = 1;
1758
1759   // Side to move OK?
1760   if (side_to_move() != WHITE && side_to_move() != BLACK)
1761       return false;
1762
1763   // Are the king squares in the position correct?
1764   if (failedStep) (*failedStep)++;
1765   if (piece_on(king_square(WHITE)) != WK)
1766       return false;
1767
1768   if (failedStep) (*failedStep)++;
1769   if (piece_on(king_square(BLACK)) != BK)
1770       return false;
1771
1772   // Do both sides have exactly one king?
1773   if (failedStep) (*failedStep)++;
1774   if (debugKingCount)
1775   {
1776       int kingCount[2] = {0, 0};
1777       for (Square s = SQ_A1; s <= SQ_H8; s++)
1778           if (type_of(piece_on(s)) == KING)
1779               kingCount[color_of(piece_on(s))]++;
1780
1781       if (kingCount[0] != 1 || kingCount[1] != 1)
1782           return false;
1783   }
1784
1785   // Can the side to move capture the opponent's king?
1786   if (failedStep) (*failedStep)++;
1787   if (debugKingCapture)
1788   {
1789       Color us = side_to_move();
1790       Color them = flip(us);
1791       Square ksq = king_square(them);
1792       if (attackers_to(ksq) & pieces(us))
1793           return false;
1794   }
1795
1796   // Is there more than 2 checkers?
1797   if (failedStep) (*failedStep)++;
1798   if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1799       return false;
1800
1801   // Bitboards OK?
1802   if (failedStep) (*failedStep)++;
1803   if (debugBitboards)
1804   {
1805       // The intersection of the white and black pieces must be empty
1806       if ((pieces(WHITE) & pieces(BLACK)) != EmptyBoardBB)
1807           return false;
1808
1809       // The union of the white and black pieces must be equal to all
1810       // occupied squares
1811       if ((pieces(WHITE) | pieces(BLACK)) != occupied_squares())
1812           return false;
1813
1814       // Separate piece type bitboards must have empty intersections
1815       for (PieceType p1 = PAWN; p1 <= KING; p1++)
1816           for (PieceType p2 = PAWN; p2 <= KING; p2++)
1817               if (p1 != p2 && (pieces(p1) & pieces(p2)))
1818                   return false;
1819   }
1820
1821   // En passant square OK?
1822   if (failedStep) (*failedStep)++;
1823   if (ep_square() != SQ_NONE)
1824   {
1825       // The en passant square must be on rank 6, from the point of view of the
1826       // side to move.
1827       if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1828           return false;
1829   }
1830
1831   // Hash key OK?
1832   if (failedStep) (*failedStep)++;
1833   if (debugKey && st->key != compute_key())
1834       return false;
1835
1836   // Pawn hash key OK?
1837   if (failedStep) (*failedStep)++;
1838   if (debugPawnKey && st->pawnKey != compute_pawn_key())
1839       return false;
1840
1841   // Material hash key OK?
1842   if (failedStep) (*failedStep)++;
1843   if (debugMaterialKey && st->materialKey != compute_material_key())
1844       return false;
1845
1846   // Incremental eval OK?
1847   if (failedStep) (*failedStep)++;
1848   if (debugIncrementalEval && st->value != compute_value())
1849       return false;
1850
1851   // Non-pawn material OK?
1852   if (failedStep) (*failedStep)++;
1853   if (debugNonPawnMaterial)
1854   {
1855       if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1856           return false;
1857
1858       if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1859           return false;
1860   }
1861
1862   // Piece counts OK?
1863   if (failedStep) (*failedStep)++;
1864   if (debugPieceCounts)
1865       for (Color c = WHITE; c <= BLACK; c++)
1866           for (PieceType pt = PAWN; pt <= KING; pt++)
1867               if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1868                   return false;
1869
1870   if (failedStep) (*failedStep)++;
1871   if (debugPieceList)
1872       for (Color c = WHITE; c <= BLACK; c++)
1873           for (PieceType pt = PAWN; pt <= KING; pt++)
1874               for (int i = 0; i < pieceCount[c][pt]; i++)
1875               {
1876                   if (piece_on(piece_list(c, pt)[i]) != make_piece(c, pt))
1877                       return false;
1878
1879                   if (index[piece_list(c, pt)[i]] != i)
1880                       return false;
1881               }
1882
1883   if (failedStep) (*failedStep)++;
1884   if (debugCastleSquares)
1885       for (CastleRight f = WHITE_OO; f <= BLACK_OOO; f = CastleRight(f << 1))
1886       {
1887           if (!can_castle(f))
1888               continue;
1889
1890           Piece rook = (f & (WHITE_OO | WHITE_OOO) ? WR : BR);
1891
1892           if (   castleRightsMask[castleRookSquare[f]] != (ALL_CASTLES ^ f)
1893               || piece_on(castleRookSquare[f]) != rook)
1894               return false;
1895       }
1896
1897   if (failedStep) *failedStep = 0;
1898   return true;
1899 }