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