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