-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtt.cpp
More file actions
74 lines (60 loc) · 2.21 KB
/
Copy pathtt.cpp
File metadata and controls
74 lines (60 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "tt.h"
#include <algorithm>
#include <iostream>
std::vector<TTEntry> TT;
namespace {
constexpr int MATE_TT_THRESHOLD = 48000;
int score_to_tt(int score, int search_ply) {
if (score > MATE_TT_THRESHOLD) return score + search_ply;
if (score < -MATE_TT_THRESHOLD) return score - search_ply;
return score;
}
int score_from_tt(int score, int search_ply) {
if (score > MATE_TT_THRESHOLD) return score - search_ply;
if (score < -MATE_TT_THRESHOLD) return score + search_ply;
return score;
}
} // namespace
void clear_tt() {
for (auto& entry : TT) {
entry.key = 0;
entry.depth = -1;
entry.flag = TT_ALPHA;
entry.score = 0;
entry.best_move = 0;
}
}
void init_tt(int size_mb) {
size_mb = std::max(1, size_mb);
std::size_t total_bytes = static_cast<std::size_t>(size_mb) * 1024ULL * 1024ULL;
std::size_t table_size = std::max<std::size_t>(1, total_bytes / sizeof(TTEntry));
TT.resize(table_size);
clear_tt();
}
int probe_tt(U64 hash, int depth, int alpha, int beta, Move& tt_move, int search_ply) {
if (TT.empty()) return TT_UNKNOWN;
TTEntry& entry = TT[hash % TT.size()];
if (entry.key != hash) return TT_UNKNOWN;
tt_move = entry.best_move;
if (entry.depth < depth) return TT_UNKNOWN;
int score = score_from_tt(entry.score, search_ply);
if (entry.flag == TT_EXACT) return score;
if (entry.flag == TT_ALPHA && score <= alpha) return alpha;
if (entry.flag == TT_BETA && score >= beta) return beta;
return TT_UNKNOWN;
}
void record_tt(U64 hash, int depth, int flag, int score, Move best_move, int search_ply) {
if (TT.empty()) return;
TTEntry& entry = TT[hash % TT.size()];
// Keep a deeper unrelated entry unless the incoming result is close enough
// in depth to be useful. Exact entries get a small replacement preference.
bool same_position = entry.key == hash;
bool empty = entry.key == 0;
bool deeper_or_close = depth + (flag == TT_EXACT ? 1 : 0) >= entry.depth - 1;
if (!empty && !same_position && !deeper_or_close) return;
entry.key = hash;
entry.depth = depth;
entry.flag = flag;
entry.score = score_to_tt(score, search_ply);
entry.best_move = best_move;
}