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