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-2012 Marco Costalba, Joona Kiiski, Tord Romstad
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.
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.
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/>.
38 Key Position::zobrist[2][8][64];
39 Key Position::zobEp[8];
40 Key Position::zobCastle[16];
41 Key Position::zobSideToMove;
42 Key Position::zobExclusion;
44 Score Position::pieceSquareTable[16][64];
46 // Material values arrays, indexed by Piece
47 const Value PieceValueMidgame[17] = {
49 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
50 RookValueMidgame, QueenValueMidgame,
51 VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
52 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
53 RookValueMidgame, QueenValueMidgame
56 const Value PieceValueEndgame[17] = {
58 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
59 RookValueEndgame, QueenValueEndgame,
60 VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
61 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
62 RookValueEndgame, QueenValueEndgame
68 // Bonus for having the side to move (modified by Joona Kiiski)
69 const Score Tempo = make_score(48, 22);
71 // To convert a Piece to and from a FEN char
72 const string PieceToChar(" PNBRQK pnbrqk .");
78 CheckInfo::CheckInfo(const Position& pos) {
80 Color them = ~pos.side_to_move();
81 ksq = pos.king_square(them);
83 pinned = pos.pinned_pieces();
84 dcCandidates = pos.discovered_check_candidates();
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];
95 /// Position::operator=() creates a copy of 'pos'. We want the new born Position
96 /// object do not depend on any external data so we detach state pointer from
99 void Position::operator=(const Position& pos) {
101 memcpy(this, &pos, sizeof(Position));
110 /// Position::from_fen() initializes the position object with the given FEN
111 /// string. This function is not very robust - make sure that input FENs are
112 /// correct (this is assumed to be the responsibility of the GUI).
114 void Position::from_fen(const string& fenStr, bool isChess960, Thread* th) {
116 A FEN string defines a particular position using only the ASCII character set.
118 A FEN string contains six fields separated by a space. The fields are:
120 1) Piece placement (from white's perspective). Each rank is described, starting
121 with rank 8 and ending with rank 1; within each rank, the contents of each
122 square are described from file A through file H. Following the Standard
123 Algebraic Notation (SAN), each piece is identified by a single letter taken
124 from the standard English names. White pieces are designated using upper-case
125 letters ("PNBRQK") while Black take lowercase ("pnbrqk"). Blank squares are
126 noted using digits 1 through 8 (the number of blank squares), and "/"
129 2) Active color. "w" means white moves next, "b" means black.
131 3) Castling availability. If neither side can castle, this is "-". Otherwise,
132 this has one or more letters: "K" (White can castle kingside), "Q" (White
133 can castle queenside), "k" (Black can castle kingside), and/or "q" (Black
134 can castle queenside).
136 4) En passant target square (in algebraic notation). If there's no en passant
137 target square, this is "-". If a pawn has just made a 2-square move, this
138 is the position "behind" the pawn. This is recorded regardless of whether
139 there is a pawn in position to make an en passant capture.
141 5) Halfmove clock. This is the number of halfmoves since the last pawn advance
142 or capture. This is used to determine if a draw can be claimed under the
145 6) Fullmove number. The number of the full move. It starts at 1, and is
146 incremented after Black's move.
149 char col, row, token;
152 std::istringstream fen(fenStr);
155 fen >> std::noskipws;
157 // 1. Piece placement
158 while ((fen >> token) && !isspace(token))
161 sq += Square(token - '0'); // Advance the given number of files
163 else if (token == '/')
164 sq = make_square(FILE_A, rank_of(sq) - Rank(2));
166 else if ((p = PieceToChar.find(token)) != string::npos)
168 put_piece(Piece(p), sq);
175 sideToMove = (token == 'w' ? WHITE : BLACK);
178 // 3. Castling availability. Compatible with 3 standards: Normal FEN standard,
179 // Shredder-FEN that uses the letters of the columns on which the rooks began
180 // the game instead of KQkq and also X-FEN standard that, in case of Chess960,
181 // if an inner rook is associated with the castling right, the castling tag is
182 // replaced by the file letter of the involved rook, as for the Shredder-FEN.
183 while ((fen >> token) && !isspace(token))
186 Color c = islower(token) ? BLACK : WHITE;
188 token = char(toupper(token));
191 for (rsq = relative_square(c, SQ_H1); type_of(piece_on(rsq)) != ROOK; rsq--) {}
193 else if (token == 'Q')
194 for (rsq = relative_square(c, SQ_A1); type_of(piece_on(rsq)) != ROOK; rsq++) {}
196 else if (token >= 'A' && token <= 'H')
197 rsq = make_square(File(token - 'A'), relative_rank(c, RANK_1));
202 set_castle_right(c, rsq);
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')))
209 st->epSquare = make_square(File(col - 'a'), Rank(row - '1'));
211 if (!(attackers_to(st->epSquare) & pieces(PAWN, sideToMove)))
212 st->epSquare = SQ_NONE;
215 // 5-6. Halfmove clock and fullmove number
216 fen >> std::skipws >> st->rule50 >> startPosPly;
218 // Convert from fullmove starting from 1 to ply starting from 0,
219 // handle also common incorrect FEN with fullmove = 0.
220 startPosPly = std::max(2 * (startPosPly - 1), 0) + int(sideToMove == BLACK);
222 st->key = compute_key();
223 st->pawnKey = compute_pawn_key();
224 st->materialKey = compute_material_key();
225 st->psqScore = compute_psq_score();
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(~sideToMove);
229 chess960 = isChess960;
236 /// Position::set_castle_right() is an helper function used to set castling
237 /// rights given the corresponding color and the rook starting square.
239 void Position::set_castle_right(Color c, Square rfrom) {
241 Square kfrom = king_square(c);
242 CastlingSide cs = kfrom < rfrom ? KING_SIDE : QUEEN_SIDE;
243 CastleRight cr = make_castle_right(c, cs);
245 st->castleRights |= cr;
246 castleRightsMask[kfrom] |= cr;
247 castleRightsMask[rfrom] |= cr;
248 castleRookSquare[c][cs] = rfrom;
250 Square kto = relative_square(c, cs == KING_SIDE ? SQ_G1 : SQ_C1);
251 Square rto = relative_square(c, cs == KING_SIDE ? SQ_F1 : SQ_D1);
253 for (Square s = std::min(rfrom, rto); s <= std::max(rfrom, rto); s++)
254 if (s != kfrom && s != rfrom)
255 castlePath[c][cs] |= s;
257 for (Square s = std::min(kfrom, kto); s <= std::max(kfrom, kto); s++)
258 if (s != kfrom && s != rfrom)
259 castlePath[c][cs] |= s;
263 /// Position::to_fen() returns a FEN representation of the position. In case
264 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
266 const string Position::to_fen() const {
268 std::ostringstream fen;
272 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
276 for (File file = FILE_A; file <= FILE_H; file++)
278 sq = make_square(file, rank);
280 if (square_empty(sq))
289 fen << PieceToChar[piece_on(sq)];
300 fen << (sideToMove == WHITE ? " w " : " b ");
302 if (can_castle(WHITE_OO))
303 fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE, KING_SIDE))))) : 'K');
305 if (can_castle(WHITE_OOO))
306 fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE, QUEEN_SIDE))))) : 'Q');
308 if (can_castle(BLACK_OO))
309 fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK, KING_SIDE))) : 'k');
311 if (can_castle(BLACK_OOO))
312 fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK, QUEEN_SIDE))) : 'q');
314 if (st->castleRights == CASTLES_NONE)
317 fen << (ep_square() == SQ_NONE ? " - " : " " + square_to_string(ep_square()) + " ")
318 << st->rule50 << " " << 1 + (startPosPly - int(sideToMove == BLACK)) / 2;
324 /// Position::print() prints an ASCII representation of the position to
325 /// the standard output. If a move is given then also the san is printed.
327 void Position::print(Move move) const {
329 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
334 cout << "\nMove is: " << (sideToMove == BLACK ? ".." : "") << move_to_san(p, move);
337 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
339 cout << dottedLine << '|';
340 for (File file = FILE_A; file <= FILE_H; file++)
342 Square sq = make_square(file, rank);
343 Piece piece = piece_on(sq);
344 char c = (color_of(piece) == BLACK ? '=' : ' ');
346 if (piece == NO_PIECE && !opposite_colors(sq, SQ_A1))
347 piece++; // Index the dot
349 cout << c << PieceToChar[piece] << c << '|';
352 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
356 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
357 /// king) pieces for the given color. Or, when template parameter FindPinned is
358 /// false, the function return the pieces of the given color candidate for a
359 /// discovery check against the enemy king.
360 template<bool FindPinned>
361 Bitboard Position::hidden_checkers() const {
363 // Pinned pieces protect our king, dicovery checks attack the enemy king
364 Bitboard b, result = 0;
365 Bitboard pinners = pieces(FindPinned ? ~sideToMove : sideToMove);
366 Square ksq = king_square(FindPinned ? sideToMove : ~sideToMove);
368 // Pinners are sliders, that give check when candidate pinned is removed
369 pinners &= (pieces(ROOK, QUEEN) & PseudoAttacks[ROOK][ksq])
370 | (pieces(BISHOP, QUEEN) & PseudoAttacks[BISHOP][ksq]);
374 b = squares_between(ksq, pop_1st_bit(&pinners)) & pieces();
376 if (b && single_bit(b) && (b & pieces(sideToMove)))
382 // Explicit template instantiations
383 template Bitboard Position::hidden_checkers<true>() const;
384 template Bitboard Position::hidden_checkers<false>() const;
387 /// Position::attackers_to() computes a bitboard of all pieces which attack a
388 /// given square. Slider attacks use occ bitboard as occupancy.
390 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
392 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
393 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
394 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
395 | (attacks_bb<ROOK>(s, occ) & pieces(ROOK, QUEEN))
396 | (attacks_bb<BISHOP>(s, occ) & pieces(BISHOP, QUEEN))
397 | (attacks_from<KING>(s) & pieces(KING));
401 /// Position::attacks_from() computes a bitboard of all attacks of a given piece
402 /// put in a given square. Slider attacks use occ bitboard as occupancy.
404 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
410 case BISHOP: return attacks_bb<BISHOP>(s, occ);
411 case ROOK : return attacks_bb<ROOK>(s, occ);
412 case QUEEN : return attacks_bb<BISHOP>(s, occ) | attacks_bb<ROOK>(s, occ);
413 default : return StepAttacksBB[p][s];
418 /// Position::move_attacks_square() tests whether a move from the current
419 /// position attacks a given square.
421 bool Position::move_attacks_square(Move m, Square s) const {
427 Square from = from_sq(m);
428 Square to = to_sq(m);
429 Piece piece = piece_moved(m);
431 assert(!square_empty(from));
433 // Update occupancy as if the piece is moving
434 occ = pieces() ^ from ^ to;
436 // The piece moved in 'to' attacks the square 's' ?
437 if (attacks_from(piece, to, occ) & s)
440 // Scan for possible X-ray attackers behind the moved piece
441 xray = (attacks_bb<ROOK>(s, occ) & pieces(ROOK, QUEEN, color_of(piece)))
442 |(attacks_bb<BISHOP>(s, occ) & pieces(BISHOP, QUEEN, color_of(piece)));
444 // Verify attackers are triggered by our move and not already existing
445 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
449 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
451 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
454 assert(pinned == pinned_pieces());
456 Color us = sideToMove;
457 Square from = from_sq(m);
459 assert(color_of(piece_moved(m)) == us);
460 assert(piece_on(king_square(us)) == make_piece(us, KING));
462 // En passant captures are a tricky special case. Because they are rather
463 // uncommon, we do it simply by testing whether the king is attacked after
468 Square to = to_sq(m);
469 Square capsq = to + pawn_push(them);
470 Square ksq = king_square(us);
471 Bitboard b = (pieces() ^ from ^ capsq) | to;
473 assert(to == ep_square());
474 assert(piece_moved(m) == make_piece(us, PAWN));
475 assert(piece_on(capsq) == make_piece(them, PAWN));
476 assert(piece_on(to) == NO_PIECE);
478 return !(attacks_bb<ROOK>(ksq, b) & pieces(ROOK, QUEEN, them))
479 && !(attacks_bb<BISHOP>(ksq, b) & pieces(BISHOP, QUEEN, them));
482 // If the moving piece is a king, check whether the destination
483 // square is attacked by the opponent. Castling moves are checked
484 // for legality during move generation.
485 if (type_of(piece_on(from)) == KING)
486 return is_castle(m) || !(attackers_to(to_sq(m)) & pieces(~us));
488 // A non-king move is legal if and only if it is not pinned or it
489 // is moving along the ray towards or away from the king.
492 || squares_aligned(from, to_sq(m), king_square(us));
496 /// Position::move_is_legal() takes a random move and tests whether the move
497 /// is legal. This version is not very fast and should be used only in non
498 /// time-critical paths.
500 bool Position::move_is_legal(const Move m) const {
502 for (MoveList<MV_LEGAL> ml(*this); !ml.end(); ++ml)
510 /// Position::is_pseudo_legal() takes a random move and tests whether the move
511 /// is pseudo legal. It is used to validate moves from TT that can be corrupted
512 /// due to SMP concurrent access or hash position key aliasing.
514 bool Position::is_pseudo_legal(const Move m) const {
516 Color us = sideToMove;
517 Color them = ~sideToMove;
518 Square from = from_sq(m);
519 Square to = to_sq(m);
520 Piece pc = piece_moved(m);
522 // Use a slower but simpler function for uncommon cases
524 return move_is_legal(m);
526 // Is not a promotion, so promotion piece must be empty
527 if (promotion_type(m) - 2 != NO_PIECE_TYPE)
530 // If the from square is not occupied by a piece belonging to the side to
531 // move, the move is obviously not legal.
532 if (pc == NO_PIECE || color_of(pc) != us)
535 // The destination square cannot be occupied by a friendly piece
536 if (color_of(piece_on(to)) == us)
539 // Handle the special case of a pawn move
540 if (type_of(pc) == PAWN)
542 // Move direction must be compatible with pawn color
543 int direction = to - from;
544 if ((us == WHITE) != (direction > 0))
547 // We have already handled promotion moves, so destination
548 // cannot be on the 8/1th rank.
549 if (rank_of(to) == RANK_8 || rank_of(to) == RANK_1)
552 // Proceed according to the square delta between the origin and
553 // destination squares.
560 // Capture. The destination square must be occupied by an enemy
561 // piece (en passant captures was handled earlier).
562 if (color_of(piece_on(to)) != them)
565 // From and to files must be one file apart, avoids a7h5
566 if (abs(file_of(from) - file_of(to)) != 1)
572 // Pawn push. The destination square must be empty.
573 if (!square_empty(to))
578 // Double white pawn push. The destination square must be on the fourth
579 // rank, and both the destination square and the square between the
580 // source and destination squares must be empty.
581 if ( rank_of(to) != RANK_4
583 || !square_empty(from + DELTA_N))
588 // Double black pawn push. The destination square must be on the fifth
589 // rank, and both the destination square and the square between the
590 // source and destination squares must be empty.
591 if ( rank_of(to) != RANK_5
593 || !square_empty(from + DELTA_S))
601 else if (!(attacks_from(pc, from) & to))
604 // Evasions generator already takes care to avoid some kind of illegal moves
605 // and pl_move_is_legal() relies on this. So we have to take care that the
606 // same kind of moves are filtered out here.
609 if (type_of(pc) != KING)
611 Bitboard b = checkers();
612 Square checksq = pop_1st_bit(&b);
614 if (b) // double check ? In this case a king move is required
617 // Our move must be a blocking evasion or a capture of the checking piece
618 if (!((squares_between(checksq, king_square(us)) | checkers()) & to))
621 // In case of king moves under check we have to remove king so to catch
622 // as invalid moves like b1a1 when opposite queen is on c1.
623 else if (attackers_to(to, pieces() ^ from) & pieces(~us))
631 /// Position::move_gives_check() tests whether a pseudo-legal move gives a check
633 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
636 assert(ci.dcCandidates == discovered_check_candidates());
637 assert(color_of(piece_moved(m)) == sideToMove);
639 Square from = from_sq(m);
640 Square to = to_sq(m);
641 PieceType pt = type_of(piece_on(from));
644 if (ci.checkSq[pt] & to)
648 if (ci.dcCandidates && (ci.dcCandidates & from))
650 // For pawn and king moves we need to verify also direction
651 if ( (pt != PAWN && pt != KING)
652 || !squares_aligned(from, to, king_square(~sideToMove)))
656 // Can we skip the ugly special cases ?
660 Color us = sideToMove;
661 Square ksq = king_square(~us);
663 // Promotion with check ?
665 return attacks_from(Piece(promotion_type(m)), to, pieces() ^ from) & ksq;
667 // En passant capture with check ? We have already handled the case
668 // of direct checks and ordinary discovered check, the only case we
669 // need to handle is the unusual case of a discovered check through
670 // the captured pawn.
673 Square capsq = make_square(file_of(to), rank_of(from));
674 Bitboard b = (pieces() ^ from ^ capsq) | to;
676 return (attacks_bb< ROOK>(ksq, b) & pieces( ROOK, QUEEN, us))
677 | (attacks_bb<BISHOP>(ksq, b) & pieces(BISHOP, QUEEN, us));
680 // Castling with check ?
684 Square rfrom = to; // 'King captures the rook' notation
685 Square kto = relative_square(us, rfrom > kfrom ? SQ_G1 : SQ_C1);
686 Square rto = relative_square(us, rfrom > kfrom ? SQ_F1 : SQ_D1);
687 Bitboard b = (pieces() ^ kfrom ^ rfrom) | rto | kto;
689 return attacks_bb<ROOK>(rto, b) & ksq;
696 /// Position::do_move() makes a move, and saves all information necessary
697 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
698 /// moves should be filtered out before this function is called.
700 void Position::do_move(Move m, StateInfo& newSt) {
703 do_move(m, newSt, ci, move_gives_check(m, ci));
706 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
709 assert(&newSt != st);
714 // Copy some fields of old state to our new StateInfo object except the ones
715 // which are recalculated from scratch anyway, then switch our state pointer
716 // to point to the new, ready to be updated, state.
717 struct ReducedStateInfo {
718 Key pawnKey, materialKey;
720 int castleRights, rule50, pliesFromNull;
725 memcpy(&newSt, st, sizeof(ReducedStateInfo));
730 // Update side to move
733 // Increment the 50 moves rule draw counter. Resetting it to zero in the
734 // case of a capture or a pawn move is taken care of later.
741 do_castle_move<true>(m);
745 Color us = sideToMove;
747 Square from = from_sq(m);
748 Square to = to_sq(m);
749 Piece piece = piece_on(from);
750 PieceType pt = type_of(piece);
751 PieceType capture = is_enpassant(m) ? PAWN : type_of(piece_on(to));
753 assert(color_of(piece) == us);
754 assert(color_of(piece_on(to)) != us);
755 assert(capture != KING);
761 // If the captured piece is a pawn, update pawn hash key, otherwise
762 // update non-pawn material.
767 capsq += pawn_push(them);
770 assert(to == st->epSquare);
771 assert(relative_rank(us, to) == RANK_6);
772 assert(piece_on(to) == NO_PIECE);
773 assert(piece_on(capsq) == make_piece(them, PAWN));
775 board[capsq] = NO_PIECE;
778 st->pawnKey ^= zobrist[them][PAWN][capsq];
781 st->npMaterial[them] -= PieceValueMidgame[capture];
783 // Remove the captured piece
784 byTypeBB[ALL_PIECES] ^= capsq;
785 byTypeBB[capture] ^= capsq;
786 byColorBB[them] ^= capsq;
788 // Update piece list, move the last piece at index[capsq] position and
791 // WARNING: This is a not revresible operation. When we will reinsert the
792 // captured piece in undo_move() we will put it at the end of the list and
793 // not in its original place, it means index[] and pieceList[] are not
794 // guaranteed to be invariant to a do_move() + undo_move() sequence.
795 Square lastSquare = pieceList[them][capture][--pieceCount[them][capture]];
796 index[lastSquare] = index[capsq];
797 pieceList[them][capture][index[lastSquare]] = lastSquare;
798 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
801 k ^= zobrist[them][capture][capsq];
802 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
804 // Update incremental scores
805 st->psqScore -= pieceSquareTable[make_piece(them, capture)][capsq];
807 // Reset rule 50 counter
812 k ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
814 // Reset en passant square
815 if (st->epSquare != SQ_NONE)
817 k ^= zobEp[file_of(st->epSquare)];
818 st->epSquare = SQ_NONE;
821 // Update castle rights if needed
822 if (st->castleRights && (castleRightsMask[from] | castleRightsMask[to]))
824 int cr = castleRightsMask[from] | castleRightsMask[to];
825 k ^= zobCastle[st->castleRights & cr];
826 st->castleRights &= ~cr;
829 // Prefetch TT access as soon as we know key is updated
830 prefetch((char*)TT.first_entry(k));
833 Bitboard from_to_bb = SquareBB[from] | SquareBB[to];
834 byTypeBB[ALL_PIECES] ^= from_to_bb;
835 byTypeBB[pt] ^= from_to_bb;
836 byColorBB[us] ^= from_to_bb;
838 board[to] = board[from];
839 board[from] = NO_PIECE;
841 // Update piece lists, index[from] is not updated and becomes stale. This
842 // works as long as index[] is accessed just by known occupied squares.
843 index[to] = index[from];
844 pieceList[us][pt][index[to]] = to;
846 // If the moving piece is a pawn do some special extra work
849 // Set en-passant square, only if moved pawn can be captured
850 if ( (int(to) ^ int(from)) == 16
851 && (attacks_from<PAWN>(from + pawn_push(us), us) & pieces(PAWN, them)))
853 st->epSquare = Square((from + to) / 2);
854 k ^= zobEp[file_of(st->epSquare)];
859 PieceType promotion = promotion_type(m);
861 assert(relative_rank(us, to) == RANK_8);
862 assert(promotion >= KNIGHT && promotion <= QUEEN);
864 // Replace the pawn with the promoted piece
865 byTypeBB[PAWN] ^= to;
866 byTypeBB[promotion] |= to;
867 board[to] = make_piece(us, promotion);
869 // Update piece lists, move the last pawn at index[to] position
870 // and shrink the list. Add a new promotion piece to the list.
871 Square lastSquare = pieceList[us][PAWN][--pieceCount[us][PAWN]];
872 index[lastSquare] = index[to];
873 pieceList[us][PAWN][index[lastSquare]] = lastSquare;
874 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
875 index[to] = pieceCount[us][promotion];
876 pieceList[us][promotion][index[to]] = to;
879 k ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
880 st->pawnKey ^= zobrist[us][PAWN][to];
881 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]++]
882 ^ zobrist[us][PAWN][pieceCount[us][PAWN]];
884 // Update incremental score
885 st->psqScore += pieceSquareTable[make_piece(us, promotion)][to]
886 - pieceSquareTable[make_piece(us, PAWN)][to];
889 st->npMaterial[us] += PieceValueMidgame[promotion];
892 // Update pawn hash key
893 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
895 // Reset rule 50 draw counter
899 // Prefetch pawn and material hash tables
900 prefetch((char*)thisThread->pawnTable.entries[st->pawnKey]);
901 prefetch((char*)thisThread->materialTable.entries[st->materialKey]);
903 // Update incremental scores
904 st->psqScore += psq_delta(piece, from, to);
907 st->capturedType = capture;
909 // Update the key with the final value
912 // Update checkers bitboard, piece must be already moved
918 st->checkersBB = attackers_to(king_square(them)) & pieces(us);
922 if (ci.checkSq[pt] & to)
923 st->checkersBB |= to;
926 if (ci.dcCandidates && (ci.dcCandidates & from))
929 st->checkersBB |= attacks_from<ROOK>(king_square(them)) & pieces(ROOK, QUEEN, us);
932 st->checkersBB |= attacks_from<BISHOP>(king_square(them)) & pieces(BISHOP, QUEEN, us);
938 sideToMove = ~sideToMove;
939 st->psqScore += (sideToMove == WHITE ? Tempo : -Tempo);
945 /// Position::undo_move() unmakes a move. When it returns, the position should
946 /// be restored to exactly the same state as before the move was made.
948 void Position::undo_move(Move m) {
952 sideToMove = ~sideToMove;
956 do_castle_move<false>(m);
960 Color us = sideToMove;
962 Square from = from_sq(m);
963 Square to = to_sq(m);
964 Piece piece = piece_on(to);
965 PieceType pt = type_of(piece);
966 PieceType capture = st->capturedType;
968 assert(square_empty(from));
969 assert(color_of(piece) == us);
970 assert(capture != KING);
974 PieceType promotion = promotion_type(m);
976 assert(promotion == pt);
977 assert(relative_rank(us, to) == RANK_8);
978 assert(promotion >= KNIGHT && promotion <= QUEEN);
980 // Replace the promoted piece with the pawn
981 byTypeBB[promotion] ^= to;
982 byTypeBB[PAWN] |= to;
983 board[to] = make_piece(us, PAWN);
985 // Update piece lists, move the last promoted piece at index[to] position
986 // and shrink the list. Add a new pawn to the list.
987 Square lastSquare = pieceList[us][promotion][--pieceCount[us][promotion]];
988 index[lastSquare] = index[to];
989 pieceList[us][promotion][index[lastSquare]] = lastSquare;
990 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
991 index[to] = pieceCount[us][PAWN]++;
992 pieceList[us][PAWN][index[to]] = to;
997 // Put the piece back at the source square
998 Bitboard from_to_bb = SquareBB[from] | SquareBB[to];
999 byTypeBB[ALL_PIECES] ^= from_to_bb;
1000 byTypeBB[pt] ^= from_to_bb;
1001 byColorBB[us] ^= from_to_bb;
1003 board[from] = board[to];
1004 board[to] = NO_PIECE;
1006 // Update piece lists, index[to] is not updated and becomes stale. This
1007 // works as long as index[] is accessed just by known occupied squares.
1008 index[from] = index[to];
1009 pieceList[us][pt][index[from]] = from;
1015 if (is_enpassant(m))
1017 capsq -= pawn_push(us);
1020 assert(to == st->previous->epSquare);
1021 assert(relative_rank(us, to) == RANK_6);
1022 assert(piece_on(capsq) == NO_PIECE);
1025 // Restore the captured piece
1026 byTypeBB[ALL_PIECES] |= capsq;
1027 byTypeBB[capture] |= capsq;
1028 byColorBB[them] |= capsq;
1030 board[capsq] = make_piece(them, capture);
1032 // Update piece list, add a new captured piece in capsq square
1033 index[capsq] = pieceCount[them][capture]++;
1034 pieceList[them][capture][index[capsq]] = capsq;
1037 // Finally point our state pointer back to the previous state
1040 assert(pos_is_ok());
1044 /// Position::do_castle_move() is a private method used to do/undo a castling
1045 /// move. Note that castling moves are encoded as "king captures friendly rook"
1046 /// moves, for instance white short castling in a non-Chess960 game is encoded
1049 void Position::do_castle_move(Move m) {
1052 assert(is_castle(m));
1054 Square kto, kfrom, rfrom, rto, kAfter, rAfter;
1056 Color us = sideToMove;
1057 Square kBefore = from_sq(m);
1058 Square rBefore = to_sq(m);
1060 // Find after-castle squares for king and rook
1061 if (rBefore > kBefore) // O-O
1063 kAfter = relative_square(us, SQ_G1);
1064 rAfter = relative_square(us, SQ_F1);
1068 kAfter = relative_square(us, SQ_C1);
1069 rAfter = relative_square(us, SQ_D1);
1072 kfrom = Do ? kBefore : kAfter;
1073 rfrom = Do ? rBefore : rAfter;
1075 kto = Do ? kAfter : kBefore;
1076 rto = Do ? rAfter : rBefore;
1078 assert(piece_on(kfrom) == make_piece(us, KING));
1079 assert(piece_on(rfrom) == make_piece(us, ROOK));
1081 // Remove pieces from source squares
1082 byTypeBB[ALL_PIECES] ^= kfrom;
1083 byTypeBB[KING] ^= kfrom;
1084 byColorBB[us] ^= kfrom;
1085 byTypeBB[ALL_PIECES] ^= rfrom;
1086 byTypeBB[ROOK] ^= rfrom;
1087 byColorBB[us] ^= rfrom;
1089 // Put pieces on destination squares
1090 byTypeBB[ALL_PIECES] |= kto;
1091 byTypeBB[KING] |= kto;
1092 byColorBB[us] |= kto;
1093 byTypeBB[ALL_PIECES] |= rto;
1094 byTypeBB[ROOK] |= rto;
1095 byColorBB[us] |= rto;
1098 Piece king = make_piece(us, KING);
1099 Piece rook = make_piece(us, ROOK);
1100 board[kfrom] = board[rfrom] = NO_PIECE;
1104 // Update piece lists
1105 pieceList[us][KING][index[kfrom]] = kto;
1106 pieceList[us][ROOK][index[rfrom]] = rto;
1107 int tmp = index[rfrom]; // In Chess960 could be kto == rfrom
1108 index[kto] = index[kfrom];
1113 // Reset capture field
1114 st->capturedType = NO_PIECE_TYPE;
1116 // Update incremental scores
1117 st->psqScore += psq_delta(king, kfrom, kto);
1118 st->psqScore += psq_delta(rook, rfrom, rto);
1121 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1122 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1124 // Clear en passant square
1125 if (st->epSquare != SQ_NONE)
1127 st->key ^= zobEp[file_of(st->epSquare)];
1128 st->epSquare = SQ_NONE;
1131 // Update castling rights
1132 st->key ^= zobCastle[st->castleRights & castleRightsMask[kfrom]];
1133 st->castleRights &= ~castleRightsMask[kfrom];
1135 // Update checkers BB
1136 st->checkersBB = attackers_to(king_square(~us)) & pieces(us);
1139 sideToMove = ~sideToMove;
1140 st->psqScore += (sideToMove == WHITE ? Tempo : -Tempo);
1143 // Undo: point our state pointer back to the previous state
1146 assert(pos_is_ok());
1150 /// Position::do_null_move() is used to do/undo a "null move": It flips the side
1151 /// to move and updates the hash key without executing any move on the board.
1153 void Position::do_null_move(StateInfo& backupSt) {
1155 assert(!in_check());
1157 // Back up the information necessary to undo the null move to the supplied
1158 // StateInfo object. Note that differently from normal case here backupSt
1159 // is actually used as a backup storage not as the new state. This reduces
1160 // the number of fields to be copied.
1161 StateInfo* src = Do ? st : &backupSt;
1162 StateInfo* dst = Do ? &backupSt : st;
1164 dst->key = src->key;
1165 dst->epSquare = src->epSquare;
1166 dst->psqScore = src->psqScore;
1167 dst->rule50 = src->rule50;
1168 dst->pliesFromNull = src->pliesFromNull;
1170 sideToMove = ~sideToMove;
1174 if (st->epSquare != SQ_NONE)
1175 st->key ^= zobEp[file_of(st->epSquare)];
1177 st->key ^= zobSideToMove;
1178 prefetch((char*)TT.first_entry(st->key));
1180 st->epSquare = SQ_NONE;
1182 st->pliesFromNull = 0;
1183 st->psqScore += (sideToMove == WHITE ? Tempo : -Tempo);
1186 assert(pos_is_ok());
1189 // Explicit template instantiations
1190 template void Position::do_null_move<false>(StateInfo& backupSt);
1191 template void Position::do_null_move<true>(StateInfo& backupSt);
1194 /// Position::see() is a static exchange evaluator: It tries to estimate the
1195 /// material gain or loss resulting from a move. There are three versions of
1196 /// this function: One which takes a destination square as input, one takes a
1197 /// move, and one which takes a 'from' and a 'to' square. The function does
1198 /// not yet understand promotions captures.
1200 int Position::see_sign(Move m) const {
1204 // Early return if SEE cannot be negative because captured piece value
1205 // is not less then capturing one. Note that king moves always return
1206 // here because king midgame value is set to 0.
1207 if (PieceValueMidgame[piece_on(to_sq(m))] >= PieceValueMidgame[piece_moved(m)])
1213 int Position::see(Move m) const {
1216 Bitboard occ, attackers, stmAttackers, b;
1217 int swapList[32], slIndex = 1;
1218 PieceType capturedType, pt;
1223 // As castle moves are implemented as capturing the rook, they have
1224 // SEE == RookValueMidgame most of the times (unless the rook is under
1231 capturedType = type_of(piece_on(to));
1234 // Handle en passant moves
1235 if (is_enpassant(m))
1237 Square capQq = to - pawn_push(sideToMove);
1239 assert(!capturedType);
1240 assert(type_of(piece_on(capQq)) == PAWN);
1242 // Remove the captured pawn
1244 capturedType = PAWN;
1247 // Find all attackers to the destination square, with the moving piece
1248 // removed, but possibly an X-ray attacker added behind it.
1250 attackers = attackers_to(to, occ);
1252 // If the opponent has no attackers we are finished
1253 stm = ~color_of(piece_on(from));
1254 stmAttackers = attackers & pieces(stm);
1256 return PieceValueMidgame[capturedType];
1258 // The destination square is defended, which makes things rather more
1259 // difficult to compute. We proceed by building up a "swap list" containing
1260 // the material gain or loss at each stop in a sequence of captures to the
1261 // destination square, where the sides alternately capture, and always
1262 // capture with the least valuable piece. After each capture, we look for
1263 // new X-ray attacks from behind the capturing piece.
1264 swapList[0] = PieceValueMidgame[capturedType];
1265 capturedType = type_of(piece_on(from));
1268 // Locate the least valuable attacker for the side to move. The loop
1269 // below looks like it is potentially infinite, but it isn't. We know
1270 // that the side to move still has at least one attacker left.
1271 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1274 // Remove the attacker we just found from the 'occupied' bitboard,
1275 // and scan for new X-ray attacks behind the attacker.
1276 b = stmAttackers & pieces(pt);
1277 occ ^= (b & (~b + 1));
1278 attackers |= (attacks_bb<ROOK>(to, occ) & pieces(ROOK, QUEEN))
1279 | (attacks_bb<BISHOP>(to, occ) & pieces(BISHOP, QUEEN));
1281 attackers &= occ; // Cut out pieces we've already done
1283 // Add the new entry to the swap list
1284 assert(slIndex < 32);
1285 swapList[slIndex] = -swapList[slIndex - 1] + PieceValueMidgame[capturedType];
1288 // Remember the value of the capturing piece, and change the side to
1289 // move before beginning the next iteration.
1292 stmAttackers = attackers & pieces(stm);
1294 // Stop before processing a king capture
1295 if (capturedType == KING && stmAttackers)
1297 assert(slIndex < 32);
1298 swapList[slIndex++] = QueenValueMidgame*10;
1301 } while (stmAttackers);
1303 // Having built the swap list, we negamax through it to find the best
1304 // achievable score from the point of view of the side to move.
1306 swapList[slIndex-1] = std::min(-swapList[slIndex], swapList[slIndex-1]);
1312 /// Position::clear() erases the position object to a pristine state, with an
1313 /// empty board, white to move, and no castling rights.
1315 void Position::clear() {
1317 memset(this, 0, sizeof(Position));
1318 startState.epSquare = SQ_NONE;
1321 for (int i = 0; i < 8; i++)
1322 for (int j = 0; j < 16; j++)
1323 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1325 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1326 board[sq] = NO_PIECE;
1330 /// Position::put_piece() puts a piece on the given square of the board,
1331 /// updating the board array, pieces list, bitboards, and piece counts.
1333 void Position::put_piece(Piece p, Square s) {
1335 Color c = color_of(p);
1336 PieceType pt = type_of(p);
1339 index[s] = pieceCount[c][pt]++;
1340 pieceList[c][pt][index[s]] = s;
1342 byTypeBB[ALL_PIECES] |= s;
1348 /// Position::compute_key() computes the hash key of the position. The hash
1349 /// key is usually updated incrementally as moves are made and unmade, the
1350 /// compute_key() function is only used when a new position is set up, and
1351 /// to verify the correctness of the hash key when running in debug mode.
1353 Key Position::compute_key() const {
1355 Key result = zobCastle[st->castleRights];
1357 for (Square s = SQ_A1; s <= SQ_H8; s++)
1358 if (!square_empty(s))
1359 result ^= zobrist[color_of(piece_on(s))][type_of(piece_on(s))][s];
1361 if (ep_square() != SQ_NONE)
1362 result ^= zobEp[file_of(ep_square())];
1364 if (sideToMove == BLACK)
1365 result ^= zobSideToMove;
1371 /// Position::compute_pawn_key() computes the hash key of the position. The
1372 /// hash key is usually updated incrementally as moves are made and unmade,
1373 /// the compute_pawn_key() function is only used when a new position is set
1374 /// up, and to verify the correctness of the pawn hash key when running in
1377 Key Position::compute_pawn_key() const {
1382 for (Color c = WHITE; c <= BLACK; c++)
1384 b = pieces(PAWN, c);
1386 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1392 /// Position::compute_material_key() computes the hash key of the position.
1393 /// The hash key is usually updated incrementally as moves are made and unmade,
1394 /// the compute_material_key() function is only used when a new position is set
1395 /// up, and to verify the correctness of the material hash key when running in
1398 Key Position::compute_material_key() const {
1402 for (Color c = WHITE; c <= BLACK; c++)
1403 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1404 for (int i = 0; i < piece_count(c, pt); i++)
1405 result ^= zobrist[c][pt][i];
1411 /// Position::compute_psq_score() computes the incremental scores for the middle
1412 /// game and the endgame. These functions are used to initialize the incremental
1413 /// scores when a new position is set up, and to verify that the scores are correctly
1414 /// updated by do_move and undo_move when the program is running in debug mode.
1415 Score Position::compute_psq_score() const {
1418 Score result = SCORE_ZERO;
1420 for (Color c = WHITE; c <= BLACK; c++)
1421 for (PieceType pt = PAWN; pt <= KING; pt++)
1425 result += pieceSquareTable[make_piece(c, pt)][pop_1st_bit(&b)];
1428 result += (sideToMove == WHITE ? Tempo / 2 : -Tempo / 2);
1433 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1434 /// game material value for the given side. Material values are updated
1435 /// incrementally during the search, this function is only used while
1436 /// initializing a new Position object.
1438 Value Position::compute_non_pawn_material(Color c) const {
1440 Value result = VALUE_ZERO;
1442 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1443 result += piece_count(c, pt) * PieceValueMidgame[pt];
1449 /// Position::is_draw() tests whether the position is drawn by material,
1450 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1451 /// must be done by the search.
1452 template<bool SkipRepetition>
1453 bool Position::is_draw() const {
1455 // Draw by material?
1457 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1460 // Draw by the 50 moves rule?
1461 if (st->rule50 > 99 && (!in_check() || MoveList<MV_LEGAL>(*this).size()))
1464 // Draw by repetition?
1465 if (!SkipRepetition)
1467 int i = 4, e = std::min(st->rule50, st->pliesFromNull);
1471 StateInfo* stp = st->previous->previous;
1474 stp = stp->previous->previous;
1476 if (stp->key == st->key)
1488 // Explicit template instantiations
1489 template bool Position::is_draw<false>() const;
1490 template bool Position::is_draw<true>() const;
1493 /// Position::init() is a static member function which initializes at startup
1494 /// the various arrays used to compute hash keys and the piece square tables.
1495 /// The latter is a two-step operation: First, the white halves of the tables
1496 /// are copied from PSQT[] tables. Second, the black halves of the tables are
1497 /// initialized by flipping and changing the sign of the white scores.
1499 void Position::init() {
1503 for (Color c = WHITE; c <= BLACK; c++)
1504 for (PieceType pt = PAWN; pt <= KING; pt++)
1505 for (Square s = SQ_A1; s <= SQ_H8; s++)
1506 zobrist[c][pt][s] = rk.rand<Key>();
1508 for (File f = FILE_A; f <= FILE_H; f++)
1509 zobEp[f] = rk.rand<Key>();
1511 for (int cr = CASTLES_NONE; cr <= ALL_CASTLES; cr++)
1516 Key k = zobCastle[1ULL << pop_1st_bit(&b)];
1517 zobCastle[cr] ^= k ? k : rk.rand<Key>();
1521 zobSideToMove = rk.rand<Key>();
1522 zobExclusion = rk.rand<Key>();
1524 for (Piece p = W_PAWN; p <= W_KING; p++)
1526 Score ps = make_score(PieceValueMidgame[p], PieceValueEndgame[p]);
1528 for (Square s = SQ_A1; s <= SQ_H8; s++)
1530 pieceSquareTable[p][s] = ps + PSQT[p][s];
1531 pieceSquareTable[p+8][~s] = -pieceSquareTable[p][s];
1537 /// Position::flip() flips position with the white and black sides reversed. This
1538 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1540 void Position::flip() {
1542 const Position pos(*this);
1546 sideToMove = ~pos.side_to_move();
1547 thisThread = pos.this_thread();
1548 nodes = pos.nodes_searched();
1549 chess960 = pos.is_chess960();
1550 startPosPly = pos.startpos_ply_counter();
1552 for (Square s = SQ_A1; s <= SQ_H8; s++)
1553 if (!pos.square_empty(s))
1554 put_piece(Piece(pos.piece_on(s) ^ 8), ~s);
1556 if (pos.can_castle(WHITE_OO))
1557 set_castle_right(BLACK, ~pos.castle_rook_square(WHITE, KING_SIDE));
1558 if (pos.can_castle(WHITE_OOO))
1559 set_castle_right(BLACK, ~pos.castle_rook_square(WHITE, QUEEN_SIDE));
1560 if (pos.can_castle(BLACK_OO))
1561 set_castle_right(WHITE, ~pos.castle_rook_square(BLACK, KING_SIDE));
1562 if (pos.can_castle(BLACK_OOO))
1563 set_castle_right(WHITE, ~pos.castle_rook_square(BLACK, QUEEN_SIDE));
1565 if (pos.st->epSquare != SQ_NONE)
1566 st->epSquare = ~pos.st->epSquare;
1568 st->key = compute_key();
1569 st->pawnKey = compute_pawn_key();
1570 st->materialKey = compute_material_key();
1571 st->psqScore = compute_psq_score();
1572 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(~sideToMove);
1573 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1574 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1576 assert(pos_is_ok());
1580 /// Position::pos_is_ok() performs some consitency checks for the position object.
1581 /// This is meant to be helpful when debugging.
1583 bool Position::pos_is_ok(int* failedStep) const {
1585 // What features of the position should be verified?
1586 const bool debugAll = false;
1588 const bool debugBitboards = debugAll || false;
1589 const bool debugKingCount = debugAll || false;
1590 const bool debugKingCapture = debugAll || false;
1591 const bool debugCheckerCount = debugAll || false;
1592 const bool debugKey = debugAll || false;
1593 const bool debugMaterialKey = debugAll || false;
1594 const bool debugPawnKey = debugAll || false;
1595 const bool debugIncrementalEval = debugAll || false;
1596 const bool debugNonPawnMaterial = debugAll || false;
1597 const bool debugPieceCounts = debugAll || false;
1598 const bool debugPieceList = debugAll || false;
1599 const bool debugCastleSquares = debugAll || false;
1601 if (failedStep) *failedStep = 1;
1604 if (sideToMove != WHITE && sideToMove != BLACK)
1607 // Are the king squares in the position correct?
1608 if (failedStep) (*failedStep)++;
1609 if (piece_on(king_square(WHITE)) != W_KING)
1612 if (failedStep) (*failedStep)++;
1613 if (piece_on(king_square(BLACK)) != B_KING)
1616 // Do both sides have exactly one king?
1617 if (failedStep) (*failedStep)++;
1620 int kingCount[2] = {0, 0};
1621 for (Square s = SQ_A1; s <= SQ_H8; s++)
1622 if (type_of(piece_on(s)) == KING)
1623 kingCount[color_of(piece_on(s))]++;
1625 if (kingCount[0] != 1 || kingCount[1] != 1)
1629 // Can the side to move capture the opponent's king?
1630 if (failedStep) (*failedStep)++;
1631 if (debugKingCapture)
1633 Color us = sideToMove;
1635 Square ksq = king_square(them);
1636 if (attackers_to(ksq) & pieces(us))
1640 // Is there more than 2 checkers?
1641 if (failedStep) (*failedStep)++;
1642 if (debugCheckerCount && popcount<Full>(st->checkersBB) > 2)
1646 if (failedStep) (*failedStep)++;
1649 // The intersection of the white and black pieces must be empty
1650 if (pieces(WHITE) & pieces(BLACK))
1653 // The union of the white and black pieces must be equal to all
1655 if ((pieces(WHITE) | pieces(BLACK)) != pieces())
1658 // Separate piece type bitboards must have empty intersections
1659 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1660 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1661 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1665 // En passant square OK?
1666 if (failedStep) (*failedStep)++;
1667 if (ep_square() != SQ_NONE)
1669 // The en passant square must be on rank 6, from the point of view of the
1671 if (relative_rank(sideToMove, ep_square()) != RANK_6)
1676 if (failedStep) (*failedStep)++;
1677 if (debugKey && st->key != compute_key())
1680 // Pawn hash key OK?
1681 if (failedStep) (*failedStep)++;
1682 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1685 // Material hash key OK?
1686 if (failedStep) (*failedStep)++;
1687 if (debugMaterialKey && st->materialKey != compute_material_key())
1690 // Incremental eval OK?
1691 if (failedStep) (*failedStep)++;
1692 if (debugIncrementalEval && st->psqScore != compute_psq_score())
1695 // Non-pawn material OK?
1696 if (failedStep) (*failedStep)++;
1697 if (debugNonPawnMaterial)
1699 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1702 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1707 if (failedStep) (*failedStep)++;
1708 if (debugPieceCounts)
1709 for (Color c = WHITE; c <= BLACK; c++)
1710 for (PieceType pt = PAWN; pt <= KING; pt++)
1711 if (pieceCount[c][pt] != popcount<Full>(pieces(pt, c)))
1714 if (failedStep) (*failedStep)++;
1716 for (Color c = WHITE; c <= BLACK; c++)
1717 for (PieceType pt = PAWN; pt <= KING; pt++)
1718 for (int i = 0; i < pieceCount[c][pt]; i++)
1720 if (piece_on(piece_list(c, pt)[i]) != make_piece(c, pt))
1723 if (index[piece_list(c, pt)[i]] != i)
1727 if (failedStep) (*failedStep)++;
1728 if (debugCastleSquares)
1729 for (Color c = WHITE; c <= BLACK; c++)
1730 for (CastlingSide s = KING_SIDE; s <= QUEEN_SIDE; s = CastlingSide(s + 1))
1732 if (!can_castle(make_castle_right(c, s)))
1735 if ( piece_on(castleRookSquare[c][s]) != make_piece(c, ROOK)
1736 || castleRightsMask[castleRookSquare[c][s]] != make_castle_right(c, s))
1740 if (failedStep) *failedStep = 0;