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