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