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