Subversion Repositories Games.Chess Giants

Rev

Rev 154 | Rev 176 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 154 Rev 169
Line 1... Line 1...
1
/*
1
/*
-
 
2
  Stockfish, a UCI chess playing engine derived from Glaurung 2.1
2
  Copyright (c) 2013 Ronald de Man
3
  Copyright (c) 2013 Ronald de Man
3
  This file may be redistributed and/or modified without restrictions.
4
  Copyright (C) 2016-2018 Marco Costalba, Lucas Braesch
4
 
5
 
-
 
6
  Stockfish is free software: you can redistribute it and/or modify
5
  tbprobe.cpp contains the Stockfish-specific routines of the
7
  it under the terms of the GNU General Public License as published by
6
  tablebase probing code. It should be relatively easy to adapt
8
  the Free Software Foundation, either version 3 of the License, or
7
  this code to other chess engines.
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/>.
8
*/
18
*/
9
 
-
 
10
#define NOMINMAX
-
 
11
 
19
 
12
#include <algorithm>
20
#include <algorithm>
-
 
21
#include <atomic>
-
 
22
#include <cstdint>
-
 
23
#include <cstring>   // For std::memset
-
 
24
#include <deque>
-
 
25
#include <fstream>
-
 
26
#include <iostream>
-
 
27
#include <list>
-
 
28
#include <sstream>
-
 
29
#include <type_traits>
13
 
30
 
-
 
31
#include "../bitboard.h"
-
 
32
#include "../movegen.h"
14
#include "../position.h"
33
#include "../position.h"
15
#include "../movegen.h"
-
 
16
#include "../bitboard.h"
-
 
17
#include "../search.h"
34
#include "../search.h"
-
 
35
#include "../thread_win32.h"
-
 
36
#include "../types.h"
18
 
37
 
19
#include "tbprobe.h"
38
#include "tbprobe.h"
20
#include "tbcore.h"
-
 
21
 
39
 
-
 
40
#ifndef _WIN32
22
#include "tbcore.cpp"
41
#include <fcntl.h>
-
 
42
#include <unistd.h>
-
 
43
#include <sys/mman.h>
-
 
44
#include <sys/stat.h>
-
 
45
#else
-
 
46
#define WIN32_LEAN_AND_MEAN
-
 
47
#define NOMINMAX
-
 
48
#include <windows.h>
-
 
49
#endif
23
 
50
 
24
namespace Zobrist {
51
using namespace Tablebases;
25
  extern Key psq[PIECE_NB][SQUARE_NB];
-
 
26
}
-
 
27
 
52
 
28
int Tablebases::MaxCardinality = 0;
53
int Tablebases::MaxCardinality;
29
 
54
 
30
// Given a position with 6 or fewer pieces, produce a text string
-
 
31
// of the form KQPvKRP, where "KQP" represents the white pieces if
-
 
32
// mirror == 0 and the black pieces if mirror == 1.
-
 
33
static void prt_str(Position& pos, char *str, int mirror)
-
 
