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