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