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