]> git.sesse.net Git - stockfish/blobdiff - src/book.cpp
Fix reading a book under-promotion move
[stockfish] / src / book.cpp
index 0212317f88ce281608af946e1bad631a58c0122b..85a88fcb801e3499376d3038a8087bebbc2bdc4f 100644 (file)
@@ -30,6 +30,7 @@
 ////
 
 #include <cassert>
+#include <iostream>
 
 #include "book.h"
 #include "movegen.h"
@@ -365,18 +366,20 @@ void Book::open(const string& fName) {
   fileName = fName;
   ifstream::open(fileName.c_str(), ifstream::in | ifstream::binary);
 
-  if (is_open())
-  {
-      // Get the book size in number of entries
-      seekg(0, ios::end);
-      bookSize = long(tellg()) / EntrySize;
-      seekg(0, ios::beg);
+  // Silently return when asked to open a non-exsistent file
+  if (!is_open())
+      return;
+
+  // Get the book size in number of entries
+  seekg(0, ios::end);
+  bookSize = long(tellg()) / EntrySize;
+  seekg(0, ios::beg);
 
-      if (good())
-          return;
+  if (!good())
+  {
+      cerr << "Failed to open book file " << fileName << endl;
+      exit(EXIT_FAILURE);
   }
-  cerr << "Failed to open book file " << fileName << endl;
-  Application::exit_with_failure();
 }
 
 
@@ -432,11 +435,27 @@ Move Book::get_move(const Position& pos, bool findBestMove) {
   if (!bookMove)
       return MOVE_NONE;
 
+  // A PolyGlot book move is encoded as follows:
+  //
+  // bit  0- 5: destination square (from 0 to 63)
+  // bit  6-11: origin square (from 0 to 63)
+  // bit 12-13-14: promotion piece (from KNIGHT == 1 to QUEEN == 4)
+  //
+  // Castling moves follow "king captures rook" representation. So in case
+  // book move is a promotion we have to convert to our representation, in
+  // all other cases we can directly compare with a Move after having
+  // masked out special Move's flags that are not supported by PolyGlot.
+  int p = (bookMove >> 12) & 7;
+
+  if (p)
+      bookMove = int(make_promotion_move(move_from(Move(bookMove)),
+                 move_to(Move(bookMove)), PieceType(p + 1)));
+
   // Verify the book move is legal
   MoveStack mlist[MOVES_MAX];
-  MoveStack* last = generate_moves(pos, mlist);
+  MoveStack* last = generate<MV_LEGAL>(pos, mlist);
   for (MoveStack* cur = mlist; cur != last; cur++)
-      if ((int(cur->move) & 07777) == bookMove)
+      if ((int(cur->move) & ~(3 << 14)) == bookMove) // Mask out special flags
           return cur->move;
 
   return MOVE_NONE;
@@ -496,7 +515,7 @@ void Book::read_entry(BookEntry& entry, int idx) {
   if (!good())
   {
       cerr << "Failed to read book entry at index " << idx << endl;
-      Application::exit_with_failure();
+      exit(EXIT_FAILURE);
   }
 }
 
@@ -528,7 +547,7 @@ namespace {
   uint64_t book_key(const Position& pos) {
 
     uint64_t result = 0;
-    Bitboard b = pos.pieces_of_color(WHITE) | pos.pieces_of_color(BLACK);
+    Bitboard b = pos.occupied_squares();
 
     while (b)
     {