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