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