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