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