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