34
{
-
 
35
  Color color;
-
 
36
  PieceType pt;
55
namespace {
37
  int i;
-
 
38
 
56
 
39
  color = !mirror ? WHITE : BLACK;
-
 
40
  for (pt = KING; pt >= PAWN; --pt)
-
 
41
    for (i = popcount(pos.pieces(color, pt)); i > 0; i--)
57
// Each table has a set of flags: all of them refer to DTZ tables, the last one to WDL tables
42
      *str++ = pchr[6 - pt];
-
 
43
  *str++ = 'v';
-
 
44
  color = ~color;
-
 
45
  for (pt = KING; pt >= PAWN; --pt)
-
 
46
    for (i = popcount(pos.pieces(color, pt)); i > 0; i--)
58
enum TBFlag { STM = 1, Mapped = 2, WinPlies = 4, LossPlies = 8, SingleValue = 128 };
47
      *str++ = pchr[6 - pt];
-
 
48
  *str++ = 0;
-
 
49
}
-
 
50
 
59
 
51
// Given a position, produce a 64-bit material signature key.
60
inline WDLScore operator-(WDLScore d) { return WDLScore(-int(d)); }
52
// If the engine supports such a key, it should equal the engine's key.
61
inline Square operator^=(Square& s, int i) { return s = Square(int(s) ^ i); }
53
static uint64 calc_key(Position& pos, int mirror)
62
inline Square operator^(Square s, int i) { return Square(int(s) ^ i); }
54
{
-
 
55
  Color color;
-
 
56
  PieceType pt;
-
 
57
  int i;
-
 
58
  uint64 key = 0;
-
 
59
 
63
 
60
  color = !mirror ? WHITE : BLACK;
64
// DTZ tables don't store valid scores for moves that reset the rule50 counter
61
  for (pt = PAWN; pt <= KING; ++pt)
65
// like captures and pawn moves but we can easily recover the correct dtz of the
62
    for (i = popcount(pos.pieces(color, pt)); i > 0; i--)
66
// previous move if we know the position's WDL score.
63
      key ^= Zobrist::psq[make_piece(WHITE, pt)][i - 1];
67
int dtz_before_zeroing(WDLScore wdl) {
64
  color = ~color;
68
    return wdl == WDLWin         ?  1   :
65
  for (pt = PAWN; pt <= KING; ++pt)
69
           wdl == WDLCursedWin   ?  101 :
66
    for (i = popcount(pos.pieces(color, pt)); i > 0; i--)
70
           wdl == WDLBlessedLoss ? -101 :
67
      key ^= Zobrist::psq[make_piece(BLACK, pt)][i - 1];
71
           wdl == WDLLoss        ? -1   : 0;
-
 
72
}
68
 
73
 
-
 
74
// Return the sign of a number (-1, 0, 1)
-
 
75
template <typename T> int sign_of(T val) {
69
  return key;
76
    return (T(0) < val) - (val < T(0));
70
}
77
}
71
 
78
 
72
// Produce a 64-bit material key corresponding to the material combination
79
// Numbers in little endian used by sparseIndex[] to point into blockLength[]
73
// defined by pcs[16], where pcs[1], ..., pcs[6] is the number of white
80
struct SparseEntry {
74
// pawns, ..., kings and pcs[9], ..., pcs[14] is the number of black
81
    char block[4];   // Number of block
75
// pawns, ..., kings.
-
 
76
static uint64 calc_key_from_pcs(int *pcs, int mirror)
82
    char offset[2];  // Offset within the block
77
{
83
};
78
  int color;
-
 
79
  PieceType pt;
-
 
80
  int i;
-
 
81
  uint64 key = 0;
-
 
82
 
84
 
83
  color = !mirror ? 0 : 8;
-
 
84
  for (pt = PAWN; pt <= KING; ++pt)
-
 
85
    for (i = 0; i < pcs[color + pt]; i++)
-
 
86
      key ^= Zobrist::psq[make_piece(WHITE, pt)][i];
-
 
87
  color ^= 8;
-
 
88
  for (pt = PAWN; pt <= KING; ++pt)
-
 
89
    for (i = 0; i < pcs[color + pt]; i++)
-
 
90
      key ^= Zobrist::psq[make_piece(BLACK, pt)][i];
85
static_assert(sizeof(SparseEntry) == 6, "SparseEntry must be 6 bytes");
91
 
86
 
92
  return key;
87
typedef uint16_t Sym; // Huffman symbol
93
}
-
 
94
 
88
 
-
 
89
struct LR {
-
 
90
    enum Side { Left, Right, Value };
-
 
91
 
-
 
92
    uint8_t lr[3]; // The first 12 bits is the left-hand symbol, the second 12
-
 
93
                   // bits is the right-hand symbol. If symbol has length 1,
-
 
94
                   // then the first byte is the stored value.
95
bool is_little_endian() {
95
    template<Side S>
-
 
96
    Sym get() {
-
 
97
        return S == Left  ? ((lr[1] & 0xF) << 8) | lr[0] :
-
 
98
               S == Right ?  (lr[2] << 4) | (lr[1] >> 4) :
-
 
99
               S == Value ?   lr[0] : (assert(false), Sym(-1));
96
  union {
100
    }
-
 
101
};
-
 
102
 
-
 
103
static_assert(sizeof(LR) == 3, "LR tree entry must be 3 bytes");
-
 
104
 
-
 
105
const int TBPIECES = 6;
-
 
106
 
-
 
107
struct PairsData {
97
    int i;
108
    int flags;
-
 
109
    size_t sizeofBlock;            // Block size in bytes
-
 
110
    size_t span;                   // About every span values there is a SparseIndex[] entry
-
 
111
    int blocksNum;                 // Number of blocks in the TB file
-
 
112
    int maxSymLen;                 // Maximum length in bits of the Huffman symbols
-
 
113
    int minSymLen;                 // Minimum length in bits of the Huffman symbols
-
 
114
    Sym* lowestSym;                // lowestSym[l] is the symbol of length l with the lowest value
-
 
115
    LR* btree;                     // btree[sym] stores the left and right symbols that expand sym
-
 
116
    uint16_t* blockLength;         // Number of stored positions (minus one) for each block: 1..65536
-
 
117
    int blockLengthSize;           // Size of blockLength[] table: padded so it's bigger than blocksNum
-
 
118
    SparseEntry* sparseIndex;      // Partial indices into blockLength[]
-
 
119
    size_t sparseIndexSize;        // Size of SparseIndex[] table
-
 
120
    uint8_t* data;                 // Start of Huffman compressed data
-
 
121
    std::vector<uint64_t> base64;  // base64[l - min_sym_len] is the 64bit-padded lowest symbol of length l
-
 
122
    std::vector<uint8_t> symlen;   // Number of values (-1) represented by a given Huffman symbol: 1..256
-
 
123
    Piece pieces[TBPIECES];        // Position pieces: the order of pieces defines the groups
-
 
124
    uint64_t groupIdx[TBPIECES+1]; // Start index used for the encoding of the group's pieces
-
 
125
    int groupLen[TBPIECES+1];      // Number of pieces in a given group: KRKN -> (3, 1)
-
 
126
};
-
 
127
 
-
 
128
// Helper struct to avoid manually defining entry copy constructor as we
-
 
129
// should because the default one is not compatible with std::atomic_bool.
-
 
130
struct Atomic {
-
 
131
    Atomic() = default;
-
 
132
    Atomic(const Atomic& e) { ready = e.ready.load(); } // MSVC 2013 wants assignment within body
-
 
133
    std::atomic_bool ready;
-
 
134
};
-
 
135
 
-
 
136
// We define types for the different parts of the WDLEntry and DTZEntry with
-
 
137
// corresponding specializations for pieces or pawns.
-
 
138
 
-
 
139
struct WDLEntryPiece {
-
 
140
    PairsData* precomp;
-
 
141
};
-
 
142
 
-
 
143
struct WDLEntryPawn {
-
 
144
    uint8_t pawnCount[2];     // [Lead color / other color]
-
 
145
    WDLEntryPiece file[2][4]; // [wtm / btm][FILE_A..FILE_D]
-
 
146
};
-
 
147
 
-
 
148
struct DTZEntryPiece {
-
 
149
    PairsData* precomp;
-
 
150
    uint16_t map_idx[4]; // WDLWin, WDLLoss, WDLCursedWin, WDLBlessedLoss
-
 
151
    uint8_t* map;
-
 
152
};
-
 
153
 
-
 
154
struct DTZEntryPawn {
-
 
155
    uint8_t pawnCount[2];
98
    char c[sizeof(int)];
156
    DTZEntryPiece file[4];
-
 
157
    uint8_t* map;
-
 
158
};
-
 
159
 
-
 
160
struct TBEntry : public Atomic {
-
 
161
    void* baseAddress;
-
 
162
    uint64_t mapping;
-
 
163
    Key key;
-
 
164
    Key key2;
-
 
165
    int pieceCount;
-
 
166
    bool hasPawns;
-
 
167
    bool hasUniquePieces;
-
 
168
};
-
 
169
 
-
 
170
// Now the main types: WDLEntry and DTZEntry
-
 
171
struct WDLEntry : public TBEntry {
-
 
172
    WDLEntry(const std::string& code);
-
 
173
   ~WDLEntry();
-
 
174
    union {
-
 
175
        WDLEntryPiece pieceTable[2]; // [wtm / btm]
-
 
176
        WDLEntryPawn  pawnTable;
99
  } x;
177
    };
-
 
178
};
-
 
179
 
-
 
180
struct DTZEntry : public TBEntry {
-
 
181
    DTZEntry(const WDLEntry& wdl);
-
 
182
   ~DTZEntry();
-
 
183
    union {
-
 
184
        DTZEntryPiece pieceTable;
-
 
185
        DTZEntryPawn  pawnTable;
100
  x.i = 1;
186
    };
-
 
187
};
-
 
188
 
-
 
189
typedef decltype(WDLEntry::pieceTable) WDLPieceTable;
-
 
190
typedef decltype(DTZEntry::pieceTable) DTZPieceTable;
-
 
191
typedef decltype(WDLEntry::pawnTable ) WDLPawnTable;
-
 
192
typedef decltype(DTZEntry::pawnTable ) DTZPawnTable;
-
 
193
 
-
 
194
auto item(WDLPieceTable& e, int stm, int  ) -> decltype(e[stm])& { return e[stm]; }
-
 
195
auto item(DTZPieceTable& e, int    , int  ) -> decltype(e)& { return e; }
-
 
196
auto item(WDLPawnTable&  e, int stm, int f) -> decltype(e.file[stm][f])& { return e.file[stm][f]; }
-
 
197
auto item(DTZPawnTable&  e, int    , int f) -> decltype(e.file[f])& { return e.file[f]; }
-
 
198
 
-
 
199
template<typename E> struct Ret { typedef int type; };
-
 
200
template<> struct Ret<WDLEntry> { typedef WDLScore type; };
-
 
201
 
-
 
202
int MapPawns[SQUARE_NB];
-
 
203
int MapB1H1H7[SQUARE_NB];
-
 
204
int MapA1D1D4[SQUARE_NB];
-
 
205
int MapKK[10][SQUARE_NB]; // [MapA1D1D4][SQUARE_NB]
-
 
206
 
-
 
207
// Comparison function to sort leading pawns in ascending MapPawns[] order
-
 
208
bool pawns_comp(Square i, Square j) { return MapPawns[i] < MapPawns[j]; }
-
 
209
int off_A1H8(Square sq) { return int(rank_of(sq)) - file_of(sq); }
-
 
210
 
-
 
211
const Value WDL_to_value[] = {
-
 
212
   -VALUE_MATE + MAX_PLY + 1,
-
 
213
    VALUE_DRAW - 2,
-
 
214
    VALUE_DRAW,
101
  return x.c[0] == 1;
215
    VALUE_DRAW + 2,
-
 
216
    VALUE_MATE - MAX_PLY - 1
102
}
217
};
-
 
218
 
-
 
219
const std::string PieceToChar = " PNBRQK  pnbrqk";
-
 
220
 
-
 
221
int Binomial[6][SQUARE_NB];    // [k][n] k elements from a set of n elements
-
 
222
int LeadPawnIdx[5][SQUARE_NB]; // [leadPawnsCnt][SQUARE_NB]
-
 
223
int LeadPawnsSize[5][4];       // [leadPawnsCnt][FILE_A..FILE_D]
-
 
224
 
-
 
225
enum { BigEndian, LittleEndian };
103
 
226
 
104
static ubyte decompress_pairs(struct PairsData *d, uint64 idx)
227
template<typename T, int Half = sizeof(T) / 2, int End = sizeof(T) - 1>
-
 
228
inline void swap_byte(T& x)
105
{
229
{
106
  static const bool isLittleEndian = is_little_endian();
230
    char tmp, *c = (char*)&x;
107
  return isLittleEndian ? decompress_pairs<true >(d, idx)
231
    for (int i = 0; i < Half; ++i)
108
                        : decompress_pairs<false>(d, idx);
232
        tmp = c[i], c[i] = c[End - i], c[End - i] = tmp;
109
}
233
}
-
 
234
template<> inline void swap_byte<uint8_t, 0, 0>(uint8_t&) {}
110
 
235
 
111
// probe_wdl_table and probe_dtz_table require similar adaptations.
236
template<typename T, int LE> T number(void* addr)
112
static int probe_wdl_table(Position& pos, int *success)
-
 
113
{
237
{
114
  struct TBEntry *ptr;
238
    const union { uint32_t i; char c[4]; } Le = { 0x01020304 };
115
  struct TBHashEntry *ptr2;
239
    const bool IsLittleEndian = (Le.c[0] == 4);
116
  uint64 idx;
-
 
117
  uint64 key;
-
 
118
  int i;
-
 
119
  ubyte res;
-
 
120
  int p[TBPIECES];
-
 
121
 
240
 
122
  // Obtain the position's material signature key.
-
 
123
  key = pos.material_key();
241
    T v;
124
 
242
 
-
 
243
    if ((uintptr_t)addr & (alignof(T) - 1)) // Unaligned pointer (very rare)
-
 
244
        std::memcpy(&v, addr, sizeof(T));
-
 
245
    else
-
 
246
        v = *((T*)addr);
-
 
247
 
-
 
248
    if (LE != IsLittleEndian)
-
 
249
        swap_byte(v);
125
  // Test for KvK.
250
    return v;
-
 
251
}
-
 
252
 
-
 
253
class HashTable {
-
 
254
 
-
 
255
    typedef std::pair<WDLEntry*, DTZEntry*> EntryPair;
-
 
256
    typedef std::pair<Key, EntryPair> Entry;
-
 
257
 
-
 
258
    static const int TBHASHBITS = 10;
-
 
259
    static const int HSHMAX     = 5;
-
 
260
 
-
 
261
    Entry hashTable[1 << TBHASHBITS][HSHMAX];
-
 
262
 
-
 
263
    std::deque<WDLEntry> wdlTable;
-
 
264
    std::deque<DTZEntry> dtzTable;
-
 
265
 
-
 
266
    void insert(Key key, WDLEntry* wdl, DTZEntry* dtz) {
-
 
267
        Entry* entry = hashTable[key >> (64 - TBHASHBITS)];
-
 
268
 
-
 
269
        for (int i = 0; i < HSHMAX; ++i, ++entry)
-
 
270
            if (!entry->second.first || entry->first == key) {
126
  if (key == (Zobrist::psq[W_KING][0] ^ Zobrist::psq[B_KING][0]))
271
                *entry = std::make_pair(key, std::make_pair(wdl, dtz));
-
 
272
                return;
127
    return 0;
273
            }
-
 
274
 
-
 
275
        std::cerr << "HSHMAX too low!" << std::endl;
-
 
276
        exit(1);
-
 
277
    }
-
 
278
 
-
 
279
public:
-
 
280
    template<typename E, int I = std::is_same<E, WDLEntry>::value ? 0 : 1>
-
 
281
    E* get(Key key) {
-
 
282
      Entry* entry = hashTable[key >> (64 - TBHASHBITS)];
-
 
283
 
-
 
284
      for (int i = 0; i < HSHMAX; ++i, ++entry)
-
 
285
          if (entry->first == key)
-
 
286
              return std::get<I>(entry->second);
128
 
287
 
129
  ptr2 = TB_hash[key >> (64 - TBHASHBITS)];
-
 
130
  for (i = 0; i < HSHMAX; i++)
-
 
131
    if (ptr2[i].key == key) break;
-
 
132
  if (i == HSHMAX) {
-
 
133
    *success = 0;
-
 
134
    return 0;
288
      return nullptr;
135
  }
289
  }
136
 
290
 
137
  ptr = ptr2[i].ptr;
291
  void clear() {
138
  if (!ptr->ready) {
292
      std::memset(hashTable, 0, sizeof(hashTable));
139
    LOCK(TB_mutex);
293
      wdlTable.clear();
140
    if (!ptr->ready) {
294
      dtzTable.clear();
141
      char str[16];
295
  }
142
      prt_str(pos, str, ptr->key != key);
296
  size_t size() const { return wdlTable.size(); }
143
      if (!init_table_wdl(ptr, str)) {
297
  void insert(const std::vector<PieceType>& pieces);
-
 
298
};
-
 
299
 
144
        ptr2[i].key = 0ULL;
300
HashTable EntryTable;
-
 
301
 
145
        *success = 0;
302
class TBFile : public std::ifstream {
-
 
303
 
146
        UNLOCK(TB_mutex);
304
    std::string fname;
-
 
305
 
147
        return 0;
306
public:
-
 
307
    // Look for and open the file among the Paths directories where the .rtbw
-
 
308
    // and .rtbz files can be found. Multiple directories are separated by ";"
-
 
309
    // on Windows and by ":" on Unix-based operating systems.
148
      }
310
    //
-
 
311
    // Example:
149
      // Memory barrier to ensure ptr->ready = 1 is not reordered.
312
    // C:\tb\wdl345;C:\tb\wdl6;D:\tb\dtz345;D:\tb\dtz6
-
 
313
    static std::string Paths;
-
 
314
 
-
 
315
    TBFile(const std::string& f) {
-
 
316
 
150
#ifdef _MSC_VER
317
#ifndef _WIN32
151
      _ReadWriteBarrier();
318
        const char SepChar = ':';
152
#else
319
#else
153
      __asm__ __volatile__ ("" ::: "memory");
320
        const char SepChar = ';';
154
#endif
321
#endif
-
 
322
        std::stringstream ss(Paths);
155
      ptr->ready = 1;
323
        std::string path;
-
 
324
 
-
 
325
        while (std::getline(ss, path, SepChar)) {
-
 
326
            fname = path + "/" + f;
-
 
327
            std::ifstream::open(fname);
-
 
328
            if (is_open())
-
 
329
                return;
-
 
330
        }
156
    }
331
    }
157
    UNLOCK(TB_mutex);
-
 
158
  }
-
 
159
 
332
 
-
 
333
    // Memory map the file and check it. File should be already open and will be
160
  int bside, mirror, cmirror;
334
    // closed after mapping.
-
 
335
    uint8_t* map(void** baseAddress, uint64_t* mapping, const uint8_t* TB_MAGIC) {
-
 
336
 
161
  if (!ptr->symmetric) {
337
        assert(is_open());
-
 
338
 
-
 
339
        close(); // Need to re-open to get native file descriptor
-
 
340
 
-
 
341
#ifndef _WIN32
162
    if (key != ptr->key) {
342
        struct stat statbuf;
-
 
343
        int fd = ::open(fname.c_str(), O_RDONLY);
-
 
344
 
163
      cmirror = 8;
345
        if (fd == -1)
-
 
346
            return *baseAddress = nullptr, nullptr;
-
 
347
 
-
 
348
        fstat(fd, &statbuf);
-
 
349
        *mapping = statbuf.st_size;
-
 
350
        *baseAddress = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
164
      mirror = 0x38;
351
        ::close(fd);
-
 
352
 
165
      bside = (pos.side_to_move() == WHITE);
353
        if (*baseAddress == MAP_FAILED) {
-
 
354
            std::cerr << "Could not mmap() " << fname << std::endl;
-
 
355
            exit(1);
166
    } else {
356
        }
-
 
357
#else
-
 
358
        HANDLE fd = CreateFile(fname.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
-
 
359
                               OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
-
 
360
 
-
 
361
        if (fd == INVALID_HANDLE_VALUE)
-
 
362
            return *baseAddress = nullptr, nullptr;
-
 
363
 
167
      cmirror = mirror = 0;
364
        DWORD size_high;
-
 
365
        DWORD size_low = GetFileSize(fd, &size_high);
-
 
366
        HANDLE mmap = CreateFileMapping(fd, nullptr, PAGE_READONLY, size_high, size_low, nullptr);
-
 
367
        CloseHandle(fd);
-
 
368
 
-
 
369
        if (!mmap) {
-
 
370
            std::cerr << "CreateFileMapping() failed" << std::endl;
-
 
371
            exit(1);
-
 
372
        }
-
 
373
 
-
 
374
        *mapping = (uint64_t)mmap;
-
 
375
        *baseAddress = MapViewOfFile(mmap, FILE_MAP_READ, 0, 0, 0);
-
 
376
 
-
 
377
        if (!*baseAddress) {
-
 
378
            std::cerr << "MapViewOfFile() failed, name = " << fname
-
 
379
                      << ", error = " << GetLastError() << std::endl;
-
 
380
            exit(1);
-
 
381
        }
-
 
382
#endif
-
 
383
        uint8_t* data = (uint8_t*)*baseAddress;
-
 
384
 
-
 
385
        if (   *data++ != *TB_MAGIC++
-
 
386
            || *data++ != *TB_MAGIC++
-
 
387
            || *data++ != *TB_MAGIC++
-
 
388
            || *data++ != *TB_MAGIC) {
-
 
389
            std::cerr << "Corrupted table in file " << fname << std::endl;
168
      bside = !(pos.side_to_move() == WHITE);
390
            unmap(*baseAddress, *mapping);
-
 
391
            return *baseAddress = nullptr, nullptr;
-
 
392
        }
-
 
393
 
-
 
394
        return data;
169
    }
395
    }
170
  } else {
-
 
171
    cmirror = pos.side_to_move() == WHITE ? 0 : 8;
-
 
172
    mirror = pos.side_to_move() == WHITE ? 0 : 0x38;
-
 
173
    bside = 0;
-
 
174
  }
-
 
175
 
396
 
176
  // p[i] is to contain the square 0-63 (A1-H8) for a piece of type
-
 
177
  // pc[i] ^ cmirror, where 1 = white pawn, ..., 14 = black king.
397
    static void unmap(void* baseAddress, uint64_t mapping) {
178
  // Pieces of the same type are guaranteed to be consecutive.
-
 
-
 
398
 
179
  if (!ptr->has_pawns) {
399
#ifndef _WIN32
180
    struct TBEntry_piece *entry = (struct TBEntry_piece *)ptr;
-
 
181
    ubyte *pc = entry->pieces[bside];
400
        munmap(baseAddress, mapping);
182
    for (i = 0; i < entry->num;) {
-
 
183
      Bitboard bb = pos.pieces((Color)((pc[i] ^ cmirror) >> 3),
-
 
184
                                      (PieceType)(pc[i] & 0x07));
-
 
185
      do {
401
#else
186
        p[i++] = pop_lsb(&bb);
402
        UnmapViewOfFile(baseAddress);
187
      } while (bb);
403
        CloseHandle((HANDLE)mapping);
-
 
404
#endif
188
    }
405
    }
189
    idx = encode_piece(entry, entry->norm[bside], p, entry->factor[bside]);
-
 
190
    res = decompress_pairs(entry->precomp[bside], idx);
-
 
191
  } else {
406
};
-
 
407
 
192
    struct TBEntry_pawn *entry = (struct TBEntry_pawn *)ptr;
408
std::string TBFile::Paths;
-
 
409
 
193
    int k = entry->file[0].pieces[0][0] ^ cmirror;
410
WDLEntry::WDLEntry(const std::string& code) {
194
    Bitboard bb = pos.pieces((Color)(k >> 3), (PieceType)(k & 0x07));
-
 
-
 
411
 
195
    i = 0;
412
    StateInfo st;
196
    do {
413
    Position pos;
-
 
414
 
197
      p[i++] = pop_lsb(&bb) ^ mirror;
415
    memset(this, 0, sizeof(WDLEntry));
-
 
416
 
198
    } while (bb);
417
    ready = false;
-
 
418
    key = pos.set(code, WHITE, &st).material_key();
199
    int f = pawn_file(entry, p);
419
    pieceCount = popcount(pos.pieces());
200
    ubyte *pc = entry->file[f].pieces[bside];
420
    hasPawns = pos.pieces(PAWN);
-
 
421
 
201
    for (; i < entry->num;) {
422
    for (Color c = WHITE; c <= BLACK; ++c)
-
 
423
        for (PieceType pt = PAWN; pt < KING; ++pt)
202
      bb = pos.pieces((Color)((pc[i] ^ cmirror) >> 3),
424
            if (popcount(pos.pieces(c, pt)) == 1)
203
                                    (PieceType)(pc[i] & 0x07));
425
                hasUniquePieces = true;
-
 
426
 
204
      do {
427
    if (hasPawns) {
-
 
428
        // Set the leading color. In case both sides have pawns the leading color
-
 
429
        // is the side with less pawns because this leads to better compression.
205
        p[i++] = pop_lsb(&bb) ^ mirror;
430
        bool c =   !pos.count<PAWN>(BLACK)
206
      } while (bb);
431
                || (   pos.count<PAWN>(WHITE)
-
 
432
                    && pos.count<PAWN>(BLACK) >= pos.count<PAWN>(WHITE));
-
 
433
 
-
 
434
        pawnTable.pawnCount[0] = pos.count<PAWN>(c ? WHITE : BLACK);
-
 
435
        pawnTable.pawnCount[1] = pos.count<PAWN>(c ? BLACK : WHITE);
207
    }
436
    }
208
    idx = encode_pawn(entry, entry->file[f].norm[bside], p, entry->file[f].factor[bside]);
-
 
209
    res = decompress_pairs(entry->file[f].precomp[bside], idx);
-
 
210
  }
-
 
211
 
437
 
212
  return ((int)res) - 2;
438
    key2 = pos.set(code, BLACK, &st).material_key();
213
}
439
}
214
 
440
 
215
static int probe_dtz_table(Position& pos, int wdl, int *success)
-
 
216
{
-
 
217
  struct TBEntry *ptr;
441
WDLEntry::~WDLEntry() {
218
  uint64 idx;
-
 
219
  int i, res;
-
 
220
  int p[TBPIECES];
-
 
221
 
442
 
222
  // Obtain the position's material signature key.
443
    if (baseAddress)
223
  uint64 key = pos.material_key();
444
        TBFile::unmap(baseAddress, mapping);
224
 
445
 
225
  if (DTZ_table[0].key1 != key && DTZ_table[0].key2 != key) {
-
 
226
    for (i = 1; i < DTZ_ENTRIES; i++)
446
    for (int i = 0; i < 2; ++i)
227
      if (DTZ_table[i].key1 == key) break;
-
 
228
    if (i < DTZ_ENTRIES) {
-
 
229
      struct DTZTableEntry table_entry = DTZ_table[i];
-
 
230
      for (; i > 0; i--)
447
        if (hasPawns)
231
        DTZ_table[i] = DTZ_table[i - 1];
448
            for (File f = FILE_A; f <= FILE_D; ++f)
232
      DTZ_table[0] = table_entry;
449
                delete pawnTable.file[i][f].precomp;
233
    } else {
450
        else
234
      struct TBHashEntry *ptr2 = TB_hash[key >> (64 - TBHASHBITS)];
451
            delete pieceTable[i].precomp;
-
 
452
}
-
 
453
 
235
      for (i = 0; i < HSHMAX; i++)
454
DTZEntry::DTZEntry(const WDLEntry& wdl) {
-
 
455
 
236
        if (ptr2[i].key == key) break;
456
    memset(this, 0, sizeof(DTZEntry));
-
 
457
 
237
      if (i == HSHMAX) {
458
    ready = false;
238
        *success = 0;
459
    key = wdl.key;
239
        return 0;
460
    key2 = wdl.key2;
240
      }
-
 
241
      ptr = ptr2[i].ptr;
461
    pieceCount = wdl.pieceCount;
242
      char str[16];
462
    hasPawns = wdl.hasPawns;
243
      int mirror = (ptr->key != key);
463
    hasUniquePieces = wdl.hasUniquePieces;
-
 
464
 
244
      prt_str(pos, str, mirror);
465
    if (hasPawns) {
245
      if (DTZ_table[DTZ_ENTRIES - 1].entry)
-
 
246
        free_dtz_entry(DTZ_table[DTZ_ENTRIES-1].entry);
466
        pawnTable.pawnCount[0] = wdl.pawnTable.pawnCount[0];
247
      for (i = DTZ_ENTRIES - 1; i > 0; i--)
-
 
248
        DTZ_table[i] = DTZ_table[i - 1];
467
        pawnTable.pawnCount[1] = wdl.pawnTable.pawnCount[1];
249
      load_dtz_table(str, calc_key(pos, mirror), calc_key(pos, !mirror));
-
 
250
    }
468
    }
251
  }
469
}
252
 
470
 
253
  ptr = DTZ_table[0].entry;
471
DTZEntry::~DTZEntry() {
254
  if (!ptr) {
-
 
255
    *success = 0;
-
 
256
    return 0;
-
 
257
  }
-
 
258
 
472
 
-
 
473
    if (baseAddress)
-
 
474
        TBFile::unmap(baseAddress, mapping);
-
 
475
 
-
 
476
    if (hasPawns)
-
 
477
        for (File f = FILE_A; f <= FILE_D; ++f)
-
 
478
            delete pawnTable.file[f].precomp;
-
 
479
    else
259
  int bside, mirror, cmirror;
480
        delete pieceTable.precomp;
-
 
481
}
-
 
482
 
-
 
483
void HashTable::insert(const std::vector<PieceType>& pieces) {
-
 
484
 
260
  if (!ptr->symmetric) {
485
    std::string code;
-
 
486
 
261
    if (key != ptr->key) {
487
    for (PieceType pt : pieces)
-
 
488
        code += PieceToChar[pt];
-
 
489
 
-
 
490
    TBFile file(code.insert(code.find('K', 1), "v") + ".rtbw"); // KRK -> KRvK
-
 
491
 
-
 
492
    if (!file.is_open()) // Only WDL file is checked
262
      cmirror = 8;
493
        return;
-
 
494
 
-
 
495
    file.close();
-
 
496
 
-
 
497
    MaxCardinality = std::max((int)pieces.size(), MaxCardinality);
-
 
498
 
-
 
499
    wdlTable.emplace_back(code);
-
 
500
    dtzTable.emplace_back(wdlTable.back());
-
 
501
 
-
 
502
    insert(wdlTable.back().key , &wdlTable.back(), &dtzTable.back());
-
 
503
    insert(wdlTable.back().key2, &wdlTable.back(), &dtzTable.back());
-
 
504
}
-
 
505
 
-
 
506
// TB tables are compressed with canonical Huffman code. The compressed data is divided into
-
 
507
// blocks of size d->sizeofBlock, and each block stores a variable number of symbols.
-
 
508
// Each symbol represents either a WDL or a (remapped) DTZ value, or a pair of other symbols
-
 
509
// (recursively). If you keep expanding the symbols in a block, you end up with up to 65536
-
 
510
// WDL or DTZ values. Each symbol represents up to 256 values and will correspond after
-
 
511
// Huffman coding to at least 1 bit. So a block of 32 bytes corresponds to at most
-
 
512
// 32 x 8 x 256 = 65536 values. This maximum is only reached for tables that consist mostly
-
 
513
// of draws or mostly of wins, but such tables are actually quite common. In principle, the
-
 
514
// blocks in WDL tables are 64 bytes long (and will be aligned on cache lines). But for
-
 
515
// mostly-draw or mostly-win tables this can leave many 64-byte blocks only half-filled, so
-
 
516
// in such cases blocks are 32 bytes long. The blocks of DTZ tables are up to 1024 bytes long.
-
 
517
// The generator picks the size that leads to the smallest table. The "book" of symbols and
-
 
518
// Huffman codes is the same for all blocks in the table. A non-symmetric pawnless TB file
-
 
519
// will have one table for wtm and one for btm, a TB file with pawns will have tables per
-
 
520
// file a,b,c,d also in this case one set for wtm and one for btm.
-
 
521
int decompress_pairs(PairsData* d, uint64_t idx) {
-
 
522
 
-
 
523
    // Special case where all table positions store the same value
-
 
524
    if (d->flags & TBFlag::SingleValue)
-
 
525
        return d->minSymLen;
-
 
526
 
-
 
527
    // First we need to locate the right block that stores the value at index "idx".
-
 
528
    // Because each block n stores blockLength[n] + 1 values, the index i of the block
-
 
529
    // that contains the value at position idx is:
-
 
530
    //
-
 
531
    //                    for (i = -1, sum = 0; sum <= idx; i++)
-
 
532
    //                        sum += blockLength[i + 1] + 1;
-
 
533
    //
-
 
534
    // This can be slow, so we use SparseIndex[] populated with a set of SparseEntry that
-
 
535
    // point to known indices into blockLength[]. Namely SparseIndex[k] is a SparseEntry
-
 
536
    // that stores the blockLength[] index and the offset within that block of the value
-
 
537
    // with index I(k), where:
-
 
538
    //
-
 
539
    //       I(k) = k * d->span + d->span / 2      (1)
-
 
540
 
-
 
541
    // First step is to get the 'k' of the I(k) nearest to our idx, using definition (1)
-
 
542
    uint32_t k = (uint32_t) (idx / d->span); // Pierre-Marie Baty -- added type cast
-
 
543
 
-
 
544
    // Then we read the corresponding SparseIndex[] entry
-
 
545
    uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block);
-
 
546
    int offset     = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset);
-
 
547
 
-
 
548
    // Now compute the difference idx - I(k). From definition of k we know that
-
 
549
    //
-
 
550
    //       idx = k * d->span + idx % d->span    (2)
-
 
551
    //
-
 
552
    // So from (1) and (2) we can compute idx - I(K):
-
 
553
    int diff = idx % d->span - d->span / 2;
-
 
554
 
-
 
555
    // Sum the above to offset to find the offset corresponding to our idx
263
      mirror = 0x38;
556
    offset += diff;
-
 
557
 
-
 
558
    // Move to previous/next block, until we reach the correct block that contains idx,
-
 
559
    // that is when 0 <= offset <= d->blockLength[block]
-
 
560
    while (offset < 0)
-
 
561
        offset += d->blockLength[--block] + 1;
-
 
562
 
-
 
563
    while (offset > d->blockLength[block])
264
      bside = (pos.side_to_move() == WHITE);
564
        offset -= d->blockLength[block++] + 1;
-
 
565
 
-
 
566
    // Finally, we find the start address of our block of canonical Huffman symbols
-
 
567
    uint32_t* ptr = (uint32_t*)(d->data + block * d->sizeofBlock);
-
 
568
 
-
 
569
    // Read the first 64 bits in our block, this is a (truncated) sequence of
-
 
570
    // unknown number of symbols of unknown length but we know the first one
-
 
571
    // is at the beginning of this 64 bits sequence.
-
 
572
    uint64_t buf64 = number<uint64_t, BigEndian>(ptr); ptr += 2;
-
 
573
    int buf64Size = 64;
265
    } else {
574
    Sym sym;
-
 
575
 
-
 
576
    while (true) {
-
 
577
        int len = 0; // This is the symbol length - d->min_sym_len
-
 
578
 
-
 
579
        // Now get the symbol length. For any symbol s64 of length l right-padded
-
 
580
        // to 64 bits we know that d->base64[l-1] >= s64 >= d->base64[l] so we
-
 
581
        // can find the symbol length iterating through base64[].
-
 
582
        while (buf64 < d->base64[len])
-
 
583
            ++len;
-
 
584
 
-
 
585
        // All the symbols of a given length are consecutive integers (numerical
-
 
586
        // sequence property), so we can compute the offset of our symbol of
-
 
587
        // length len, stored at the beginning of buf64.
-
 
588
        sym = (Sym) ((buf64 - d->base64[len]) >> (64 - len - d->minSymLen)); // Pierre-Marie Baty -- added type cast
-
 
589
 
-
 
590
        // Now add the value of the lowest symbol of length len to get our symbol
-
 
591
        sym += number<Sym, LittleEndian>(&d->lowestSym[len]);
-
 
592
 
-
 
593
        // If our offset is within the number of values represented by symbol sym
266
      cmirror = mirror = 0;
594
        // we are done...
267
      bside = !(pos.side_to_move() == WHITE);
595
        if (offset < d->symlen[sym] + 1)
-
 
596
            break;
-
 
597
 
-
 
598
        // ...otherwise update the offset and continue to iterate
-
 
599
        offset -= d->symlen[sym] + 1;
-
 
600
        len += d->minSymLen; // Get the real length
-
 
601
        buf64 <<= len;       // Consume the just processed symbol
-
 
602
        buf64Size -= len;
-
 
603
 
-
 
604
        if (buf64Size <= 32) { // Refill the buffer
-
 
605
            buf64Size += 32;
-
 
606
            buf64 |= (uint64_t)number<uint32_t, BigEndian>(ptr++) << (64 - buf64Size);
-
 
607
        }
268
    }
608
    }
269
  } else {
-
 
270
    cmirror = pos.side_to_move() == WHITE ? 0 : 8;
-
 
271
    mirror = pos.side_to_move() == WHITE ? 0 : 0x38;
-
 
272
    bside = 0;
-
 
273
  }
-
 
274
 
609
 
-
 
610
    // Ok, now we have our symbol that expands into d->symlen[sym] + 1 symbols.
-
 
611
    // We binary-search for our value recursively expanding into the left and
-
 
612
    // right child symbols until we reach a leaf node where symlen[sym] + 1 == 1
-
 
613
    // that will store the value we need.
275
  if (!ptr->has_pawns) {
614
    while (d->symlen[sym]) {
-
 
615
 
276
    struct DTZEntry_piece *entry = (struct DTZEntry_piece *)ptr;
616
        Sym left = d->btree[sym].get<LR::Left>();
-
 
617
 
277
    if ((entry->flags & 1) != bside && !entry->symmetric) {
618
        // If a symbol contains 36 sub-symbols (d->symlen[sym] + 1 = 36) and
-
 
619
        // expands in a pair (d->symlen[left] = 23, d->symlen[right] = 11), then
-
 
620
        // we know that, for instance the ten-th value (offset = 10) will be on
-
 
621
        // the left side because in Recursive Pairing child symbols are adjacent.
-
 
622
        if (offset < d->symlen[left] + 1)
278
      *success = -1;
623
            sym = left;
279
      return 0;
624
        else {
-
 
625
            offset -= d->symlen[left] + 1;
-
 
626
            sym = d->btree[sym].get<LR::Right>();
-
 
627
        }
280
    }
628
    }
281
    ubyte *pc = entry->pieces;
-
 
282
    for (i = 0; i < entry->num;) {
-
 
283
      Bitboard bb = pos.pieces((Color)((pc[i] ^ cmirror) >> 3),
-
 
284
                                    (PieceType)(pc[i] & 0x07));
-
 
285
      do {
-
 
286
        p[i++] = pop_lsb(&bb);
-
 
287
      } while (bb);
-
 
288
    }
-
 
289
    idx = encode_piece((struct TBEntry_piece *)entry, entry->norm, p, entry->factor);
-
 
290
    res = decompress_pairs(entry->precomp, idx);
-
 
291
 
629
 
292
    if (entry->flags & 2)
-
 
293
      res = entry->map[entry->map_idx[wdl_to_map[wdl + 2]] + res];
630
    return d->btree[sym].get<LR::Value>();
-
 
631
}
294
 
632
 
-
 
633
bool check_dtz_stm(WDLEntry*, int, File) { return true; }
-
 
634
 
-
 
635
bool check_dtz_stm(DTZEntry* entry, int stm, File f) {
-
 
636
 
-
 
637
    int flags = entry->hasPawns ? entry->pawnTable.file[f].precomp->flags
-
 
638
                                : entry->pieceTable.precomp->flags;
-
 
639
 
-
 
640
    return   (flags & TBFlag::STM) == stm
-
 
641
          || ((entry->key == entry->key2) && !entry->hasPawns);
-
 
642
}
-
 
643
 
-
 
644
// DTZ scores are sorted by frequency of occurrence and then assigned the
-
 
645
// values 0, 1, 2, ... in order of decreasing frequency. This is done for each
-
 
646
// of the four WDLScore values. The mapping information necessary to reconstruct
-
 
647
// the original values is stored in the TB file and read during map[] init.
-
 
648
WDLScore map_score(WDLEntry*, File, int value, WDLScore) { return WDLScore(value - 2); }
-
 
649
 
-
 
650
int map_score(DTZEntry* entry, File f, int value, WDLScore wdl) {
-
 
651
 
-
 
652
    const int WDLMap[] = { 1, 3, 0, 2, 0 };
-
 
653
 
-
 
654
    int flags = entry->hasPawns ? entry->pawnTable.file[f].precomp->flags
-
 
655
                                : entry->pieceTable.precomp->flags;
-
 
656
 
-
 
657
    uint8_t* map = entry->hasPawns ? entry->pawnTable.map
-
 
658
                                   : entry->pieceTable.map;
-
 
659
 
-
 
660
    uint16_t* idx = entry->hasPawns ? entry->pawnTable.file[f].map_idx
-
 
661
                                    : entry->pieceTable.map_idx;
-
 
662
    if (flags & TBFlag::Mapped)
295
    if (!(entry->flags & pa_flags[wdl + 2]) || (wdl & 1))
663
        value = map[idx[WDLMap[wdl + 2]] + value];
-
 
664
 
-
 
665
    // DTZ tables store distance to zero in number of moves or plies. We
-
 
666
    // want to return plies, so we have convert to plies when needed.
-
 
667
    if (   (wdl == WDLWin  && !(flags & TBFlag::WinPlies))
-
 
668
        || (wdl == WDLLoss && !(flags & TBFlag::LossPlies))
-
 
669
        ||  wdl == WDLCursedWin
-
 
670
        ||  wdl == WDLBlessedLoss)
296
      res *= 2;
671
        value *= 2;
-
 
672
 
-
 
673
    return value + 1;
-
 
674
}
-
 
675
 
-
 
676
// Compute a unique index out of a position and use it to probe the TB file. To
-
 
677
// encode k pieces of same type and color, first sort the pieces by square in
-
 
678
// ascending order s1 <= s2 <= ... <= sk then compute the unique index as:
-
 
679
//
-
 
680
//      idx = Binomial[1][s1] + Binomial[2][s2] + ... + Binomial[k][sk]
-
 
681
//
-
 
682
template<typename Entry, typename T = typename Ret<Entry>::type>
-
 
683
T do_probe_table(const Position& pos, Entry* entry, WDLScore wdl, ProbeState* result) {
-
 
684
 
-
 
685
    const bool IsWDL = std::is_same<Entry, WDLEntry>::value;
-
 
686
 
-
 
687
    Square squares[TBPIECES];
-
 
688
    Piece pieces[TBPIECES];
-
 
689
    uint64_t idx;
-
 
690
    int next = 0, size = 0, leadPawnsCnt = 0;
297
  } else {
691
    PairsData* d;
-
 
692
    Bitboard b, leadPawns = 0;
-
 
693
    File tbFile = FILE_A;
-
 
694
 
-
 
695
    // A given TB entry like KRK has associated two material keys: KRvk and Kvkr.
-
 
696
    // If both sides have the same pieces keys are equal. In this case TB tables
-
 
697
    // only store the 'white to move' case, so if the position to lookup has black
-
 
698
    // to move, we need to switch the color and flip the squares before to lookup.
-
 
699
    bool symmetricBlackToMove = (entry->key == entry->key2 && pos.side_to_move());
-
 
700
 
-
 
701
    // TB files are calculated for white as stronger side. For instance we have
-
 
702
    // KRvK, not KvKR. A position where stronger side is white will have its
-
 
703
    // material key == entry->key, otherwise we have to switch the color and
-
 
704
    // flip the squares before to lookup.
298
    struct DTZEntry_pawn *entry = (struct DTZEntry_pawn *)ptr;
705
    bool blackStronger = (pos.material_key() != entry->key);
-
 
706
 
-
 
707
    int flipColor   = (symmetricBlackToMove || blackStronger) * 8;
-
 
708
    int flipSquares = (symmetricBlackToMove || blackStronger) * 070;
-
 
709
    int stm         = (symmetricBlackToMove || blackStronger) ^ pos.side_to_move();
-
 
710
 
-
 
711
    // For pawns, TB files store 4 separate tables according if leading pawn is on
-
 
712
    // file a, b, c or d after reordering. The leading pawn is the one with maximum
-
 
713
    // MapPawns[] value, that is the one most toward the edges and with lowest rank.
-
 
714
    if (entry->hasPawns) {
-
 
715
 
-
 
716
        // In all the 4 tables, pawns are at the beginning of the piece sequence and
-
 
717
        // their color is the reference one. So we just pick the first one.
299
    int k = entry->file[0].pieces[0] ^ cmirror;
718
        Piece pc = Piece(item(entry->pawnTable, 0, 0).precomp->pieces[0] ^ flipColor);
-
 
719
 
-
 
720
        assert(type_of(pc) == PAWN);
-
 
721
 
300
    Bitboard bb = pos.pieces((Color)(k >> 3), (PieceType)(k & 0x07));
722
        leadPawns = b = pos.pieces(color_of(pc), PAWN);
301
    i = 0;
723
        do
-
 
724
            squares[size++] = pop_lsb(&b) ^ flipSquares;
-
 
725
        while (b);
-
 
726
 
-
 
727
        leadPawnsCnt = size;
-
 
728
 
-
 
729
        std::swap(squares[0], *std::max_element(squares, squares + leadPawnsCnt, pawns_comp));
-
 
730
 
-
 
731
        tbFile = file_of(squares[0]);
-
 
732
        if (tbFile > FILE_D)
-
 
733
            tbFile = file_of(squares[0] ^ 7); // Horizontal flip: SQ_H1 -> SQ_A1
-
 
734
 
-
 
735
        d = item(entry->pawnTable , stm, tbFile).precomp;
-
 
736
    } else
-
 
737
        d = item(entry->pieceTable, stm, tbFile).precomp;
-
 
738
 
-
 
739
    // DTZ tables are one-sided, i.e. they store positions only for white to
-
 
740
    // move or only for black to move, so check for side to move to be stm,
-
 
741
    // early exit otherwise.
-
 
742
    if (!IsWDL && !check_dtz_stm(entry, stm, tbFile))
-
 
743
        return *result = CHANGE_STM, T();
-
 
744
 
-
 
745
    // Now we are ready to get all the position pieces (but the lead pawns) and
-
 
746
    // directly map them to the correct color and square.
-
 
747
    b = pos.pieces() ^ leadPawns;
302
    do {
748
    do {
303
      p[i++] = pop_lsb(&bb) ^ mirror;
749
        Square s = pop_lsb(&b);
-
 
750
        squares[size] = s ^ flipSquares;
-
 
751
        pieces[size++] = Piece(pos.piece_on(s) ^ flipColor);
304
    } while (bb);
752
    } while (b);
-
 
753
 
-
 
754
    assert(size >= 2);
-
 
755
 
-
 
756
    // Then we reorder the pieces to have the same sequence as the one stored
-
 
757
    // in precomp->pieces[i]: the sequence that ensures the best compression.
305
    int f = pawn_file((struct TBEntry_pawn *)entry, p);
758
    for (int i = leadPawnsCnt; i < size; ++i)
-
 
759
        for (int j = i; j < size; ++j)
306
    if ((entry->flags[f] & 1) != bside) {
760
            if (d->pieces[i] == pieces[j])
-
 
761
            {
-
 
762
                std::swap(pieces[i], pieces[j]);
-
 
763
                std::swap(squares[i], squares[j]);
307
      *success = -1;
764
                break;
308
      return 0;
765
            }
-
 
766
 
-
 
767
    // Now we map again the squares so that the square of the lead piece is in
-
 
768
    // the triangle A1-D1-D4.
-
 
769
    if (file_of(squares[0]) > FILE_D)
-
 
770
        for (int i = 0; i < size; ++i)
-
 
771
            squares[i] ^= 7; // Horizontal flip: SQ_H1 -> SQ_A1
-
 
772
 
-
 
773
    // Encode leading pawns starting with the one with minimum MapPawns[] and
-
 
774
    // proceeding in ascending order.
-
 
775
    if (entry->hasPawns) {
-
 
776
        idx = LeadPawnIdx[leadPawnsCnt][squares[0]];
-
 
777
 
-
 
778
        std::sort(squares + 1, squares + leadPawnsCnt, pawns_comp);
-
 
779
 
-
 
780
        for (int i = 1; i < leadPawnsCnt; ++i)
-
 
781
            idx += Binomial[i][MapPawns[squares[i]]];
-
 
782
 
-
 
783
        goto encode_remaining; // With pawns we have finished special treatments
309
    }
784
    }
-
 
785
 
-
 
786
    // In positions withouth pawns, we further flip the squares to ensure leading
310
    ubyte *pc = entry->file[f].pieces;
787
    // piece is below RANK_5.
-
 
788
    if (rank_of(squares[0]) > RANK_4)
311
    for (; i < entry->num;) {
789
        for (int i = 0; i < size; ++i)
312
      bb = pos.pieces((Color)((pc[i] ^ cmirror) >> 3),
790
            squares[i] ^= 070; // Vertical flip: SQ_A8 -> SQ_A1
-
 
791
 
-
 
792
    // Look for the first piece of the leading group not on the A1-D4 diagonal
-
 
793
    // and ensure it is mapped below the diagonal.
313
                            (PieceType)(pc[i] & 0x07));
794
    for (int i = 0; i < d->groupLen[0]; ++i) {
-
 
795
        if (!off_A1H8(squares[i]))
314
      do {
796
            continue;
-
 
797
 
-
 
798
        if (off_A1H8(squares[i]) > 0) // A1-H8 diagonal flip: SQ_A3 -> SQ_C3
315
        p[i++] = pop_lsb(&bb) ^ mirror;
799
            for (int j = i; j < size; ++j)
-
 
800
                squares[j] = Square(((squares[j] >> 3) | (squares[j] << 3)) & 63);
316
      } while (bb);
801
        break;
317
    }
802
    }
318
    idx = encode_pawn((struct TBEntry_pawn *)entry, entry->file[f].norm, p, entry->file[f].factor);
-
 
319
    res = decompress_pairs(entry->file[f].precomp, idx);
-
 
320
 
803
 
-
 
804
    // Encode the leading group.
-
 
805
    //
-
 
806
    // Suppose we have KRvK. Let's say the pieces are on square numbers wK, wR
-
 
807
    // and bK (each 0...63). The simplest way to map this position to an index
-
 
808
    // is like this:
-
 
809
    //
-
 
810
    //   index = wK * 64 * 64 + wR * 64 + bK;
-
 
811
    //
-
 
812
    // But this way the TB is going to have 64*64*64 = 262144 positions, with
-
 
813
    // lots of positions being equivalent (because they are mirrors of each
-
 
814
    // other) and lots of positions being invalid (two pieces on one square,
321
    if (entry->flags[f] & 2)
815
    // adjacent kings, etc.).
-
 
816
    // Usually the first step is to take the wK and bK together. There are just
-
 
817
    // 462 ways legal and not-mirrored ways to place the wK and bK on the board.
-
 
818
    // Once we have placed the wK and bK, there are 62 squares left for the wR
-
 
819
    // Mapping its square from 0..63 to available squares 0..61 can be done like:
-
 
820
    //
-
 
821
    //   wR -= (wR > wK) + (wR > bK);
-
 
822
    //
322
      res = entry->map[entry->map_idx[f][wdl_to_map[wdl + 2]] + res];
823
    // In words: if wR "comes later" than wK, we deduct 1, and the same if wR
-
 
824
    // "comes later" than bK. In case of two same pieces like KRRvK we want to
-
 
825
    // place the two Rs "together". If we have 62 squares left, we can place two
-
 
826
    // Rs "together" in 62 * 61 / 2 ways (we divide by 2 because rooks can be
-
 
827
    // swapped and still get the same position.)
-
 
828
    //
-
 
829
    // In case we have at least 3 unique pieces (inlcuded kings) we encode them
-
 
830
    // together.
-
 
831
    if (entry->hasUniquePieces) {
323
 
832
 
324
    if (!(entry->flags[f] & pa_flags[wdl + 2]) || (wdl & 1))
833
        int adjust1 =  squares[1] > squares[0];
325
      res *= 2;
834
        int adjust2 = (squares[2] > squares[0]) + (squares[2] > squares[1]);
326
  }
-
 
327
 
835
 
-
 
836
        // First piece is below a1-h8 diagonal. MapA1D1D4[] maps the b1-d1-d3
-
 
837
        // triangle to 0...5. There are 63 squares for second piece and and 62
-
 
838
        // (mapped to 0...61) for the third.
-
 
839
        if (off_A1H8(squares[0]))
-
 
840
            idx = (   MapA1D1D4[squares[0]]  * 63
-
 
841
                   + (squares[1] - adjust1)) * 62
-
 
842
                   +  squares[2] - adjust2;
-
 
843
 
-
 
844
        // First piece is on a1-h8 diagonal, second below: map this occurence to
-
 
845
        // 6 to differentiate from the above case, rank_of() maps a1-d4 diagonal
-
 
846
        // to 0...3 and finally MapB1H1H7[] maps the b1-h1-h7 triangle to 0..27.
-
 
847
        else if (off_A1H8(squares[1]))
-
 
848
            idx = (  6 * 63 + rank_of(squares[0]) * 28
-
 
849
                   + MapB1H1H7[squares[1]])       * 62
-
 
850
                   + squares[2] - adjust2;
-
 
851
 
-
 
852
        // First two pieces are on a1-h8 diagonal, third below
-
 
853
        else if (off_A1H8(squares[2]))
-
 
854
            idx =  6 * 63 * 62 + 4 * 28 * 62
-
 
855
                 +  rank_of(squares[0])        * 7 * 28
-
 
856
                 + (rank_of(squares[1]) - adjust1) * 28
-
 
857
                 +  MapB1H1H7[squares[2]];
-
 
858
 
-
 
859
        // All 3 pieces on the diagonal a1-h8
328
  return res;
860
        else
-
 
861
            idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28
-
 
862
                 +  rank_of(squares[0])         * 7 * 6
-
 
863
                 + (rank_of(squares[1]) - adjust1)  * 6
-
 
864
                 + (rank_of(squares[2]) - adjust2);
-
 
865
    } else
-
 
866
        // We don't have at least 3 unique pieces, like in KRRvKBB, just map
-
 
867
        // the kings.
-
 
868
        idx = MapKK[MapA1D1D4[squares[0]]][squares[1]];
-
 
869
 
-
 
870
encode_remaining:
-
 
871
    idx *= d->groupIdx[0];
-
 
872
    Square* groupSq = squares + d->groupLen[0];
-
 
873
 
-
 
874
    // Encode remainig pawns then pieces according to square, in ascending order
-
 
875
    bool remainingPawns = entry->hasPawns && entry->pawnTable.pawnCount[1];
-
 
876
 
-
 
877
    while (d->groupLen[++next])
-
 
878
    {
-
 
879
        std::sort(groupSq, groupSq + d->groupLen[next]);
-
 
880
        uint64_t n = 0;
-
 
881
 
-
 
882
        // Map down a square if "comes later" than a square in the previous
-
 
883
        // groups (similar to what done earlier for leading group pieces).
-
 
884
        for (int i = 0; i < d->groupLen[next]; ++i)
-
 
885
        {
-
 
886
            auto f = [&](Square s) { return groupSq[i] > s; };
-
 
887
            auto adjust = std::count_if(squares, groupSq, f);
-
 
888
            n += Binomial[i + 1][groupSq[i] - adjust - 8 * remainingPawns];
-
 
889
        }
-
 
890
 
-
 
891
        remainingPawns = false;
-
 
892
        idx += n * d->groupIdx[next];
-
 
893
        groupSq += d->groupLen[next];
-
 
894
    }
-
 
895
 
-
 
896
    // Now that we have the index, decompress the pair and get the score
-
 
897
    return map_score(entry, tbFile, decompress_pairs(d, idx), wdl);
329
}
898
}
330
 
