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