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