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