899
 
331
// Add underpromotion captures to list of captures.
900
// Group together pieces that will be encoded together. The general rule is that
-
 
901
// a group contains pieces of same type and color. The exception is the leading
332
static ExtMove *add_underprom_caps(Position& pos, ExtMove *stack, ExtMove *end)
902
// group that, in case of positions withouth pawns, can be formed by 3 different
-
 
903
// pieces (default) or by the king pair when there is not a unique piece apart
-
 
904
// from the kings. When there are pawns, pawns are always first in pieces[].
-
 
905
//
-
 
906
// As example KRKN -> KRK + N, KNNK -> KK + NN, KPPKP -> P + PP + K + K
333
{
907
//
-
 
908
// The actual grouping depends on the TB generator and can be inferred from the
334
  ExtMove *moves, *extra = end;
909
// sequence of pieces in piece[] array.
-
 
910
template<typename T>
-
 
911
void set_groups(T& e, PairsData* d, int order[], File f) {
335
 
912
 
-
 
913
    int n = 0, firstLen = e.hasPawns ? 0 : e.hasUniquePieces ? 3 : 2;
-
 
914
    d->groupLen[n] = 1;
-
 
915
 
-
 
916
    // Number of pieces per group is stored in groupLen[], for instance in KRKN
-
 
917
    // the encoder will default on '111', so groupLen[] will be (3, 1).
336
  for (moves = stack; moves < end; moves++) {
918
    for (int i = 1; i < e.pieceCount; ++i)
-
 
919
        if (--firstLen > 0 || d->pieces[i] == d->pieces[i - 1])
-
 
920
            d->groupLen[n]++;
-
 
921
        else
-
 
922
            d->groupLen[++n] = 1;
-
 
923
 
-
 
924
    d->groupLen[++n] = 0; // Zero-terminated
-
 
925
 
-
 
926
    // The sequence in pieces[] defines the groups, but not the order in which
-
 
927
    // they are encoded. If the pieces in a group g can be combined on the board
-
 
928
    // in N(g) different ways, then the position encoding will be of the form:
-
 
929
    //
-
 
930
    //           g1 * N(g2) * N(g3) + g2 * N(g3) + g3
-
 
931
    //
-
 
932
    // This ensures unique encoding for the whole position. The order of the
-
 
933
    // groups is a per-table parameter and could not follow the canonical leading
-
 
934
    // pawns/pieces -> remainig pawns -> remaining pieces. In particular the
-
 
935
    // first group is at order[0] position and the remaining pawns, when present,
-
 
936
    // are at order[1] position.
-
 
937
    bool pp = e.hasPawns && e.pawnTable.pawnCount[1]; // Pawns on both sides
337
    Move move = moves->move;
938
    int next = pp ? 2 : 1;
-
 
939
    int freeSquares = 64 - d->groupLen[0] - (pp ? d->groupLen[1] : 0);
-
 
940
    uint64_t idx = 1;
-
 
941
 
-
 
942
    for (int k = 0; next < n || k == order[0] || k == order[1]; ++k)
-
 
943
        if (k == order[0]) // Leading pawns or pieces
-
 
944
        {
-
 
945
            d->groupIdx[0] = idx;
-
 
946
            idx *=         e.hasPawns ? LeadPawnsSize[d->groupLen[0]][f]
-
 
947
                  : e.hasUniquePieces ? 31332 : 462;
-
 
948
        }
-
 
949
        else if (k == order[1]) // Remaining pawns
-
 
950
        {
-
 
951
            d->groupIdx[1] = idx;
-
 
952
            idx *= Binomial[d->groupLen[1]][48 - d->groupLen[0]];
-
 
953
        }
-
 
954
        else // Remainig pieces
-
 
955
        {
-
 
956
            d->groupIdx[next] = idx;
-
 
957
            idx *= Binomial[d->groupLen[next]][freeSquares];
-
 
958
            freeSquares -= d->groupLen[next++];
-
 
959
        }
-
 
960
 
-
 
961
    d->groupIdx[n] = idx;
-
 
962
}
-
 
963
 
-
 
964
// In Recursive Pairing each symbol represents a pair of childern symbols. So
-
 
965
// read d->btree[] symbols data and expand each one in his left and right child
-
 
966
// symbol until reaching the leafs that represent the symbol value.
-
 
967
uint8_t set_symlen(PairsData* d, Sym s, std::vector<bool>& visited) {
-
 
968
 
338
    if (type_of(move) == PROMOTION && !pos.empty(to_sq(move))) {
969
    visited[s] = true; // We can set it now because tree is acyclic
-
 
970
    Sym sr = d->btree[s].get<LR::Right>();
-
 
971
 
-
 
972
    if (sr == 0xFFF)
-
 
973
        return 0;
-
 
974
 
-
 
975
    Sym sl = d->btree[s].get<LR::Left>();
-
 
976
 
-
 
977
    if (!visited[sl])
339
      (*extra++).move = (Move)(move - (1 << 12));
978
        d->symlen[sl] = set_symlen(d, sl, visited);
-
 
979
 
-
 
980
    if (!visited[sr])
340
      (*extra++).move = (Move)(move - (2 << 12));
981
        d->symlen[sr] = set_symlen(d, sr, visited);
-
 
982
 
-
 
983
    return d->symlen[sl] + d->symlen[sr] + 1;
-
 
984
}
-
 
985
 
-
 
986
uint8_t* set_sizes(PairsData* d, uint8_t* data) {
-
 
987
 
-
 
988
    d->flags = *data++;
-
 
989
 
-
 
990
    if (d->flags & TBFlag::SingleValue) {
341
      (*extra++).move = (Move)(move - (3 << 12));
991
        d->blocksNum = d->blockLengthSize = 0;
-
 
992
        d->span = d->sparseIndexSize = 0; // Broken MSVC zero-init
-
 
993
        d->minSymLen = *data++; // Here we store the single value
-
 
994
        return data;
342
    }
995
    }
343
  }
-
 
344
 
996
 
-
 
997
    // groupLen[] is a zero-terminated list of group lengths, the last groupIdx[]
-
 
998
    // element stores the biggest index that is the tb size.
-
 
999
    uint64_t tbSize = d->groupIdx[std::find(d->groupLen, d->groupLen + 7, 0) - d->groupLen];
-
 
1000
 
-
 
1001
    d->sizeofBlock = 1ULL << *data++;
-
 
1002
    d->span = 1ULL << *data++;
-
 
1003
    d->sparseIndexSize = (size_t) ((tbSize + d->span - 1) / d->span); // Round up // Pierre-Marie Baty -- added type cast
-
 
1004
    int padding = number<uint8_t, LittleEndian>(data++);
-
 
1005
    d->blocksNum = number<uint32_t, LittleEndian>(data); data += sizeof(uint32_t);
-
 
1006
    d->blockLengthSize = d->blocksNum + padding; // Padded to ensure SparseIndex[]
-
 
1007
                                                 // does not point out of range.
-
 
1008
    d->maxSymLen = *data++;
-
 
1009
    d->minSymLen = *data++;
-
 
1010
    d->lowestSym = (Sym*)data;
-
 
1011
    d->base64.resize(d->maxSymLen - d->minSymLen + 1);
-
 
1012
 
-
 
1013
    // The canonical code is ordered such that longer symbols (in terms of
-
 
1014
    // the number of bits of their Huffman code) have lower numeric value,
-
 
1015
    // so that d->lowestSym[i] >= d->lowestSym[i+1] (when read as LittleEndian).
-
 
1016
    // Starting from this we compute a base64[] table indexed by symbol length
-
 
1017
    // and containing 64 bit values so that d->base64[i] >= d->base64[i+1].
-
 
1018
    // See http://www.eecs.harvard.edu/~michaelm/E210/huffman.pdf
-
 
1019
    for (int i = d->base64.size() - 2; i >= 0; --i) {
-
 
1020
        d->base64[i] = (d->base64[i + 1] + number<Sym, LittleEndian>(&d->lowestSym[i])
-
 
1021
                                         - number<Sym, LittleEndian>(&d->lowestSym[i + 1])) / 2;
-
 
1022
 
-
 
1023
        assert(d->base64[i] * 2 >= d->base64[i+1]);
-
 
1024
    }
-
 
1025
 
-
 
1026
    // Now left-shift by an amount so that d->base64[i] gets shifted 1 bit more
-
 
1027
    // than d->base64[i+1] and given the above assert condition, we ensure that
-
 
1028
    // d->base64[i] >= d->base64[i+1]. Moreover for any symbol s64 of length i
-
 
1029
    // and right-padded to 64 bits holds d->base64[i-1] >= s64 >= d->base64[i].
-
 
1030
    for (size_t i = 0; i < d->base64.size(); ++i)
-
 
1031
        d->base64[i] <<= 64 - i - d->minSymLen; // Right-padding to 64 bits
-
 
1032
 
-
 
1033
    data += d->base64.size() * sizeof(Sym);
-
 
1034
    d->symlen.resize(number<uint16_t, LittleEndian>(data)); data += sizeof(uint16_t);
345
  return extra;
1035
    d->btree = (LR*)data;
-
 
1036
 
-
 
1037
    // The comrpession scheme used is "Recursive Pairing", that replaces the most
-
 
1038
    // frequent adjacent pair of symbols in the source message by a new symbol,
-
 
1039
    // reevaluating the frequencies of all of the symbol pairs with respect to
-
 
1040
    // the extended alphabet, and then repeating the process.
-
 
1041
    // See http://www.larsson.dogma.net/dcc99.pdf
-
 
1042
    std::vector<bool> visited(d->symlen.size());
-
 
1043
 
-
 
1044
    for (Sym sym = 0; sym < d->symlen.size(); ++sym)
-
 
1045
        if (!visited[sym])
-
 
1046
            d->symlen[sym] = set_symlen(d, sym, visited);
-
 
1047
 
-
 
1048
    return data + d->symlen.size() * sizeof(LR) + (d->symlen.size() & 1);
346
}
1049
}
347
 
