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