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