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