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