1050
 
-
 
1051
template<typename T>
348
static int probe_ab(Position& pos, int alpha, int beta, int *success)
1052
uint8_t* set_dtz_map(WDLEntry&, T&, uint8_t*, File) { return nullptr; }
349
{
1053
 
350
  int v;
-
 
351
  ExtMove stack[64];
1054
template<typename T>
352
  ExtMove *moves, *end;
1055
uint8_t* set_dtz_map(DTZEntry&, T& p, uint8_t* data, File maxFile) {
353
  StateInfo st;
-
 
354
 
1056
 
355
  // Generate (at least) all legal non-ep captures including (under)promotions.
-
 
356
  // It is OK to generate more, as long as they are filtered out below.
-
 
357
  if (!pos.checkers()) {
1057
    p.map = data;
358
    end = generate<CAPTURES>(pos, stack);
-
 
359
    // Since underpromotion captures are not included, we need to add them.
-
 
360
    end = add_underprom_caps(pos, stack, end);
-
 
361
  } else
-
 
362
    end = generate<EVASIONS>(pos, stack);
-
 
363
 
1058
 
364
  for (moves = stack; moves < end; moves++) {
1059
    for (File f = FILE_A; f <= maxFile; ++f) {
365
    Move capture = moves->move;
-
 
366
    if (!pos.capture(capture) || type_of(capture) == ENPASSANT
1060
        if (item(p, 0, f).precomp->flags & TBFlag::Mapped)
367
                        || !pos.legal(capture))
1061
            for (int i = 0; i < 4; ++i) { // Sequence like 3,x,x,x,1,x,0,2,x,x
368
      continue;
-
 
369
    pos.do_move(capture, st, pos.gives_check(capture));
1062
                item(p, 0, f).map_idx[i] = (uint16_t)(data - p.map + 1);
370
    v = -probe_ab(pos, -beta, -alpha, success);
-
 
371
    pos.undo_move(capture);
-
 
372
    if (*success == 0) return 0;
1063
                data += *data + 1;
373
    if (v > alpha) {
-
 
374
      if (v >= beta) {
-
 
375
        *success = 2;
-
 
376
        return v;
1064
            }
377
      }
-
 
378
      alpha = v;
-
 
379
    }
1065
    }
380
  }
-
 
381
 
1066
 
382
  v = probe_wdl_table(pos, success);
1067
    return data += (uintptr_t)data & 1; // Word alignment
383
  if (*success == 0) return 0;
-
 
384
  if (alpha >= v) {
-
 
385
    *success = 1 + (alpha > 0);
-
 
386
    return alpha;
-
 
387
  } else {
-
 
388
    *success = 1;
-
 
389
    return v;
-
 
390
  }
-
 
391
}
1068
}
392
 
