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