]> git.sesse.net Git - stockfish/blob - src/position.cpp
f24c2f2c0c3d72c1bb332b5589bdc71f6edd0781
[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 /// Position::see() is a static exchange evaluator: It tries to estimate the
1305 /// material gain or loss resulting from a move. There are three versions of
1306 /// this function: One which takes a destination square as input, one takes a
1307 /// move, and one which takes a 'from' and a 'to' square. The function does
1308 /// not yet understand promotions captures.
1309
1310 int Position::see(Square to) const {
1311
1312   assert(square_is_ok(to));
1313   return see(SQ_NONE, to);
1314 }
1315
1316 int Position::see(Move m) const {
1317
1318   assert(move_is_ok(m));
1319   return see(move_from(m), move_to(m));
1320 }
1321
1322 int Position::see_sign(Move m) const {
1323
1324   assert(move_is_ok(m));
1325
1326   Square from = move_from(m);
1327   Square to = move_to(m);
1328
1329   // Early return if SEE cannot be negative because capturing piece value
1330   // is not bigger then captured one.
1331   if (   midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1332       && type_of_piece_on(from) != KING)
1333          return 1;
1334
1335   return see(from, to);
1336 }
1337
1338 int Position::see(Square from, Square to) const {
1339
1340   // Material values
1341   static const int seeValues[18] = {
1342     0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1343        RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1344     0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1345        RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1346     0, 0
1347   };
1348
1349   Bitboard attackers, stmAttackers, b;
1350
1351   assert(square_is_ok(from) || from == SQ_NONE);
1352   assert(square_is_ok(to));
1353
1354   // Initialize colors
1355   Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1356   Color them = opposite_color(us);
1357
1358   // Initialize pieces
1359   Piece piece = piece_on(from);
1360   Piece capture = piece_on(to);
1361   Bitboard occ = occupied_squares();
1362
1363   // King cannot be recaptured
1364   if (type_of_piece(piece) == KING)
1365       return seeValues[capture];
1366
1367   // Handle en passant moves
1368   if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1369   {
1370       assert(capture == EMPTY);
1371
1372       Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1373       capture = piece_on(capQq);
1374       assert(type_of_piece_on(capQq) == PAWN);
1375
1376       // Remove the captured pawn
1377       clear_bit(&occ, capQq);
1378   }
1379
1380   while (true)
1381   {
1382       // Find all attackers to the destination square, with the moving piece
1383       // removed, but possibly an X-ray attacker added behind it.
1384       clear_bit(&occ, from);
1385       attackers =  (rook_attacks_bb(to, occ)      & pieces(ROOK, QUEEN))
1386                  | (bishop_attacks_bb(to, occ)    & pieces(BISHOP, QUEEN))
1387                  | (attacks_from<KNIGHT>(to)      & pieces(KNIGHT))
1388                  | (attacks_from<KING>(to)        & pieces(KING))
1389                  | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1390                  | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1391
1392       if (from != SQ_NONE)
1393           break;
1394
1395       // If we don't have any attacker we are finished
1396       if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1397           return 0;
1398
1399       // Locate the least valuable attacker to the destination square
1400       // and use it to initialize from square.
1401       stmAttackers = attackers & pieces_of_color(us);
1402       PieceType pt;
1403       for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1404           assert(pt < KING);
1405
1406       from = first_1(stmAttackers & pieces(pt));
1407       piece = piece_on(from);
1408   }
1409
1410   // If the opponent has no attackers we are finished
1411   stmAttackers = attackers & pieces_of_color(them);
1412   if (!stmAttackers)
1413       return seeValues[capture];
1414
1415   attackers &= occ; // Remove the moving piece
1416
1417   // The destination square is defended, which makes things rather more
1418   // difficult to compute. We proceed by building up a "swap list" containing
1419   // the material gain or loss at each stop in a sequence of captures to the
1420   // destination square, where the sides alternately capture, and always
1421   // capture with the least valuable piece. After each capture, we look for
1422   // new X-ray attacks from behind the capturing piece.
1423   int lastCapturingPieceValue = seeValues[piece];
1424   int swapList[32], n = 1;
1425   Color c = them;
1426   PieceType pt;
1427
1428   swapList[0] = seeValues[capture];
1429
1430   do {
1431       // Locate the least valuable attacker for the side to move. The loop
1432       // below looks like it is potentially infinite, but it isn't. We know
1433       // that the side to move still has at least one attacker left.
1434       for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1435           assert(pt < KING);
1436
1437       // Remove the attacker we just found from the 'attackers' bitboard,
1438       // and scan for new X-ray attacks behind the attacker.
1439       b = stmAttackers & pieces(pt);
1440       occ ^= (b & (~b + 1));
1441       attackers |=  (rook_attacks_bb(to, occ) &  pieces(ROOK, QUEEN))
1442                   | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1443
1444       attackers &= occ;
1445
1446       // Add the new entry to the swap list
1447       assert(n < 32);
1448       swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1449       n++;
1450
1451       // Remember the value of the capturing piece, and change the side to move
1452       // before beginning the next iteration
1453       lastCapturingPieceValue = seeValues[pt];
1454       c = opposite_color(c);
1455       stmAttackers = attackers & pieces_of_color(c);
1456
1457       // Stop after a king capture
1458       if (pt == KING && stmAttackers)
1459       {
1460           assert(n < 32);
1461           swapList[n++] = QueenValueMidgame*10;
1462           break;
1463       }
1464   } while (stmAttackers);
1465
1466   // Having built the swap list, we negamax through it to find the best
1467   // achievable score from the point of view of the side to move
1468   while (--n)
1469       swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1470
1471   return swapList[0];
1472 }
1473
1474
1475 /// Position::clear() erases the position object to a pristine state, with an
1476 /// empty board, white to move, and no castling rights.
1477
1478 void Position::clear() {
1479
1480   st = &startState;
1481   memset(st, 0, sizeof(StateInfo));
1482   st->epSquare = SQ_NONE;
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] = EMPTY;
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   sideToMove = WHITE;
1497   gamePly = 0;
1498   initialKFile = FILE_E;
1499   initialKRFile = FILE_H;
1500   initialQRFile = FILE_A;
1501 }
1502
1503
1504 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1505 /// UCI interface code, whenever a non-reversible move is made in a
1506 /// 'position fen <fen> moves m1 m2 ...' command.  This makes it possible
1507 /// for the program to handle games of arbitrary length, as long as the GUI
1508 /// handles draws by the 50 move rule correctly.
1509
1510 void Position::reset_game_ply() {
1511
1512   gamePly = 0;
1513 }
1514
1515
1516 /// Position::put_piece() puts a piece on the given square of the board,
1517 /// updating the board array, bitboards, and piece counts.
1518
1519 void Position::put_piece(Piece p, Square s) {
1520
1521   Color c = color_of_piece(p);
1522   PieceType pt = type_of_piece(p);
1523
1524   board[s] = p;
1525   index[s] = pieceCount[c][pt];
1526   pieceList[c][pt][index[s]] = s;
1527
1528   set_bit(&(byTypeBB[pt]), s);
1529   set_bit(&(byColorBB[c]), s);
1530   set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1531
1532   pieceCount[c][pt]++;
1533 }
1534
1535
1536 /// Position::allow_oo() gives the given side the right to castle kingside.
1537 /// Used when setting castling rights during parsing of FEN strings.
1538
1539 void Position::allow_oo(Color c) {
1540
1541   st->castleRights |= (1 + int(c));
1542 }
1543
1544
1545 /// Position::allow_ooo() gives the given side the right to castle queenside.
1546 /// Used when setting castling rights during parsing of FEN strings.
1547
1548 void Position::allow_ooo(Color c) {
1549
1550   st->castleRights |= (4 + 4*int(c));
1551 }
1552
1553
1554 /// Position::compute_key() computes the hash key of the position. The hash
1555 /// key is usually updated incrementally as moves are made and unmade, the
1556 /// compute_key() function is only used when a new position is set up, and
1557 /// to verify the correctness of the hash key when running in debug mode.
1558
1559 Key Position::compute_key() const {
1560
1561   Key result = Key(0ULL);
1562
1563   for (Square s = SQ_A1; s <= SQ_H8; s++)
1564       if (square_is_occupied(s))
1565           result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1566
1567   if (ep_square() != SQ_NONE)
1568       result ^= zobEp[ep_square()];
1569
1570   result ^= zobCastle[st->castleRights];
1571   if (side_to_move() == BLACK)
1572       result ^= zobSideToMove;
1573
1574   return result;
1575 }
1576
1577
1578 /// Position::compute_pawn_key() computes the hash key of the position. The
1579 /// hash key is usually updated incrementally as moves are made and unmade,
1580 /// the compute_pawn_key() function is only used when a new position is set
1581 /// up, and to verify the correctness of the pawn hash key when running in
1582 /// debug mode.
1583
1584 Key Position::compute_pawn_key() const {
1585
1586   Key result = Key(0ULL);
1587   Bitboard b;
1588   Square s;
1589
1590   for (Color c = WHITE; c <= BLACK; c++)
1591   {
1592       b = pieces(PAWN, c);
1593       while (b)
1594       {
1595           s = pop_1st_bit(&b);
1596           result ^= zobrist[c][PAWN][s];
1597       }
1598   }
1599   return result;
1600 }
1601
1602
1603 /// Position::compute_material_key() computes the hash key of the position.
1604 /// The hash key is usually updated incrementally as moves are made and unmade,
1605 /// the compute_material_key() function is only used when a new position is set
1606 /// up, and to verify the correctness of the material hash key when running in
1607 /// debug mode.
1608
1609 Key Position::compute_material_key() const {
1610
1611   Key result = Key(0ULL);
1612   for (Color c = WHITE; c <= BLACK; c++)
1613       for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1614       {
1615           int count = piece_count(c, pt);
1616           for (int i = 0; i <= count; i++)
1617               result ^= zobMaterial[c][pt][i];
1618       }
1619   return result;
1620 }
1621
1622
1623 /// Position::compute_value() compute the incremental scores for the middle
1624 /// game and the endgame. These functions are used to initialize the incremental
1625 /// scores when a new position is set up, and to verify that the scores are correctly
1626 /// updated by do_move and undo_move when the program is running in debug mode.
1627 Score Position::compute_value() const {
1628
1629   Score result = make_score(0, 0);
1630   Bitboard b;
1631   Square s;
1632
1633   for (Color c = WHITE; c <= BLACK; c++)
1634       for (PieceType pt = PAWN; pt <= KING; pt++)
1635       {
1636           b = pieces(pt, c);
1637           while (b)
1638           {
1639               s = pop_1st_bit(&b);
1640               assert(piece_on(s) == piece_of_color_and_type(c, pt));
1641               result += pst(c, pt, s);
1642           }
1643       }
1644
1645   result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1646   return result;
1647 }
1648
1649
1650 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1651 /// game material score for the given side. Material scores are updated
1652 /// incrementally during the search, this function is only used while
1653 /// initializing a new Position object.
1654
1655 Value Position::compute_non_pawn_material(Color c) const {
1656
1657   Value result = Value(0);
1658
1659   for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1660   {
1661       Bitboard b = pieces(pt, c);
1662       while (b)
1663       {
1664           assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1665           pop_1st_bit(&b);
1666           result += piece_value_midgame(pt);
1667       }
1668   }
1669   return result;
1670 }
1671
1672
1673 /// Position::is_draw() tests whether the position is drawn by material,
1674 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1675 /// must be done by the search.
1676 // FIXME: Currently we are not handling 50 move rule correctly when in check
1677
1678 bool Position::is_draw() const {
1679
1680   // Draw by material?
1681   if (   !pieces(PAWN)
1682       && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1683       return true;
1684
1685   // Draw by the 50 moves rule?
1686   if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1687       return true;
1688
1689   // Draw by repetition?
1690   for (int i = 4; i <= Min(Min(gamePly, st->rule50), st->pliesFromNull); i += 2)
1691       if (history[gamePly - i] == st->key)
1692           return true;
1693
1694   return false;
1695 }
1696
1697
1698 /// Position::is_mate() returns true or false depending on whether the
1699 /// side to move is checkmated.
1700
1701 bool Position::is_mate() const {
1702
1703   MoveStack moves[256];
1704   return is_check() && (generate_moves(*this, moves, false) == moves);
1705 }
1706
1707
1708 /// Position::has_mate_threat() tests whether a given color has a mate in one
1709 /// from the current position.
1710
1711 bool Position::has_mate_threat(Color c) {
1712
1713   StateInfo st1, st2;
1714   Color stm = side_to_move();
1715
1716   if (is_check())
1717       return false;
1718
1719   // If the input color is not equal to the side to move, do a null move
1720   if (c != stm)
1721       do_null_move(st1);
1722
1723   MoveStack mlist[120];
1724   bool result = false;
1725   Bitboard pinned = pinned_pieces(sideToMove);
1726
1727   // Generate pseudo-legal non-capture and capture check moves
1728   MoveStack* last = generate_non_capture_checks(*this, mlist);
1729   last = generate_captures(*this, last);
1730
1731   // Loop through the moves, and see if one of them is mate
1732   for (MoveStack* cur = mlist; cur != last; cur++)
1733   {
1734       Move move = cur->move;
1735       if (!pl_move_is_legal(move, pinned))
1736           continue;
1737
1738       do_move(move, st2);
1739       if (is_mate())
1740           result = true;
1741
1742       undo_move(move);
1743   }
1744
1745   // Undo null move, if necessary
1746   if (c != stm)
1747       undo_null_move();
1748
1749   return result;
1750 }
1751
1752
1753 /// Position::init_zobrist() is a static member function which initializes the
1754 /// various arrays used to compute hash keys.
1755
1756 void Position::init_zobrist() {
1757
1758   for (int i = 0; i < 2; i++)
1759       for (int j = 0; j < 8; j++)
1760           for (int k = 0; k < 64; k++)
1761               zobrist[i][j][k] = Key(genrand_int64());
1762
1763   for (int i = 0; i < 64; i++)
1764       zobEp[i] = Key(genrand_int64());
1765
1766   for (int i = 0; i < 16; i++)
1767       zobCastle[i] = genrand_int64();
1768
1769   zobSideToMove = genrand_int64();
1770
1771   for (int i = 0; i < 2; i++)
1772       for (int j = 0; j < 8; j++)
1773           for (int k = 0; k < 16; k++)
1774               zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1775
1776   for (int i = 0; i < 16; i++)
1777       zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1778
1779   zobExclusion = genrand_int64();
1780 }
1781
1782
1783 /// Position::init_piece_square_tables() initializes the piece square tables.
1784 /// This is a two-step operation:  First, the white halves of the tables are
1785 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1786 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1787 /// Second, the black halves of the tables are initialized by mirroring
1788 /// and changing the sign of the corresponding white scores.
1789
1790 void Position::init_piece_square_tables() {
1791
1792   int r = get_option_value_int("Randomness"), i;
1793   for (Square s = SQ_A1; s <= SQ_H8; s++)
1794       for (Piece p = WP; p <= WK; p++)
1795       {
1796           i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1797           PieceSquareTable[p][s] = make_score(MgPST[p][s] + i, EgPST[p][s] + i);
1798       }
1799
1800   for (Square s = SQ_A1; s <= SQ_H8; s++)
1801       for (Piece p = BP; p <= BK; p++)
1802           PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1803 }
1804
1805
1806 /// Position::flipped_copy() makes a copy of the input position, but with
1807 /// the white and black sides reversed. This is only useful for debugging,
1808 /// especially for finding evaluation symmetry bugs.
1809
1810 void Position::flipped_copy(const Position& pos) {
1811
1812   assert(pos.is_ok());
1813
1814   clear();
1815
1816   // Board
1817   for (Square s = SQ_A1; s <= SQ_H8; s++)
1818       if (!pos.square_is_empty(s))
1819           put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1820
1821   // Side to move
1822   sideToMove = opposite_color(pos.side_to_move());
1823
1824   // Castling rights
1825   if (pos.can_castle_kingside(WHITE))  allow_oo(BLACK);
1826   if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1827   if (pos.can_castle_kingside(BLACK))  allow_oo(WHITE);
1828   if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1829
1830   initialKFile  = pos.initialKFile;
1831   initialKRFile = pos.initialKRFile;
1832   initialQRFile = pos.initialQRFile;
1833
1834   for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1835       castleRightsMask[sq] = ALL_CASTLES;
1836
1837   castleRightsMask[make_square(initialKFile,  RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1838   castleRightsMask[make_square(initialKFile,  RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1839   castleRightsMask[make_square(initialKRFile, RANK_1)] ^=  WHITE_OO;
1840   castleRightsMask[make_square(initialKRFile, RANK_8)] ^=  BLACK_OO;
1841   castleRightsMask[make_square(initialQRFile, RANK_1)] ^=  WHITE_OOO;
1842   castleRightsMask[make_square(initialQRFile, RANK_8)] ^=  BLACK_OOO;
1843
1844   // En passant square
1845   if (pos.st->epSquare != SQ_NONE)
1846       st->epSquare = flip_square(pos.st->epSquare);
1847
1848   // Checkers
1849   find_checkers();
1850
1851   // Hash keys
1852   st->key = compute_key();
1853   st->pawnKey = compute_pawn_key();
1854   st->materialKey = compute_material_key();
1855
1856   // Incremental scores
1857   st->value = compute_value();
1858
1859   // Material
1860   st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1861   st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1862
1863   assert(is_ok());
1864 }
1865
1866
1867 /// Position::is_ok() performs some consitency checks for the position object.
1868 /// This is meant to be helpful when debugging.
1869
1870 bool Position::is_ok(int* failedStep) const {
1871
1872   // What features of the position should be verified?
1873   static const bool debugBitboards = false;
1874   static const bool debugKingCount = false;
1875   static const bool debugKingCapture = false;
1876   static const bool debugCheckerCount = false;
1877   static const bool debugKey = false;
1878   static const bool debugMaterialKey = false;
1879   static const bool debugPawnKey = false;
1880   static const bool debugIncrementalEval = false;
1881   static const bool debugNonPawnMaterial = false;
1882   static const bool debugPieceCounts = false;
1883   static const bool debugPieceList = false;
1884   static const bool debugCastleSquares = false;
1885
1886   if (failedStep) *failedStep = 1;
1887
1888   // Side to move OK?
1889   if (!color_is_ok(side_to_move()))
1890       return false;
1891
1892   // Are the king squares in the position correct?
1893   if (failedStep) (*failedStep)++;
1894   if (piece_on(king_square(WHITE)) != WK)
1895       return false;
1896
1897   if (failedStep) (*failedStep)++;
1898   if (piece_on(king_square(BLACK)) != BK)
1899       return false;
1900
1901   // Castle files OK?
1902   if (failedStep) (*failedStep)++;
1903   if (!file_is_ok(initialKRFile))
1904       return false;
1905
1906   if (!file_is_ok(initialQRFile))
1907       return false;
1908
1909   // Do both sides have exactly one king?
1910   if (failedStep) (*failedStep)++;
1911   if (debugKingCount)
1912   {
1913       int kingCount[2] = {0, 0};
1914       for (Square s = SQ_A1; s <= SQ_H8; s++)
1915           if (type_of_piece_on(s) == KING)
1916               kingCount[color_of_piece_on(s)]++;
1917
1918       if (kingCount[0] != 1 || kingCount[1] != 1)
1919           return false;
1920   }
1921
1922   // Can the side to move capture the opponent's king?
1923   if (failedStep) (*failedStep)++;
1924   if (debugKingCapture)
1925   {
1926       Color us = side_to_move();
1927       Color them = opposite_color(us);
1928       Square ksq = king_square(them);
1929       if (attackers_to(ksq) & pieces_of_color(us))
1930           return false;
1931   }
1932
1933   // Is there more than 2 checkers?
1934   if (failedStep) (*failedStep)++;
1935   if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1936       return false;
1937
1938   // Bitboards OK?
1939   if (failedStep) (*failedStep)++;
1940   if (debugBitboards)
1941   {
1942       // The intersection of the white and black pieces must be empty
1943       if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1944           return false;
1945
1946       // The union of the white and black pieces must be equal to all
1947       // occupied squares
1948       if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1949           return false;
1950
1951       // Separate piece type bitboards must have empty intersections
1952       for (PieceType p1 = PAWN; p1 <= KING; p1++)
1953           for (PieceType p2 = PAWN; p2 <= KING; p2++)
1954               if (p1 != p2 && (pieces(p1) & pieces(p2)))
1955                   return false;
1956   }
1957
1958   // En passant square OK?
1959   if (failedStep) (*failedStep)++;
1960   if (ep_square() != SQ_NONE)
1961   {
1962       // The en passant square must be on rank 6, from the point of view of the
1963       // side to move.
1964       if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1965           return false;
1966   }
1967
1968   // Hash key OK?
1969   if (failedStep) (*failedStep)++;
1970   if (debugKey && st->key != compute_key())
1971       return false;
1972
1973   // Pawn hash key OK?
1974   if (failedStep) (*failedStep)++;
1975   if (debugPawnKey && st->pawnKey != compute_pawn_key())
1976       return false;
1977
1978   // Material hash key OK?
1979   if (failedStep) (*failedStep)++;
1980   if (debugMaterialKey && st->materialKey != compute_material_key())
1981       return false;
1982
1983   // Incremental eval OK?
1984   if (failedStep) (*failedStep)++;
1985   if (debugIncrementalEval && st->value != compute_value())
1986       return false;
1987
1988   // Non-pawn material OK?
1989   if (failedStep) (*failedStep)++;
1990   if (debugNonPawnMaterial)
1991   {
1992       if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1993           return false;
1994
1995       if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1996           return false;
1997   }
1998
1999   // Piece counts OK?
2000   if (failedStep) (*failedStep)++;
2001   if (debugPieceCounts)
2002       for (Color c = WHITE; c <= BLACK; c++)
2003           for (PieceType pt = PAWN; pt <= KING; pt++)
2004               if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
2005                   return false;
2006
2007   if (failedStep) (*failedStep)++;
2008   if (debugPieceList)
2009   {
2010       for (Color c = WHITE; c <= BLACK; c++)
2011           for (PieceType pt = PAWN; pt <= KING; pt++)
2012               for (int i = 0; i < pieceCount[c][pt]; i++)
2013               {
2014                   if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2015                       return false;
2016
2017                   if (index[piece_list(c, pt, i)] != i)
2018                       return false;
2019               }
2020   }
2021
2022   if (failedStep) (*failedStep)++;
2023   if (debugCastleSquares) {
2024       for (Color c = WHITE; c <= BLACK; c++) {
2025           if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2026               return false;
2027           if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2028               return false;
2029       }
2030       if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2031           return false;
2032       if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2033           return false;
2034       if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2035           return false;
2036       if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2037           return false;
2038   }
2039
2040   if (failedStep) *failedStep = 0;
2041   return true;
2042 }