1069
 
393
// Probe the WDL table for a particular position.
-
 
394
// If *success != 0, the probe was successful.
-
 
395
// The return value is from the point of view of the side to move:
-
 
396
// -2 : loss
-
 
397
// -1 : loss, but draw under 50-move rule
1070
template<typename Entry, typename T>
398
//  0 : draw
-
 
399
//  1 : win, but draw under 50-move rule
1071
void do_init(Entry& e, T& p, uint8_t* data) {
400
//  2 : win
-
 
401
int Tablebases::probe_wdl(Position& pos, int *success)
-
 
402
{
-
 
403
  int v;
-
 
404
 
1072
 
405
  *success = 1;
-
 
406
  v = probe_ab(pos, -2, 2, success);
1073
    const bool IsWDL = std::is_same<Entry, WDLEntry>::value;
407
 
1074
 
408
  // If en passant is not possible, we are done.
-
 
409
  if (pos.ep_square() == SQ_NONE)
-
 
410
    return v;
1075
    PairsData* d;
411
  if (!(*success)) return 0;
-
 
412
 
1076
 
413
  // Now handle en passant.
1077
    enum { Split = 1, HasPawns = 2 };
414
  int v1 = -3;
-
 
415
  // Generate (at least) all legal en passant captures.
-
 
416
  ExtMove stack[192];
-
 
417
  ExtMove *moves, *end;
-
 
418
  StateInfo st;
-
 
419
 
1078
 
420
  if (!pos.checkers())
-
 
421
    end = generate<CAPTURES>(pos, stack);
1079
    assert(e.hasPawns        == !!(*data & HasPawns));
422
  else
-
 
423
    end = generate<EVASIONS>(pos, stack);
1080
    assert((e.key != e.key2) == !!(*data & Split));
424
 
1081
 
425
  for (moves = stack; moves < end; moves++) {
-
 
426
    Move capture = moves->move;
1082
    data++; // First byte stores flags
-
 
1083
 
427
    if (type_of(capture) != ENPASSANT
1084
    const int Sides = IsWDL && (e.key != e.key2) ? 2 : 1;
428
          || !pos.legal(capture))
-
 
429
      continue;
-
 
430
    pos.do_move(capture, st, pos.gives_check(capture));
1085
    const File MaxFile = e.hasPawns ? FILE_D : FILE_A;
-
 
1086
 
431
    int v0 = -probe_ab(pos, -2, 2, success);
1087
    bool pp = e.hasPawns && e.pawnTable.pawnCount[1]; // Pawns on both sides
-
 
1088
 
432
    pos.undo_move(capture);
1089
    assert(!pp || e.pawnTable.pawnCount[0]);
-
 
1090
 
433
    if (*success == 0) return 0;
1091
    for (File f = FILE_A; f <= MaxFile; ++f) {
434
    if (v0 > v1) v1 = v0;
-
 
435
  }
1092
 
436
  if (v1 > -3) {
-
 
437
    if (v1 >= v) v = v1;
1093
        for (int i = 0; i < Sides; i++)
438
    else if (v == 0) {
-
 
439
      // Check whether there is at least one legal non-ep move.
1094
            item(p, i, f).precomp = new PairsData();
-
 
1095
 
440
      for (moves = stack; moves < end; moves++) {
1096
        int order[][2] = { { *data & 0xF, pp ? *(data + 1) & 0xF : 0xF },
441
        Move capture = moves->move;
-
 
442
        if (type_of(capture) == ENPASSANT) continue;
1097
                           { *data >>  4, pp ? *(data + 1) >>  4 : 0xF } };
443
        if (pos.legal(capture)) break;
1098
        data += 1 + pp;
444
      }
1099
 
445
      if (moves == end && !pos.checkers()) {
-
 
446
        end = generate<QUIETS>(pos, end);
1100
        for (int k = 0; k < e.pieceCount; ++k, ++data)
447
        for (; moves < end; moves++) {
1101
            for (int i = 0; i < Sides; i++)
448
          Move move = moves->move;
1102
                item(p, i, f).precomp->pieces[k] = Piece(i ? *data >>  4 : *data & 0xF);
-
 
1103
 
449
          if (pos.legal(move))
1104
        for (int i = 0; i < Sides; ++i)
450
            break;
-
 
451
        }
-
 
452
      }
-
 
453
      // If not, then we are forced to play the losing ep capture.
1105
            set_groups(e, item(p, i, f).precomp, order[i], f);
454
      if (moves == end)
-
 
455
        v = v1;
-
 
456
    }
1106
    }
457
  }
-
 
458
 
1107
 
-
 
1108
    data += (uintptr_t)data & 1; // Word alignment
-
 
1109
 
-
 
1110
    for (File f = FILE_A; f <= MaxFile; ++f)
-
 
1111
        for (int i = 0; i < Sides; i++)
-
 
1112
            data = set_sizes(item(p, i, f).precomp, data);
-
 
1113
 
-
 
1114
    if (!IsWDL)
-
 
1115
        data = set_dtz_map(e, p, data, MaxFile);
-
 
1116
 
-
 
1117
    for (File f = FILE_A; f <= MaxFile; ++f)
-
 
1118
        for (int i = 0; i < Sides; i++) {
-
 
1119
            (d = item(p, i, f).precomp)->sparseIndex = (SparseEntry*)data;
-
 
1120
            data += d->sparseIndexSize * sizeof(SparseEntry);
459
  return v;
1121
        }
-
 
1122
 
-
 
1123
    for (File f = FILE_A; f <= MaxFile; ++f)
-
 
1124
        for (int i = 0; i < Sides; i++) {
-
 
1125
            (d = item(p, i, f).precomp)->blockLength = (uint16_t*)data;
-
 
1126
            data += d->blockLengthSize * sizeof(uint16_t);
-
 
1127
        }
-
 
1128
 
-
 
1129
    for (File f = FILE_A; f <= MaxFile; ++f)
-
 
1130
        for (int i = 0; i < Sides; i++) {
-
 
1131
            data = (uint8_t*)(((uintptr_t)data + 0x3F) & ~0x3F); // 64 byte alignment
-
 
1132
            (d = item(p, i, f).precomp)->data = data;
-
 
1133
            data += d->blocksNum * d->sizeofBlock;
-
 
1134
        }
460
}
1135
}
461
 
