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