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