1136
 
462
// This routine treats a position with en passant captures as one without.
1137
template<typename Entry>
463
static int probe_dtz_no_ep(Position& pos, int *success)
1138
void* init(Entry& e, const Position& pos) {
464
{
-
 
465
  int wdl, dtz;
-
 
466
 
1139
 
467
  wdl = probe_ab(pos, -2, 2, success);
1140
    const bool IsWDL = std::is_same<Entry, WDLEntry>::value;
468
  if (*success == 0) return 0;
-
 
469
 
1141
 
470
  if (wdl == 0) return 0;
1142
    static Mutex mutex;
471
 
1143
 
-
 
1144
    // Avoid a thread reads 'ready' == true while another is still in do_init(),
-
 
1145
    // this could happen due to compiler reordering.
472
  if (*success == 2)
1146
    if (e.ready.load(std::memory_order_acquire))
473
    return wdl == 2 ? 1 : 101;
1147
        return e.baseAddress;
474
 
1148
 
475
  ExtMove stack[192];
-
 
476
  ExtMove *moves, *end = NULL;
1149
    std::unique_lock<Mutex> lk(mutex);
477
  StateInfo st;
-
 
478
 
1150
 
479
  if (wdl > 0) {
-
 
480
    // Generate at least all legal non-capturing pawn moves
1151
    if (e.ready.load(std::memory_order_relaxed)) // Recheck under lock
481
    // including non-capturing promotions.
-
 
482
    if (!pos.checkers())
1152
        return e.baseAddress;
483
      end = generate<NON_EVASIONS>(pos, stack);
-
 
484
    else
-
 
485
      end = generate<EVASIONS>(pos, stack);
-
 
486
 
1153
 
487
    for (moves = stack; moves < end; moves++) {
1154
    // Pieces strings in decreasing order for each color, like ("KPP","KR")
488
      Move move = moves->move;
1155
    std::string fname, w, b;
489
      if (type_of(pos.moved_piece(move)) != PAWN || pos.capture(move)
1156
    for (PieceType pt = KING; pt >= PAWN; --pt) {
490
                || !pos.legal(move))
-
 
491
        continue;
-
 
492
      pos.do_move(move, st, pos.gives_check(move));
1157
        w += std::string(popcount(pos.pieces(WHITE, pt)), PieceToChar[pt]);
493
      int v = -Tablebases::probe_wdl(pos, success);
1158
        b += std::string(popcount(pos.pieces(BLACK, pt)), PieceToChar[pt]);
494
      pos.undo_move(move);
-
 
495
      if (*success == 0) return 0;
-
 
496
      if (v == wdl)
-
 
497
        return v == 2 ? 1 : 101;
-
 
498
    }
1159
    }
499
  }
-
 
500
 
1160
 
501
  dtz = 1 + probe_dtz_table(pos, wdl, success);
1161
    const uint8_t TB_MAGIC[][4] = { { 0xD7, 0x66, 0x0C, 0xA5 },
502
  if (*success >= 0) {
-
 
503
    if (wdl & 1) dtz += 100;
-
 
504
    return wdl >= 0 ? dtz : -dtz;
1162
                                    { 0x71, 0xE8, 0x23, 0x5D } };
505
  }
-
 
506
 
1163
 
-
 
1164
    fname =  (e.key == pos.material_key() ? w + 'v' + b : b + 'v' + w)
-
 
1165
           + (IsWDL ? ".rtbw" : ".rtbz");
-
 
1166
 
-
 
1167
    uint8_t* data = TBFile(fname).map(&e.baseAddress, &e.mapping, TB_MAGIC[IsWDL]);
507
  if (wdl > 0) {
1168
    if (data)
-
 
1169
        e.hasPawns ? do_init(e, e.pawnTable, data) : do_init(e, e.pieceTable, data);
-
 
1170
 
-
 
1171
    e.ready.store(true, std::memory_order_release);
-
 
1172
    return e.baseAddress;
-
 
1173
}
-
 
1174
 
-
 
1175
template<typename E, typename T = typename Ret<E>::type>
-
 
1176
T probe_table(const Position& pos, ProbeState* result, WDLScore wdl = WDLDraw) {
-
 
1177
 
-
 
1178
    if (!(pos.pieces() ^ pos.pieces(KING)))
-
 
1179
        return T(WDLDraw); // KvK
-
 
1180
 
-
 
1181
    E* entry = EntryTable.get<E>(pos.material_key());
-
 
1182
 
-
 
1183
    if (!entry || !init(*entry, pos))
-
 
1184
        return *result = FAIL, T();
-
 
1185
 
-
 
1186
    return do_probe_table(pos, entry, wdl, result);
-
 
1187
}
-
 
1188
 
-
 
1189
// For a position where the side to move has a winning capture it is not necessary
-
 
1190
// to store a winning value so the generator treats such positions as "don't cares"
-
 
1191
// and tries to assign to it a value that improves the compression ratio. Similarly,
-
 
1192
// if the side to move has a drawing capture, then the position is at least drawn.
-
 
1193
// If the position is won, then the TB needs to store a win value. But if the
-
 
1194
// position is drawn, the TB may store a loss value if that is better for compression.
-
 
1195
// All of this means that during probing, the engine must look at captures and probe
-
 
1196
// their results and must probe the position itself. The "best" result of these
-
 
1197
// probes is the correct result for the position.
-
 
1198
// DTZ table don't store values when a following move is a zeroing winning move
-
 
1199
// (winning capture or winning pawn move). Also DTZ store wrong values for positions
-
 
1200
// where the best move is an ep-move (even if losing). So in all these cases set
-
 
1201
// the state to ZEROING_BEST_MOVE.
-
 
1202
template<bool CheckZeroingMoves = false>
-
 
1203
WDLScore search(Position& pos, ProbeState* result) {
-
 
1204
 
-
 
1205
    WDLScore value, bestValue = WDLLoss;
508
    int best = 0xffff;
1206
    StateInfo st;
-
 
1207
 
-
 
1208
    auto moveList = MoveList<LEGAL>(pos);
-
 
1209
    size_t totalCount = moveList.size(), moveCount = 0;
-
 
1210
 
509
    for (moves = stack; moves < end; moves++) {
1211
    for (const Move& move : moveList)
-
 
1212
    {
510
      Move move = moves->move;
1213
        if (   !pos.capture(move)
511
      if (pos.capture(move) || type_of(pos.moved_piece(move)) == PAWN
1214
            && (!CheckZeroingMoves || type_of(pos.moved_piece(move)) != PAWN))
512
                || !pos.legal(move))
1215
            continue;
-
 
1216
 
513
        continue;
1217
        moveCount++;
-
 
1218
 
514
      pos.do_move(move, st, pos.gives_check(move));
1219
        pos.do_move(move, st);
515
      int v = -Tablebases::probe_dtz(pos, success);
1220
        value = -search(pos, result);
516
      pos.undo_move(move);
1221
        pos.undo_move(move);
-
 
1222
 
517
      if (*success == 0) return 0;
1223
        if (*result == FAIL)
-
 
1224
            return WDLDraw;
-
 
1225
 
518
      if (v > 0 && v + 1 < best)
1226
        if (value > bestValue)
-
 
1227
        {
519
        best = v + 1;
1228
            bestValue = value;
-
 
1229
 
-
 
1230
            if (value >= WDLWin)
-
 
1231
            {
-
 
1232
                *result = ZEROING_BEST_MOVE; // Winning DTZ-zeroing move
-
 
1233
                return value;
-
 
1234
            }
-
 
1235
        }
520
    }
1236
    }
-
 
1237
 
-
 
1238
    // In case we have already searched all the legal moves we don't have to probe
-
 
1239
    // the TB because the stored score could be wrong. For instance TB tables
-
 
1240
    // do not contain information on position with ep rights, so in this case
-
 
1241
    // the result of probe_wdl_table is wrong. Also in case of only capture
-
 
1242
    // moves, for instance here 4K3/4q3/6p1/2k5/6p1/8/8/8 w - - 0 7, we have to
521
    return best;
1243
    // return with ZEROING_BEST_MOVE set.
522
  } else {
-
 
523
    int best = -1;
1244
    bool noMoreMoves = (moveCount && moveCount == totalCount);
-
 
1245
 
524
    if (!pos.checkers())
1246
    if (noMoreMoves)
525
      end = generate<NON_EVASIONS>(pos, stack);
1247
        value = bestValue;
526
    else
1248
    else
-
 
1249
    {
527
      end = generate<EVASIONS>(pos, stack);
1250
        value = probe_table<WDLEntry>(pos, result);
-
 
1251
 
-
 
1252
        if (*result == FAIL)
-
 
1253
            return WDLDraw;
-
 
1254
    }
-
 
1255
 
-
 
1256
    // DTZ stores a "don't care" value if bestValue is a win
-
 
1257
    if (bestValue >= value)
-
 
1258
        return *result = (   bestValue > WDLDraw
-
 
1259
                          || noMoreMoves ? ZEROING_BEST_MOVE : OK), bestValue;
-
 
1260
 
-
 
1261
    return *result = OK, value;
-
 
1262
}
-
 
1263
 
-
 
1264
} // namespace
-
 
1265
 
-
 
1266
void Tablebases::init(const std::string& paths) {
-
 
1267
 
-
 
1268
    EntryTable.clear();
-
 
1269
    MaxCardinality = 0;
-
 
1270
    TBFile::Paths = paths;
-
 
1271
 
-
 
1272
    if (paths.empty() || paths == "<empty>")
-
 
1273
        return;
-
 
1274
 
-
 
1275
    // MapB1H1H7[] encodes a square below a1-h8 diagonal to 0..27
-
 
1276
    int code = 0;
528
    for (moves = stack; moves < end; moves++) {
1277
    for (Square s = SQ_A1; s <= SQ_H8; ++s)
-
 
1278
        if (off_A1H8(s) < 0)
-
 
1279
            MapB1H1H7[s] = code++;
-
 
1280
 
-
 
1281
    // MapA1D1D4[] encodes a square in the a1-d1-d4 triangle to 0..9
-
 
1282
    std::vector<Square> diagonal;
529
      int v;
1283
    code = 0;
-
 
1284
    for (Square s = SQ_A1; s <= SQ_D4; ++s)
-
 
1285
        if (off_A1H8(s) < 0 && file_of(s) <= FILE_D)
530
      Move move = moves->move;
1286
            MapA1D1D4[s] = code++;
-
 
1287
 
-
 
1288
        else if (!off_A1H8(s) && file_of(s) <= FILE_D)
-
 
1289
            diagonal.push_back(s);
-
 
1290
 
-
 
1291
    // Diagonal squares are encoded as last ones
531
      if (!pos.legal(move))
1292
    for (auto s : diagonal)
-
 
1293
        MapA1D1D4[s] = code++;
-
 
1294
 
-
 
1295
    // MapKK[] encodes all the 461 possible legal positions of two kings where
-
 
1296
    // the first is in the a1-d1-d4 triangle. If the first king is on the a1-d4
-
 
1297
    // diagonal, the other one shall not to be above the a1-h8 diagonal.
-
 
1298
    std::vector<std::pair<int, Square>> bothOnDiagonal;
-
 
1299
    code = 0;
-
 
1300
    for (int idx = 0; idx < 10; idx++)
-
 
1301
        for (Square s1 = SQ_A1; s1 <= SQ_D4; ++s1)
-
 
1302
            if (MapA1D1D4[s1] == idx && (idx || s1 == SQ_B1)) // SQ_B1 is mapped to 0
532
        continue;
1303
            {
-
 
1304
                for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
-
 
1305
                    if ((PseudoAttacks[KING][s1] | s1) & s2)
-
 
1306
                        continue; // Illegal position
-
 
1307
 
-
 
1308
                    else if (!off_A1H8(s1) && off_A1H8(s2) > 0)
-
 
1309
                        continue; // First on diagonal, second above
-
 
1310
 
-
 
1311
                    else if (!off_A1H8(s1) && !off_A1H8(s2))
-
 
1312
                        bothOnDiagonal.push_back(std::make_pair(idx, s2));
-
 
1313
 
-
 
1314
                    else
533
      pos.do_move(move, st, pos.gives_check(move));
1315
                        MapKK[idx][s2] = code++;
-
 
1316
            }
-
 
1317
 
-
 
1318
    // Legal positions with both kings on diagonal are encoded as last ones
-
 
1319
    for (auto p : bothOnDiagonal)
-
 
1320
        MapKK[p.first][p.second] = code++;
-
 
1321
 
-
 
1322
    // Binomial[] stores the Binomial Coefficents using Pascal rule. There
-
 
1323
    // are Binomial[k][n] ways to choose k elements from a set of n elements.
534
      if (st.rule50 == 0) {
1324
    Binomial[0][0] = 1;
-
 
1325
 
-
 
1326
    for (int n = 1; n < 64; n++) // Squares
-
 
1327
        for (int k = 0; k < 6 && k <= n; ++k) // Pieces
-
 
1328
            Binomial[k][n] =  (k > 0 ? Binomial[k - 1][n - 1] : 0)
-
 
1329
                            + (k < n ? Binomial[k    ][n - 1] : 0);
-
 
1330
 
-
 
1331
    // MapPawns[s] encodes squares a2-h7 to 0..47. This is the number of possible
-
 
1332
    // available squares when the leading one is in 's'. Moreover the pawn with
-
 
1333
    // highest MapPawns[] is the leading pawn, the one nearest the edge and,
-
 
1334
    // among pawns with same file, the one with lowest rank.
-
 
1335
    int availableSquares = 47; // Available squares when lead pawn is in a2
-
 
1336
 
-
 
1337
    // Init the tables for the encoding of leading pawns group: with 6-men TB we
-
 
1338
    // can have up to 4 leading pawns (KPPPPK).
-
 
1339
    for (int leadPawnsCnt = 1; leadPawnsCnt <= 4; ++leadPawnsCnt)
-
 
1340
        for (File f = FILE_A; f <= FILE_D; ++f)
-
 
1341
        {
-
 
1342
            // Restart the index at every file because TB table is splitted
-
 
1343
            // by file, so we can reuse the same index for different files.
535
        if (wdl == -2) v = -1;
1344
            int idx = 0;
-
 
1345
 
-
 
1346
            // Sum all possible combinations for a given file, starting with
-
 
1347
            // the leading pawn on rank 2 and increasing the rank.
-
 
1348
            for (Rank r = RANK_2; r <= RANK_7; ++r)
536
        else {
1349
            {
537
          v = probe_ab(pos, 1, 2, success);
1350
                Square sq = make_square(f, r);
-
 
1351
 
-
 
1352
                // Compute MapPawns[] at first pass.
-
 
1353
                // If sq is the leading pawn square, any other pawn cannot be
-
 
1354
                // below or more toward the edge of sq. There are 47 available
-
 
1355
                // squares when sq = a2 and reduced by 2 for any rank increase
-
 
1356
                // due to mirroring: sq == a3 -> no a2, h2, so MapPawns[a3] = 45
538
          v = (v == 2) ? 0 : -101;
1357
                if (leadPawnsCnt == 1)
-
 
1358
                {
-
 
1359
                    MapPawns[sq] = availableSquares--;
-
 
1360
                    MapPawns[sq ^ 7] = availableSquares--; // Horizontal flip
-
 
1361
                }
-
 
1362
                LeadPawnIdx[leadPawnsCnt][sq] = idx;
-
 
1363
                idx += Binomial[leadPawnsCnt - 1][MapPawns[sq]];
-
 
1364
            }
-
 
1365
            // After a file is traversed, store the cumulated per-file index
-
 
1366
            LeadPawnsSize[leadPawnsCnt][f] = idx;
-
 
1367
        }
-
 
1368
 
-
 
1369
    for (PieceType p1 = PAWN; p1 < KING; ++p1) {
-
 
1370
        EntryTable.insert({KING, p1, KING});
-
 
1371
 
-
 
1372
        for (PieceType p2 = PAWN; p2 <= p1; ++p2) {
-
 
1373
            EntryTable.insert({KING, p1, p2, KING});
-
 
1374
            EntryTable.insert({KING, p1, KING, p2});
-
 
1375
 
-
 
1376
            for (PieceType p3 = PAWN; p3 < KING; ++p3)
-
 
1377
                EntryTable.insert({KING, p1, p2, KING, p3});
-
 
1378
 
-
 
1379
            for (PieceType p3 = PAWN; p3 <= p2; ++p3) {
-
 
1380
                EntryTable.insert({KING, p1, p2, p3, KING});
-
 
1381
 
-
 
1382
                for (PieceType p4 = PAWN; p4 <= p3; ++p4)
-
 
1383
                    EntryTable.insert({KING, p1, p2, p3, p4, KING});
-
 
1384
 
-
 
1385
                for (PieceType p4 = PAWN; p4 < KING; ++p4)
-
 
1386
                    EntryTable.insert({KING, p1, p2, p3, KING, p4});
-
 
1387
            }
-
 
1388
 
-
 
1389
            for (PieceType p3 = PAWN; p3 <= p1; ++p3)
-
 
1390
                for (PieceType p4 = PAWN; p4 <= (p1 == p3 ? p2 : p3); ++p4)
-
 
1391
                    EntryTable.insert({KING, p1, p2, KING, p3, p4});
539
        }
1392
        }
540
      } else {
-
 
541
        v = -Tablebases::probe_dtz(pos, success) - 1;
-
 
542
      }
-
 
543
      pos.undo_move(move);
-
 
544
      if (*success == 0) return 0;
-
 
545
      if (v < best)
-
 
546
        best = v;
-
 
547
    }
1393
    }
548
    return best;
-
 
549
  }
1394
 
-
 
1395
    sync_cout << "info string Found " << EntryTable.size() << " tablebases" << sync_endl;
550
}
1396
}
551
 
