-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoc.cpp
More file actions
7310 lines (6755 loc) · 217 KB
/
Roc.cpp
File metadata and controls
7310 lines (6755 loc) · 217 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
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
// This code is public domain, as defined by the "CC0" Creative Commons license
// This code is public domain, as defined by the "CC0" Creative Commons license
//#define REGRESSION
//#define W32_BUILD
#define _CRT_SECURE_NO_WARNINGS
//#define CPU_TIMING
//#define TWO_PHASE
#define LARGE_PAGES
#define MP_NPS
//#define TIME_TO_DEPTH
//#define HNI
//#define VERBOSE
#ifdef W32_BUILD
#define NTDDI_VERSION 0x05010200
#define _WIN32_WINNT 0x0501
#else
#define _WIN32_WINNT 0x0600
#endif
#include <iostream>
#include <fstream>
#include <array>
#include <numeric>
#include <string>
#include <vector>
#include <thread>
#include <cmath>
#include <algorithm>
#include <chrono>
#include <unordered_map>
#include <bitset>
typedef std::chrono::high_resolution_clock::time_point time_point;
#include <windows.h>
#undef min
#undef max
#include <assert.h>
template<class T> std::string Str(const T& src) { return std::to_string(src); }
#include "Base/Platform.h"
#include "Chess/Chess.h"
#include "Chess/Bit.h"
#include "Chess/Pack.h"
#include "Chess/Board.h"
#include "Chess/Score.h"
#include "Chess/Move.h"
#include "Chess/Killer.h"
#include "Chess/Piece.h"
#include "Chess/Material.h"
#include "Chess/PawnEval.h"
#include "Chess/Eval.h"
#include "Chess/PasserEval.h"
#include "Chess/Locus.h"
#include "Chess/Weights.h"
#include "Chess/Magic.h"
#include "Chess/Futility.h"
#include "Chess/Shared.h"
#include "Chess/Roc.h"
//#include "TunerParams.inc"
using Gull::Board_;
using std::array;
CommonData_ DATA;
CommonData_* const& RO = &DATA; // generally we access DATA through RO
// Constants controlling play
constexpr int PliesToEvalCut = 50; // halfway to 50-move
constexpr int KingSafetyNoQueen = 8; // numerator; denominator is 16
constexpr int SeeThreshold = 40 * CP_EVAL;
constexpr int DrawCapConstant = 110 * CP_EVAL;
constexpr int DrawCapLinear = 0; // numerator; denominator is 64
constexpr int DeltaDecrement = (3 * CP_SEARCH) / 2; // 5 (+91/3) vs 3
int TBMinDepth = 2;
constexpr int InitiativeConst = int(1.5 * CP_SEARCH);
constexpr int InitiativePhase = int(4.5 * CP_SEARCH);
struct NoWatch_
{
template<class T_> bool operator()(const char*, bool m, T_) const { return m; }
template<class T_> void operator()(const char*, T_) const {}
};
#define IncWatch(var, x, n, loc) (WATCH()(loc, me, x) ? (var -= (n) * (x)) : (var += (n) * (x)))
#define IncVMultiple(var, n, x) IncWatch(var, x, n, #x) // support tuner
#define IncV(var, x) IncWatch(var, x, 1, #x) // support tuner
//#define IncV(var, x) (me ? (var -= (x)) : (var += (x))) // tournament mode
#define DecV(var, x) IncV(var, -(x))
#define NOTICE(x) WATCH()(#x, x)
constexpr sint16 KpkValue = 300 * CP_EVAL;
constexpr sint16 EvalValue = 30000;
constexpr sint16 MateValue = 32760 - 8 * (CP_SEARCH - 1);
/*
general move:
0 - 11: from & to
12 - 15: flags
16 - 23: history
24 - 25: spectial moves: killers, refutations...
26 - 30: MvvLva
delta move:
0 - 11: from & to
12 - 15: flags
16 - 31: sint16 delta + (sint16)0x4000
*/
constexpr array<int, 16> MvvLvaVictim = { 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3 };
constexpr array<int, 16> MvvLvaAttacker = { 0, 0, 5, 5, 4, 4, 3, 3, 3, 3, 2, 2, 1, 1, 6, 6 };
constexpr array<int, 16> MvvLvaAttackerKB = { 0, 0, 9, 9, 7, 7, 5, 5, 5, 5, 3, 3, 1, 1, 11, 11 };
INLINE int PawnCaptureMvvLva(int attacker) { return MvvLvaAttacker[attacker]; }
constexpr int MaxPawnCaptureMvvLva = MvvLvaAttacker[15]; // 6
INLINE int KnightCaptureMvvLva(int attacker) { return MaxPawnCaptureMvvLva + MvvLvaAttackerKB[attacker]; }
constexpr int MaxKnightCaptureMvvLva = MaxPawnCaptureMvvLva + MvvLvaAttackerKB[15]; // 17
INLINE int BishopCaptureMvvLva(int attacker) { return MaxPawnCaptureMvvLva + MvvLvaAttackerKB[attacker] + 1; }
constexpr int MaxBishopCaptureMvvLva = MaxPawnCaptureMvvLva + MvvLvaAttackerKB[15] + 1; // usually 18
INLINE int RookCaptureMvvLva(int attacker) { return MaxBishopCaptureMvvLva + MvvLvaAttacker[attacker]; }
constexpr int MaxRookCaptureMvvLva = MaxBishopCaptureMvvLva + MvvLvaAttacker[15]; // usually 24
INLINE int QueenCaptureMvvLva(int attacker) { return MaxRookCaptureMvvLva + MvvLvaAttacker[attacker]; }
INLINE int MvvLvaXrayCap(int capture) { return MvvLva[WhiteKing][capture]; }
constexpr int RefOneScore = (0xFF << 16) | (3 << 24);
constexpr int RefTwoScore = (0xFF << 16) | (2 << 24);
INLINE int ExtToFlag(int ext)
{
return ext << 16;
}
INLINE int ExtFromFlag(int flags)
{
return (flags >> 16) & 0xF;
}
constexpr int FlagHashCheck = 1 << 20; // first 20 bits are reserved for the hash killer and extension
constexpr int FlagHaltCheck = 1 << 21;
constexpr int FlagCallEvaluation = 1 << 22;
constexpr int FlagDisableNull = 1 << 23;
constexpr int FlagNeatSearch = FlagHashCheck | FlagHaltCheck | FlagCallEvaluation;
constexpr int FlagNoKillerUpdate = 1 << 24;
constexpr int FlagReturnBestMove = 1 << 25;
typedef struct
{
array<uint8, 64> square;
uint64 key, pawn_key;
packed_t material, pst;
uint16 move;
uint8 turn, castle_flags, ply, ep_square, piece, capture;
} GPosData;
typedef struct
{
array<uint16, 2> moves_;
} Ref1_;
struct TimeLimits_
{
time_point start_;
uint64 softLimit_, hardLimit_;
} TheTimeLimit;
template<typename T_, int N> struct Circle_
{
array<T_, N> vals_ = {};
int loc_ = 0;
void push(T_ val)
{
vals_[loc_++] = val;
loc_ %= N;
}
bool same() const
{
return adjacent_find(vals_.begin(), vals_.end(), std::not_equal_to<T_>()) == vals_.end();
}
};
struct SearchInfo_
{
int singular_, hashDepth_;
bool early_, failLow_, failHigh_;
Circle_<uint16, 3> moves_;
};
constexpr int N_PAWN_HASH = 1 << 17;
constexpr int PAWN_HASH_MASK = N_PAWN_HASH - 1;
constexpr uint64 N_REF_1 = 4096, N_REF_MULTI = 62717;
struct State_
{
std::array<PlyState_, MAX_HEIGHT> stack_;
PlyState_* current_;
Board_ board_;
SearchInfo_ searchInfo_;
std::vector<uint64> hashHist_;
std::vector<array<array<uint16, 2>, 64>> historyVals_;
std::vector<sint16> deltaVals_;
std::vector<Ref1_> ref1_;
uint64 nodes_, tbHits_;
int selDepth_;
std::vector<GPawnEntry> pawnHash_;
State_() : current_(&stack_[0]), pawnHash_(N_PAWN_HASH), historyVals_(16), deltaVals_(16 * 4096), ref1_(N_REF_1) {}
void ClearStack()
{
memset(&stack_[1], 0, (MAX_HEIGHT - 1) * sizeof(PlyState_));
current_ = &stack_[0];
}
void Reset(const State_& exemplar)
{
stack_ = exemplar.stack_;
current_ = &stack_[exemplar.Height()];
board_ = exemplar.board_;
searchInfo_ = exemplar.searchInfo_;
hashHist_ = exemplar.hashHist_;
historyVals_ = exemplar.historyVals_;
for (auto& hp : historyVals_)
for (auto& hs: hp)
for (auto& hv: hs)
if (F(hv & 0x00FF))
hv = 1;
deltaVals_ = exemplar.deltaVals_;
ref1_ = exemplar.ref1_;
nodes_ = tbHits_ = 0;
if (exemplar.pawnHash_.size() == N_PAWN_HASH)
pawnHash_ = exemplar.pawnHash_;
}
INLINE const PlyState_& operator[](int lookback) const { return *(current_ - lookback); }
INLINE int Height() const { return static_cast<int>(current_ - &stack_[0]); }
INLINE const Board_& operator()() const { return board_; }
INLINE const uint64& operator()(int piece_id) const { return board_.Piece(piece_id); }
};
constexpr uint8 FlagSort = 1 << 0;
constexpr uint8 FlagNoBcSort = 1 << 1;
constexpr sint16 TBMateValue = 31380;
constexpr sint16 TBCursedMateValue = 13;
const int TbValues[5] = { -TBMateValue, -TBCursedMateValue, 0, TBCursedMateValue, TBMateValue };
constexpr int NominalTbDepth = 33;
constexpr int MaxDepth = 125;
inline int TbDepth(int depth) { return Min(depth + NominalTbDepth, 117); }
extern int TB_LARGEST;
unsigned PyrrhicWDL(const State_& state, int depth);
enum
{
stage_search,
s_hash_move,
s_good_cap,
s_special,
s_quiet,
s_bad_cap,
s_none,
stage_evasion,
e_hash_move,
e_ev,
e_none,
stage_razoring,
r_hash_move,
r_cap,
r_checks,
r_none
};
inline Progress_ Progress(const Board_& board) { return Progress_(popcnt(board.Piece(White)), popcnt(board.Piece(Black))); }
struct GEntry
{
uint32 key;
uint16 date;
uint16 move;
score_t low;
score_t high;
uint8 low_depth;
uint8 high_depth;
};
constexpr GEntry NullEntry = { 0, 1, 0, 0, 0, 0, 0 };
typedef struct
{
int knodes;
int ply;
uint32 key;
uint16 date;
uint16 move;
score_t value;
score_t exclusion;
uint8 depth;
uint8 ex_depth;
} GPVEntry;
constexpr GPVEntry NullPVEntry = { 0, 0, 0, 1, 0, 0, 0, 0, 0 };
constexpr int N_PV_HASH = 1 << 19;
constexpr int PV_CLUSTER = 1 << 2;
constexpr int PV_HASH_MASK = N_PV_HASH - PV_CLUSTER;
constexpr int MAX_MOVES = 256;
std::vector<int> RootList;
template<class T> void prefetch(T* p)
{
_mm_prefetch(reinterpret_cast<const char*>(p), _MM_HINT_NTA);
}
template<bool me> INLINE int OwnRank(int loc)
{
return me ? (7 - RankOf(loc)) : RankOf(loc);
}
INLINE int OwnRank(bool me, int loc)
{
return me ? (7 - RankOf(loc)) : RankOf(loc);
}
namespace Futility
{
constexpr std::array<sint16, 10> PieceThreshold = { 12, 18, 22, 24, 25, 26, 27, 26, 40, 40 }; // in CP
constexpr std::array<sint16, 8> PasserThreshold = { 0, 0, 0, 0, 0, 20, 40, 0 };
template<bool me> inline sint16 x(const State_& state)
{
sint16 retval = PieceThreshold[pop0(state().NonPawnKing(me))];
if (uint64 passer = state[0].passer & state().Pawn(me))
retval = Max(retval, PasserThreshold[OwnRank<me>(NB<opp>(passer))]);
return retval;
}
template<bool me> inline sint16 HashCut(const State_& state, bool did_delta_moves)
{
return (did_delta_moves ? 4 : 8) * x<me>(state);
}
template<bool me> inline sint16 CheckCut(const State_& state)
{
return 11 * x<me>(state);
}
template<bool me> inline sint16 DeltaCut(const State_& state)
{
return HashCut<me>(state, false);
}
template<bool me> inline sint16 ScoutCut(const State_& state, int depth)
{
return (depth > 3 ? 4 : 7) * x<me>(state);
}
};
#ifdef HNI
inline uint64 BishopAttacks(int sq, const uint64& occ)
{
return RO->BMagic_.Attacks[Magic::BOffset[sq] + _pext_u64(occ, RO->BMagic_.Mask[sq])];
}
inline uint64 RookAttacks(int sq, const uint64& occ)
{
return RO->RMagic_.Attacks[Magic::ROffset[sq] + _pext_u64(occ, RO->RMagic_.Mask[sq])];
}
#else
inline uint64 BishopAttacks(int sq, const uint64& occ)
{
return RO->BMagic_.attacks_[Magic::BOffset[sq] + (((RO->BMagic_.masks_[sq] & occ) * Magic::BMagic[sq]) >> Magic::BShift[sq])];
}
inline uint64 RookAttacks(int sq, const uint64& occ)
{
return RO->RMagic_.attacks_[Magic::ROffset[sq] + (((RO->RMagic_.masks_[sq] & occ) * Magic::RMagic[sq]) >> Magic::RShift[sq])];
}
#endif
INLINE uint64 QueenAttacks(int sq, const uint64& occ)
{
return BishopAttacks(sq, occ) | RookAttacks(sq, occ);
}
#define kingAttacks(sq) KAtt[sq]
#define rookAttacks RookAttacks
#define bishopAttacks BishopAttacks
#define knightAttacks(sq) NAtt[sq]
#define pawnAttacks(turn, sq) PAtt[turn][sq]
#define popcount pop1
inline int poplsb(uint64* bb)
{
int retval = lsb(*bb);
*bb &= *bb - 1;
return retval;
}
#include "pyrrhic/tbprobe.cpp"
#undef popcount
#undef pawnAttacks
#undef knightAttacks
#undef bishopAttacks
#undef rookAttacks
#undef kingAttacks
using namespace std; // only after Pyrrhic
// helper to divide intermediate quantities to form scores
// note that straight integer division (a la Gull) creates an attractor at 0
// we support this, especially for weights inherited from Gull which have not been tuned for Roc
template<int DEN, int SINK = DEN> struct Div_
{
constexpr int operator()(int x) const
{
constexpr int shift = std::numeric_limits<int>::max() / (2 * DEN);
constexpr int shrink = (SINK - DEN) / 2;
const int y = x > 0 ? Max(0, x - shrink) : Min(0, x + shrink);
return (y + DEN * shift) / DEN - shift;
}
};
namespace PstW
{
struct Weights_
{
struct Phase_
{
array<int, 4> quad_;
array<int, 4> linear_;
array<int, 2> quadMixed_;
} op_, md_, eg_, cl_;
};
constexpr Weights_ Pawn = {
{ { -48, -275, 165, 0 },{ -460, -357, -359, 437 },{ 69, -28 } },
{ { -85, -171, 27, 400 },{ -160, -133, 93, 1079 },{ 13, -6 } },
{ { -80, -41, -85, 782 },{ 336, 303, 295, 1667 },{ -35, 13 } },
{ { 2, 13, 11, 23 },{ 6, 14, 37, -88 },{ 14, -2 } } };
constexpr Weights_ Knight = {
{ { -134, 6, -12, -72 },{ -680, -343, -557, 1128 },{ -32, 14 } },
{ { -315, -123, -12, -90 },{ -449, -257, -390, 777 },{ -24, -3 } },
{ { -501, -246, -12, -107 },{ 61, -274, -357, 469 },{ -1, -16 } },
{ { -12, -5, -2, -22 },{ 96, 69, -64, -23 },{ -5, -8 } } };
constexpr Weights_ Bishop = {
{ { -123, -62, 54, -116 },{ 24, -486, -350, -510 },{ 8, -58 } },
{ { -168, -49, 24, -48 },{ -323, -289, -305, -254 },{ -7, -21 } },
{ { -249, -33, 4, -14 },{ -529, -232, -135, 31 },{ -32, 0 } },
{ { 4, -10, 9, -13 },{ 91, -43, -34, 29 },{ -13, -10 } } };
constexpr Weights_ Rook = {
{ { -260, 12, -49, 324 },{ -777, -223, 245, 670 },{ -7, -25 } },
{ { -148, -88, -9, 165 },{ -448, -278, -63, 580 },{ -7, 0 } },
{ { 13, -149, 14, 46 },{ -153, -225, -246, 578 },{ -6, 16 } },
{ { 0, 8, -15, 8 },{ -32, -29, 10, -51 },{ -6, -23 } } };
constexpr Weights_ Queen = {
{ { -270, -18, -19, -68 }, { -520, 444, 474, -186 }, { 18, -6 } },
{ { -114, -209, 21, -103 }, { -224, -300, 73, 529 }, { -13, 1 } },
{ { 2, -341, 58, -160 }, { 40, -943, -171, 1328 }, { -34, 27 } },
{ { -3, -26, 9, 5 }, { -43, -18, -107, 60 }, { 5, 12 } } };
constexpr Weights_ King = {
{ { -266, -694, -12, 170 }, { 1077, 3258, 20, -186 }, { -18, 3 } },
{ { -284, -451, -31, 43 }, { 230, 1219, -425, 577 }, { -1, 5 } },
{ { -334, -157, -67, -93 }, { -510, -701, -863, 1402 }, { 37, -8 } },
{ { 22, 14, -16, 0 }, { 7, 70, 40, 78 }, { 9, -3 } } };
}
constexpr std::array<std::array<packed_t, 64>, 16> MakePst()
{
constexpr std::array<sint8, 8> DistC = { 3, 2, 1, 0, 0, 1, 2, 3 };
constexpr std::array<sint8, 8> RankR = { -3, -2, -1, 0, 1, 2, 3, 4 };
std::array<std::array<packed_t, 64>, 16> retval = {};
for (int i = 0; i < 64; ++i)
{
int r = RankOf(i);
int f = FileOf(i);
int d = f > r ? f - r : r - f;
int e = f + r > 7 ? f + r - 7 : 7 - f - r;
array<int, 4> distL = { DistC[f], DistC[r], RankR[d] + RankR[e], RankR[r] };
array<int, 4> distQ = { DistC[f] * DistC[f], DistC[r] * DistC[r], RankR[d] * RankR[d] + RankR[e] * RankR[e], RankR[r] * RankR[r] };
array<int, 2> distM = { DistC[f] * DistC[r], DistC[f] * RankR[r] };
array<const PstW::Weights_*, 6> weights = { &PstW::Pawn, &PstW::Knight, &PstW::Bishop, &PstW::Rook, &PstW::Queen, &PstW::King };
for (int j = 2; j < 16; j += 2)
{
int index = PieceType[j];
const PstW::Weights_& src = *weights[index];
int op = 0, md = 0, eg = 0, cl = 0;
for (int k = 0; k < 2; ++k)
{
op += src.op_.quadMixed_[k] * distM[k];
md += src.md_.quadMixed_[k] * distM[k];
eg += src.eg_.quadMixed_[k] * distM[k];
cl += src.cl_.quadMixed_[k] * distM[k];
}
for (int k = 0; k < 4; ++k)
{
op += src.op_.quad_[k] * distQ[k] + src.op_.linear_[k] * distL[k];
md += src.md_.quad_[k] * distQ[k] + src.md_.linear_[k] * distL[k];
eg += src.eg_.quad_[k] * distQ[k] + src.eg_.linear_[k] * distL[k];
cl += src.cl_.quad_[k] * distQ[k] + src.cl_.linear_[k] * distL[k];
}
// Regularize(&op, &md, &eg);
Div_<64> d64;
retval[j][i] = Pack(d64(op), d64(md), d64(eg), d64(cl));
}
}
retval[WhiteKnight][56] -= Pack(100 * CP_EVAL, 0);
retval[WhiteKnight][63] -= Pack(100 * CP_EVAL, 0);
// now for black
for (int i = 0; i < 64; ++i)
for (int j = 3; j < 16; j += 2)
{
auto src = retval[j - 1][63 - i];
retval[j][i] = Pack(-Opening(src), -Middle(src), -Endgame(src), -Closed(src));
}
return retval;
}
constexpr std::array<std::array<packed_t, 64>, 16> PstVals = MakePst();
INLINE packed_t Pst(int piece, int sq)
{
return PstVals[piece][sq];
};
INLINE int* AddMove(int* list, int from, int to, int flags, int score)
{
*list = ((from) << 6) | (to) | (flags) | (score);
return ++list;
}
INLINE int* AddCapturePP(int* list, int att, int vic, int from, int to)
{
return AddMove(list, from, to, 0, MvvLva[att][vic]);
}
INLINE int* AddCaptureP(int* list, const Board_& board, int piece, int from, int to)
{
return AddCapturePP(list, piece, board.PieceAt(to), from, to);
}
INLINE int* AddCaptureP(int* list, const Board_& board, int piece, int from, int to, uint8 min_vic)
{
return AddCapturePP(list, piece, Max(min_vic, board.PieceAt(to)), from, to);
}
INLINE int* AddCapture(int* list, const Board_& board, int from, int to)
{
return AddCaptureP(list, board, board.PieceAt(from), from, to);
}
INLINE uint16 JoinFlag(uint16 move)
{
return (move & FlagCastling) ? 1 : 0;
}
INLINE uint16& HistoryScore(State_* state, int join, int piece, int from, int to)
{
return state->historyVals_[piece][to][join];
}
INLINE int HistoryMerit(uint16 hs)
{
return hs / (1 | ((hs & 0x00FF) << 1));
}
INLINE int HistoryP(State_* state, int join, int piece, int from, int to)
{
return HistoryMerit(HistoryScore(state, join, piece, from, to)) << 16;
}
INLINE int History(State_* state, int join, int from, int to)
{
return HistoryP(state, join, state->board_.PieceAt(from), from, to);
}
INLINE uint16& HistoryM(State_* state, int move)
{
return HistoryScore(state, JoinFlag(move), state->board_.PieceAt(From(move)), From(move), To(move));
}
INLINE int HistoryInc(int depth)
{
return Square(Min((depth) >> 1, 8));
}
INLINE void HistoryBad(uint16* hist, int inc)
{
if ((*hist & 0x00FF) >= 256 - inc)
*hist = ((*hist & 0xFEFE) >> 1);
*hist += inc;
}
INLINE void HistoryBad(State_* state, int move, int depth)
{
HistoryBad(&HistoryM(state, move), HistoryInc(depth));
}
INLINE void HistoryGood(uint16* hist, int inc)
{
HistoryBad(hist, inc);
*hist += inc << 8;
}
INLINE void HistoryGood(State_* state, int move, int depth)
{
HistoryGood(&HistoryM(state, move), HistoryInc(depth));
}
INLINE int* AddHistoryP(State_* state, int* list, int piece, int from, int to, int flags)
{
return AddMove(list, from, to, flags, HistoryP(state, JoinFlag(flags), piece, from, to));
}
INLINE int* AddHistoryP(State_* state, int* list, int piece, int from, int to, int flags, uint8 p_min)
{
return AddMove(list, from, to, flags, max(int(p_min) << 16, HistoryP(state, JoinFlag(flags), piece, from, to)));
}
INLINE sint16& DeltaScore(State_* state, int piece, int from, int to)
{
return state->deltaVals_[(piece << 12) | (from << 6) | to];
}
INLINE sint16& Delta(State_* state, int from, int to)
{
return DeltaScore(state, state->board_.PieceAt(from), from, to);
}
INLINE sint16& DeltaM(State_* state, int move)
{
return Delta(state, From(move), To(move));
}
INLINE int* AddCDeltaP(State_* state, int* list, int margin, int piece, int from, int to, int flags)
{
return DeltaScore(state, piece, from, to) < margin
? list
: AddMove(list, from, to, flags, (DeltaScore(state, piece, from, to) + 0x4000) << 16);
}
#ifdef CPU_TIMING
int CpuTiming = 0, UciMaxDepth = 0, UciMaxKNodes = 0, UciBaseTime = 1000, UciIncTime = 5;
int GlobalTime[2] = { 0, 0 };
int GlobalInc[2] = { 0, 0 };
int GlobalTurn = 0;
constexpr sint64 CyclesPerMSec = 3400000;
#endif
constexpr int Aspiration = 1, LargePages = 1;
constexpr int TimeSingTwoMargin = 20;
constexpr int TimeSingOneMargin = 30;
constexpr int TimeNoPVSCOMargin = 60;
constexpr int TimeNoChangeMargin = 70;
constexpr int TimeRatio = 120;
constexpr int PonderRatio = 120;
constexpr int InfoLag = 5000;
constexpr int InfoDelay = 1000;
time_point StartTime, InfoTime, CurrTime;
uint16 SMoves[256];
jmp_buf Jump, ResetJump;
HANDLE StreamHandle;
INLINE int ExclSingle(int depth)
{
return 8 * CP_SEARCH;
}
INLINE int ExclDouble(int depth)
{
return 16 * CP_SEARCH;
}
// EVAL
const sint8 DistC[8] = { 3, 2, 1, 0, 0, 1, 2, 3 };
const sint8 RankR[8] = { -3, -2, -1, 0, 1, 2, 3, 4 };
constexpr uint16 SeeValue[16] = { 0, 0, 360, 360, 1300, 1300, 1300, 1300, 1300, 1300, 2040, 2040, 3900, 3900, 30000, 30000 };
constexpr array<int, 5> Phase = { 0, SeeValue[4], SeeValue[6], SeeValue[10], SeeValue[12] };
constexpr int PhaseMin = 2 * Phase[3] + Phase[1] + Phase[2];
constexpr int PhaseMax = 16 * Phase[0] + 3 * Phase[1] + 3 * Phase[2] + 4 * Phase[3] + 2 * Phase[4];
#define V(x) (x)
template<class T_> constexpr auto Av(const T_& x, int width, int row, int column) -> decltype(x[0])
{
return x[row * width + column];
}
template<class T_> constexpr auto TrAv(const T_& x, int w, int r, int c) -> decltype(x[0])
{
return x[(r * (2 * w - r + 1)) / 2 + c];
}
template<int N> constexpr array<packed_t, N / 4> PackAll(const array<int, N>& src)
{
const int M = N / 4;
array<packed_t, M> dst;
for (int ii = 0; ii < M; ++ii)
dst[ii] = Pack(src[4 * ii], src[4 * ii + 1], src[4 * ii + 2], src[4 * ii + 3]);
return dst;
}
// EVAL WEIGHTS
// pawn, knight, bishop, rook, queen, pair
constexpr array<int, 6> MatLinear = { 39, -11, -14, 86, -15, -1 };
constexpr int MatWinnable = 1;
// T(pawn), pawn, knight, bishop, rook, queen
const int MatQuadMe[21] = { // tuner: type=array, var=1000, active=0
NULL, 0, 0, 0, 0, 0,
-33, 17, -23, -155, -247,
15, 296, -105, -83,
-162, 327, 315,
-861, -1013,
NULL
};
const int MatQuadOpp[15] = { // tuner: type=array, var=1000, active=0
0, 0, 0, 0, 0,
-14, -96, -20, -278,
35, 39, 49,
9, -2,
75
};
const int BishopPairQuad[9] = { // tuner: type=array, var=1000, active=0
-38, 164, 99, 246, -84, -57, -184, 88, -186
};
constexpr array<int, 6> MatClosed = { -20, 22, -33, 18, -2, 26 };
namespace Values
{
static const packed_t MatRB = Pack(52, 0, -52, 0);
static const packed_t MatRN = Pack(40, 2, -36, 0);
static const packed_t MatQRR = Pack(32, 40, 48, 0);
static const packed_t MatQRB = Pack(16, 20, 24, 0);
static const packed_t MatQRN = Pack(20, 28, 36, 0);
static const packed_t MatQ3 = Pack(-12, -22, -32, 0);
static const packed_t MatBBR = Pack(-10, 20, 64, 0);
static const packed_t MatBNR = Pack(6, 21, 20, 0);
static const packed_t MatNNR = Pack(0, -12, -24, 0);
static const packed_t MatM = Pack(4, 8, 12, 0);
static const packed_t MatPawnOnly = Pack(0, 0, 0, -50);
}
// coefficient (Linear, Log, Locus) * phase (4)
constexpr array<int, 12> MobCoeffsKnight = { 1281, 857, 650, 27, 2000, 891, 89, -175, 257, 206, 0, 163 };
constexpr array<int, 12> MobCoeffsBishop = { 1484, 748, 558, 127, 1687, 1644, 1594, -565, 0, 337, 136, 502 };
constexpr array<int, 12> MobCoeffsRook = { 1096, 887, 678, 10, -565, 248, 1251, -5, 74, 72, 45, -12 };
constexpr array<int, 12> MobCoeffsQueen = { 597, 876, 1152, -7, 1755, 324, -1091, -9, 78, 100, 17, -12 };
constexpr int N_LOCUS = 22;
// file type (3) * distance from 2d rank/open (5)
constexpr array<int, 15> ShelterValue = { // tuner: type=array, var=26, active=0
8, 36, 44, 0, 0, // h-pawns
48, 72, 44, 0, 8, // g
96, 28, 32, 0, 0 // f
};
enum
{
StormHofValue,
StormHofScale,
StormOfValue,
StormOfScale
};
constexpr array<int, 4> ShelterMod = { 0, 0, 88, 0 };
namespace StormValues
{
constexpr std::array<sint16, 4> Blocked = { 3, 11, 30, 58 };
constexpr std::array<sint16, 4> ShelterAtt = { 6, 25, 71, 143 };
constexpr std::array<sint16, 4> Connected = { 17, 53, 126, 236 };
constexpr std::array<sint16, 4> Open = { 12, 34, 73, 128 };
constexpr std::array<sint16, 4> Free = { 0, 4, 15, 34 };
}
namespace PasserValues
{
// not much point in using 3 parameters for 4 degrees of freedom
constexpr array<packed_t, 7> Candidate = { 0ull, 0ull, 0ull, Pack(10, 10, 0, 0), Pack(26, 24, 5, 0), Pack(49, 42, 17, 0), Pack(79, 64, 37, 0) }; // 3-wide group where our pawns outnumber his
constexpr array<packed_t, 7> General = { 0ull, 0ull, 0ull, Pack(6, 4, 3, 14), Pack(31, 16, 6, 11), Pack(56, 48, 18, 7), Pack(81, 91, 36, 4) };
constexpr array<packed_t, 7> Protected = { 0ull, 0ull, 0ull, Pack(0, 5, 28, 11), Pack(23, 53, 66, 26), Pack(91, 138, 148, 10), Pack(174, 242, 261, 0) }; // supported by our pawn
constexpr array<packed_t, 7> Outside = { 0ull, 0ull, 0ull, Pack(20, 18, 10, 3), Pack(54, 40, 20, 0), Pack(87, 76, 21, 0), Pack(120, 123, 16, 0) }; // is easternmost/westernmost of all pawns
constexpr array<packed_t, 7> Movable = { 0ull, 0ull, 0ull, Pack(21, 18, 19, 21), Pack(58, 51, 37, 20), Pack(103, 113, 61, 15), Pack(154, 189, 89, 11) }; // can be pushed now
constexpr array<packed_t, 7> Clear = { 0ull, 0ull, 0ull, Pack(10, 11, 12, 0), Pack(30, 33, 36, 0), Pack(68, 74, 80, 0), Pack(121, 131, 142, 0) }; // no opponent pieces in path
constexpr array<packed_t, 7> Connected = { 0ull, 0ull, 0ull, Pack(12, 10, 11, 0), Pack(30, 29, 30, 0), Pack(57, 66, 56, 13), Pack(92, 112, 79, 36) }; // clear && directly beside another passer
constexpr array<packed_t, 7> Free = { 0ull, 0ull, 0ull, Pack(53, 49, 72, 0), Pack(95, 124, 166, 0), Pack(116, 274, 378, 3), Pack(121, 468, 672, 6) }; // clear && no sq
constexpr array<packed_t, 7> Supported = { 0ull, 0ull, 0ull, Pack(41, 36, 33, 5), Pack(90, 84, 77, 2), Pack(141, 157, 172, 0), Pack(194, 246, 297, 0) }; // clear && directly backed by major
}
// type (2: att, def) * scaling (2: linear, log)
constexpr array<int, 4> PasserAttDefQuad = { // tuner: type=array, var=500, active=0
764, 204, 332, 76
};
constexpr array<int, 4> PasserAttDefLinear = { // tuner: type=array, var=500, active=0
2536, 16, 932, 264
};
constexpr array<int, 4> PasserAttDefConst = { // tuner: type=array, var=500, active=0
0, 0, 0, 0
};
enum { PasserOnePiece, PasserOpKingControl, PasserOpMinorControl, PasserOpRookBlock };
// case(4) * phase(3 -- no opening)
constexpr array<int, 12> PasserSpecial = { // tuner: type=array, var=100, active=0
26, 52, 0
};
namespace Values
{
constexpr packed_t PasserOpRookBlock =
Pack(0, Av(PasserSpecial, 3, ::PasserOpRookBlock, 0), Av(PasserSpecial, 3, ::PasserOpRookBlock, 1), Av(PasserSpecial, 3, ::PasserOpRookBlock, 2));
}
namespace Values
{
constexpr packed_t IsolatedOpen = Pack(36, 28, 19, 1);
constexpr packed_t IsolatedClosed = Pack(40, 21, 1, 12);
constexpr packed_t IsolatedBlocked = Pack(-40, -20, -3, -3);
constexpr packed_t IsolatedDoubledOpen = Pack(0, 10, 45, 3);
constexpr packed_t IsolatedDoubledClosed = Pack(27, 27, 36, 8);
constexpr packed_t UpBlocked = Pack(18, 45, 31, -6);
constexpr packed_t PasserTarget = Pack(-16, -36, -38, 22);
constexpr packed_t PasserTarget2 = Pack(-3, -10, -39, 9);
constexpr packed_t ChainRoot = Pack(7, -3, -3, -14);
constexpr packed_t BackwardOpen = Pack(77, 63, 42, -8);
constexpr packed_t BackwardClosed = Pack(21, 11, 12, -1);
constexpr packed_t DoubledOpen = Pack(12, 6, 0, 0);
constexpr packed_t DoubledClosed = Pack(4, 2, 0, 0);
constexpr packed_t RookHof = Pack(32, 16, 0, 0);
constexpr packed_t RookHofWeakPAtt = Pack(8, 4, 0, 0);
constexpr packed_t RookOf = Pack(44, 38, 32, 0);
constexpr packed_t RookOfOpen = Pack(-4, 2, 8, 0);
constexpr packed_t RookOfMinorFixed = Pack(-4, -4, -4, 0);
constexpr packed_t RookOfMinorHanging = Pack(56, 26, -4, 0);
constexpr packed_t RookOfKingAtt = Pack(20, 0, -20, 0);
constexpr packed_t Rook7th = Pack(-20, -10, 0, 0);
constexpr packed_t Rook7thK8th = Pack(-24, 4, 32, 0);
constexpr packed_t Rook7thDoubled = Pack(-28, 48, 124, 0);
constexpr packed_t TacticalQueenPawn = Pack(4, 1, 3, 3);
constexpr packed_t TacticalQueenMinor = Pack(53, 20, 69, -7);
constexpr packed_t TacticalRookPawn = Pack(6, 11, 37, 22);
constexpr packed_t TacticalRookMinor = Pack(29, 29, 66, 10);
constexpr packed_t TacticalBishopPawn = Pack(0, 28, 35, 30);
constexpr packed_t TacticalB2N = Pack(26, 59, 71, 30);
constexpr packed_t TacticalN2B = Pack(89, 78, 74, 20);
constexpr packed_t Threat = Pack(79, 64, 45, -3);
constexpr packed_t ThreatDouble = Pack(164, 106, 48, 0);
constexpr packed_t KingDefKnight = Pack(8, 4, 0, 0);
constexpr packed_t KingDefQueen = Pack(16, 8, 0, 0);
constexpr packed_t PawnChainLinear = Pack(44, 40, 36, 0);
constexpr packed_t PawnChain = Pack(36, 26, 16, 0);
constexpr packed_t PawnBlocked = Pack(0, 18, 36, 0);
constexpr packed_t PawnRestrictsK = Pack(23, 9, 1, 45);
constexpr packed_t BishopPawnBlock = Pack(0, 6, 14, 6);
constexpr packed_t BishopOutpostNoMinor = Pack(60, 60, 45, 0);
constexpr packed_t KnightOutpost = Pack(40, 36, 24, 0);
constexpr packed_t KnightOutpostProtected = Pack(41, 31, 0, 0);
constexpr packed_t KnightOutpostPawnAtt = Pack(44, 38, 18, 0);
constexpr packed_t KnightOutpostNoMinor = Pack(41, 31, 0, 0);
constexpr packed_t KnightPawnSpread = Pack(0, 4, 15, -10);
constexpr packed_t KnightPawnGap = Pack(0, 2, 5, 0);
constexpr packed_t QueenPawnPin = Pack(34, 44, 42, 59);
constexpr packed_t QueenSelfPin = Pack(88, 232, -45, 130);
constexpr packed_t QueenWeakPin = Pack(86, 108, 72, 56);
constexpr packed_t RookPawnPin = Pack(121, 39, 1, 39);
constexpr packed_t RookSelfPin = Pack(25, 170, 71, 165);
constexpr packed_t RookWeakPin = Pack(68, 153, 146, 108);
constexpr packed_t RookThreatPin = Pack(632, 716, 614, -190);
constexpr packed_t BishopPawnPin = Pack(58, 130, 106, 46);
constexpr packed_t BishopSelfPin = Pack(233, 249, 122, 52);
constexpr packed_t StrongPin = Pack(-16, 136, 262, -22);
constexpr packed_t BishopThreatPin = Pack(342, 537, 629, -34);
constexpr packed_t QKingRay = Pack(17, 26, 33, -2);
constexpr packed_t RKingRay = Pack(-14, 15, 42, 0);
constexpr packed_t BKingRay = Pack(43, 14, -9, -1);
}
constexpr array<int, 12> KingAttackWeight = { // tuner: type=array, var=51, active=0
65, 79, 50, 58, 70, 94, 137, 191, 16, 192, 256, 64 };
constexpr uint16 KingAttackThreshold = 48;
constexpr array<uint64, 2> Outpost = { 0x00007E7E3C000000ull, 0x0000003C7E7E0000ull };
constexpr array<int, 2> PushW = { 7, -9 };
constexpr array<int, 2> Push = { 8, -8 };
constexpr array<int, 2> PushE = { 9, -7 };
constexpr uint32 KingNAttack1 = Pack(1, KingAttackWeight[0]);
constexpr uint32 KingNAttack = Pack(2, KingAttackWeight[1]);
constexpr uint32 KingBAttack1 = Pack(1, KingAttackWeight[2]);
constexpr uint32 KingBAttack = Pack(2, KingAttackWeight[3]);
constexpr uint32 KingRAttack1 = Pack(1, KingAttackWeight[4]);
constexpr uint32 KingRAttack = Pack(2, KingAttackWeight[5]);
constexpr uint32 KingQAttack1 = Pack(1, KingAttackWeight[6]);
constexpr uint32 KingQAttack = Pack(2, KingAttackWeight[7]);
constexpr uint32 KingPAttack = Pack(2, 0);
constexpr uint32 KingPRestrict = Pack(2, 58);
constexpr uint32 KingAttack = Pack(1, 0);
constexpr uint32 KingPAttackInc = Pack(0, KingAttackWeight[8]);
constexpr uint32 KingAttackSquare = KingAttackWeight[9];
constexpr uint32 KingNoMoves = KingAttackWeight[10];
constexpr uint32 KingShelterQuad = KingAttackWeight[11]; // a scale factor, not a score amount
template<int N> array<uint16, N> CoerceUnsigned(const array<int, N>& src)
{
array<uint16, N> retval;
for (int ii = 0; ii < N; ++ii)
retval[ii] = static_cast<uint16>(max(0, src[ii]));
return retval;
}
constexpr array<uint16, 16> XKingAttackScale = { 0, 1, 1, 2, 4, 5, 8, 12, 15, 19, 23, 28, 34, 39, 39, 39 };
// tuner: stop
// END EVAL WEIGHTS
#define log_msg(...)
#define error_msg(format, ...) \
do { \
log_msg("error_msg: " format "\n", ##__VA_ARGS__); \
fprintf(stderr, "error_msg: " format "\n", ##__VA_ARGS__); \
abort(); \
} while (false)
// data sharing for multithreading
void delete_object(void *addr, size_t size)
{
if (!UnmapViewOfFile(addr))
error_msg("failed to unmap object (%d)", GetLastError());
}
// SMP
// Windows threading routines
constexpr size_t PAGE_SIZE = 4096;
constexpr int PIPE_BUF = 4096;
constexpr int PATH_MAX = 4096;
inline size_t size_to_page(size_t size)
{
return ((size - 1) / PAGE_SIZE) * PAGE_SIZE + PAGE_SIZE;
}
int get_num_cpus()
{
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
}
string object_name(const char *basename, int id, int idx)
{
return "Local\\Roc" + to_string(id) + basename + to_string(idx);
}
static DWORD forward_input(void* param)
{
char buf[4 * PIPE_BUF];
HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
HANDLE out = (HANDLE)param;
while (true)
{
DWORD len;
if (!ReadFile(in, buf, sizeof(buf), &len, NULL))
error_msg("failed to read input (%d)", GetLastError());
if (len == 0)
{
CloseHandle(out);
return 0;
}
DWORD ptr = 0;
while (ptr < len)
{
DWORD writelen;
if (!WriteFile(out, buf + ptr, len - ptr, &writelen, NULL))
error_msg("failed to forward input (%d)", GetLastError());
ptr += writelen;
}
FlushFileBuffers(out);
}
}
struct AspirationState_
{
int depth_, alpha_, beta_, delta_;
};
constexpr AspirationState_ ASPIRATION_INIT = { 2, -200, 200, 50 };
struct RootScores_
{
struct Record_
{
uint16 depth_, move_;
score_t lower_, upper_;
};
vector<Record_> results_;
void Add(uint16 move, score_t score, uint16 depth, score_t alpha, score_t beta)
{
if (score <= alpha)
return; // nothing learned
if (depth >= results_.size())
results_.resize(depth + 1, { 0, 0, -MateValue, -MateValue });
if (score >= results_[depth].lower_)
{
results_[depth] = { depth, move, score, score < beta ? score : MateValue };
if (TheShare.depth_ < depth)