return (T(0) < val) - (val < T(0));
}
-// Numbers in little endian used by sparseIndex[] to point into blockLength[]
+// Numbers in little-endian used by sparseIndex[] to point into blockLength[]
struct SparseEntry {
char block[4]; // Number of block
char offset[2]; // Offset within the block
enum Side { Left, Right };
uint8_t lr[3]; // The first 12 bits is the left-hand symbol, the second 12
- // bits is the right-hand symbol. If symbol has length 1,
+ // bits is the right-hand symbol. If the symbol has length 1,
// then the left-hand symbol is the stored value.
template<Side S>
Sym get() {
std::string TBFile::Paths;
-// struct PairsData contains low level indexing information to access TB data.
-// There are 8, 4 or 2 PairsData records for each TBTable, according to type of
-// table and if positions have pawns or not. It is populated at first access.
+// struct PairsData contains low-level indexing information to access TB data.
+// There are 8, 4, or 2 PairsData records for each TBTable, according to the type
+// of table and if positions have pawns or not. It is populated at first access.
struct PairsData {
uint8_t flags; // Table flags, see enum TBFlag
uint8_t maxSymLen; // Maximum length in bits of the Huffman symbols
hasUniquePieces = true;
// Set the leading color. In case both sides have pawns the leading color
- // is the side with less pawns because this leads to better compression.
+ // is the side with fewer pawns because this leads to better compression.
bool c = !pos.count<PAWN>(BLACK)
|| ( pos.count<PAWN>(WHITE)
&& pos.count<PAWN>(BLACK) >= pos.count<PAWN>(WHITE));
}
// class TBTables creates and keeps ownership of the TBTable objects, one for
-// each TB file found. It supports a fast, hash based, table lookup. Populated
+// each TB file found. It supports a fast, hash-based, table lookup. Populated
// at init time, accessed at probe time.
class TBTables {
// mostly-draw or mostly-win tables this can leave many 64-byte blocks only half-filled, so
// in such cases blocks are 32 bytes long. The blocks of DTZ tables are up to 1024 bytes long.
// The generator picks the size that leads to the smallest table. The "book" of symbols and
-// Huffman codes is the same for all blocks in the table. A non-symmetric pawnless TB file
+// Huffman codes are the same for all blocks in the table. A non-symmetric pawnless TB file
// will have one table for wtm and one for btm, a TB file with pawns will have tables per
-// file a,b,c,d also in this case one set for wtm and one for btm.
+// file a,b,c,d also, in this case, one set for wtm and one for btm.
int decompress_pairs(PairsData* d, uint64_t idx) {
// Special case where all table positions store the same value
uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block);
int offset = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset);
- // Now compute the difference idx - I(k). From definition of k we know that
+ // Now compute the difference idx - I(k). From the definition of k, we know that
//
// idx = k * d->span + idx % d->span (2)
//
// Sum the above to offset to find the offset corresponding to our idx
offset += diff;
- // Move to previous/next block, until we reach the correct block that contains idx,
+ // Move to the previous/next block, until we reach the correct block that contains idx,
// that is when 0 <= offset <= d->blockLength[block]
while (offset < 0)
offset += d->blockLength[--block] + 1;
// Read the first 64 bits in our block, this is a (truncated) sequence of
// unknown number of symbols of unknown length but we know the first one
- // is at the beginning of this 64 bits sequence.
+ // is at the beginning of this 64-bit sequence.
uint64_t buf64 = number<uint64_t, BigEndian>(ptr); ptr += 2;
int buf64Size = 64;
Sym sym;
// Now add the value of the lowest symbol of length len to get our symbol
sym += number<Sym, LittleEndian>(&d->lowestSym[len]);
- // If our offset is within the number of values represented by symbol sym
- // we are done...
+ // If our offset is within the number of values represented by symbol sym,
+ // we are done.
if (offset < d->symlen[sym] + 1)
break;
}
}
- // Ok, now we have our symbol that expands into d->symlen[sym] + 1 symbols.
+ // Now we have our symbol that expands into d->symlen[sym] + 1 symbols.
// We binary-search for our value recursively expanding into the left and
// right child symbols until we reach a leaf node where symlen[sym] + 1 == 1
// that will store the value we need.
// If a symbol contains 36 sub-symbols (d->symlen[sym] + 1 = 36) and
// expands in a pair (d->symlen[left] = 23, d->symlen[right] = 11), then
- // we know that, for instance the ten-th value (offset = 10) will be on
+ // we know that, for instance, the tenth value (offset = 10) will be on
// the left side because in Recursive Pairing child symbols are adjacent.
if (offset < d->symlen[left] + 1)
sym = left;
// DTZ scores are sorted by frequency of occurrence and then assigned the
// values 0, 1, 2, ... in order of decreasing frequency. This is done for each
// of the four WDLScore values. The mapping information necessary to reconstruct
-// the original values is stored in the TB file and read during map[] init.
+// the original values are stored in the TB file and read during map[] init.
WDLScore map_score(TBTable<WDL>*, File, int value, WDLScore) { return WDLScore(value - 2); }
int map_score(TBTable<DTZ>* entry, File f, int value, WDLScore wdl) {
}
// DTZ tables store distance to zero in number of moves or plies. We
- // want to return plies, so we have convert to plies when needed.
+ // want to return plies, so we have to convert to plies when needed.
if ( (wdl == WDLWin && !(flags & TBFlag::WinPlies))
|| (wdl == WDLLoss && !(flags & TBFlag::LossPlies))
|| wdl == WDLCursedWin
}
// Compute a unique index out of a position and use it to probe the TB file. To
-// encode k pieces of same type and color, first sort the pieces by square in
+// encode k pieces of the same type and color, first sort the pieces by square in
// ascending order s1 <= s2 <= ... <= sk then compute the unique index as:
//
// idx = Binomial[1][s1] + Binomial[2][s2] + ... + Binomial[k][sk]
// A given TB entry like KRK has associated two material keys: KRvk and Kvkr.
// If both sides have the same pieces keys are equal. In this case TB tables
- // only store the 'white to move' case, so if the position to lookup has black
+ // only stores the 'white to move' case, so if the position to lookup has black
// to move, we need to switch the color and flip the squares before to lookup.
bool symmetricBlackToMove = (entry->key == entry->key2 && pos.side_to_move());
- // TB files are calculated for white as stronger side. For instance we have
- // KRvK, not KvKR. A position where stronger side is white will have its
- // material key == entry->key, otherwise we have to switch the color and
+ // TB files are calculated for white as the stronger side. For instance, we
+ // have KRvK, not KvKR. A position where the stronger side is white will have
+ // its material key == entry->key, otherwise we have to switch the color and
// flip the squares before to lookup.
bool blackStronger = (pos.material_key() != entry->key);
// Rs "together" in 62 * 61 / 2 ways (we divide by 2 because rooks can be
// swapped and still get the same position.)
//
- // In case we have at least 3 unique pieces (included kings) we encode them
+ // In case we have at least 3 unique pieces (including kings) we encode them
// together.
if (entry->hasUniquePieces) {
idx *= d->groupIdx[0];
Square* groupSq = squares + d->groupLen[0];
- // Encode remaining pawns then pieces according to square, in ascending order
+ // Encode remaining pawns and then pieces according to square, in ascending order
bool remainingPawns = entry->hasPawns && entry->pawnCount[1];
while (d->groupLen[++next])
uint64_t n = 0;
// Map down a square if "comes later" than a square in the previous
- // groups (similar to what done earlier for leading group pieces).
+ // groups (similar to what was done earlier for leading group pieces).
for (int i = 0; i < d->groupLen[next]; ++i)
{
auto f = [&](Square s) { return groupSq[i] > s; };
}
// Group together pieces that will be encoded together. The general rule is that
-// a group contains pieces of same type and color. The exception is the leading
+// a group contains pieces of the same type and color. The exception is the leading
// group that, in case of positions without pawns, can be formed by 3 different
// pieces (default) or by the king pair when there is not a unique piece apart
// from the kings. When there are pawns, pawns are always first in pieces[].
// In Recursive Pairing each symbol represents a pair of children symbols. So
// read d->btree[] symbols data and expand each one in his left and right child
-// symbol until reaching the leafs that represent the symbol value.
+// symbol until reaching the leaves that represent the symbol value.
uint8_t set_symlen(PairsData* d, Sym s, std::vector<bool>& visited) {
visited[s] = true; // We can set it now because tree is acyclic
// See https://en.wikipedia.org/wiki/Huffman_coding
// The canonical code is ordered such that longer symbols (in terms of
- // the number of bits of their Huffman code) have lower numeric value,
+ // the number of bits of their Huffman code) have a lower numeric value,
// so that d->lowestSym[i] >= d->lowestSym[i+1] (when read as LittleEndian).
// Starting from this we compute a base64[] table indexed by symbol length
// and containing 64 bit values so that d->base64[i] >= d->base64[i+1].
return data += uintptr_t(data) & 1; // Word alignment
}
-// Populate entry's PairsData records with data from the just memory mapped file.
+// Populate entry's PairsData records with data from the just memory-mapped file.
// Called at first access.
template<typename T>
void set(T& e, uint8_t* data) {
}
}
-// If the TB file corresponding to the given position is already memory mapped
-// then return its base address, otherwise try to memory map and init it. Called
-// at every probe, memory map and init only at first access. Function is thread
+// If the TB file corresponding to the given position is already memory-mapped
+// then return its base address, otherwise, try to memory map and init it. Called
+// at every probe, memory map, and init only at first access. Function is thread
// safe and can be called concurrently.
template<TBType Type>
void* mapped(TBTable<Type>& e, const Position& pos) {
}
// For a position where the side to move has a winning capture it is not necessary
-// to store a winning value so the generator treats such positions as "don't cares"
+// to store a winning value so the generator treats such positions as "don't care"
// and tries to assign to it a value that improves the compression ratio. Similarly,
// if the side to move has a drawing capture, then the position is at least drawn.
// If the position is won, then the TB needs to store a win value. But if the
// their results and must probe the position itself. The "best" result of these
// probes is the correct result for the position.
// DTZ tables do not store values when a following move is a zeroing winning move
-// (winning capture or winning pawn move). Also DTZ store wrong values for positions
+// (winning capture or winning pawn move). Also, DTZ store wrong values for positions
// where the best move is an ep-move (even if losing). So in all these cases set
// the state to ZEROING_BEST_MOVE.
template<bool CheckZeroingMoves>
} // namespace
-/// Tablebases::init() is called at startup and after every change to
-/// "SyzygyPath" UCI option to (re)create the various tables. It is not thread
-/// safe, nor it needs to be.
+// Tablebases::init() is called at startup and after every change to
+// "SyzygyPath" UCI option to (re)create the various tables. It is not thread
+// safe, nor it needs to be.
void Tablebases::init(const std::string& paths) {
TBTables.clear();
// MapKK[] encodes all the 462 possible legal positions of two kings where
// the first is in the a1-d1-d4 triangle. If the first king is on the a1-d4
- // diagonal, the other one shall not to be above the a1-h8 diagonal.
+ // diagonal, the other one shall not be above the a1-h8 diagonal.
std::vector<std::pair<int, Square>> bothOnDiagonal;
code = 0;
for (int idx = 0; idx < 10; idx++)
MapKK[idx][s2] = code++;
}
- // Legal positions with both kings on diagonal are encoded as last ones
+ // Legal positions with both kings on a diagonal are encoded as last ones
for (auto p : bothOnDiagonal)
MapKK[p.first][p.second] = code++;
// MapPawns[s] encodes squares a2-h7 to 0..47. This is the number of possible
// available squares when the leading one is in 's'. Moreover the pawn with
- // highest MapPawns[] is the leading pawn, the one nearest the edge and,
- // among pawns with same file, the one with lowest rank.
+ // highest MapPawns[] is the leading pawn, the one nearest the edge, and
+ // among pawns with the same file, the one with the lowest rank.
int availableSquares = 47; // Available squares when lead pawn is in a2
// Init the tables for the encoding of leading pawns group: with 7-men TB we
if (*result == FAIL || wdl == WDLDraw) // DTZ tables don't store draws
return 0;
- // DTZ stores a 'don't care' value in this case, or even a plain wrong
+ // DTZ stores a 'don't care value in this case, or even a plain wrong
// one as in case the best move is a losing ep, so it cannot be probed.
if (*result == ZEROING_BEST_MOVE)
return dtz_before_zeroing(wdl);
// For zeroing moves we want the dtz of the move _before_ doing it,
// otherwise we will get the dtz of the next move sequence. Search the
// position after the move to get the score sign (because even in a
- // winning position we could make a losing capture or going for a draw).
+ // winning position we could make a losing capture or go for a draw).
dtz = zeroing ? -dtz_before_zeroing(search<false>(pos, result))
: -probe_dtz(pos, result);
}
else if (pos.is_draw(1))
{
- // In case a root move leads to a draw by repetition or
- // 50-move rule, we set dtz to zero. Note: since we are
- // only 1 ply from the root, this must be a true 3-fold
- // repetition inside the game history.
+ // In case a root move leads to a draw by repetition or 50-move rule,
+ // we set dtz to zero. Note: since we are only 1 ply from the root,
+ // this must be a true 3-fold repetition inside the game history.
dtz = 0;
}
else