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