]> git.sesse.net Git - stockfish/blob - src/position.cpp
d2aeb8221209ad391e54480e6442444d91d19749
[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-2013 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 <algorithm>
21 #include <cassert>
22 #include <cstring>
23 #include <iomanip>
24 #include <sstream>
25
26 #include "bitcount.h"
27 #include "movegen.h"
28 #include "notation.h"
29 #include "position.h"
30 #include "psqtab.h"
31 #include "rkiss.h"
32 #include "thread.h"
33 #include "tt.h"
34
35 using std::string;
36
37 static const string PieceToChar(" PNBRQK  pnbrqk");
38
39 CACHE_LINE_ALIGNMENT
40
41 Score psq[COLOR_NB][PIECE_TYPE_NB][SQUARE_NB];
42 Value PieceValue[PHASE_NB][PIECE_NB] = {
43 { VALUE_ZERO, PawnValueMg, KnightValueMg, BishopValueMg, RookValueMg, QueenValueMg },
44 { VALUE_ZERO, PawnValueEg, KnightValueEg, BishopValueEg, RookValueEg, QueenValueEg } };
45
46 namespace Zobrist {
47
48   Key psq[COLOR_NB][PIECE_TYPE_NB][SQUARE_NB];
49   Key enpassant[FILE_NB];
50   Key castling[CASTLING_FLAG_NB];
51   Key side;
52   Key exclusion;
53 }
54
55 Key Position::exclusion_key() const { return st->key ^ Zobrist::exclusion;}
56
57 namespace {
58
59 // min_attacker() is a helper function used by see() to locate the least
60 // valuable attacker for the side to move, remove the attacker we just found
61 // from the bitboards and scan for new X-ray attacks behind it.
62
63 template<int Pt> FORCE_INLINE
64 PieceType min_attacker(const Bitboard* bb, const Square& to, const Bitboard& stmAttackers,
65                        Bitboard& occupied, Bitboard& attackers) {
66
67   Bitboard b = stmAttackers & bb[Pt];
68   if (!b)
69       return min_attacker<Pt+1>(bb, to, stmAttackers, occupied, attackers);
70
71   occupied ^= b & ~(b - 1);
72
73   if (Pt == PAWN || Pt == BISHOP || Pt == QUEEN)
74       attackers |= attacks_bb<BISHOP>(to, occupied) & (bb[BISHOP] | bb[QUEEN]);
75
76   if (Pt == ROOK || Pt == QUEEN)
77       attackers |= attacks_bb<ROOK>(to, occupied) & (bb[ROOK] | bb[QUEEN]);
78
79   attackers &= occupied; // After X-ray that may add already processed pieces
80   return (PieceType)Pt;
81 }
82
83 template<> FORCE_INLINE
84 PieceType min_attacker<KING>(const Bitboard*, const Square&, const Bitboard&, Bitboard&, Bitboard&) {
85   return KING; // No need to update bitboards: it is the last cycle
86 }
87
88 } // namespace
89
90
91 /// CheckInfo c'tor
92
93 CheckInfo::CheckInfo(const Position& pos) {
94
95   Color them = ~pos.side_to_move();
96   ksq = pos.king_square(them);
97
98   pinned = pos.pinned_pieces(pos.side_to_move());
99   dcCandidates = pos.discovered_check_candidates();
100
101   checkSq[PAWN]   = pos.attacks_from<PAWN>(ksq, them);
102   checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
103   checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
104   checkSq[ROOK]   = pos.attacks_from<ROOK>(ksq);
105   checkSq[QUEEN]  = checkSq[BISHOP] | checkSq[ROOK];
106   checkSq[KING]   = 0;
107 }
108
109
110 /// Position::init() initializes at startup the various arrays used to compute
111 /// hash keys and the piece square tables. The latter is a two-step operation:
112 /// Firstly, the white halves of the tables are copied from PSQT[] tables.
113 /// Secondly, the black halves of the tables are initialized by flipping and
114 /// changing the sign of the white scores.
115
116 void Position::init() {
117
118   RKISS rk;
119
120   for (Color c = WHITE; c <= BLACK; ++c)
121       for (PieceType pt = PAWN; pt <= KING; ++pt)
122           for (Square s = SQ_A1; s <= SQ_H8; ++s)
123               Zobrist::psq[c][pt][s] = rk.rand<Key>();
124
125   for (File f = FILE_A; f <= FILE_H; ++f)
126       Zobrist::enpassant[f] = rk.rand<Key>();
127
128   for (int cf = NO_CASTLING; cf <= ANY_CASTLING; ++cf)
129   {
130       Bitboard b = cf;
131       while (b)
132       {
133           Key k = Zobrist::castling[1ULL << pop_lsb(&b)];
134           Zobrist::castling[cf] ^= k ? k : rk.rand<Key>();
135       }
136   }
137
138   Zobrist::side = rk.rand<Key>();
139   Zobrist::exclusion  = rk.rand<Key>();
140
141   for (PieceType pt = PAWN; pt <= KING; ++pt)
142   {
143       PieceValue[MG][make_piece(BLACK, pt)] = PieceValue[MG][pt];
144       PieceValue[EG][make_piece(BLACK, pt)] = PieceValue[EG][pt];
145
146       Score v = make_score(PieceValue[MG][pt], PieceValue[EG][pt]);
147
148       for (Square s = SQ_A1; s <= SQ_H8; ++s)
149       {
150          psq[WHITE][pt][ s] =  (v + PSQT[pt][s]);
151          psq[BLACK][pt][~s] = -(v + PSQT[pt][s]);
152       }
153   }
154 }
155
156
157 /// Position::operator=() creates a copy of 'pos'. We want the new born Position
158 /// object to not depend on any external data so we detach state pointer from
159 /// the source one.
160
161 Position& Position::operator=(const Position& pos) {
162
163   std::memcpy(this, &pos, sizeof(Position));
164   startState = *st;
165   st = &startState;
166   nodes = 0;
167
168   assert(pos_is_ok());
169
170   return *this;
171 }
172
173
174 /// Position::set() initializes the position object with the given FEN string.
175 /// This function is not very robust - make sure that input FENs are correct,
176 /// this is assumed to be the responsibility of the GUI.
177
178 void Position::set(const string& fenStr, bool isChess960, Thread* th) {
179 /*
180    A FEN string defines a particular position using only the ASCII character set.
181
182    A FEN string contains six fields separated by a space. The fields are:
183
184    1) Piece placement (from white's perspective). Each rank is described, starting
185       with rank 8 and ending with rank 1. Within each rank, the contents of each
186       square are described from file A through file H. Following the Standard
187       Algebraic Notation (SAN), each piece is identified by a single letter taken
188       from the standard English names. White pieces are designated using upper-case
189       letters ("PNBRQK") whilst Black uses lowercase ("pnbrqk"). Blank squares are
190       noted using digits 1 through 8 (the number of blank squares), and "/"
191       separates ranks.
192
193    2) Active color. "w" means white moves next, "b" means black.
194
195    3) Castling availability. If neither side can castle, this is "-". Otherwise,
196       this has one or more letters: "K" (White can castle kingside), "Q" (White
197       can castle queenside), "k" (Black can castle kingside), and/or "q" (Black
198       can castle queenside).
199
200    4) En passant target square (in algebraic notation). If there's no en passant
201       target square, this is "-". If a pawn has just made a 2-square move, this
202       is the position "behind" the pawn. This is recorded regardless of whether
203       there is a pawn in position to make an en passant capture.
204
205    5) Halfmove clock. This is the number of halfmoves since the last pawn advance
206       or capture. This is used to determine if a draw can be claimed under the
207       fifty-move rule.
208
209    6) Fullmove number. The number of the full move. It starts at 1, and is
210       incremented after Black's move.
211 */
212
213   char col, row, token;
214   size_t idx;
215   Square sq = SQ_A8;
216   std::istringstream ss(fenStr);
217
218   clear();
219   ss >> std::noskipws;
220
221   // 1. Piece placement
222   while ((ss >> token) && !isspace(token))
223   {
224       if (isdigit(token))
225           sq += Square(token - '0'); // Advance the given number of files
226
227       else if (token == '/')
228           sq -= Square(16);
229
230       else if ((idx = PieceToChar.find(token)) != string::npos)
231       {
232           put_piece(sq, color_of(Piece(idx)), type_of(Piece(idx)));
233           ++sq;
234       }
235   }
236
237   // 2. Active color
238   ss >> token;
239   sideToMove = (token == 'w' ? WHITE : BLACK);
240   ss >> token;
241
242   // 3. Castling availability. Compatible with 3 standards: Normal FEN standard,
243   // Shredder-FEN that uses the letters of the columns on which the rooks began
244   // the game instead of KQkq and also X-FEN standard that, in case of Chess960,
245   // if an inner rook is associated with the castling right, the castling tag is
246   // replaced by the file letter of the involved rook, as for the Shredder-FEN.
247   while ((ss >> token) && !isspace(token))
248   {
249       Square rsq;
250       Color c = islower(token) ? BLACK : WHITE;
251
252       token = char(toupper(token));
253
254       if (token == 'K')
255           for (rsq = relative_square(c, SQ_H1); type_of(piece_on(rsq)) != ROOK; --rsq) {}
256
257       else if (token == 'Q')
258           for (rsq = relative_square(c, SQ_A1); type_of(piece_on(rsq)) != ROOK; ++rsq) {}
259
260       else if (token >= 'A' && token <= 'H')
261           rsq = File(token - 'A') | relative_rank(c, RANK_1);
262
263       else
264           continue;
265
266       set_castling_flag(c, rsq);
267   }
268
269   // 4. En passant square. Ignore if no pawn capture is possible
270   if (   ((ss >> col) && (col >= 'a' && col <= 'h'))
271       && ((ss >> row) && (row == '3' || row == '6')))
272   {
273       st->epSquare = File(col - 'a') | Rank(row - '1');
274
275       if (!(attackers_to(st->epSquare) & pieces(sideToMove, PAWN)))
276           st->epSquare = SQ_NONE;
277   }
278
279   // 5-6. Halfmove clock and fullmove number
280   ss >> std::skipws >> st->rule50 >> gamePly;
281
282   // Convert from fullmove starting from 1 to ply starting from 0,
283   // handle also common incorrect FEN with fullmove = 0.
284   gamePly = std::max(2 * (gamePly - 1), 0) + int(sideToMove == BLACK);
285
286   st->key = compute_key();
287   st->pawnKey = compute_pawn_key();
288   st->materialKey = compute_material_key();
289   st->psq = compute_psq_score();
290   st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
291   st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
292   st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(~sideToMove);
293   chess960 = isChess960;
294   thisThread = th;
295
296   assert(pos_is_ok());
297 }
298
299
300 /// Position::set_castling_flag() is a helper function used to set castling
301 /// flags given the corresponding color and the rook starting square.
302
303 void Position::set_castling_flag(Color c, Square rfrom) {
304
305   Square kfrom = king_square(c);
306   CastlingSide cs = kfrom < rfrom ? KING_SIDE : QUEEN_SIDE;
307   CastlingFlag cf = make_castling_flag(c, cs);
308
309   st->castlingFlags |= cf;
310   castlingFlagsMask[kfrom] |= cf;
311   castlingFlagsMask[rfrom] |= cf;
312   castlingRookSquare[c][cs] = rfrom;
313
314   Square kto = relative_square(c, cs == KING_SIDE ? SQ_G1 : SQ_C1);
315   Square rto = relative_square(c, cs == KING_SIDE ? SQ_F1 : SQ_D1);
316
317   for (Square s = std::min(rfrom, rto); s <= std::max(rfrom, rto); ++s)
318       if (s != kfrom && s != rfrom)
319           castlingPath[c][cs] |= s;
320
321   for (Square s = std::min(kfrom, kto); s <= std::max(kfrom, kto); ++s)
322       if (s != kfrom && s != rfrom)
323           castlingPath[c][cs] |= s;
324 }
325
326
327 /// Position::fen() returns a FEN representation of the position. In case of
328 /// Chess960 the Shredder-FEN notation is used. This is mainly a debugging function.
329
330 const string Position::fen() const {
331
332   int emptyCnt;
333   std::ostringstream ss;
334
335   for (Rank rank = RANK_8; rank >= RANK_1; --rank)
336   {
337       for (File file = FILE_A; file <= FILE_H; ++file)
338       {
339           for (emptyCnt = 0; file <= FILE_H && empty(file | rank); ++file)
340               ++emptyCnt;
341
342           if (emptyCnt)
343               ss << emptyCnt;
344
345           if (file <= FILE_H)
346               ss << PieceToChar[piece_on(file | rank)];
347       }
348
349       if (rank > RANK_1)
350           ss << '/';
351   }
352
353   ss << (sideToMove == WHITE ? " w " : " b ");
354
355   if (can_castle(WHITE_OO))
356       ss << (chess960 ? file_to_char(file_of(castling_rook_square(WHITE,  KING_SIDE)), false) : 'K');
357
358   if (can_castle(WHITE_OOO))
359       ss << (chess960 ? file_to_char(file_of(castling_rook_square(WHITE, QUEEN_SIDE)), false) : 'Q');
360
361   if (can_castle(BLACK_OO))
362       ss << (chess960 ? file_to_char(file_of(castling_rook_square(BLACK,  KING_SIDE)),  true) : 'k');
363
364   if (can_castle(BLACK_OOO))
365       ss << (chess960 ? file_to_char(file_of(castling_rook_square(BLACK, QUEEN_SIDE)),  true) : 'q');
366
367   if (!can_castle(WHITE) && !can_castle(BLACK))
368       ss << '-';
369
370   ss << (ep_square() == SQ_NONE ? " - " : " " + square_to_string(ep_square()) + " ")
371      << st->rule50 << " " << 1 + (gamePly - int(sideToMove == BLACK)) / 2;
372
373   return ss.str();
374 }
375
376
377 /// Position::pretty() returns an ASCII representation of the position to be
378 /// printed to the standard output together with the move's san notation.
379
380 const string Position::pretty(Move move) const {
381
382   const string dottedLine =            "\n+---+---+---+---+---+---+---+---+";
383   const string twoRows =  dottedLine + "\n|   | . |   | . |   | . |   | . |"
384                         + dottedLine + "\n| . |   | . |   | . |   | . |   |";
385
386   string brd = twoRows + twoRows + twoRows + twoRows + dottedLine;
387
388   for (Bitboard b = pieces(); b; )
389   {
390       Square s = pop_lsb(&b);
391       brd[513 - 68 * rank_of(s) + 4 * file_of(s)] = PieceToChar[piece_on(s)];
392   }
393
394   std::ostringstream ss;
395
396   if (move)
397       ss << "\nMove: " << (sideToMove == BLACK ? ".." : "")
398          << move_to_san(*const_cast<Position*>(this), move);
399
400   ss << brd << "\nFen: " << fen() << "\nKey: " << std::hex << std::uppercase
401      << std::setfill('0') << std::setw(16) << st->key << "\nCheckers: ";
402
403   for (Bitboard b = checkers(); b; )
404       ss << square_to_string(pop_lsb(&b)) << " ";
405
406   ss << "\nLegal moves: ";
407   for (MoveList<LEGAL> it(*this); *it; ++it)
408       ss << move_to_san(*const_cast<Position*>(this), *it) << " ";
409
410   return ss.str();
411 }
412
413
414 /// Position:hidden_checkers() returns a bitboard of all pinned / discovered check
415 /// pieces, according to the call parameters. Pinned pieces protect our king and
416 /// discovered check pieces attack the enemy king.
417
418 Bitboard Position::hidden_checkers(Square ksq, Color c, Color toMove) const {
419
420   Bitboard b, pinners, result = 0;
421
422   // Pinners are sliders that give check when a pinned piece is removed
423   pinners = (  (pieces(  ROOK, QUEEN) & PseudoAttacks[ROOK  ][ksq])
424              | (pieces(BISHOP, QUEEN) & PseudoAttacks[BISHOP][ksq])) & pieces(c);
425
426   while (pinners)
427   {
428       b = between_bb(ksq, pop_lsb(&pinners)) & pieces();
429
430       if (!more_than_one(b))
431           result |= b & pieces(toMove);
432   }
433   return result;
434 }
435
436
437 /// Position::attackers_to() computes a bitboard of all pieces which attack a
438 /// given square. Slider attacks use the occ bitboard to indicate occupancy.
439
440 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
441
442   return  (attacks_from<PAWN>(s, BLACK) & pieces(WHITE, PAWN))
443         | (attacks_from<PAWN>(s, WHITE) & pieces(BLACK, PAWN))
444         | (attacks_from<KNIGHT>(s)      & pieces(KNIGHT))
445         | (attacks_bb<ROOK>(s, occ)     & pieces(ROOK, QUEEN))
446         | (attacks_bb<BISHOP>(s, occ)   & pieces(BISHOP, QUEEN))
447         | (attacks_from<KING>(s)        & pieces(KING));
448 }
449
450
451 /// Position::legal() tests whether a pseudo-legal move is legal
452
453 bool Position::legal(Move m, Bitboard pinned) const {
454
455   assert(is_ok(m));
456   assert(pinned == pinned_pieces(sideToMove));
457
458   Color us = sideToMove;
459   Square from = from_sq(m);
460
461   assert(color_of(moved_piece(m)) == us);
462   assert(piece_on(king_square(us)) == make_piece(us, KING));
463
464   // En passant captures are a tricky special case. Because they are rather
465   // uncommon, we do it simply by testing whether the king is attacked after
466   // the move is made.
467   if (type_of(m) == ENPASSANT)
468   {
469       Color them = ~us;
470       Square to = to_sq(m);
471       Square capsq = to + pawn_push(them);
472       Square ksq = king_square(us);
473       Bitboard b = (pieces() ^ from ^ capsq) | to;
474
475       assert(to == ep_square());
476       assert(moved_piece(m) == make_piece(us, PAWN));
477       assert(piece_on(capsq) == make_piece(them, PAWN));
478       assert(piece_on(to) == NO_PIECE);
479
480       return   !(attacks_bb<  ROOK>(ksq, b) & pieces(them, QUEEN, ROOK))
481             && !(attacks_bb<BISHOP>(ksq, b) & pieces(them, QUEEN, BISHOP));
482   }
483
484   // If the moving piece is a king, check whether the destination
485   // square is attacked by the opponent. Castling moves are checked
486   // for legality during move generation.
487   if (type_of(piece_on(from)) == KING)
488       return type_of(m) == CASTLING || !(attackers_to(to_sq(m)) & pieces(~us));
489
490   // A non-king move is legal if and only if it is not pinned or it
491   // is moving along the ray towards or away from the king.
492   return   !pinned
493         || !(pinned & from)
494         ||  aligned(from, to_sq(m), king_square(us));
495 }
496
497
498 /// Position::pseudo_legal() takes a random move and tests whether the move is
499 /// pseudo legal. It is used to validate moves from TT that can be corrupted
500 /// due to SMP concurrent access or hash position key aliasing.
501
502 bool Position::pseudo_legal(const Move m) const {
503
504   Color us = sideToMove;
505   Square from = from_sq(m);
506   Square to = to_sq(m);
507   Piece pc = moved_piece(m);
508
509   // Use a slower but simpler function for uncommon cases
510   if (type_of(m) != NORMAL)
511       return MoveList<LEGAL>(*this).contains(m);
512
513   // Is not a promotion, so promotion piece must be empty
514   if (promotion_type(m) - 2 != NO_PIECE_TYPE)
515       return false;
516
517   // If the from square is not occupied by a piece belonging to the side to
518   // move, the move is obviously not legal.
519   if (pc == NO_PIECE || color_of(pc) != us)
520       return false;
521
522   // The destination square cannot be occupied by a friendly piece
523   if (pieces(us) & to)
524       return false;
525
526   // Handle the special case of a pawn move
527   if (type_of(pc) == PAWN)
528   {
529       // Move direction must be compatible with pawn color
530       int direction = to - from;
531       if ((us == WHITE) != (direction > 0))
532           return false;
533
534       // We have already handled promotion moves, so destination
535       // cannot be on the 8th/1st rank.
536       if (rank_of(to) == RANK_8 || rank_of(to) == RANK_1)
537           return false;
538
539       // Proceed according to the square delta between the origin and
540       // destination squares.
541       switch (direction)
542       {
543       case DELTA_NW:
544       case DELTA_NE:
545       case DELTA_SW:
546       case DELTA_SE:
547       // Capture. The destination square must be occupied by an enemy
548       // piece (en passant captures was handled earlier).
549       if (piece_on(to) == NO_PIECE || color_of(piece_on(to)) != ~us)
550           return false;
551
552       // From and to files must be one file apart, avoids a7h5
553       if (abs(file_of(from) - file_of(to)) != 1)
554           return false;
555       break;
556
557       case DELTA_N:
558       case DELTA_S:
559       // Pawn push. The destination square must be empty.
560       if (!empty(to))
561           return false;
562       break;
563
564       case DELTA_NN:
565       // Double white pawn push. The destination square must be on the fourth
566       // rank, and both the destination square and the square between the
567       // source and destination squares must be empty.
568       if (    rank_of(to) != RANK_4
569           || !empty(to)
570           || !empty(from + DELTA_N))
571           return false;
572       break;
573
574       case DELTA_SS:
575       // Double black pawn push. The destination square must be on the fifth
576       // rank, and both the destination square and the square between the
577       // source and destination squares must be empty.
578       if (    rank_of(to) != RANK_5
579           || !empty(to)
580           || !empty(from + DELTA_S))
581           return false;
582       break;
583
584       default:
585           return false;
586       }
587   }
588   else if (!(attacks_from(pc, from) & to))
589       return false;
590
591   // Evasions generator already takes care to avoid some kind of illegal moves
592   // and pl_move_is_legal() relies on this. We therefore have to take care that
593   // the same kind of moves are filtered out here.
594   if (checkers())
595   {
596       if (type_of(pc) != KING)
597       {
598           // Double check? In this case a king move is required
599           if (more_than_one(checkers()))
600               return false;
601
602           // Our move must be a blocking evasion or a capture of the checking piece
603           if (!((between_bb(lsb(checkers()), king_square(us)) | checkers()) & to))
604               return false;
605       }
606       // In case of king moves under check we have to remove king so to catch
607       // as invalid moves like b1a1 when opposite queen is on c1.
608       else if (attackers_to(to, pieces() ^ from) & pieces(~us))
609           return false;
610   }
611
612   return true;
613 }
614
615
616 /// Position::move_gives_check() tests whether a pseudo-legal move gives a check
617
618 bool Position::gives_check(Move m, const CheckInfo& ci) const {
619
620   assert(is_ok(m));
621   assert(ci.dcCandidates == discovered_check_candidates());
622   assert(color_of(moved_piece(m)) == sideToMove);
623
624   Square from = from_sq(m);
625   Square to = to_sq(m);
626   PieceType pt = type_of(piece_on(from));
627
628   // Is there a direct check ?
629   if (ci.checkSq[pt] & to)
630       return true;
631
632   // Is there a discovered check ?
633   if (   unlikely(ci.dcCandidates)
634       && (ci.dcCandidates & from)
635       && !aligned(from, to, king_square(~sideToMove)))
636       return true;
637
638   // Can we skip the ugly special cases ?
639   if (type_of(m) == NORMAL)
640       return false;
641
642   Color us = sideToMove;
643   Square ksq = king_square(~us);
644
645   switch (type_of(m))
646   {
647   case PROMOTION:
648       return attacks_bb(Piece(promotion_type(m)), to, pieces() ^ from) & ksq;
649
650   // En passant capture with check ? We have already handled the case
651   // of direct checks and ordinary discovered check, so the only case we
652   // need to handle is the unusual case of a discovered check through
653   // the captured pawn.
654   case ENPASSANT:
655   {
656       Square capsq = file_of(to) | rank_of(from);
657       Bitboard b = (pieces() ^ from ^ capsq) | to;
658
659       return  (attacks_bb<  ROOK>(ksq, b) & pieces(us, QUEEN, ROOK))
660             | (attacks_bb<BISHOP>(ksq, b) & pieces(us, QUEEN, BISHOP));
661   }
662   case CASTLING:
663   {
664       Square kfrom = from;
665       Square rfrom = to; // Castling is encoded as 'King captures the rook'
666       Square kto = relative_square(us, rfrom > kfrom ? SQ_G1 : SQ_C1);
667       Square rto = relative_square(us, rfrom > kfrom ? SQ_F1 : SQ_D1);
668
669       return   (PseudoAttacks[ROOK][rto] & ksq)
670             && (attacks_bb<ROOK>(rto, (pieces() ^ kfrom ^ rfrom) | rto | kto) & ksq);
671   }
672   default:
673       assert(false);
674       return false;
675   }
676 }
677
678
679 /// Position::do_move() makes a move, and saves all information necessary
680 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
681 /// moves should be filtered out before this function is called.
682
683 void Position::do_move(Move m, StateInfo& newSt) {
684
685   CheckInfo ci(*this);
686   do_move(m, newSt, ci, gives_check(m, ci));
687 }
688
689 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
690
691   assert(is_ok(m));
692   assert(&newSt != st);
693
694   ++nodes;
695   Key k = st->key;
696
697   // Copy some fields of old state to our new StateInfo object except the ones
698   // which are going to be recalculated from scratch anyway, then switch our state
699   // pointer to point to the new (ready to be updated) state.
700   std::memcpy(&newSt, st, StateCopySize64 * sizeof(uint64_t));
701
702   newSt.previous = st;
703   st = &newSt;
704
705   // Update side to move
706   k ^= Zobrist::side;
707
708   // Increment ply counters.In particular rule50 will be reset to zero later on
709   // in case of a capture or a pawn move.
710   ++gamePly;
711   ++st->rule50;
712   ++st->pliesFromNull;
713
714   Color us = sideToMove;
715   Color them = ~us;
716   Square from = from_sq(m);
717   Square to = to_sq(m);
718   Piece pc = piece_on(from);
719   PieceType pt = type_of(pc);
720   PieceType captured = type_of(m) == ENPASSANT ? PAWN : type_of(piece_on(to));
721
722   assert(color_of(pc) == us);
723   assert(piece_on(to) == NO_PIECE || color_of(piece_on(to)) == them || type_of(m) == CASTLING);
724   assert(captured != KING);
725
726   if (type_of(m) == CASTLING)
727   {
728       assert(pc == make_piece(us, KING));
729
730       bool kingSide = to > from;
731       Square rfrom = to; // Castling is encoded as "king captures friendly rook"
732       Square rto = relative_square(us, kingSide ? SQ_F1 : SQ_D1);
733       to = relative_square(us, kingSide ? SQ_G1 : SQ_C1);
734       captured = NO_PIECE_TYPE;
735
736       do_castling(from, to, rfrom, rto);
737
738       st->psq += psq[us][ROOK][rto] - psq[us][ROOK][rfrom];
739       k ^= Zobrist::psq[us][ROOK][rfrom] ^ Zobrist::psq[us][ROOK][rto];
740   }
741
742   if (captured)
743   {
744       Square capsq = to;
745
746       // If the captured piece is a pawn, update pawn hash key, otherwise
747       // update non-pawn material.
748       if (captured == PAWN)
749       {
750           if (type_of(m) == ENPASSANT)
751           {
752               capsq += pawn_push(them);
753
754               assert(pt == PAWN);
755               assert(to == st->epSquare);
756               assert(relative_rank(us, to) == RANK_6);
757               assert(piece_on(to) == NO_PIECE);
758               assert(piece_on(capsq) == make_piece(them, PAWN));
759
760               board[capsq] = NO_PIECE;
761           }
762
763           st->pawnKey ^= Zobrist::psq[them][PAWN][capsq];
764       }
765       else
766           st->npMaterial[them] -= PieceValue[MG][captured];
767
768       // Update board and piece lists
769       remove_piece(capsq, them, captured);
770
771       // Update material hash key and prefetch access to materialTable
772       k ^= Zobrist::psq[them][captured][capsq];
773       st->materialKey ^= Zobrist::psq[them][captured][pieceCount[them][captured]];
774       prefetch((char*)thisThread->materialTable[st->materialKey]);
775
776       // Update incremental scores
777       st->psq -= psq[them][captured][capsq];
778
779       // Reset rule 50 counter
780       st->rule50 = 0;
781   }
782
783   // Update hash key
784   k ^= Zobrist::psq[us][pt][from] ^ Zobrist::psq[us][pt][to];
785
786   // Reset en passant square
787   if (st->epSquare != SQ_NONE)
788   {
789       k ^= Zobrist::enpassant[file_of(st->epSquare)];
790       st->epSquare = SQ_NONE;
791   }
792
793   // Update castling flags if needed
794   if (st->castlingFlags && (castlingFlagsMask[from] | castlingFlagsMask[to]))
795   {
796       int cf = castlingFlagsMask[from] | castlingFlagsMask[to];
797       k ^= Zobrist::castling[st->castlingFlags & cf];
798       st->castlingFlags &= ~cf;
799   }
800
801   // Prefetch TT access as soon as we know the new hash key
802   prefetch((char*)TT.first_entry(k));
803
804   // Move the piece. The tricky Chess960 castling is handled earlier
805   if (type_of(m) != CASTLING)
806       move_piece(from, to, us, pt);
807
808   // If the moving piece is a pawn do some special extra work
809   if (pt == PAWN)
810   {
811       // Set en-passant square if the moved pawn can be captured
812       if (   (int(to) ^ int(from)) == 16
813           && (attacks_from<PAWN>(from + pawn_push(us), us) & pieces(them, PAWN)))
814       {
815           st->epSquare = Square((from + to) / 2);
816           k ^= Zobrist::enpassant[file_of(st->epSquare)];
817       }
818
819       if (type_of(m) == PROMOTION)
820       {
821           PieceType promotion = promotion_type(m);
822
823           assert(relative_rank(us, to) == RANK_8);
824           assert(promotion >= KNIGHT && promotion <= QUEEN);
825
826           remove_piece(to, us, PAWN);
827           put_piece(to, us, promotion);
828
829           // Update hash keys
830           k ^= Zobrist::psq[us][PAWN][to] ^ Zobrist::psq[us][promotion][to];
831           st->pawnKey ^= Zobrist::psq[us][PAWN][to];
832           st->materialKey ^=  Zobrist::psq[us][promotion][pieceCount[us][promotion]-1]
833                             ^ Zobrist::psq[us][PAWN][pieceCount[us][PAWN]];
834
835           // Update incremental score
836           st->psq += psq[us][promotion][to] - psq[us][PAWN][to];
837
838           // Update material
839           st->npMaterial[us] += PieceValue[MG][promotion];
840       }
841
842       // Update pawn hash key and prefetch access to pawnsTable
843       st->pawnKey ^= Zobrist::psq[us][PAWN][from] ^ Zobrist::psq[us][PAWN][to];
844       prefetch((char*)thisThread->pawnsTable[st->pawnKey]);
845
846       // Reset rule 50 draw counter
847       st->rule50 = 0;
848   }
849
850   // Update incremental scores
851   st->psq += psq[us][pt][to] - psq[us][pt][from];
852
853   // Set capture piece
854   st->capturedType = captured;
855
856   // Update the key with the final value
857   st->key = k;
858
859   // Update checkers bitboard: piece must be already moved
860   st->checkersBB = 0;
861
862   if (moveIsCheck)
863   {
864       if (type_of(m) != NORMAL)
865           st->checkersBB = attackers_to(king_square(them)) & pieces(us);
866       else
867       {
868           // Direct checks
869           if (ci.checkSq[pt] & to)
870               st->checkersBB |= to;
871
872           // Discovered checks
873           if (ci.dcCandidates && (ci.dcCandidates & from))
874           {
875               if (pt != ROOK)
876                   st->checkersBB |= attacks_from<ROOK>(king_square(them)) & pieces(us, QUEEN, ROOK);
877
878               if (pt != BISHOP)
879                   st->checkersBB |= attacks_from<BISHOP>(king_square(them)) & pieces(us, QUEEN, BISHOP);
880           }
881       }
882   }
883
884   sideToMove = ~sideToMove;
885
886   assert(pos_is_ok());
887 }
888
889
890 /// Position::undo_move() unmakes a move. When it returns, the position should
891 /// be restored to exactly the same state as before the move was made.
892
893 void Position::undo_move(Move m) {
894
895   assert(is_ok(m));
896
897   sideToMove = ~sideToMove;
898
899   Color us = sideToMove;
900   Color them = ~us;
901   Square from = from_sq(m);
902   Square to = to_sq(m);
903   PieceType pt = type_of(piece_on(to));
904   PieceType captured = st->capturedType;
905
906   assert(empty(from) || type_of(m) == CASTLING);
907   assert(captured != KING);
908
909   if (type_of(m) == PROMOTION)
910   {
911       PieceType promotion = promotion_type(m);
912
913       assert(promotion == pt);
914       assert(relative_rank(us, to) == RANK_8);
915       assert(promotion >= KNIGHT && promotion <= QUEEN);
916
917       remove_piece(to, us, promotion);
918       put_piece(to, us, PAWN);
919       pt = PAWN;
920   }
921
922   if (type_of(m) == CASTLING)
923   {
924       bool kingSide = to > from;
925       Square rfrom = to; // Castling is encoded as "king captures friendly rook"
926       Square rto = relative_square(us, kingSide ? SQ_F1 : SQ_D1);
927       to = relative_square(us, kingSide ? SQ_G1 : SQ_C1);
928       captured = NO_PIECE_TYPE;
929       pt = KING;
930       do_castling(to, from, rto, rfrom);
931   }
932   else
933       move_piece(to, from, us, pt); // Put the piece back at the source square
934
935   if (captured)
936   {
937       Square capsq = to;
938
939       if (type_of(m) == ENPASSANT)
940       {
941           capsq -= pawn_push(us);
942
943           assert(pt == PAWN);
944           assert(to == st->previous->epSquare);
945           assert(relative_rank(us, to) == RANK_6);
946           assert(piece_on(capsq) == NO_PIECE);
947       }
948
949       put_piece(capsq, them, captured); // Restore the captured piece
950   }
951
952   // Finally point our state pointer back to the previous state
953   st = st->previous;
954   --gamePly;
955
956   assert(pos_is_ok());
957 }
958
959
960 /// Position::do_castling() is a helper used to do/undo a castling move. This
961 /// is a bit tricky, especially in Chess960.
962
963 void Position::do_castling(Square kfrom, Square kto, Square rfrom, Square rto) {
964
965   // Remove both pieces first since squares could overlap in Chess960
966   remove_piece(kfrom, sideToMove, KING);
967   remove_piece(rfrom, sideToMove, ROOK);
968   board[kfrom] = board[rfrom] = NO_PIECE; // Since remove_piece doesn't do it for us
969   put_piece(kto, sideToMove, KING);
970   put_piece(rto, sideToMove, ROOK);
971 }
972
973
974 /// Position::do(undo)_null_move() is used to do(undo) a "null move": It flips
975 /// the side to move without executing any move on the board.
976
977 void Position::do_null_move(StateInfo& newSt) {
978
979   assert(!checkers());
980
981   std::memcpy(&newSt, st, sizeof(StateInfo)); // Fully copy here
982
983   newSt.previous = st;
984   st = &newSt;
985
986   if (st->epSquare != SQ_NONE)
987   {
988       st->key ^= Zobrist::enpassant[file_of(st->epSquare)];
989       st->epSquare = SQ_NONE;
990   }
991
992   st->key ^= Zobrist::side;
993   prefetch((char*)TT.first_entry(st->key));
994
995   ++st->rule50;
996   st->pliesFromNull = 0;
997
998   sideToMove = ~sideToMove;
999
1000   assert(pos_is_ok());
1001 }
1002
1003 void Position::undo_null_move() {
1004
1005   assert(!checkers());
1006
1007   st = st->previous;
1008   sideToMove = ~sideToMove;
1009 }
1010
1011
1012 /// Position::see() is a static exchange evaluator: It tries to estimate the
1013 /// material gain or loss resulting from a move. Parameter 'asymmThreshold' takes
1014 /// tempi into account. If the side who initiated the capturing sequence does the
1015 /// last capture, he loses a tempo and if the result is below 'asymmThreshold'
1016 /// the capturing sequence is considered bad.
1017
1018 int Position::see_sign(Move m) const {
1019
1020   assert(is_ok(m));
1021
1022   // Early return if SEE cannot be negative because captured piece value
1023   // is not less then capturing one. Note that king moves always return
1024   // here because king midgame value is set to 0.
1025   if (PieceValue[MG][moved_piece(m)] <= PieceValue[MG][piece_on(to_sq(m))])
1026       return 1;
1027
1028   return see(m);
1029 }
1030
1031 int Position::see(Move m, int asymmThreshold) const {
1032
1033   Square from, to;
1034   Bitboard occupied, attackers, stmAttackers;
1035   int swapList[32], slIndex = 1;
1036   PieceType captured;
1037   Color stm;
1038
1039   assert(is_ok(m));
1040
1041   from = from_sq(m);
1042   to = to_sq(m);
1043   swapList[0] = PieceValue[MG][piece_on(to)];
1044   stm = color_of(piece_on(from));
1045   occupied = pieces() ^ from;
1046
1047   // Castling moves are implemented as king capturing the rook so cannot be
1048   // handled correctly. Simply return 0 that is always the correct value
1049   // unless in the rare case the rook ends up under attack.
1050   if (type_of(m) == CASTLING)
1051       return 0;
1052
1053   if (type_of(m) == ENPASSANT)
1054   {
1055       occupied ^= to - pawn_push(stm); // Remove the captured pawn
1056       swapList[0] = PieceValue[MG][PAWN];
1057   }
1058
1059   // Find all attackers to the destination square, with the moving piece
1060   // removed, but possibly an X-ray attacker added behind it.
1061   attackers = attackers_to(to, occupied) & occupied;
1062
1063   // If the opponent has no attackers we are finished
1064   stm = ~stm;
1065   stmAttackers = attackers & pieces(stm);
1066   if (!stmAttackers)
1067       return swapList[0];
1068
1069   // The destination square is defended, which makes things rather more
1070   // difficult to compute. We proceed by building up a "swap list" containing
1071   // the material gain or loss at each stop in a sequence of captures to the
1072   // destination square, where the sides alternately capture, and always
1073   // capture with the least valuable piece. After each capture, we look for
1074   // new X-ray attacks from behind the capturing piece.
1075   captured = type_of(piece_on(from));
1076
1077   do {
1078       assert(slIndex < 32);
1079
1080       // Add the new entry to the swap list
1081       swapList[slIndex] = -swapList[slIndex - 1] + PieceValue[MG][captured];
1082       ++slIndex;
1083
1084       // Locate and remove the next least valuable attacker
1085       captured = min_attacker<PAWN>(byTypeBB, to, stmAttackers, occupied, attackers);
1086       stm = ~stm;
1087       stmAttackers = attackers & pieces(stm);
1088
1089       // Stop before processing a king capture
1090       if (captured == KING && stmAttackers)
1091       {
1092           swapList[slIndex++] = QueenValueMg * 16;
1093           break;
1094       }
1095
1096   } while (stmAttackers);
1097
1098   // If we are doing asymmetric SEE evaluation and the same side does the first
1099   // and the last capture, he loses a tempo and gain must be at least worth
1100   // 'asymmThreshold', otherwise we replace the score with a very low value,
1101   // before negamaxing.
1102   if (asymmThreshold)
1103       for (int i = 0; i < slIndex; i += 2)
1104           if (swapList[i] < asymmThreshold)
1105               swapList[i] = - QueenValueMg * 16;
1106
1107   // Having built the swap list, we negamax through it to find the best
1108   // achievable score from the point of view of the side to move.
1109   while (--slIndex)
1110       swapList[slIndex - 1] = std::min(-swapList[slIndex], swapList[slIndex - 1]);
1111
1112   return swapList[0];
1113 }
1114
1115
1116 /// Position::clear() erases the position object to a pristine state, with an
1117 /// empty board, white to move, and no castling rights.
1118
1119 void Position::clear() {
1120
1121   std::memset(this, 0, sizeof(Position));
1122   startState.epSquare = SQ_NONE;
1123   st = &startState;
1124
1125   for (int i = 0; i < PIECE_TYPE_NB; ++i)
1126       for (int j = 0; j < 16; ++j)
1127           pieceList[WHITE][i][j] = pieceList[BLACK][i][j] = SQ_NONE;
1128 }
1129
1130
1131 /// Position::compute_key() computes the hash key of the position. The hash
1132 /// key is usually updated incrementally as moves are made and unmade. The
1133 /// compute_key() function is only used when a new position is set up, and
1134 /// to verify the correctness of the hash key when running in debug mode.
1135
1136 Key Position::compute_key() const {
1137
1138   Key k = Zobrist::castling[st->castlingFlags];
1139
1140   for (Bitboard b = pieces(); b; )
1141   {
1142       Square s = pop_lsb(&b);
1143       k ^= Zobrist::psq[color_of(piece_on(s))][type_of(piece_on(s))][s];
1144   }
1145
1146   if (ep_square() != SQ_NONE)
1147       k ^= Zobrist::enpassant[file_of(ep_square())];
1148
1149   if (sideToMove == BLACK)
1150       k ^= Zobrist::side;
1151
1152   return k;
1153 }
1154
1155
1156 /// Position::compute_pawn_key() computes the hash key of the position. The
1157 /// hash key is usually updated incrementally as moves are made and unmade.
1158 /// The compute_pawn_key() function is only used when a new position is set
1159 /// up, and to verify the correctness of the pawn hash key when running in
1160 /// debug mode.
1161
1162 Key Position::compute_pawn_key() const {
1163
1164   Key k = 0;
1165
1166   for (Bitboard b = pieces(PAWN); b; )
1167   {
1168       Square s = pop_lsb(&b);
1169       k ^= Zobrist::psq[color_of(piece_on(s))][PAWN][s];
1170   }
1171
1172   return k;
1173 }
1174
1175
1176 /// Position::compute_material_key() computes the hash key of the position.
1177 /// The hash key is usually updated incrementally as moves are made and unmade.
1178 /// The compute_material_key() function is only used when a new position is set
1179 /// up, and to verify the correctness of the material hash key when running in
1180 /// debug mode.
1181
1182 Key Position::compute_material_key() const {
1183
1184   Key k = 0;
1185
1186   for (Color c = WHITE; c <= BLACK; ++c)
1187       for (PieceType pt = PAWN; pt <= QUEEN; ++pt)
1188           for (int cnt = 0; cnt < pieceCount[c][pt]; ++cnt)
1189               k ^= Zobrist::psq[c][pt][cnt];
1190
1191   return k;
1192 }
1193
1194
1195 /// Position::compute_psq_score() computes the incremental scores for the middle
1196 /// game and the endgame. These functions are used to initialize the incremental
1197 /// scores when a new position is set up, and to verify that the scores are correctly
1198 /// updated by do_move and undo_move when the program is running in debug mode.
1199
1200 Score Position::compute_psq_score() const {
1201
1202   Score score = SCORE_ZERO;
1203
1204   for (Bitboard b = pieces(); b; )
1205   {
1206       Square s = pop_lsb(&b);
1207       Piece pc = piece_on(s);
1208       score += psq[color_of(pc)][type_of(pc)][s];
1209   }
1210
1211   return score;
1212 }
1213
1214
1215 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1216 /// game material value for the given side. Material values are updated
1217 /// incrementally during the search. This function is only used when
1218 /// initializing a new Position object.
1219
1220 Value Position::compute_non_pawn_material(Color c) const {
1221
1222   Value value = VALUE_ZERO;
1223
1224   for (PieceType pt = KNIGHT; pt <= QUEEN; ++pt)
1225       value += pieceCount[c][pt] * PieceValue[MG][pt];
1226
1227   return value;
1228 }
1229
1230
1231 /// Position::is_draw() tests whether the position is drawn by material,
1232 /// repetition, or the 50 moves rule. It does not detect stalemates: this
1233 /// must be done by the search.
1234 bool Position::is_draw() const {
1235
1236   // Draw by material?
1237   if (   !pieces(PAWN)
1238       && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMg))
1239       return true;
1240
1241   // Draw by the 50 moves rule?
1242   if (st->rule50 > 99 && (!checkers() || MoveList<LEGAL>(*this).size()))
1243       return true;
1244
1245   int i = 4, e = std::min(st->rule50, st->pliesFromNull);
1246
1247   if (i <= e)
1248   {
1249       StateInfo* stp = st->previous->previous;
1250
1251       do {
1252           stp = stp->previous->previous;
1253
1254           if (stp->key == st->key)
1255               return true; // Draw after first repetition
1256
1257           i += 2;
1258
1259       } while (i <= e);
1260   }
1261
1262   return false;
1263 }
1264
1265
1266 /// Position::flip() flips position with the white and black sides reversed. This
1267 /// is only useful for debugging e.g. for finding evaluation symmetry bugs.
1268
1269 static char toggle_case(char c) {
1270   return char(islower(c) ? toupper(c) : tolower(c));
1271 }
1272
1273 void Position::flip() {
1274
1275   string f, token;
1276   std::stringstream ss(fen());
1277
1278   for (Rank rank = RANK_8; rank >= RANK_1; --rank) // Piece placement
1279   {
1280       std::getline(ss, token, rank > RANK_1 ? '/' : ' ');
1281       f.insert(0, token + (f.empty() ? " " : "/"));
1282   }
1283
1284   ss >> token; // Active color
1285   f += (token == "w" ? "B " : "W "); // Will be lowercased later
1286
1287   ss >> token; // Castling availability
1288   f += token + " ";
1289
1290   std::transform(f.begin(), f.end(), f.begin(), toggle_case);
1291
1292   ss >> token; // En passant square
1293   f += (token == "-" ? token : token.replace(1, 1, token[1] == '3' ? "6" : "3"));
1294
1295   std::getline(ss, token); // Half and full moves
1296   f += token;
1297
1298   set(f, is_chess960(), this_thread());
1299
1300   assert(pos_is_ok());
1301 }
1302
1303
1304 /// Position::pos_is_ok() performs some consistency checks for the position object.
1305 /// This is meant to be helpful when debugging.
1306
1307 bool Position::pos_is_ok(int* failedStep) const {
1308
1309   int dummy, *step = failedStep ? failedStep : &dummy;
1310
1311   // What features of the position should be verified?
1312   const bool all = false;
1313
1314   const bool debugBitboards       = all || false;
1315   const bool debugKingCount       = all || false;
1316   const bool debugKingCapture     = all || false;
1317   const bool debugCheckerCount    = all || false;
1318   const bool debugKey             = all || false;
1319   const bool debugMaterialKey     = all || false;
1320   const bool debugPawnKey         = all || false;
1321   const bool debugIncrementalEval = all || false;
1322   const bool debugNonPawnMaterial = all || false;
1323   const bool debugPieceCounts     = all || false;
1324   const bool debugPieceList       = all || false;
1325   const bool debugCastlingSquares = all || false;
1326
1327   *step = 1;
1328
1329   if (sideToMove != WHITE && sideToMove != BLACK)
1330       return false;
1331
1332   if ((*step)++, piece_on(king_square(WHITE)) != W_KING)
1333       return false;
1334
1335   if ((*step)++, piece_on(king_square(BLACK)) != B_KING)
1336       return false;
1337
1338   if ((*step)++, debugKingCount)
1339   {
1340       int kingCount[COLOR_NB] = {};
1341
1342       for (Square s = SQ_A1; s <= SQ_H8; ++s)
1343           if (type_of(piece_on(s)) == KING)
1344               ++kingCount[color_of(piece_on(s))];
1345
1346       if (kingCount[0] != 1 || kingCount[1] != 1)
1347           return false;
1348   }
1349
1350   if ((*step)++, debugKingCapture)
1351       if (attackers_to(king_square(~sideToMove)) & pieces(sideToMove))
1352           return false;
1353
1354   if ((*step)++, debugCheckerCount && popcount<Full>(st->checkersBB) > 2)
1355       return false;
1356
1357   if ((*step)++, debugBitboards)
1358   {
1359       // The intersection of the white and black pieces must be empty
1360       if (pieces(WHITE) & pieces(BLACK))
1361           return false;
1362
1363       // The union of the white and black pieces must be equal to all
1364       // occupied squares
1365       if ((pieces(WHITE) | pieces(BLACK)) != pieces())
1366           return false;
1367
1368       // Separate piece type bitboards must have empty intersections
1369       for (PieceType p1 = PAWN; p1 <= KING; ++p1)
1370           for (PieceType p2 = PAWN; p2 <= KING; ++p2)
1371               if (p1 != p2 && (pieces(p1) & pieces(p2)))
1372                   return false;
1373   }
1374
1375   if ((*step)++, ep_square() != SQ_NONE && relative_rank(sideToMove, ep_square()) != RANK_6)
1376       return false;
1377
1378   if ((*step)++, debugKey && st->key != compute_key())
1379       return false;
1380
1381   if ((*step)++, debugPawnKey && st->pawnKey != compute_pawn_key())
1382       return false;
1383
1384   if ((*step)++, debugMaterialKey && st->materialKey != compute_material_key())
1385       return false;
1386
1387   if ((*step)++, debugIncrementalEval && st->psq != compute_psq_score())
1388       return false;
1389
1390   if ((*step)++, debugNonPawnMaterial)
1391       if (   st->npMaterial[WHITE] != compute_non_pawn_material(WHITE)
1392           || st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1393           return false;
1394
1395   if ((*step)++, debugPieceCounts)
1396       for (Color c = WHITE; c <= BLACK; ++c)
1397           for (PieceType pt = PAWN; pt <= KING; ++pt)
1398               if (pieceCount[c][pt] != popcount<Full>(pieces(c, pt)))
1399                   return false;
1400
1401   if ((*step)++, debugPieceList)
1402       for (Color c = WHITE; c <= BLACK; ++c)
1403           for (PieceType pt = PAWN; pt <= KING; ++pt)
1404               for (int i = 0; i < pieceCount[c][pt];  ++i)
1405                   if (   board[pieceList[c][pt][i]] != make_piece(c, pt)
1406                       || index[pieceList[c][pt][i]] != i)
1407                       return false;
1408
1409   if ((*step)++, debugCastlingSquares)
1410       for (Color c = WHITE; c <= BLACK; ++c)
1411           for (CastlingSide s = KING_SIDE; s <= QUEEN_SIDE; s = CastlingSide(s + 1))
1412           {
1413               CastlingFlag cf = make_castling_flag(c, s);
1414
1415               if (!can_castle(cf))
1416                   continue;
1417
1418               if (  (castlingFlagsMask[king_square(c)] & cf) != cf
1419                   || piece_on(castlingRookSquare[c][s]) != make_piece(c, ROOK)
1420                   || castlingFlagsMask[castlingRookSquare[c][s]] != cf)
1421                   return false;
1422           }
1423
1424   *step = 0;
1425   return true;
1426 }