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