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