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
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[64];
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 TempoValue = 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 = flip(pos.side_to_move());
81 Square 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];
91 checkSq[KING] = EmptyBoardBB;
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.
99 Position::Position(const Position& pos, int th) {
101 memcpy(this, &pos, sizeof(Position));
108 Position::Position(const string& fen, bool isChess960, int th) {
110 from_fen(fen, isChess960);
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).
119 void Position::from_fen(const string& fenStr, bool isChess960) {
121 A FEN string defines a particular position using only the ASCII character set.
123 A FEN string contains six fields. The separator between fields is a space. The fields are:
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.
132 2) Active color. "w" means white moves next, "b" means black.
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).
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.
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.
145 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
148 char col, row, token;
151 std::istringstream fen(fenStr);
154 fen >> std::noskipws;
156 // 1. Piece placement
157 while ((fen >> token) && !isspace(token))
160 sq -= Square(16); // Jump back of 2 rows
162 else if (isdigit(token))
163 sq += Square(token - '0'); // Skip the given number of files
165 else if ((p = PieceToChar.find(token)) != string::npos)
167 put_piece(Piece(p), sq);
174 sideToMove = (token == 'w' ? WHITE : BLACK);
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))
185 Color c = islower(token) ? BLACK : WHITE;
186 Piece rook = make_piece(c, ROOK);
188 token = char(toupper(token));
191 for (rsq = relative_square(c, SQ_H1); piece_on(rsq) != rook; rsq--) {}
193 else if (token == 'Q')
194 for (rsq = relative_square(c, SQ_A1); 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(king_square(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 = 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->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;
235 /// Position::set_castle_right() is an helper function used to set castling
236 /// rights given the corresponding king and rook starting squares.
238 void Position::set_castle_right(Square ksq, Square rsq) {
240 int f = (rsq < ksq ? WHITE_OOO : WHITE_OO) << color_of(piece_on(ksq));
242 st->castleRights |= f;
243 castleRightsMask[ksq] ^= f;
244 castleRightsMask[rsq] ^= f;
245 castleRookSquare[f] = rsq;
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.
252 const string Position::to_fen() const {
254 std::ostringstream fen;
258 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
262 for (File file = FILE_A; file <= FILE_H; file++)
264 sq = make_square(file, rank);
266 if (!square_is_empty(sq))
273 fen << PieceToChar[piece_on(sq)];
286 fen << (sideToMove == WHITE ? " w " : " b ");
288 if (st->castleRights != CASTLES_NONE)
290 if (can_castle(WHITE_OO))
291 fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE_OO))))) : 'K');
293 if (can_castle(WHITE_OOO))
294 fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE_OOO))))) : 'Q');
296 if (can_castle(BLACK_OO))
297 fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK_OO))) : 'k');
299 if (can_castle(BLACK_OOO))
300 fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK_OOO))) : 'q');
304 fen << (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()))
305 << " " << st->rule50 << " " << 1 + (startPosPly - int(sideToMove == BLACK)) / 2;
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.
314 void Position::print(Move move) const {
316 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
320 Position p(*this, thread());
321 string dd = (sideToMove == BLACK ? ".." : "");
322 cout << "\nMove is: " << dd << move_to_san(p, move);
325 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
327 cout << dottedLine << '|';
328 for (File file = FILE_A; file <= FILE_H; file++)
330 Square sq = make_square(file, rank);
331 Piece piece = piece_on(sq);
333 if (piece == PIECE_NONE && color_of(sq) == DARK)
334 piece = PIECE_NONE_DARK_SQ;
336 char c = (color_of(piece_on(sq)) == BLACK ? '=' : ' ');
337 cout << c << PieceToChar[piece] << c << '|';
340 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
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.
349 template<bool FindPinned>
350 Bitboard Position::hidden_checkers() const {
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));
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]);
363 b = squares_between(ksq, pop_1st_bit(&pinners)) & occupied_squares();
365 // Only one bit set and is an our piece?
366 if (b && !(b & (b - 1)) && (b & pieces(sideToMove)))
373 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
374 /// king) pieces for the side to move.
376 Bitboard Position::pinned_pieces() const {
378 return hidden_checkers<true>();
382 /// Position:discovered_check_candidates() returns a bitboard containing all
383 /// pieces for the side to move which are candidates for giving a discovered
386 Bitboard Position::discovered_check_candidates() const {
388 return hidden_checkers<false>();
391 /// Position::attackers_to() computes a bitboard of all pieces which attacks a
392 /// given square. Slider attacks use occ bitboard as occupancy.
394 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
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));
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.
407 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
409 assert(square_is_ok(s));
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];
421 /// Position::move_attacks_square() tests whether a move from the current
422 /// position attacks a given square.
424 bool Position::move_attacks_square(Move m, Square s) const {
427 assert(square_is_ok(s));
430 Square f = move_from(m), t = move_to(m);
432 assert(!square_is_empty(f));
434 if (bit_is_set(attacks_from(piece_on(f), t), s))
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)));
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)));
450 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
452 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
455 assert(pinned == pinned_pieces());
457 Color us = side_to_move();
458 Square from = move_from(m);
460 assert(color_of(piece_on(from)) == us);
461 assert(piece_on(king_square(us)) == make_piece(us, KING));
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
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();
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);
480 clear_bit(&b, capsq);
483 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
484 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
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)));
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.
496 || !bit_is_set(pinned, from)
497 || squares_aligned(from, move_to(m), king_square(us));
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.
505 bool Position::move_is_legal(const Move m) const {
507 for (MoveList<MV_LEGAL> ml(*this); !ml.end(); ++ml)
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.
519 bool Position::is_pseudo_legal(const Move m) const {
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);
527 // Use a slower but simpler function for uncommon cases
529 return move_is_legal(m);
531 // Is not a promotion, so promotion piece must be empty
532 if (promotion_piece_type(m) - 2 != PIECE_TYPE_NONE)
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)
540 // The destination square cannot be occupied by a friendly piece
541 if (color_of(piece_on(to)) == us)
544 // Handle the special case of a pawn move
545 if (type_of(pc) == PAWN)
547 // Move direction must be compatible with pawn color
548 int direction = to - from;
549 if ((us == WHITE) != (direction > 0))
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)
557 // Proceed according to the square delta between the origin and
558 // destination squares.
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)
570 // From and to files must be one file apart, avoids a7h5
571 if (abs(file_of(from) - file_of(to)) != 1)
577 // Pawn push. The destination square must be empty.
578 if (!square_is_empty(to))
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))
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))
606 else if (!bit_is_set(attacks_from(pc, from), to))
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.
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)
618 Bitboard b = occupied_squares();
620 if (attackers_to(move_to(m), b) & pieces(flip(us)))
625 Bitboard target = checkers();
626 Square checksq = pop_1st_bit(&target);
628 if (target) // double check ? In this case a king move is required
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)))
642 /// Position::move_gives_check() tests whether a pseudo-legal move gives a check
644 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
647 assert(ci.dcCandidates == discovered_check_candidates());
648 assert(color_of(piece_on(move_from(m))) == side_to_move());
650 Square from = move_from(m);
651 Square to = move_to(m);
652 PieceType pt = type_of(piece_on(from));
655 if (bit_is_set(ci.checkSq[pt], to))
659 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
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()))))
667 // Can we skip the ugly special cases ?
671 Color us = side_to_move();
672 Bitboard b = occupied_squares();
673 Square ksq = king_square(flip(us));
675 // Promotion with check ?
679 return bit_is_set(attacks_from(Piece(promotion_piece_type(m)), to, b), ksq);
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.
688 Square capsq = make_square(file_of(to), rank_of(from));
690 clear_bit(&b, capsq);
692 return (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
693 ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
696 // Castling with check ?
699 Square kfrom, kto, rfrom, rto;
705 kto = relative_square(us, SQ_G1);
706 rto = relative_square(us, SQ_F1);
708 kto = relative_square(us, SQ_C1);
709 rto = relative_square(us, SQ_D1);
711 clear_bit(&b, kfrom);
712 clear_bit(&b, rfrom);
715 return bit_is_set(rook_attacks_bb(rto, b), ksq);
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.
726 void Position::do_move(Move m, StateInfo& newSt) {
729 do_move(m, newSt, ci, move_gives_check(m, ci));
732 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
735 assert(&newSt != st);
740 // Copy some fields of old state to our new StateInfo object except the ones
741 // which are recalculated from scratch anyway, then switch our state pointer
742 // to point to the new, ready to be updated, state.
743 struct ReducedStateInfo {
744 Key pawnKey, materialKey;
746 int castleRights, rule50, pliesFromNull;
751 memcpy(&newSt, st, sizeof(ReducedStateInfo));
756 // Update side to move
757 key ^= zobSideToMove;
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.
767 do_castle_move<true>(m);
771 Color us = side_to_move();
772 Color them = flip(us);
773 Square from = move_from(m);
774 Square to = move_to(m);
775 Piece piece = piece_on(from);
776 PieceType pt = type_of(piece);
777 PieceType capture = is_enpassant(m) ? PAWN : type_of(piece_on(to));
779 assert(color_of(piece) == us);
780 assert(color_of(piece_on(to)) != us);
781 assert(capture != KING);
787 // If the captured piece is a pawn, update pawn hash key, otherwise
788 // update non-pawn material.
793 capsq += pawn_push(them);
796 assert(to == st->epSquare);
797 assert(relative_rank(us, to) == RANK_6);
798 assert(piece_on(to) == PIECE_NONE);
799 assert(piece_on(capsq) == make_piece(them, PAWN));
801 board[capsq] = PIECE_NONE;
804 st->pawnKey ^= zobrist[them][PAWN][capsq];
807 st->npMaterial[them] -= PieceValueMidgame[capture];
809 // Remove the captured piece
810 clear_bit(&byColorBB[them], capsq);
811 clear_bit(&byTypeBB[capture], capsq);
812 clear_bit(&occupied, capsq);
814 // Update piece list, move the last piece at index[capsq] position and
817 // WARNING: This is a not revresible operation. When we will reinsert the
818 // captured piece in undo_move() we will put it at the end of the list and
819 // not in its original place, it means index[] and pieceList[] are not
820 // guaranteed to be invariant to a do_move() + undo_move() sequence.
821 Square lastSquare = pieceList[them][capture][--pieceCount[them][capture]];
822 index[lastSquare] = index[capsq];
823 pieceList[them][capture][index[lastSquare]] = lastSquare;
824 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
827 key ^= zobrist[them][capture][capsq];
828 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
830 // Update incremental scores
831 st->value -= pst(make_piece(them, capture), capsq);
833 // Reset rule 50 counter
838 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
840 // Reset en passant square
841 if (st->epSquare != SQ_NONE)
843 key ^= zobEp[st->epSquare];
844 st->epSquare = SQ_NONE;
847 // Update castle rights if needed
848 if ( st->castleRights != CASTLES_NONE
849 && (castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
851 key ^= zobCastle[st->castleRights];
852 st->castleRights &= castleRightsMask[from] & castleRightsMask[to];
853 key ^= zobCastle[st->castleRights];
856 // Prefetch TT access as soon as we know key is updated
857 prefetch((char*)TT.first_entry(key));
860 Bitboard move_bb = make_move_bb(from, to);
861 do_move_bb(&byColorBB[us], move_bb);
862 do_move_bb(&byTypeBB[pt], move_bb);
863 do_move_bb(&occupied, move_bb);
865 board[to] = board[from];
866 board[from] = PIECE_NONE;
868 // Update piece lists, index[from] is not updated and becomes stale. This
869 // works as long as index[] is accessed just by known occupied squares.
870 index[to] = index[from];
871 pieceList[us][pt][index[to]] = to;
873 // If the moving piece is a pawn do some special extra work
876 // Set en-passant square, only if moved pawn can be captured
877 if ( (to ^ from) == 16
878 && (attacks_from<PAWN>(from + pawn_push(us), us) & pieces(PAWN, them)))
880 st->epSquare = Square((from + to) / 2);
881 key ^= zobEp[st->epSquare];
886 PieceType promotion = promotion_piece_type(m);
888 assert(relative_rank(us, to) == RANK_8);
889 assert(promotion >= KNIGHT && promotion <= QUEEN);
891 // Replace the pawn with the promoted piece
892 clear_bit(&byTypeBB[PAWN], to);
893 set_bit(&byTypeBB[promotion], to);
894 board[to] = make_piece(us, promotion);
896 // Update piece lists, move the last pawn at index[to] position
897 // and shrink the list. Add a new promotion piece to the list.
898 Square lastSquare = pieceList[us][PAWN][--pieceCount[us][PAWN]];
899 index[lastSquare] = index[to];
900 pieceList[us][PAWN][index[lastSquare]] = lastSquare;
901 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
902 index[to] = pieceCount[us][promotion];
903 pieceList[us][promotion][index[to]] = to;
906 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
907 st->pawnKey ^= zobrist[us][PAWN][to];
908 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]++]
909 ^ zobrist[us][PAWN][pieceCount[us][PAWN]];
911 // Update incremental score
912 st->value += pst(make_piece(us, promotion), to)
913 - pst(make_piece(us, PAWN), to);
916 st->npMaterial[us] += PieceValueMidgame[promotion];
919 // Update pawn hash key
920 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
922 // Reset rule 50 draw counter
926 // Prefetch pawn and material hash tables
927 Threads[threadID].pawnTable.prefetch(st->pawnKey);
928 Threads[threadID].materialTable.prefetch(st->materialKey);
930 // Update incremental scores
931 st->value += pst_delta(piece, from, to);
934 st->capturedType = capture;
936 // Update the key with the final value
939 // Update checkers bitboard, piece must be already moved
940 st->checkersBB = EmptyBoardBB;
945 st->checkersBB = attackers_to(king_square(them)) & pieces(us);
949 if (bit_is_set(ci.checkSq[pt], to))
950 st->checkersBB = SetMaskBB[to];
953 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
956 st->checkersBB |= attacks_from<ROOK>(king_square(them)) & pieces(ROOK, QUEEN, us);
959 st->checkersBB |= attacks_from<BISHOP>(king_square(them)) & pieces(BISHOP, QUEEN, us);
965 sideToMove = flip(sideToMove);
966 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
972 /// Position::undo_move() unmakes a move. When it returns, the position should
973 /// be restored to exactly the same state as before the move was made.
975 void Position::undo_move(Move m) {
979 sideToMove = flip(sideToMove);
983 do_castle_move<false>(m);
987 Color us = side_to_move();
988 Color them = flip(us);
989 Square from = move_from(m);
990 Square to = move_to(m);
991 Piece piece = piece_on(to);
992 PieceType pt = type_of(piece);
993 PieceType capture = st->capturedType;
995 assert(square_is_empty(from));
996 assert(color_of(piece) == us);
997 assert(capture != KING);
1001 PieceType promotion = promotion_piece_type(m);
1003 assert(promotion == pt);
1004 assert(relative_rank(us, to) == RANK_8);
1005 assert(promotion >= KNIGHT && promotion <= QUEEN);
1007 // Replace the promoted piece with the pawn
1008 clear_bit(&byTypeBB[promotion], to);
1009 set_bit(&byTypeBB[PAWN], to);
1010 board[to] = make_piece(us, PAWN);
1012 // Update piece lists, move the last promoted piece at index[to] position
1013 // and shrink the list. Add a new pawn to the list.
1014 Square lastSquare = pieceList[us][promotion][--pieceCount[us][promotion]];
1015 index[lastSquare] = index[to];
1016 pieceList[us][promotion][index[lastSquare]] = lastSquare;
1017 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1018 index[to] = pieceCount[us][PAWN]++;
1019 pieceList[us][PAWN][index[to]] = to;
1024 // Put the piece back at the source square
1025 Bitboard move_bb = make_move_bb(to, from);
1026 do_move_bb(&byColorBB[us], move_bb);
1027 do_move_bb(&byTypeBB[pt], move_bb);
1028 do_move_bb(&occupied, move_bb);
1030 board[from] = board[to];
1031 board[to] = PIECE_NONE;
1033 // Update piece lists, index[to] is not updated and becomes stale. This
1034 // works as long as index[] is accessed just by known occupied squares.
1035 index[from] = index[to];
1036 pieceList[us][pt][index[from]] = from;
1042 if (is_enpassant(m))
1044 capsq -= pawn_push(us);
1047 assert(to == st->previous->epSquare);
1048 assert(relative_rank(us, to) == RANK_6);
1049 assert(piece_on(capsq) == PIECE_NONE);
1052 // Restore the captured piece
1053 set_bit(&byColorBB[them], capsq);
1054 set_bit(&byTypeBB[capture], capsq);
1055 set_bit(&occupied, capsq);
1057 board[capsq] = make_piece(them, capture);
1059 // Update piece list, add a new captured piece in capsq square
1060 index[capsq] = pieceCount[them][capture]++;
1061 pieceList[them][capture][index[capsq]] = capsq;
1064 // Finally point our state pointer back to the previous state
1067 assert(pos_is_ok());
1071 /// Position::do_castle_move() is a private method used to do/undo a castling
1072 /// move. Note that castling moves are encoded as "king captures friendly rook"
1073 /// moves, for instance white short castling in a non-Chess960 game is encoded
1076 void Position::do_castle_move(Move m) {
1079 assert(is_castle(m));
1081 Square kto, kfrom, rfrom, rto, kAfter, rAfter;
1083 Color us = side_to_move();
1084 Square kBefore = move_from(m);
1085 Square rBefore = move_to(m);
1087 // Find after-castle squares for king and rook
1088 if (rBefore > kBefore) // O-O
1090 kAfter = relative_square(us, SQ_G1);
1091 rAfter = relative_square(us, SQ_F1);
1095 kAfter = relative_square(us, SQ_C1);
1096 rAfter = relative_square(us, SQ_D1);
1099 kfrom = Do ? kBefore : kAfter;
1100 rfrom = Do ? rBefore : rAfter;
1102 kto = Do ? kAfter : kBefore;
1103 rto = Do ? rAfter : rBefore;
1105 assert(piece_on(kfrom) == make_piece(us, KING));
1106 assert(piece_on(rfrom) == make_piece(us, ROOK));
1108 // Remove pieces from source squares
1109 clear_bit(&byColorBB[us], kfrom);
1110 clear_bit(&byTypeBB[KING], kfrom);
1111 clear_bit(&occupied, kfrom);
1112 clear_bit(&byColorBB[us], rfrom);
1113 clear_bit(&byTypeBB[ROOK], rfrom);
1114 clear_bit(&occupied, rfrom);
1116 // Put pieces on destination squares
1117 set_bit(&byColorBB[us], kto);
1118 set_bit(&byTypeBB[KING], kto);
1119 set_bit(&occupied, kto);
1120 set_bit(&byColorBB[us], rto);
1121 set_bit(&byTypeBB[ROOK], rto);
1122 set_bit(&occupied, rto);
1125 Piece king = make_piece(us, KING);
1126 Piece rook = make_piece(us, ROOK);
1127 board[kfrom] = board[rfrom] = PIECE_NONE;
1131 // Update piece lists
1132 pieceList[us][KING][index[kfrom]] = kto;
1133 pieceList[us][ROOK][index[rfrom]] = rto;
1134 int tmp = index[rfrom]; // In Chess960 could be kto == rfrom
1135 index[kto] = index[kfrom];
1140 // Reset capture field
1141 st->capturedType = PIECE_TYPE_NONE;
1143 // Update incremental scores
1144 st->value += pst_delta(king, kfrom, kto);
1145 st->value += pst_delta(rook, rfrom, rto);
1148 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1149 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1151 // Clear en passant square
1152 if (st->epSquare != SQ_NONE)
1154 st->key ^= zobEp[st->epSquare];
1155 st->epSquare = SQ_NONE;
1158 // Update castling rights
1159 st->key ^= zobCastle[st->castleRights];
1160 st->castleRights &= castleRightsMask[kfrom];
1161 st->key ^= zobCastle[st->castleRights];
1163 // Reset rule 50 counter
1166 // Update checkers BB
1167 st->checkersBB = attackers_to(king_square(flip(us))) & pieces(us);
1170 sideToMove = flip(sideToMove);
1171 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1174 // Undo: point our state pointer back to the previous state
1177 assert(pos_is_ok());
1181 /// Position::do_null_move() is used to do/undo a "null move": It flips the side
1182 /// to move and updates the hash key without executing any move on the board.
1184 void Position::do_null_move(StateInfo& backupSt) {
1186 assert(!in_check());
1188 // Back up the information necessary to undo the null move to the supplied
1189 // StateInfo object. Note that differently from normal case here backupSt
1190 // is actually used as a backup storage not as the new state. This reduces
1191 // the number of fields to be copied.
1192 StateInfo* src = Do ? st : &backupSt;
1193 StateInfo* dst = Do ? &backupSt : st;
1195 dst->key = src->key;
1196 dst->epSquare = src->epSquare;
1197 dst->value = src->value;
1198 dst->rule50 = src->rule50;
1199 dst->pliesFromNull = src->pliesFromNull;
1201 sideToMove = flip(sideToMove);
1205 if (st->epSquare != SQ_NONE)
1206 st->key ^= zobEp[st->epSquare];
1208 st->key ^= zobSideToMove;
1209 prefetch((char*)TT.first_entry(st->key));
1211 st->epSquare = SQ_NONE;
1213 st->pliesFromNull = 0;
1214 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1217 assert(pos_is_ok());
1220 // Explicit template instantiations
1221 template void Position::do_null_move<false>(StateInfo& backupSt);
1222 template void Position::do_null_move<true>(StateInfo& backupSt);
1225 /// Position::see() is a static exchange evaluator: It tries to estimate the
1226 /// material gain or loss resulting from a move. There are three versions of
1227 /// this function: One which takes a destination square as input, one takes a
1228 /// move, and one which takes a 'from' and a 'to' square. The function does
1229 /// not yet understand promotions captures.
1231 int Position::see_sign(Move m) const {
1235 Square from = move_from(m);
1236 Square to = move_to(m);
1238 // Early return if SEE cannot be negative because captured piece value
1239 // is not less then capturing one. Note that king moves always return
1240 // here because king midgame value is set to 0.
1241 if (PieceValueMidgame[piece_on(to)] >= PieceValueMidgame[piece_on(from)])
1247 int Position::see(Move m) const {
1250 Bitboard occ, attackers, stmAttackers, b;
1251 int swapList[32], slIndex = 1;
1252 PieceType capturedType, pt;
1257 // As castle moves are implemented as capturing the rook, they have
1258 // SEE == RookValueMidgame most of the times (unless the rook is under
1263 from = move_from(m);
1265 capturedType = type_of(piece_on(to));
1266 occ = occupied_squares();
1268 // Handle en passant moves
1269 if (is_enpassant(m))
1271 Square capQq = to - pawn_push(side_to_move());
1273 assert(capturedType == PIECE_TYPE_NONE);
1274 assert(type_of(piece_on(capQq)) == PAWN);
1276 // Remove the captured pawn
1277 clear_bit(&occ, capQq);
1278 capturedType = PAWN;
1281 // Find all attackers to the destination square, with the moving piece
1282 // removed, but possibly an X-ray attacker added behind it.
1283 clear_bit(&occ, from);
1284 attackers = attackers_to(to, occ);
1286 // If the opponent has no attackers we are finished
1287 stm = flip(color_of(piece_on(from)));
1288 stmAttackers = attackers & pieces(stm);
1290 return PieceValueMidgame[capturedType];
1292 // The destination square is defended, which makes things rather more
1293 // difficult to compute. We proceed by building up a "swap list" containing
1294 // the material gain or loss at each stop in a sequence of captures to the
1295 // destination square, where the sides alternately capture, and always
1296 // capture with the least valuable piece. After each capture, we look for
1297 // new X-ray attacks from behind the capturing piece.
1298 swapList[0] = PieceValueMidgame[capturedType];
1299 capturedType = type_of(piece_on(from));
1302 // Locate the least valuable attacker for the side to move. The loop
1303 // below looks like it is potentially infinite, but it isn't. We know
1304 // that the side to move still has at least one attacker left.
1305 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1308 // Remove the attacker we just found from the 'occupied' bitboard,
1309 // and scan for new X-ray attacks behind the attacker.
1310 b = stmAttackers & pieces(pt);
1311 occ ^= (b & (~b + 1));
1312 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1313 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1315 attackers &= occ; // Cut out pieces we've already done
1317 // Add the new entry to the swap list
1318 assert(slIndex < 32);
1319 swapList[slIndex] = -swapList[slIndex - 1] + PieceValueMidgame[capturedType];
1322 // Remember the value of the capturing piece, and change the side to
1323 // move before beginning the next iteration.
1326 stmAttackers = attackers & pieces(stm);
1328 // Stop before processing a king capture
1329 if (capturedType == KING && stmAttackers)
1331 assert(slIndex < 32);
1332 swapList[slIndex++] = QueenValueMidgame*10;
1335 } while (stmAttackers);
1337 // Having built the swap list, we negamax through it to find the best
1338 // achievable score from the point of view of the side to move.
1340 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1346 /// Position::clear() erases the position object to a pristine state, with an
1347 /// empty board, white to move, and no castling rights.
1349 void Position::clear() {
1352 memset(st, 0, sizeof(StateInfo));
1353 st->epSquare = SQ_NONE;
1355 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1356 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1357 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1358 memset(index, 0, sizeof(int) * 64);
1360 for (int i = 0; i < 8; i++)
1361 for (int j = 0; j < 16; j++)
1362 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1364 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1366 board[sq] = PIECE_NONE;
1367 castleRightsMask[sq] = ALL_CASTLES;
1375 /// Position::put_piece() puts a piece on the given square of the board,
1376 /// updating the board array, pieces list, bitboards, and piece counts.
1378 void Position::put_piece(Piece p, Square s) {
1380 Color c = color_of(p);
1381 PieceType pt = type_of(p);
1384 index[s] = pieceCount[c][pt]++;
1385 pieceList[c][pt][index[s]] = s;
1387 set_bit(&byTypeBB[pt], s);
1388 set_bit(&byColorBB[c], s);
1389 set_bit(&occupied, s);
1393 /// Position::compute_key() computes the hash key of the position. The hash
1394 /// key is usually updated incrementally as moves are made and unmade, the
1395 /// compute_key() function is only used when a new position is set up, and
1396 /// to verify the correctness of the hash key when running in debug mode.
1398 Key Position::compute_key() const {
1400 Key result = zobCastle[st->castleRights];
1402 for (Square s = SQ_A1; s <= SQ_H8; s++)
1403 if (!square_is_empty(s))
1404 result ^= zobrist[color_of(piece_on(s))][type_of(piece_on(s))][s];
1406 if (ep_square() != SQ_NONE)
1407 result ^= zobEp[ep_square()];
1409 if (side_to_move() == BLACK)
1410 result ^= zobSideToMove;
1416 /// Position::compute_pawn_key() computes the hash key of the position. The
1417 /// hash key is usually updated incrementally as moves are made and unmade,
1418 /// the compute_pawn_key() function is only used when a new position is set
1419 /// up, and to verify the correctness of the pawn hash key when running in
1422 Key Position::compute_pawn_key() const {
1427 for (Color c = WHITE; c <= BLACK; c++)
1429 b = pieces(PAWN, c);
1431 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1437 /// Position::compute_material_key() computes the hash key of the position.
1438 /// The hash key is usually updated incrementally as moves are made and unmade,
1439 /// the compute_material_key() function is only used when a new position is set
1440 /// up, and to verify the correctness of the material hash key when running in
1443 Key Position::compute_material_key() const {
1447 for (Color c = WHITE; c <= BLACK; c++)
1448 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1449 for (int i = 0; i < piece_count(c, pt); i++)
1450 result ^= zobrist[c][pt][i];
1456 /// Position::compute_value() compute the incremental scores for the middle
1457 /// game and the endgame. These functions are used to initialize the incremental
1458 /// scores when a new position is set up, and to verify that the scores are correctly
1459 /// updated by do_move and undo_move when the program is running in debug mode.
1460 Score Position::compute_value() const {
1463 Score result = SCORE_ZERO;
1465 for (Color c = WHITE; c <= BLACK; c++)
1466 for (PieceType pt = PAWN; pt <= KING; pt++)
1470 result += pst(make_piece(c, pt), pop_1st_bit(&b));
1473 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1478 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1479 /// game material value for the given side. Material values are updated
1480 /// incrementally during the search, this function is only used while
1481 /// initializing a new Position object.
1483 Value Position::compute_non_pawn_material(Color c) const {
1485 Value result = VALUE_ZERO;
1487 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1488 result += piece_count(c, pt) * PieceValueMidgame[pt];
1494 /// Position::is_draw() tests whether the position is drawn by material,
1495 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1496 /// must be done by the search.
1497 template<bool SkipRepetition>
1498 bool Position::is_draw() const {
1500 // Draw by material?
1502 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1505 // Draw by the 50 moves rule?
1506 if (st->rule50 > 99 && !is_mate())
1509 // Draw by repetition?
1510 if (!SkipRepetition)
1512 int i = 4, e = Min(st->rule50, st->pliesFromNull);
1516 StateInfo* stp = st->previous->previous;
1519 stp = stp->previous->previous;
1521 if (stp->key == st->key)
1533 // Explicit template instantiations
1534 template bool Position::is_draw<false>() const;
1535 template bool Position::is_draw<true>() const;
1538 /// Position::is_mate() returns true or false depending on whether the
1539 /// side to move is checkmated.
1541 bool Position::is_mate() const {
1543 return in_check() && !MoveList<MV_LEGAL>(*this).size();
1547 /// Position::init() is a static member function which initializes at startup
1548 /// the various arrays used to compute hash keys and the piece square tables.
1549 /// The latter is a two-step operation: First, the white halves of the tables
1550 /// are copied from PSQT[] tables. Second, the black halves of the tables are
1551 /// initialized by flipping and changing the sign of the white scores.
1553 void Position::init() {
1557 for (Color c = WHITE; c <= BLACK; c++)
1558 for (PieceType pt = PAWN; pt <= KING; pt++)
1559 for (Square s = SQ_A1; s <= SQ_H8; s++)
1560 zobrist[c][pt][s] = rk.rand<Key>();
1562 for (Square s = SQ_A1; s <= SQ_H8; s++)
1563 zobEp[s] = rk.rand<Key>();
1565 for (int i = 0; i < 16; i++)
1566 zobCastle[i] = rk.rand<Key>();
1568 zobSideToMove = rk.rand<Key>();
1569 zobExclusion = rk.rand<Key>();
1571 for (Piece p = WP; p <= WK; p++)
1573 Score ps = make_score(PieceValueMidgame[p], PieceValueEndgame[p]);
1575 for (Square s = SQ_A1; s <= SQ_H8; s++)
1577 pieceSquareTable[p][s] = ps + PSQT[p][s];
1578 pieceSquareTable[p+8][flip(s)] = -pieceSquareTable[p][s];
1584 /// Position::flip_me() flips position with the white and black sides reversed. This
1585 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1587 void Position::flip_me() {
1589 // Make a copy of current position before to start changing
1590 const Position pos(*this, threadID);
1593 threadID = pos.thread();
1596 for (Square s = SQ_A1; s <= SQ_H8; s++)
1597 if (!pos.square_is_empty(s))
1598 put_piece(Piece(pos.piece_on(s) ^ 8), flip(s));
1601 sideToMove = flip(pos.side_to_move());
1604 if (pos.can_castle(WHITE_OO))
1605 set_castle_right(king_square(BLACK), flip(pos.castle_rook_square(WHITE_OO)));
1606 if (pos.can_castle(WHITE_OOO))
1607 set_castle_right(king_square(BLACK), flip(pos.castle_rook_square(WHITE_OOO)));
1608 if (pos.can_castle(BLACK_OO))
1609 set_castle_right(king_square(WHITE), flip(pos.castle_rook_square(BLACK_OO)));
1610 if (pos.can_castle(BLACK_OOO))
1611 set_castle_right(king_square(WHITE), flip(pos.castle_rook_square(BLACK_OOO)));
1613 // En passant square
1614 if (pos.st->epSquare != SQ_NONE)
1615 st->epSquare = flip(pos.st->epSquare);
1618 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(flip(sideToMove));
1621 st->key = compute_key();
1622 st->pawnKey = compute_pawn_key();
1623 st->materialKey = compute_material_key();
1625 // Incremental scores
1626 st->value = compute_value();
1629 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1630 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1632 assert(pos_is_ok());
1636 /// Position::pos_is_ok() performs some consitency checks for the position object.
1637 /// This is meant to be helpful when debugging.
1639 bool Position::pos_is_ok(int* failedStep) const {
1641 // What features of the position should be verified?
1642 const bool debugAll = false;
1644 const bool debugBitboards = debugAll || false;
1645 const bool debugKingCount = debugAll || false;
1646 const bool debugKingCapture = debugAll || false;
1647 const bool debugCheckerCount = debugAll || false;
1648 const bool debugKey = debugAll || false;
1649 const bool debugMaterialKey = debugAll || false;
1650 const bool debugPawnKey = debugAll || false;
1651 const bool debugIncrementalEval = debugAll || false;
1652 const bool debugNonPawnMaterial = debugAll || false;
1653 const bool debugPieceCounts = debugAll || false;
1654 const bool debugPieceList = debugAll || false;
1655 const bool debugCastleSquares = debugAll || false;
1657 if (failedStep) *failedStep = 1;
1660 if (side_to_move() != WHITE && side_to_move() != BLACK)
1663 // Are the king squares in the position correct?
1664 if (failedStep) (*failedStep)++;
1665 if (piece_on(king_square(WHITE)) != WK)
1668 if (failedStep) (*failedStep)++;
1669 if (piece_on(king_square(BLACK)) != BK)
1672 // Do both sides have exactly one king?
1673 if (failedStep) (*failedStep)++;
1676 int kingCount[2] = {0, 0};
1677 for (Square s = SQ_A1; s <= SQ_H8; s++)
1678 if (type_of(piece_on(s)) == KING)
1679 kingCount[color_of(piece_on(s))]++;
1681 if (kingCount[0] != 1 || kingCount[1] != 1)
1685 // Can the side to move capture the opponent's king?
1686 if (failedStep) (*failedStep)++;
1687 if (debugKingCapture)
1689 Color us = side_to_move();
1690 Color them = flip(us);
1691 Square ksq = king_square(them);
1692 if (attackers_to(ksq) & pieces(us))
1696 // Is there more than 2 checkers?
1697 if (failedStep) (*failedStep)++;
1698 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1702 if (failedStep) (*failedStep)++;
1705 // The intersection of the white and black pieces must be empty
1706 if ((pieces(WHITE) & pieces(BLACK)) != EmptyBoardBB)
1709 // The union of the white and black pieces must be equal to all
1711 if ((pieces(WHITE) | pieces(BLACK)) != occupied_squares())
1714 // Separate piece type bitboards must have empty intersections
1715 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1716 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1717 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1721 // En passant square OK?
1722 if (failedStep) (*failedStep)++;
1723 if (ep_square() != SQ_NONE)
1725 // The en passant square must be on rank 6, from the point of view of the
1727 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1732 if (failedStep) (*failedStep)++;
1733 if (debugKey && st->key != compute_key())
1736 // Pawn hash key OK?
1737 if (failedStep) (*failedStep)++;
1738 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1741 // Material hash key OK?
1742 if (failedStep) (*failedStep)++;
1743 if (debugMaterialKey && st->materialKey != compute_material_key())
1746 // Incremental eval OK?
1747 if (failedStep) (*failedStep)++;
1748 if (debugIncrementalEval && st->value != compute_value())
1751 // Non-pawn material OK?
1752 if (failedStep) (*failedStep)++;
1753 if (debugNonPawnMaterial)
1755 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1758 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1763 if (failedStep) (*failedStep)++;
1764 if (debugPieceCounts)
1765 for (Color c = WHITE; c <= BLACK; c++)
1766 for (PieceType pt = PAWN; pt <= KING; pt++)
1767 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1770 if (failedStep) (*failedStep)++;
1772 for (Color c = WHITE; c <= BLACK; c++)
1773 for (PieceType pt = PAWN; pt <= KING; pt++)
1774 for (int i = 0; i < pieceCount[c][pt]; i++)
1776 if (piece_on(piece_list(c, pt)[i]) != make_piece(c, pt))
1779 if (index[piece_list(c, pt)[i]] != i)
1783 if (failedStep) (*failedStep)++;
1784 if (debugCastleSquares)
1785 for (CastleRight f = WHITE_OO; f <= BLACK_OOO; f = CastleRight(f << 1))
1790 Piece rook = (f & (WHITE_OO | WHITE_OOO) ? WR : BR);
1792 if ( castleRightsMask[castleRookSquare[f]] != (ALL_CASTLES ^ f)
1793 || piece_on(castleRookSquare[f]) != rook)
1797 if (failedStep) *failedStep = 0;