-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.cpp
2135 lines (1740 loc) · 65.6 KB
/
context.cpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Sturddle Chess Engine (C) 2022, 2023 Cristian Vlasceanu
* --------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* --------------------------------------------------------------------------
* Third-party files included in this project are subject to copyright
* and licensed as stated in their respective header notes.
* --------------------------------------------------------------------------
*/
#include "common.h"
/*
* Move ordering, board state evaluation, and other stuff
* pertaining to the Context of the node being searched.
*/
#include <cerrno>
#include <chrono>
#include <iomanip>
#include <iterator>
#include <map>
#include <sstream>
#include "chess.h"
#define CONFIG_IMPL
#include "context.h"
#undef CONFIG_IMPL
#if WITH_NNUE
#include "auto.h" /* for NNUE_CONFIG */
#include "nnue.h"
#endif
#if USE_VECTOR
#include <xmmintrin.h>
#endif
using namespace chess;
using search::TranspositionTable;
using std::chrono::duration_cast;
using std::chrono::high_resolution_clock;
using std::chrono::nanoseconds;
/*
* Late-move reduction tables (adapted from berserk)
*/
struct LMR
{
int _table[PLY_MAX][64] = { { 0 }, { 0 } };
LMR()
{
for (int depth = 1; depth < PLY_MAX; ++depth)
for (int moves = 1; moves < 64; ++moves)
_table[depth][moves] = 0.1 + log(depth) * log(moves) / 2;
}
} LMR;
/*---------------------------------------------------------------------------
*
* Configuration API, for tweaking parameters via Python scripts
* (such as https://chess-tuning-tools.readthedocs.io/en/latest/)
*
*--------------------------------------------------------------------------*/
std::map<std::string, Param> _get_param_info()
{
std::map<std::string, Param> info;
for (const auto& elem : Config::_namespace)
{
if (USE_NNUE && elem.second._group == "Eval" && elem.first.find("MOBILITY") != 0)
continue;
info.emplace(elem.first,
Param {
*elem.second._val,
elem.second._min,
elem.second._max,
elem.second._group
});
}
info.emplace("Hash", Param {
int(TranspositionTable::get_hash_size()),
HASH_MIN,
int(TranspositionTable::max_hash_size()),
"Settings",
});
return info;
}
void _set_param(const std::string& name, int value, bool echo)
{
if (name == "Hash")
{
const int HASH_MAX = int(TranspositionTable::max_hash_size());
TranspositionTable::set_hash_size(std::max(std::min(value, HASH_MAX), HASH_MIN));
if (echo)
std::cout << "info string " << name << "=" << TranspositionTable::get_hash_size() << "\n";
return;
}
const auto iter = Config::_namespace.find(name);
if (iter == Config::_namespace.end())
{
search::Context::log_message(LogLevel::ERROR, "unknown parameter: \"" + name + "\"");
}
else if (USE_NNUE && iter->second._group == "Eval" && name.find("MOBILITY") != 0)
{
search::Context::log_message(LogLevel::WARN, "not used in NNUE mode: \"" + name + "\"");
}
else if (value < iter->second._min || value > iter->second._max)
{
std::ostringstream err;
err << name << ": " << value << " is out of range [";
err << iter->second._min << ", " << iter->second._max << "]";
search::Context::log_message(LogLevel::ERROR, err.str());
}
else
{
ASSERT_ALWAYS(iter->second._val);
if (*iter->second._val != value)
{
*iter->second._val = value;
if (echo)
std::cout << "info string " << name << "=" << *iter->second._val << std::endl;
}
}
}
std::map<std::string, int> _get_params()
{
std::map<std::string, int> cfg;
for (const auto& elem : Config::_namespace)
{
cfg.emplace(elem.first, *elem.second._val);
}
cfg.emplace(std::string("Hash"), int(TranspositionTable::get_hash_size()));
return cfg;
}
void assert_param_ref()
{
#if REFCOUNT_PARAM
for (auto& p : Config::_namespace)
{
if (p.second._val->_refcount == 0)
search::Context::log_message(LogLevel::ERROR, p.first + ": unreferenced");
ASSERT_ALWAYS(p.second._val->_refcount);
p.second._val->_refcount = 0;
}
#endif /* REFCOUNT_PARAM */
}
/*---------------------------------------------------------------------------
* Evaluation
*--------------------------------------------------------------------------*/
template<typename F>
static INLINE score_t eval_insufficient_material(const State& state, score_t eval, F f)
{
if (state.is_endgame() && state.has_insufficient_material(state.turn))
{
if (state.has_insufficient_material(!state.turn))
{
eval = 0; /* neither side can win */
}
else
{
eval = std::min<score_t>(eval, 0); /* cannot do better than draw */
}
}
else
{
eval = f();
}
return eval;
}
/*
* Allow apps built on top of the engine to implement strength levels
* by "fuzzing" the evaluation.
*/
static INLINE int eval_fuzz()
{
#if EVAL_FUZZ_ENABLED
return EVAL_FUZZ ? random_int(-EVAL_FUZZ, EVAL_FUZZ) : 0;
#else
return 0;
#endif /* EVAL_FUZZ_ENABLED */
}
/*****************************************************************************
* NNUE
*****************************************************************************/
#if WITH_NNUE
bool USE_NNUE = true;
/* Logging may not be initialized when NNUE::init() is called */
/* Hold on to message and log on first search. */
static std::string NNUE_init_msg;
static std::vector<std::array<NNUEdata, PLY_MAX>> NNUE_accumulator_data(SMP_CORES);
void NNUE::log_init_message()
{
if (!NNUE_init_msg.empty())
{
search::Context::log_message(LogLevel::INFO, NNUE_init_msg);
NNUE_init_msg.clear();
}
}
bool NNUE::init(const std::string& data_dir, const std::string& eval_file)
{
if (nnue_init((data_dir + eval_file).c_str()))
{
USE_NNUE = true;
NNUE_init_msg = std::string(NNUE_CONFIG) + " " + eval_file;
}
else
{
USE_NNUE = false;
NNUE_init_msg = "nnue_init errno=" + std::to_string(errno);
}
return USE_NNUE;
}
/*
* Convert from bitboard representation to the format expected by nnue.
*/
template<bool Full=true, typename T=int8_t> static INLINE void
NNUE_convert_position(const BoardPosition& pos, T (&pieces)[33], T (&squares)[33])
{
pieces[0] = NNUE::piece(KING, WHITE); squares[0] = pos.king(WHITE);
pieces[1] = NNUE::piece(KING, BLACK); squares[1] = pos.king(BLACK);
int i = 2;
if constexpr(Full)
{
for (auto color : { BLACK, WHITE })
for_each_square(pos.occupied_co(color) & ~pos.kings, [&](Square s) {
pieces[i] = NNUE::piece(pos.piece_type_at(s), color);
squares[i] = s;
++i;
});
}
ASSERT(i < 33);
pieces[i] = 0;
squares[i] = 0;
}
/* Testing */
int NNUE::eval(const chess::BoardPosition& pos)
{
int pieces[33];
int squares[33];
NNUE_convert_position(pos, pieces, squares);
/* nnue-probe colors are inverted */
const int turn = (pos.turn == WHITE) ? white : black;
return nnue_evaluate(turn, pieces, squares);
}
int NNUE::eval_fen(const std::string& fen)
{
return nnue_evaluate_fen(fen.c_str());
}
static INLINE void
NNUE_update_dirty_pieces(
const State& from_pos,
const State& to_pos,
const Move& move,
Color color, /* color of side that moved */
DirtyPiece& dp)
{
dp.dirtyNum = 1;
dp.to[0] = move.to_square();
if (to_pos.promotion)
{
dp.pc[0] = NNUE::piece(to_pos.promotion, color);
dp.from[0] = NNUE::NO_SQUARE;
dp.pc[1] = NNUE::piece(chess::PieceType::PAWN, color);
dp.to[1] = NNUE::NO_SQUARE;
dp.from[1] = move.from_square();
++dp.dirtyNum;
}
else
{
dp.pc[0] = NNUE::piece(from_pos.piece_type_at(move.from_square()), color);
dp.from[0] = move.from_square();
if (to_pos.is_castle)
{
const auto king_file = square_file(move.to_square());
dp.pc[1] = NNUE::piece(chess::PieceType::ROOK, color);
dp.from[1] = chess::rook_castle_squares[king_file == 2][0][color];
dp.to[1] = chess::rook_castle_squares[king_file == 2][1][color];
++dp.dirtyNum;
}
}
if (to_pos.capture_value)
{
const auto capture_square = from_pos.is_en_passant(move)
? Square(from_pos.en_passant_square - 8 * SIGN[color])
: move.to_square();
const auto victim_type = from_pos.piece_type_at(capture_square);
dp.pc[dp.dirtyNum] = NNUE::piece(victim_type, !color);
dp.to[dp.dirtyNum] = NNUE::NO_SQUARE;
dp.from[dp.dirtyNum] = capture_square;
++dp.dirtyNum;
}
}
/*
* Incremental position evaluation using (a fork of) nnue-probe.
*
* https://github.com/dshawul/nnue-probe
* https://github.com/cristivlas/nnue-probe
* https://www.chessprogramming.org/NNUE
*/
void search::Context::eval_incremental()
{
int8_t pieces[33];
int8_t squares[33];
NNUE_convert_position<false>(state(), pieces, squares);
NNUEdata* nnue_data[3] = { nullptr, nullptr, nullptr };
auto& acc = NNUE_accumulator_data[tid()];
nnue_data[0] = &acc[_ply];
nnue_data[0]->accumulator.computedAccumulation = 0;
if (_parent)
{
if (is_null_move())
{
ASSERT(_parent->_parent);
nnue_data[0]->dirtyPiece = acc[_parent->_ply].dirtyPiece;
nnue_data[1] = &acc[_parent->_parent->_ply];
}
else
{
nnue_data[1] = &acc[_parent->_ply];
auto& dp = nnue_data[0]->dirtyPiece;
NNUE_update_dirty_pieces(_parent->state(), state(), _move, !turn(), dp);
}
if (_parent->_parent)
{
nnue_data[2] = &acc[_parent->_parent->_ply];
}
}
const nnue::Position pos{
bool(!turn()),
pieces,
squares,
nnue_data,
_state,
[](const void* board, int8_t (&pcs)[33], int8_t (&sqrs)[33]) {
NNUE_convert_position(*reinterpret_cast<const State*>(board), pcs, sqrs);
}
};
auto eval = nnue::evaluate(pos);
/* Verify incremental result against full eval. */
ASSERT(eval == NNUE::eval(state()));
eval += eval_fuzz();
/* Make sure that insufficient material conditions are detected. */
eval = eval_insufficient_material(state(), eval, [eval](){ return eval; });
eval *= NNUE_EVAL_SCALE + evaluate_material() / 32;
eval /= 1024;
_eval = std::max(-CHECKMATE, std::min(CHECKMATE, eval));
}
#else
bool USE_NNUE = false;
bool NNUE::init(const std::string&, const std::string&) { return false; }
void NNUE::log_init_message() {}
int NNUE::eval_fen(const std::string&) { return 0; }
int NNUE::eval(const chess::BoardPosition&) { return 0; }
#endif /* WITH_NNUE */
namespace search
{
/*---------------------------------------------------------------------
* Context
*---------------------------------------------------------------------*/
atomic_bool Context::_cancel(false);
atomic_int Context::_tb_cardinality(6);
atomic_int Context::_time_limit(-1); /* milliseconds */
atomic_time Context::_time_start;
size_t Context::_callback_count(0);
HistoryPtr Context::_history; /* moves played so far */
std::vector<Context::ContextStack> Context::_context_stacks(SMP_CORES);
std::vector<Context::MoveStack> Context::_move_stacks(SMP_CORES);
std::vector<Context::StateStack> Context::_state_stacks(SMP_CORES);
/* Cython callbacks */
PyObject* Context::_engine = nullptr;
bool (*Context::_book_init)(const std::string&) = nullptr;
BaseMove (*Context::_book_lookup)(const State&, bool) = nullptr;
std::string (*Context::_epd)(const State&) = nullptr;
void (*Context::_log_message)(int, const std::string&, bool) = nullptr;
void (*Context::_on_iter)(PyObject*, Context*, const IterationInfo*) = nullptr;
void (*Context::_on_move)(PyObject*, const std::string&, int) = nullptr;
void (*Context::_on_next)(PyObject*, int64_t) = nullptr;
std::string(*Context::_pgn)(Context*) = nullptr;
void (*Context::_print_state)(const State&, bool) = nullptr;
void (*Context::_report)(PyObject*, std::vector<Context*>&) = nullptr;
bool (*Context::_tb_probe_wdl)(const State&, int*) = nullptr;
size_t (*Context::_vmem_avail)() = nullptr;
std::string Context::_syzygy_path = "syzygy/3-4-5";
/* Init attack masks and other magic bitboards in chess.cpp */
/* static */ void Context::init()
{
_init();
}
/* Call into the Python logger */
/* static */
void Context::log_message(LogLevel level, const std::string& msg, bool force)
{
cython_wrapper::call(_log_message, int(level), msg, force);
}
/*
* Copy context for two specific use cases:
* 1) clone root at the beginning of SMP searches, and
* 2) create a temporary context for singularity search.
*/
Context* Context::clone(ContextBuffer& buffer, int ply) const
{
Context* ctxt = new (buffer.as_context()) Context;
ctxt->_algorithm = _algorithm;
ctxt->_alpha = _alpha;
ctxt->_beta = _beta;
ctxt->_score = _score;
ctxt->_max_depth = _max_depth;
ctxt->_parent = _parent;
ctxt->_ply = ply;
ctxt->_prev = _prev;
ctxt->_state = &buffer._state;
*ctxt->_state = this->state();
ctxt->_move = _move;
ctxt->_excluded = _excluded;
ctxt->_tt_entry = _tt_entry;
ctxt->_counter_move = _counter_move;
ctxt->_is_null_move = _is_null_move;
ctxt->_double_ext = _double_ext;
ctxt->_extension = _extension;
return ctxt;
}
/* static */ void Context::ensure_stacks()
{
const size_t n_threads(SMP_CORES);
if (_context_stacks.size() < n_threads)
{
_context_stacks.resize(n_threads);
_move_stacks.resize(n_threads);
_state_stacks.resize(n_threads);
#if WITH_NNUE
NNUE_accumulator_data.resize(n_threads);
#endif
for (size_t n = 0; n < n_threads; ++n)
{
/* pre-allocate memory */
for (size_t ply = 0; ply < PLY_MAX; ++ply)
{
_move_stacks[n][ply].reserve(PREALLOCATE_MOVE_COUNT);
_state_stacks[n][ply].reserve(PREALLOCATE_MOVE_COUNT);
}
}
}
}
/*
* Track the best score and move so far, return true if beta cutoff;
* called from search right after: score = -negamax(*next_ctxt).
*/
bool Context::is_beta_cutoff(Context* next_ctxt, score_t score)
{
ASSERT(!next_ctxt->is_root());
ASSERT(score > SCORE_MIN && score < SCORE_MAX);
ASSERT(_alpha >= _score); /* invariant */
if (score > _score)
{
if (next_ctxt->is_null_move())
{
/* consecutive null moves not allowed by design */
ASSERT(!is_null_move());
/* ignore if not fail-high */
if (score < _beta)
return false;
}
if (score > _alpha)
{
if (!next_ctxt->is_null_move())
{
if (next_ctxt->_retry_above_alpha == RETRY::Reduced)
{
_retry_next = true;
if constexpr(EXTRA_STATS)
++_tt->_retry_reductions;
/* increment, so that late_move_reduce() skips it */
_full_depth_count = next_move_index() + 1;
}
else if (next_ctxt->_retry_above_alpha == RETRY::PVS && score < _beta)
{
_retry_next = true;
_retry_beta = -score;
}
if (_retry_next)
{
/* rewind and search again at full depth */
rewind(-1);
return false;
}
if (score >= _beta)
{
_cutoff_move = next_ctxt->_move;
if (is_null_move())
{
ASSERT(_parent);
if (next_ctxt->is_capture()) /* null move refuted by capture */
_parent->_capture_square = next_ctxt->_move.to_square();
if (score >= CHECKMATE - next_ctxt->depth())
_parent->_mate_detected = CHECKMATE - score + 1;
}
}
}
_alpha = score;
}
_score = score;
if (!next_ctxt->is_null_move())
{
ASSERT(next_ctxt->_move._state == next_ctxt->_state);
_best_move = next_ctxt->_move;
}
}
ASSERT(_alpha >= _score); /* invariant */
return _alpha >= _beta;
}
/*
* Called when there are no more moves available (endgame reached or
* qsearch has examined all non-quiet moves in the current position).
*/
score_t Context::evaluate_end()
{
/* precondition for calling this function */
ASSERT(!has_moves());
if (_pruned_count || _move_maker.have_skipped_moves())
{
ASSERT(_ply > 0);
ASSERT(!is_check());
return evaluate();
}
return is_check() ? checkmated(_ply) : 0;
}
/*
* Make the capturing move, return false if not legal.
*/
static bool INLINE apply_capture(const State& state, State& next_state, const Move& move)
{
state.clone_into(next_state);
next_state.apply_move(move);
ASSERT(next_state.turn != state.turn);
ASSERT(next_state.capture_value > 0);
return !next_state.is_check(state.turn); /* legal move? */
}
template<bool Debug>
int do_exchanges(const State& state, Bitboard mask, score_t gain, int tid, int ply)
{
ASSERT(popcount(mask) == 1);
ASSERT(gain >= 0);
/* use top half of moves stacks */
ASSERT(ply >= PLY_MAX);
if (size_t(ply) >= Context::MAX_MOVE)
return 0;
mask &= ~state.kings;
auto& moves = Context::moves(tid, ply);
state.generate_pseudo_legal_moves(moves, mask);
/* sort moves by piece type */
for (auto& move : moves)
{
ASSERT(state.piece_type_at(move.from_square()));
move._score = state.piece_weight_at(move.from_square());
}
/* sort lower-value attackers first */
insertion_sort(moves.begin(), moves.end(),
[](const Move& lhs, const Move& rhs) {
return lhs._score < rhs._score;
});
if constexpr(Debug)
{
std::ostringstream out;
out << "\tdo_exchanges (" << Context::epd(state) << ") gain=" << gain << " ";
for (const auto& move : moves)
out << move.uci() << "(" << move._score << ") ";
Context::log_message(LogLevel::DEBUG, out.str());
}
int score = 0;
int moves_count = 0;
(void) moves_count; /* silence off compiler warning */
State next_state;
/* iterate over pseudo-legal moves */
for (const auto& move : moves)
{
ASSERT((BB_SQUARES[move.to_square()] & ~mask) == 0);
ASSERT((state.kings & BB_SQUARES[move.to_square()]) == 0);
if (!apply_capture(state, next_state, move))
continue;
++moves_count;
if constexpr(Debug)
Context::log_message(LogLevel::DEBUG, "\t>>> " + move.uci());
const score_t capturer_value = move._score;
ASSERT(capturer_value == state.piece_weight_at(move.from_square()));
/*
* If the value of the capture exceeds the other's side gain plus the value of the
* capturing piece there is no need to call ourselves recursively, as even in the
* worst case scenario of the capturer being taken the difference cannot be offset.
*/
if (next_state.capture_value > gain + capturer_value)
{
#if EXCHANGES_DETECT_CHECKMATE
if (next_state.is_checkmate())
{
score = CHECKMATE - (ply + 1 - FIRST_EXCHANGE_PLY);
if constexpr(Debug)
{
std::ostringstream out;
out << "\t<<< " << move.uci() << ": CHECKMATE " << score;
Context::log_message(LogLevel::DEBUG, out.str());
}
break; /* impractical to keep looping in hope of a faster mate */
}
#endif /* EXCHANGES_DETECT_CHECKMATE */
score = std::max(score, next_state.capture_value - gain - capturer_value);
if constexpr(Debug)
{
std::ostringstream out;
out << "\t<<< " << move.uci() << ": " << next_state.capture_value
<< " - " << gain << " - " << capturer_value;
Context::log_message(LogLevel::DEBUG, out.str());
}
continue;
}
/****************************************************************/
score_t other = 0;
/* Call recursively if the capture offsets the opponent's gain. */
if (next_state.capture_value >= gain)
{
next_state.castling_rights = 0; /* castling do not capture */
other = do_exchanges<Debug>(
next_state,
mask,
next_state.capture_value - gain,
tid,
ply + 1);
}
/*****************************************************************/
if constexpr(Debug)
{
std::ostringstream out;
out << "\t<<< " << move.uci() << ": "
<< next_state.capture_value << " - " << other;
Context::log_message(LogLevel::DEBUG, out.str());
}
/* could continue and look for a quicker mate, but impractical */
if (other < MATE_LOW)
return -other;
score = std::max(score, next_state.capture_value - other);
}
#if EXCHANGES_DETECT_CHECKMATE
if (moves_count == 0 && state.is_checkmate())
{
score = -CHECKMATE + ply - FIRST_EXCHANGE_PLY;
}
#endif /* EXCHANGES_DETECT_CHECKMATE */
if constexpr(Debug)
{
std::ostringstream out;
out << "\tscore: " << score;
Context::log_message(LogLevel::DEBUG, out.str());
}
return score;
}
/*
* Look at all captures the side-to-move can make, "play through"
* same square exchanges and return lower bound of maximum gain.
*
* Skip the exchanges when the value of the captured piece exceeds
* the value of the capturer.
*/
INLINE int do_captures(int tid, const State& state, Bitboard from_mask, Bitboard to_mask)
{
static constexpr auto ply = FIRST_EXCHANGE_PLY;
const auto mask = to_mask & state.occupied_co(!state.turn) & ~state.kings;
/*
* Generate all pseudo-legal captures.
* NOTE: generate... function takes mask args in reverse: to, from.
*/
auto& moves = Context::moves(tid, ply);
if (state.generate_pseudo_legal_moves(moves, mask, from_mask).empty())
{
return 0;
}
/*
* 1) Go over the captures and assign the "victim" value to each move.
*/
for (auto& move : moves)
{
ASSERT(state.piece_type_at(move.to_square()));
ASSERT(state.piece_type_at(move.from_square()));
move._score = state.piece_weight_at(move.to_square());
}
/*
* 2) Sort most valuable victims first.
*/
insertion_sort(moves.begin(), moves.end(), [](const Move& lhs, const Move& rhs) {
return lhs._score > rhs._score;
});
if constexpr(DEBUG_CAPTURES)
{
std::ostringstream out;
out << "do_captures (" << Context::epd(state) << ") ";
for (const auto& move : moves)
out << move.uci() << "(" << move._score << ") ";
Context::log_message(LogLevel::DEBUG, out.str());
}
int score = 0;
State next_state;
/*
* 3) Go through the moves and "play out" the exchanges.
*/
for (const auto& move : moves)
{
/* do not expect to capture the king */
ASSERT((state.kings & BB_SQUARES[move.to_square()]) == 0);
#if !EXCHANGES_DETECT_CHECKMATE
/* victim values less than what we got so far? bail */
if (move._score <= score)
{
if constexpr(DEBUG_CAPTURES)
{
std::ostringstream out;
out << "\t" << move.uci() << " " << move._score << " <= " << score;
Context::log_message(LogLevel::DEBUG, out.str());
}
break;
}
#endif /* !EXCHANGES_DETECT_CHECKMATE */
if constexpr(DEBUG_CAPTURES)
Context::log_message(LogLevel::DEBUG, "*** " + move.uci());
/****************************************************************/
if (!apply_capture(state, next_state, move))
continue;
ASSERT(move._score == next_state.capture_value);
ASSERT(next_state.capture_value > score || EXCHANGES_DETECT_CHECKMATE);
auto attacker_value = state.piece_weight_at(move.from_square());
auto gain = next_state.capture_value - attacker_value;
/*
* Worst case scenario the attacker gets captured, capturing
* side still has a nice gain; skip "playing" the exchanges.
*/
if (gain > 0)
{
#if !EXCHANGES_DETECT_CHECKMATE
return gain;
#else
if (next_state.is_checkmate())
return CHECKMATE - (ply + 1 - FIRST_EXCHANGE_PLY);
if constexpr(DEBUG_CAPTURES)
Context::log_message(
LogLevel::DEBUG,
move.uci() + ": skip exchanges: " + std::to_string(gain));
if (gain > score)
score = gain;
continue;
#endif /* EXCHANGES_DETECT_CHECKMATE */
}
/****************************************************************/
/* "play through" same square exchanges */
next_state.castling_rights = 0; /* castling moves can't capture */
const auto other = do_exchanges<DEBUG_CAPTURES>(
next_state,
BB_SQUARES[move.to_square()],
next_state.capture_value,
tid,
ply + 1);
/****************************************************************/
if (other < MATE_LOW)
{
if constexpr(DEBUG_CAPTURES)
Context::log_message(LogLevel::DEBUG, move.uci() + ": checkmate");
return -other;
}
const auto value = next_state.capture_value - other;
if (value > score)
score = value;
if constexpr(DEBUG_CAPTURES)
{
std::ostringstream out;
out << "\t" << move.uci() << ": " << value << " ("
<< next_state.capture_value << " - " << other
<< ") score: " << score;
Context::log_message(LogLevel::DEBUG, out.str());
}
}
return score;
}
score_t eval_captures(Context& ctxt)
{
if constexpr(DEBUG_CAPTURES)
ctxt.log_message(LogLevel::DEBUG, "eval_captures");
const auto* const state = ctxt._state;
score_t result;
if constexpr(STATIC_EXCHANGES)
result = estimate_captures(*state);
else
result = do_captures(ctxt.tid(), *state, BB_ALL, BB_ALL);
ASSERT(result >= 0);
if constexpr(DEBUG_CAPTURES)
ctxt.log_message(LogLevel::DEBUG, "captures: " + std::to_string(result));
return result;
}
/*----------------------------------------------------------------------
* Tactical evaluations.
* All tactical scores are computed from the white side's perspective.
*----------------------------------------------------------------------*/
static INLINE int eval_center(const State& state, int pc)
{
int attacks = 0;
int occupancy = 0;
for (auto color : { BLACK, WHITE })
{
const auto s = SIGN[color];
occupancy += s * popcount(state.pawns & state.occupied_co(color) & BB_CENTER);
for_each_square(BB_CENTER, [&](Square square) {
attacks += s * popcount(state.pawns & BB_PAWN_ATTACKS[!color][square]);
});
}
return attacks * interpolate(pc, CENTER_ATTACKS, 0)
+ occupancy * interpolate(pc, CENTER_OCCUPANCY, 0);
}
static INLINE Bitboard king_area(const State& state, Square king)