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