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