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