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