1397
 
-
 
1398
// Probe the WDL table for a particular position.
-
 
1399
// If *result != FAIL, the probe was successful.
-
 
1400
// The return value is from the point of view of the side to move:
-
 
1401
// -2 : loss
-
 
1402
// -1 : loss, but draw under 50-move rule
-
 
1403
//  0 : draw
552
static int wdl_to_dtz[] = {
1404
//  1 : win, but draw under 50-move rule
-
 
1405
//  2 : win
-
 
1406
WDLScore Tablebases::probe_wdl(Position& pos, ProbeState* result) {
-
 
1407
 
553
  -1, -101, 0, 101, 1
1408
    *result = OK;
-
 
1409
    return search(pos, result);
554
};
1410
}
555
 
1411
 
556
// Probe the DTZ table for a particular position.
1412
// Probe the DTZ table for a particular position.
557
// If *success != 0, the probe was successful.
1413
// If *result != FAIL, the probe was successful.
558
// The return value is from the point of view of the side to move:
1414
// The return value is from the point of view of the side to move:
559
//         n < -100 : loss, but draw under 50-move rule
1415
//         n < -100 : loss, but draw under 50-move rule
560
// -100 <= n < -1   : loss in n ply (assuming 50-move counter == 0)
1416
// -100 <= n < -1   : loss in n ply (assuming 50-move counter == 0)
561
//         0        : draw
1417
//         0        : draw
562
//     1 < n <= 100 : win in n ply (assuming 50-move counter == 0)
1418
//     1 < n <= 100 : win in n ply (assuming 50-move counter == 0)
Line 576... Line 1432...
576
// capture or pawn move, the inequality to be preserved is
1432
// capture or pawn move, the inequality to be preserved is
577
// dtz + 50-movecounter <= 100.
1433
// dtz + 50-movecounter <= 100.
578
//
1434
//
579
// In short, if a move is available resulting in dtz + 50-move-counter <= 99,
1435
// In short, if a move is available resulting in dtz + 50-move-counter <= 99,
580
// then do not accept moves leading to dtz + 50-move-counter == 100.
1436
// then do not accept moves leading to dtz + 50-move-counter == 100.
581
//
-
 
582
int Tablebases::probe_dtz(Position& pos, int *success)
1437
int Tablebases::probe_dtz(Position& pos, ProbeState* result) {
583
{
-
 
584
  *success = 1;
-
 
585
  int v = probe_dtz_no_ep(pos, success);
-
 
586
 
1438
 
587
  if (pos.ep_square() == SQ_NONE)
-
 
588
    return v;
1439
    *result = OK;
589
  if (*success == 0) return 0;
1440
    WDLScore wdl = search<true>(pos, result);
590
 
1441
 
591
  // Now handle en passant.
1442
    if (*result == FAIL || wdl == WDLDraw) // DTZ tables don't store draws
592
  int v1 = -3;
1443
        return 0;
593
 
1444
 
-
 
1445
    // DTZ stores a 'don't care' value in this case, or even a plain wrong
594
  ExtMove stack[192];
1446
    // one as in case the best move is a losing ep, so it cannot be probed.
595
  ExtMove *moves, *end;
1447
    if (*result == ZEROING_BEST_MOVE)
596
  StateInfo st;
1448
        return dtz_before_zeroing(wdl);
597
 
1449
 
598
  if (!pos.checkers())
-
 
599
    end = generate<CAPTURES>(pos, stack);
-
 
600
  else
-
 
601
    end = generate<EVASIONS>(pos, stack);
1450
    int dtz = probe_table<DTZEntry>(pos, result, wdl);
602
 
1451
 
603
  for (moves = stack; moves < end; moves++) {
1452
    if (*result == FAIL)
604
    Move capture = moves->move;
1453
        return 0;
-
 
1454
 
605
    if (type_of(capture) != ENPASSANT
1455
    if (*result != CHANGE_STM)
606
                || !pos.legal(capture))
1456
        return (dtz + 100 * (wdl == WDLBlessedLoss || wdl == WDLCursedWin)) * sign_of(wdl);
607
      continue;
1457
 
608
    pos.do_move(capture, st, pos.gives_check(capture));
1458
    // DTZ stores results for the other side, so we need to do a 1-ply search and
609
    int v0 = -probe_ab(pos, -2, 2, success);
1459
    // find the winning move that minimizes DTZ.
610
    pos.undo_move(capture);
1460
    StateInfo st;
611
    if (*success == 0) return 0;
-
 
612
    if (v0 > v1) v1 = v0;
1461
    int minDTZ = 0xFFFF;
613
  }
1462
 
614
  if (v1 > -3) {
-
 
615
    v1 = wdl_to_dtz[v1 + 2];
1463
    for (const Move& move : MoveList<LEGAL>(pos))
616
    if (v < -100) {
-
 
617
      if (v1 >= 0)
-
 
618
        v = v1;
1464
    {
619
    } else if (v < 0) {
-
 
620
      if (v1 >= 0 || v1 < -100)
1465
        bool zeroing = pos.capture(move) || type_of(pos.moved_piece(move)) == PAWN;
-
 
1466
 
621
        v = v1;
1467
        pos.do_move(move, st);
-
 
1468
 
622
    } else if (v > 100) {
1469
        // For zeroing moves we want the dtz of the move _before_ doing it,
623
      if (v1 > 0)
-
 
624
        v = v1;
-
 
625
    } else if (v > 0) {
1470
        // otherwise we will get the dtz of the next move sequence. Search the
626
      if (v1 == 1)
-
 
627
        v = v1;
-
 
628
    } else if (v1 >= 0) {
1471
        // position after the move to get the score sign (because even in a
629
      v = v1;
-
 
630
    } else {
-
 
631
      for (moves = stack; moves < end; moves++) {
1472
        // winning position we could make a losing capture or going for a draw).
632
        Move move = moves->move;
1473
        dtz = zeroing ? -dtz_before_zeroing(search(pos, result))
633
        if (type_of(move) == ENPASSANT) continue;
1474
                      : -probe_dtz(pos, result);
-
 
1475
 
634
        if (pos.legal(move)) break;
1476
        pos.undo_move(move);
635
      }
1477
 
636
      if (moves == end && !pos.checkers()) {
1478
        if (*result == FAIL)
637
        end = generate<QUIETS>(pos, end);
1479
            return 0;
-
 
1480
 
638
        for (; moves < end; moves++) {
1481
        // Convert result from 1-ply search. Zeroing moves are already accounted
639
          Move move = moves->move;
1482
        // by dtz_before_zeroing() that returns the DTZ of the previous move.
640
          if (pos.legal(move))
1483
        if (!zeroing)
641
            break;
1484
            dtz += sign_of(dtz);
642
        }
-
 
643
      }
1485
 
-
 
1486
        // Skip the draws and if we are winning only pick positive dtz
644
      if (moves == end)
1487
        if (dtz < minDTZ && sign_of(dtz) == sign_of(wdl))
645
        v = v1;
1488
            minDTZ = dtz;
646
    }
1489
    }
647
  }
-
 
648
 
1490
 
-
 
1491
    // Special handle a mate position, when there are no legal moves, in this
-
 
1492
    // case return value is somewhat arbitrary, so stick to the original TB code
649
  return v;
1493
    // that returns -1 in this case.
-
 
1494
    return minDTZ == 0xFFFF ? -1 : minDTZ;
650
}
1495
}
651
 
1496
 
