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