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