652
// Check whether there has been at least one repetition of positions
1497
// Check whether there has been at least one repetition of positions
653
// since the last capture or pawn move.
1498
// since the last capture or pawn move.
654
static int has_repeated(StateInfo *st)
1499
static int has_repeated(StateInfo *st)
655
{
1500
{
656
  while (1) {
1501
    while (1) {
657
    int i = 4, e = std::min(st->rule50, st->pliesFromNull);
1502
        int i = 4, e = std::min(st->rule50, st->pliesFromNull);
658
    if (e < i)
-
 
659
      return 0;
-
 
660
    StateInfo *stp = st->previous->previous;
-
 
661
    do {
-
 
662
      stp = stp->previous->previous;
-
 
663
      if (stp->key == st->key)
-
 
664
        return 1;
-
 
665
      i += 2;
-
 
666
    } while (i <= e);
-
 
667
    st = st->previous;
-
 
668
  }
-
 
669
}
-
 
670
 
1503
 
671
static Value wdl_to_Value[5] = {
1504
        if (e < i)
672
  -VALUE_MATE + MAX_PLY + 1,
1505
            return 0;
-
 
1506
 
-
 
1507
        StateInfo *stp = st->previous->previous;
-
 
1508
 
673
  VALUE_DRAW - 2,
1509
        do {
-
 
1510
            stp = stp->previous->previous;
-
 
1511
 
-
 
1512
            if (stp->key == st->key)
674
  VALUE_DRAW,
1513
                return 1;
-
 
1514
 
675
  VALUE_DRAW + 2,
1515
            i += 2;
-
 
1516
        } while (i <= e);
-
 
1517
 
676
  VALUE_MATE - MAX_PLY - 1
1518
        st = st->previous;
-
 
1519
    }
677
};
1520
}
678
 
1521
 
679
// Use the DTZ tables to filter out moves that don't preserve the win or draw.
1522
// Use the DTZ tables to filter out moves that don't preserve the win or draw.
680
// If the position is lost, but DTZ is fairly high, only keep moves that
1523
// If the position is lost, but DTZ is fairly high, only keep moves that
681
// maximise DTZ.
1524
// maximise DTZ.
682
//
1525
//
683
// A return value false indicates that not all probes were successful and that
1526
// A return value false indicates that not all probes were successful and that
684
// no moves were filtered out.
1527
// no moves were filtered out.
685
bool Tablebases::root_probe(Position& pos, Search::RootMoves& rootMoves, Value& score)
1528
bool Tablebases::root_probe(Position& pos, Search::RootMoves& rootMoves, Value& score)
686
{
1529
{
687
  int success;
1530
    assert(rootMoves.size());
688
 
1531
 
689
  int dtz = probe_dtz(pos, &success);
1532
    ProbeState result;
690
  if (!success) return false;
1533
    int dtz = probe_dtz(pos, &result);
691
 
1534
 
-
 
1535
    if (result == FAIL)
692
  StateInfo st;
1536
        return false;
693
 
1537
 
-
 
1538
    StateInfo st;
-
 
1539
 
694
  // Probe each move.
1540
    // Probe each move
695
  for (size_t i = 0; i < rootMoves.size(); i++) {
1541
    for (size_t i = 0; i < rootMoves.size(); ++i) {
696
    Move move = rootMoves[i].pv[0];
1542
        Move move = rootMoves[i].pv[0];
697
    pos.do_move(move, st, pos.gives_check(move));
1543
        pos.do_move(move, st);
698
    int v = 0;
1544
        int v = 0;
-
 
1545
 
699
    if (pos.checkers() && dtz > 0) {
1546
        if (pos.checkers() && dtz > 0) {
700
      ExtMove s[192];
1547
            ExtMove s[MAX_MOVES];
-
 
1548
 
701
      if (generate<LEGAL>(pos, s) == s)
1549
            if (generate<LEGAL>(pos, s) == s)
-
 
1550
                v = 1;
-
 
1551
        }
-
 
1552
 
-
 
1553
        if (!v) {
-
 
1554
            if (st.rule50 != 0) {
-
 
1555
                v = -probe_dtz(pos, &result);
-
 
1556
 
-
 
1557
                if (v > 0)
-
 
1558
                    ++v;
-
 
1559
                else if (v < 0)
-
 
1560
                    --v;
-
 
1561
            } else {
-
 
1562
                v = -probe_wdl(pos, &result);
-
 
1563
                v = dtz_before_zeroing(WDLScore(v));
702
        v = 1;
1564
            }
-
 
1565
        }
-
 
1566
 
-
 
1567
        pos.undo_move(move);
-
 
1568
 
-
 
1569
        if (result == FAIL)
-
 
1570
            return false;
-
 
1571
 
-
 
1572
        rootMoves[i].score = (Value)v;
703
    }
1573
    }
704
    if (!v) {
-
 
705
      if (st.rule50 != 0) {
-
 
706
        v = -Tablebases::probe_dtz(pos, &success);
-
 
707
        if (v > 0) v++;
-
 
708
        else if (v < 0) v--;
-
 
709
      } else {
-
 
710
        v = -Tablebases::probe_wdl(pos, &success);
-
 
711
        v = wdl_to_dtz[v + 2];
-
 
712
      }
-
 
713
    }
-
 
714
    pos.undo_move(move);
-
 
715
    if (!success) return false;
-
 
716
    rootMoves[i].score = (Value)v;
-
 
717
  }
-
 
718
 
1574
 
719
  // Obtain 50-move counter for the root position.
1575
    // Obtain 50-move counter for the root position.
720
  // In Stockfish there seems to be no clean way, so we do it like this:
1576
    // In Stockfish there seems to be no clean way, so we do it like this:
721
  int cnt50 = st.previous->rule50;
1577
    int cnt50 = st.previous ? st.previous->rule50 : 0;
722
 
1578
 
723
  // Use 50-move counter to determine whether the root position is
1579
    // Use 50-move counter to determine whether the root position is
724
  // won, lost or drawn.
1580
    // won, lost or drawn.
725
  int wdl = 0;
1581
    WDLScore wdl = WDLDraw;
726
  if (dtz > 0)
-
 
727
    wdl = (dtz + cnt50 <= 100) ? 2 : 1;
-
 
728
  else if (dtz < 0)
-
 
729
    wdl = (-dtz + cnt50 <= 100) ? -2 : -1;
-
 
730
 
1582
 
731
  // Determine the score to report to the user.
-
 
732
  score = wdl_to_Value[wdl + 2];
-
 
733
  // If the position is winning or losing, but too few moves left, adjust the
-
 
734
  // score to show how close it is to winning or losing.
-
 
735
  // NOTE: int(PawnValueEg) is used as scaling factor in score_to_uci().
-
 
736
  if (wdl == 1 && dtz <= 100)
1583
    if (dtz > 0)
737
    score = (Value)(((200 - dtz - cnt50) * int(PawnValueEg)) / 200);
1584
        wdl = (dtz + cnt50 <= 100) ? WDLWin : WDLCursedWin;
738
  else if (wdl == -1 && dtz >= -100)
1585
    else if (dtz < 0)
739
    score = -(Value)(((200 + dtz - cnt50) * int(PawnValueEg)) / 200);
1586
        wdl = (-dtz + cnt50 <= 100) ? WDLLoss : WDLBlessedLoss;
740
 
1587
 
-
 
1588
    // Determine the score to report to the user.
-
 
1589
    score = WDL_to_value[wdl + 2];
-
 
1590
 
-
 
1591
    // If the position is winning or losing, but too few moves left, adjust the
-
 
1592
    // score to show how close it is to winning or losing.
-
 
1593
    // NOTE: int(PawnValueEg) is used as scaling factor in score_to_uci().
-
 
1594
    if (wdl == WDLCursedWin && dtz <= 100)
-
 
1595
        score = (Value)(((200 - dtz - cnt50) * int(PawnValueEg)) / 200);
-
 
1596
    else if (wdl == WDLBlessedLoss && dtz >= -100)
-
 
1597
        score = -(Value)(((200 + dtz - cnt50) * int(PawnValueEg)) / 200);
-
 
1598
 
741
  // Now be a bit smart about filtering out moves.
1599
    // Now be a bit smart about filtering out moves.
742
  size_t j = 0;
1600
    size_t j = 0;
-
 
1601
 
743
  if (dtz > 0) { // winning (or 50-move rule draw)
1602
    if (dtz > 0) { // winning (or 50-move rule draw)
744
    int best = 0xffff;
1603
        int best = 0xffff;
-
 
1604
 
745
    for (size_t i = 0; i < rootMoves.size(); i++) {
1605
        for (size_t i = 0; i < rootMoves.size(); ++i) {
746
      int v = rootMoves[i].score;
1606
            int v = rootMoves[i].score;
-
 
1607
 
747
      if (v > 0 && v < best)
1608
            if (v > 0 && v < best)
748
        best = v;
1609
                best = v;
749
    }
1610
        }
-
 
1611
 
750
    int max = best;
1612
        int max = best;
-
 
1613
 
751
    // If the current phase has not seen repetitions, then try all moves
1614
        // If the current phase has not seen repetitions, then try all moves
752
    // that stay safely within the 50-move budget, if there are any.
1615
        // that stay safely within the 50-move budget, if there are any.
753
    if (!has_repeated(st.previous) && best + cnt50 <= 99)
1616
        if (!has_repeated(st.previous) && best + cnt50 <= 99)
754
      max = 99 - cnt50;
1617
            max = 99 - cnt50;
-
 
1618
 
755
    for (size_t i = 0; i < rootMoves.size(); i++) {
1619
        for (size_t i = 0; i < rootMoves.size(); ++i) {
756
      int v = rootMoves[i].score;
1620
            int v = rootMoves[i].score;
-
 
1621
 
757
      if (v > 0 && v <= max)
1622
            if (v > 0 && v <= max)
758
        rootMoves[j++] = rootMoves[i];
1623
                rootMoves[j++] = rootMoves[i];
759
    }
1624
        }
760
  } else if (dtz < 0) { // losing (or 50-move rule draw)
1625
    } else if (dtz < 0) { // losing (or 50-move rule draw)
761
    int best = 0;
1626
        int best = 0;
-
 
1627
 
762
    for (size_t i = 0; i < rootMoves.size(); i++) {
1628
        for (size_t i = 0; i < rootMoves.size(); ++i) {
763
      int v = rootMoves[i].score;
1629
            int v = rootMoves[i].score;
-
 
1630
 
764
      if (v < best)
1631
            if (v < best)
765
        best = v;
1632
                best = v;
766
    }
1633
        }
-
 
1634
 
767
    // Try all moves, unless we approach or have a 50-move rule draw.
1635
        // Try all moves, unless we approach or have a 50-move rule draw.
768
    if (-best * 2 + cnt50 < 100)
1636
        if (-best * 2 + cnt50 < 100)
769
      return true;
1637
            return true;
-
 
1638
 
770
    for (size_t i = 0; i < rootMoves.size(); i++) {
1639
        for (size_t i = 0; i < rootMoves.size(); ++i) {
771
      if (rootMoves[i].score == best)
1640
            if (rootMoves[i].score == best)
-
 
1641
                rootMoves[j++] = rootMoves[i];
-
 
1642
        }
-
 
1643
    } else { // drawing
-
 
1644
        // Try all moves that preserve the draw.
-
 
1645
        for (size_t i = 0; i < rootMoves.size(); ++i) {
-
 
1646
            if (rootMoves[i].score == 0)
772
        rootMoves[j++] = rootMoves[i];
1647
                rootMoves[j++] = rootMoves[i];
-
 
1648
        }
773
    }
1649
    }
774
  } else { // drawing
-
 
775
    // Try all moves that preserve the draw.
-
 
776
    for (size_t i = 0; i < rootMoves.size(); i++) {
-
 
777
      if (rootMoves[i].score == 0)
-
 
778
        rootMoves[j++] = rootMoves[i];
-
 
779
    }
-
 
780
  }
-
 
781
  rootMoves.resize(j, Search::RootMove(MOVE_NONE));
-
 
782
 
1650
 
-
 
1651
    rootMoves.resize(j, Search::RootMove(MOVE_NONE));
-
 
1652
 
783
  return true;
1653
    return true;
784
}
1654
}
785
 
1655
 
786
// Use the WDL tables to filter out moves that don't preserve the win or draw.
1656
// Use the WDL tables to filter out moves that don't preserve the win or draw.
787
// This is a fallback for the case that some or all DTZ tables are missing.
1657
// This is a fallback for the case that some or all DTZ tables are missing.
788
//
1658
//
789
// A return value false indicates that not all probes were successful and that
1659
// A return value false indicates that not all probes were successful and that
790
// no moves were filtered out.
1660
// no moves were filtered out.
791
bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves, Value& score)
1661
bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves, Value& score)
792
{
1662
{
793
  int success;
1663
    ProbeState result;
794
 
1664
 
795
  int wdl = Tablebases::probe_wdl(pos, &success);
1665
    WDLScore wdl = Tablebases::probe_wdl(pos, &result);
796
  if (!success) return false;
-
 
797
  score = wdl_to_Value[wdl + 2];
-
 
798
 
1666
 
-
 
1667
    if (result == FAIL)
799
  StateInfo st;
1668
        return false;
800
 
1669
 
801
  int best = -2;
1670
    score = WDL_to_value[wdl + 2];
802
 
1671
 
803
  // Probe each move.
-
 
804
  for (size_t i = 0; i < rootMoves.size(); i++) {
-
 
805
    Move move = rootMoves[i].pv[0];
-
 
806
    pos.do_move(move, st, pos.gives_check(move));
-
 
807
    int v = -Tablebases::probe_wdl(pos, &success);
-
 
808
    pos.undo_move(move);
-
 
809
    if (!success) return false;
-
 
810
    rootMoves[i].score = (Value)v;
-
 
811
    if (v > best)
-
 
812
      best = v;
1672
    StateInfo st;
813
  }
-
 
814
 
1673
 
815
  size_t j = 0;
1674
    int best = WDLLoss;
816
  for (size_t i = 0; i < rootMoves.size(); i++) {
-
 
817
    if (rootMoves[i].score == best)
-
 
818
      rootMoves[j++] = rootMoves[i];
-
 
819
  }
-
 
820
  rootMoves.resize(j, Search::RootMove(MOVE_NONE));
-
 
821
 
1675
 
822
  return true;
1676
    // Probe each move
823
}
-
 
-
 
1677
    for (size_t i = 0; i < rootMoves.size(); ++i) {
-
 
1678
        Move move = rootMoves[i].pv[0];
-
 
1679
        pos.do_move(move, st);
-
 
1680
        WDLScore v = -Tablebases::probe_wdl(pos, &result);
-
 
1681
        pos.undo_move(move);
824
 
1682
 
-
 
1683
        if (result == FAIL)
-
 
1684
            return false;
-
 
1685
 
-
 
1686
        rootMoves[i].score = (Value)v;
-
 
1687
 
-
 
1688
        if (v > best)
-
 
1689
            best = v;
-
 
1690
    }
-
 
1691
 
-
 
1692
    size_t j = 0;
-
 
1693
 
-
 
1694
    for (size_t i = 0; i < rootMoves.size(); ++i) {
-
 
1695
        if (rootMoves[i].score == best)
-
 
1696
            rootMoves[j++] = rootMoves[i];
-
 
1697
    }
-
 
1698
 
-
 
1699
    rootMoves.resize(j, Search::RootMove(MOVE_NONE));
-
 
1700
 
-
 
1701
    return true;
-
 
1702
}