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