-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrelude.cpp
3752 lines (3064 loc) · 131 KB
/
Prelude.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
/*
Prelude
Copyright (C) 2024 Quinniboi10
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 <https://www.gnu.org/licenses/>.
*/
// TODO (Ordered):
// More pruning in search
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <deque>
#include <chrono>
#include <array>
#include <bitset>
#include <algorithm>
#include <cassert>
#include <optional>
#include <thread>
#include <memory>
#include <random>
#include <cstring>
#include <cstdlib>
#include <immintrin.h>
#ifndef EVALFILE
#define EVALFILE "./nnue.bin"
#endif
#ifdef _MSC_VER
#define MSVC
#pragma push_macro("_MSC_VER")
#undef _MSC_VER
#endif
#include "./external/incbin.h"
#ifdef MSVC
#pragma pop_macro("_MSC_VER")
#undef MSVC
#endif
#if !defined(_MSC_VER) || defined(__clang__)
INCBIN(EVAL, EVALFILE);
#endif
int getLine(int line) { return line; }
#define exit(code) \
cout << "Exit from line " << getLine(__LINE__) << endl; \
exit(code);
#define ctzll(x) std::countr_zero(x)
#define popcountll(x) std::popcount(x)
#ifdef DEBUG
constexpr bool ISDBG = true;
#else
constexpr bool ISDBG = false;
#endif
#define IFDBG if constexpr (ISDBG)
using std::cerr;
using std::string;
using std::array;
using std::cout;
using std::endl;
#define m_assert(expr, msg) assert(((void) (msg), (expr)))
using u64 = uint64_t;
using u32 = uint32_t;
using u16 = uint16_t;
using u8 = uint8_t;
using i64 = int64_t;
using i32 = int32_t;
using i16 = int16_t;
constexpr u64 INF = std::numeric_limits<uint64_t>::max();
constexpr int INF_INT = std::numeric_limits<int>::max();
enum Color : int {
WHITE = 1,
BLACK = 0
};
//Inverts the color (WHITE -> BLACK) and (BLACK -> WHITE)
constexpr Color operator~(Color c) { return Color(c ^ 1); }
enum PieceType : int {
PAWN,
KNIGHT,
BISHOP,
ROOK,
QUEEN,
KING,
NO_PIECE_TYPE
};
array<int, 5> kPieceValues = {100, 316, 328, 493, 982};
// clang-format off
enum Square : int {
a1, b1, c1, d1, e1, f1, g1, h1,
a2, b2, c2, d2, e2, f2, g2, h2,
a3, b3, c3, d3, e3, f3, g3, h3,
a4, b4, c4, d4, e4, f4, g4, h4,
a5, b5, c5, d5, e5, f5, g5, h5,
a6, b6, c6, d6, e6, f6, g6, h6,
a7, b7, c7, d7, e7, f7, g7, h7,
a8, b8, c8, d8, e8, f8, g8, h8,
NO_SQUARE
};
enum Direction : int {
NORTH = 8,
NORTH_EAST = 9,
EAST = 1,
SOUTH_EAST = -7,
SOUTH = -8,
SOUTH_WEST = -9,
WEST = -1,
NORTH_WEST = 7,
NORTH_NORTH = 16,
SOUTH_SOUTH = -16
};
enum File : int {
AFILE, BFILE, CFILE, DFILE, EFILE, FFILE, GFILE, HFILE
};
enum Rank : int {
RANK1, RANK2, RANK3, RANK4, RANK5, RANK6, RANK7, RANK8
};
Square& operator++(Square& s) { return s = Square(int(s) + 1); }
Square& operator--(Square& s) { return s = Square(int(s) - 1); }
constexpr Square operator+(Square s, Direction d) { return Square(int(s) + int(d)); }
constexpr Square operator-(Square s, Direction d) { return Square(int(s) - int(d)); }
Square& operator+=(Square& s, Direction d) { return s = s + d; }
Square& operator-=(Square& s, Direction d) { return s = s - d; }
//clang-format on
static inline const union {
uint32_t i;
char c[4];
} Le = { 0x01020304 };
static inline const bool IsLittleEndian = (Le.c[0] == 4);
// Names binary encoding flags from Move class
enum MoveType {
STANDARD_MOVE = 0, DOUBLE_PUSH = 0b1, CASTLE_K = 0b10, CASTLE_Q = 0b11, CAPTURE = 0b100, EN_PASSANT = 0b101, KNIGHT_PROMO = 0b1000, BISHOP_PROMO = 0b1001, ROOK_PROMO = 0b1010, QUEEN_PROMO = 0b1011, KNIGHT_PROMO_CAPTURE = 0b1100, BISHOP_PROMO_CAPTURE = 0b1101, ROOK_PROMO_CAPTURE = 0b1110, QUEEN_PROMO_CAPTURE = 0b1111
};
enum flags {
UNDEFINED, FAILLOW, BETACUTOFF, EXACT
};
struct Colors {
// ANSI codes for colors https://raw.githubusercontent.com/fidian/ansi/master/images/color-codes.png
constexpr static const string reset = "\033[0m";
// Basic colors
constexpr static const string black = "\033[30m";
constexpr static const string red = "\033[31m";
constexpr static const string green = "\033[32m";
constexpr static const string yellow = "\033[33m";
constexpr static const string blue = "\033[34m";
constexpr static const string magenta = "\033[35m";
constexpr static const string cyan = "\033[36m";
constexpr static const string white = "\033[37m";
// Bright colors
constexpr static const string bright_black = "\033[90m";
constexpr static const string bright_red = "\033[91m";
constexpr static const string bright_green = "\033[92m";
constexpr static const string bright_yellow = "\033[93m";
constexpr static const string bright_blue = "\033[94m";
constexpr static const string bright_magenta = "\033[95m";
constexpr static const string bright_cyan = "\033[96m";
constexpr static const string bright_white = "\033[97m";
constexpr static const string grey = bright_black;
};
static int parseSquare(const string& square) {
return (square.at(1) - '1') * 8 + (square.at(0) - 'a'); // Calculate the index of any square
}
static string squareToAlgebraic(int sq) {
return string(1, 'a' + (sq % 8)) + string(1, '1' + (sq / 8));
};
template <typename BitboardType>
static bool readBit(BitboardType bitboard, int index) {
return (bitboard & (1ULL << index)) != 0;
}
template <typename BitboardType>
static void setBit(BitboardType& bitboard, int index, bool value) {
if (value) bitboard |= (1ULL << index);
else bitboard &= ~(1ULL << index);
}
class Board;
class Move {
// Bit indexes of various things
// See https://www.chessprogramming.org/Encoding_Moves
// Does not use double pawn push flag
// PROMO = 15
// CAPTURE = 14
// SPECIAL 1 = 13
// SPECIAL 0 = 12
private:
uint16_t move;
public:
constexpr Move() {
move = 0;
}
Move(string in, Board& board);
constexpr Move(u8 startSquare, u8 endSquare, int flags = STANDARD_MOVE) {
move = startSquare;
move |= endSquare << 6;
move |= flags << 12;
}
string toString();
int startSquare() { return move & 0b111111; }
int endSquare() { return (move >> 6) & 0b111111; }
MoveType typeOf() { return MoveType(move >> 12); } // Return the flag bits
bool isNull() { return !move; }
bool operator==(const Move other) const {
return move == other.move;
}
};
std::deque<string> split(const string& s, char delim) {
std::deque<string> result;
std::stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
result.push_back(item);
}
return result;
}
int getPadding(string str, int targetLen) {
targetLen -= str.length();
return std::max(targetLen, 2);
}
template<typename objType>
string padStr(objType obj, int targetLen) {
std::string objStr;
if constexpr (std::is_same_v<objType, std::string> || std::is_same_v<objType, std::basic_string<char>>) {
objStr = obj; // Strings make everything explode
}
else {
objStr = std::to_string(obj); // Convert other types
}
int padding = getPadding(objStr, targetLen);
for (int i = 0; i < padding; i++) {
objStr += " ";
}
return objStr;
}
template<typename objType>
int getLength(objType obj) {
return std::to_string(obj).length();
}
template<typename arrType>
int findIndexOf(const arrType arr, string entry) {
auto it = std::find(arr.begin(), arr.end(), entry);
if (it != arr.end()) {
return std::distance(arr.begin(), it); // Calculate the index
}
return -1; // Not found
}
void printBitboard(u64 bitboard) {
for (int rank = 7; rank >= 0; --rank) {
cout << "+---+---+---+---+---+---+---+---+" << endl;
for (int file = 0; file < 8; ++file) {
int i = rank * 8 + file; // Map rank and file to bitboard index
char currentPiece = readBit(bitboard, i) ? '1' : ' ';
cout << "| " << currentPiece << " ";
}
cout << "|" << endl;
}
cout << "+---+---+---+---+---+---+---+---+" << endl;
}
string formatTime(u64 timeInMS) {
long long seconds = timeInMS / 1000;
long long hours = seconds / 3600;
seconds %= 3600;
long long minutes = seconds / 60;
seconds %= 60;
string result;
if (hours > 0) result += std::to_string(hours) + "h ";
if (minutes > 0 || hours > 0) result += std::to_string(minutes) + "m ";
if (seconds > 0 || minutes > 0 || hours > 0) result += std::to_string(seconds) + "s";
if (result == "") return std::to_string(timeInMS) + "ms";
return result;
}
string formatNum(i64 v) {
auto s = std::to_string(v);
int n = s.length() - 3;
if (v < 0) n--;
while (n > 0) {
s.insert(n, ",");
n -= 3;
}
return s;
}
string abbreviateNum(const i64 v) {
if (v > 1000000000) return std::format("{:.2f} g", v / 1000000000.0);
if (v > 1000000) return std::format("{:.2f} m", v / 1000000.0);
if (v > 1000) return std::format("{:.2f} k", v / 1000.0);
return std::to_string(v) + " ";
}
class Precomputed {
public:
static array<array<array<u64, 64>, 12>, 2> zobrist;
// EP zobrist is 65 because ctzll of 0 returns 64
static array<u64, 65> zobristEP;
static array<u64, 16> zobristCastling;
static array<u64, 2> zobristSide;
static u64 isOnA;
static u64 isOnB;
static u64 isOnC;
static u64 isOnD;
static u64 isOnE;
static u64 isOnF;
static u64 isOnG;
static u64 isOnH;
static u64 isOn1;
static u64 isOn2;
static u64 isOn3;
static u64 isOn4;
static u64 isOn5;
static u64 isOn6;
static u64 isOn7;
static u64 isOn8;
static void compute() {
// *** FILE AND COL ARRAYS ***
isOnA = 0;
isOnB = 0;
isOnC = 0;
isOnD = 0;
isOnE = 0;
isOnF = 0;
isOnG = 0;
isOnH = 0;
isOn1 = 0;
isOn2 = 0;
isOn3 = 0;
isOn4 = 0;
isOn5 = 0;
isOn6 = 0;
isOn7 = 0;
isOn8 = 0;
for (int i = 0; i < 64; ++i) {
int file = i % 8; // File index (0 = A, 1 = B, ..., 7 = H)
if (file == 0) isOnA |= 1ULL << i;
if (file == 1) isOnB |= 1ULL << i;
if (file == 2) isOnC |= 1ULL << i;
if (file == 3) isOnD |= 1ULL << i;
if (file == 4) isOnE |= 1ULL << i;
if (file == 5) isOnF |= 1ULL << i;
if (file == 6) isOnG |= 1ULL << i;
if (file == 7) isOnH |= 1ULL << i;
// Fill ranks (1-8)
int rank = i / 8; // Rank index (0 = 1, 1 = 2, ..., 7 = 8)
if (rank == 0) isOn1 |= 1ULL << i;
if (rank == 1) isOn2 |= 1ULL << i;
if (rank == 2) isOn3 |= 1ULL << i;
if (rank == 3) isOn4 |= 1ULL << i;
if (rank == 4) isOn5 |= 1ULL << i;
if (rank == 5) isOn6 |= 1ULL << i;
if (rank == 6) isOn7 |= 1ULL << i;
if (rank == 7) isOn8 |= 1ULL << i;
}
// *** MAKE RANDOM ZOBRIST TABLE ****
std::random_device rd;
std::mt19937_64 engine(rd());
engine.seed(69420); // Nice
std::uniform_int_distribution<u64> dist(0, INF);
for (auto& side : zobrist) {
for (auto& pieceTable : side) {
for (auto& square : pieceTable) {
square = dist(engine);
}
}
}
for (auto& square : zobristEP) {
square = dist(engine);
}
// If no EP square, set it to 0
zobristEP[64] = 0;
for (auto& castlingValue : zobristCastling) {
castlingValue = dist(engine);
}
for (auto& sideValue : zobristSide) {
sideValue = dist(engine);
}
}
};
array<array<array<u64, 64>, 12>, 2> Precomputed::zobrist;
array<u64, 65> Precomputed::zobristEP;
array<u64, 16> Precomputed::zobristCastling;
array<u64, 2> Precomputed::zobristSide;
u64 Precomputed::isOnA;
u64 Precomputed::isOnB;
u64 Precomputed::isOnC;
u64 Precomputed::isOnD;
u64 Precomputed::isOnE;
u64 Precomputed::isOnF;
u64 Precomputed::isOnG;
u64 Precomputed::isOnH;
u64 Precomputed::isOn1;
u64 Precomputed::isOn2;
u64 Precomputed::isOn3;
u64 Precomputed::isOn4;
u64 Precomputed::isOn5;
u64 Precomputed::isOn6;
u64 Precomputed::isOn7;
u64 Precomputed::isOn8;
constexpr Rank rankOf(Square s) { return Rank(s >> 3); }
constexpr File fileOf(Square s) { return File(s & 0b111); }
constexpr Rank flipRank(Square s) { return Rank(s ^ 0b111000); }
template<Direction shiftDir>
u64 shift(u64 bb) {
if constexpr (shiftDir < 0) {
return bb >> -shiftDir;
}
return bb << shiftDir;
}
template<Color c>
u64 pawnAttacksBB(const int sq) {
const u64 pawnBB = 1ULL << sq;
if constexpr (c == WHITE) {
if (pawnBB & Precomputed::isOnA) return shift<NORTH_EAST>(pawnBB);
if (pawnBB & Precomputed::isOnH) return shift<NORTH_WEST>(pawnBB);
return shift<NORTH_EAST>(pawnBB) | shift<NORTH_WEST>(pawnBB);
}
else {
if (pawnBB & Precomputed::isOnA) return shift<SOUTH_EAST>(pawnBB);
if (pawnBB & Precomputed::isOnH) return shift<SOUTH_WEST>(pawnBB);
return shift<SOUTH_EAST>(pawnBB) | shift<SOUTH_WEST>(pawnBB);
}
}
// Tables from https://github.com/Disservin/chess-library/blob/cf3bd56474168605201a01eb78b3222b8f9e65e4/include/chess.hpp#L780
static constexpr u64 KnightAttacks[64] = {
0x0000000000020400, 0x0000000000050800, 0x00000000000A1100, 0x0000000000142200, 0x0000000000284400,
0x0000000000508800, 0x0000000000A01000, 0x0000000000402000, 0x0000000002040004, 0x0000000005080008,
0x000000000A110011, 0x0000000014220022, 0x0000000028440044, 0x0000000050880088, 0x00000000A0100010,
0x0000000040200020, 0x0000000204000402, 0x0000000508000805, 0x0000000A1100110A, 0x0000001422002214,
0x0000002844004428, 0x0000005088008850, 0x000000A0100010A0, 0x0000004020002040, 0x0000020400040200,
0x0000050800080500, 0x00000A1100110A00, 0x0000142200221400, 0x0000284400442800, 0x0000508800885000,
0x0000A0100010A000, 0x0000402000204000, 0x0002040004020000, 0x0005080008050000, 0x000A1100110A0000,
0x0014220022140000, 0x0028440044280000, 0x0050880088500000, 0x00A0100010A00000, 0x0040200020400000,
0x0204000402000000, 0x0508000805000000, 0x0A1100110A000000, 0x1422002214000000, 0x2844004428000000,
0x5088008850000000, 0xA0100010A0000000, 0x4020002040000000, 0x0400040200000000, 0x0800080500000000,
0x1100110A00000000, 0x2200221400000000, 0x4400442800000000, 0x8800885000000000, 0x100010A000000000,
0x2000204000000000, 0x0004020000000000, 0x0008050000000000, 0x00110A0000000000, 0x0022140000000000,
0x0044280000000000, 0x0088500000000000, 0x0010A00000000000, 0x0020400000000000 };
static constexpr u64 KingAttacks[64] = {
0x0000000000000302, 0x0000000000000705, 0x0000000000000E0A, 0x0000000000001C14, 0x0000000000003828,
0x0000000000007050, 0x000000000000E0A0, 0x000000000000C040, 0x0000000000030203, 0x0000000000070507,
0x00000000000E0A0E, 0x00000000001C141C, 0x0000000000382838, 0x0000000000705070, 0x0000000000E0A0E0,
0x0000000000C040C0, 0x0000000003020300, 0x0000000007050700, 0x000000000E0A0E00, 0x000000001C141C00,
0x0000000038283800, 0x0000000070507000, 0x00000000E0A0E000, 0x00000000C040C000, 0x0000000302030000,
0x0000000705070000, 0x0000000E0A0E0000, 0x0000001C141C0000, 0x0000003828380000, 0x0000007050700000,
0x000000E0A0E00000, 0x000000C040C00000, 0x0000030203000000, 0x0000070507000000, 0x00000E0A0E000000,
0x00001C141C000000, 0x0000382838000000, 0x0000705070000000, 0x0000E0A0E0000000, 0x0000C040C0000000,
0x0003020300000000, 0x0007050700000000, 0x000E0A0E00000000, 0x001C141C00000000, 0x0038283800000000,
0x0070507000000000, 0x00E0A0E000000000, 0x00C040C000000000, 0x0302030000000000, 0x0705070000000000,
0x0E0A0E0000000000, 0x1C141C0000000000, 0x3828380000000000, 0x7050700000000000, 0xE0A0E00000000000,
0xC040C00000000000, 0x0203000000000000, 0x0507000000000000, 0x0A0E000000000000, 0x141C000000000000,
0x2838000000000000, 0x5070000000000000, 0xA0E0000000000000, 0x40C0000000000000 };
// Magic code from https://github.com/nkarve/surge/blob/master/src/tables.cpp
constexpr int diagonalOf(Square s) { return 7 + rankOf(s) - fileOf(s); }
constexpr int antiDiagonalOf(Square s) { return rankOf(s) + fileOf(s); }
//Precomputed file masks
const u64 MASK_FILE[8] = {
0x101010101010101, 0x202020202020202, 0x404040404040404, 0x808080808080808,
0x1010101010101010, 0x2020202020202020, 0x4040404040404040, 0x8080808080808080,
};
//Precomputed rank masks
const u64 MASK_RANK[8] = {
0xff, 0xff00, 0xff0000, 0xff000000,
0xff00000000, 0xff0000000000, 0xff000000000000, 0xff00000000000000
};
//Precomputed diagonal masks
const u64 MASK_DIAGONAL[15] = {
0x80, 0x8040, 0x804020,
0x80402010, 0x8040201008, 0x804020100804,
0x80402010080402, 0x8040201008040201, 0x4020100804020100,
0x2010080402010000, 0x1008040201000000, 0x804020100000000,
0x402010000000000, 0x201000000000000, 0x100000000000000,
};
//Precomputed anti-diagonal masks
const u64 MASK_ANTI_DIAGONAL[15] = {
0x1, 0x102, 0x10204,
0x1020408, 0x102040810, 0x10204081020,
0x1020408102040, 0x102040810204080, 0x204081020408000,
0x408102040800000, 0x810204080000000, 0x1020408000000000,
0x2040800000000000, 0x4080000000000000, 0x8000000000000000,
};
//Precomputed square masks
const u64 SQUARE_BB[65] = {
0x1, 0x2, 0x4, 0x8,
0x10, 0x20, 0x40, 0x80,
0x100, 0x200, 0x400, 0x800,
0x1000, 0x2000, 0x4000, 0x8000,
0x10000, 0x20000, 0x40000, 0x80000,
0x100000, 0x200000, 0x400000, 0x800000,
0x1000000, 0x2000000, 0x4000000, 0x8000000,
0x10000000, 0x20000000, 0x40000000, 0x80000000,
0x100000000, 0x200000000, 0x400000000, 0x800000000,
0x1000000000, 0x2000000000, 0x4000000000, 0x8000000000,
0x10000000000, 0x20000000000, 0x40000000000, 0x80000000000,
0x100000000000, 0x200000000000, 0x400000000000, 0x800000000000,
0x1000000000000, 0x2000000000000, 0x4000000000000, 0x8000000000000,
0x10000000000000, 0x20000000000000, 0x40000000000000, 0x80000000000000,
0x100000000000000, 0x200000000000000, 0x400000000000000, 0x800000000000000,
0x1000000000000000, 0x2000000000000000, 0x4000000000000000, 0x8000000000000000,
0x0
};
//Reverses a bitboard
u64 reverse(u64 b) {
b = (b & 0x5555555555555555) << 1 | (b >> 1) & 0x5555555555555555;
b = (b & 0x3333333333333333) << 2 | (b >> 2) & 0x3333333333333333;
b = (b & 0x0f0f0f0f0f0f0f0f) << 4 | (b >> 4) & 0x0f0f0f0f0f0f0f0f;
b = (b & 0x00ff00ff00ff00ff) << 8 | (b >> 8) & 0x00ff00ff00ff00ff;
return (b << 48) | ((b & 0xffff0000) << 16) |
((b >> 16) & 0xffff0000) | (b >> 48);
}
//Calculates sliding attacks from a given square, on a given axis, taking into
//account the blocking pieces. This uses the Hyperbola Quintessence Algorithm.
u64 sliding_attacks(Square square, u64 occ, u64 mask) {
return (((mask & occ) - SQUARE_BB[square] * 2) ^
reverse(reverse(mask & occ) - reverse(SQUARE_BB[square]) * 2)) & mask;
}
//Returns rook attacks from a given square, using the Hyperbola Quintessence Algorithm. Only used to initialize
//the magic lookup table
u64 get_rook_attacks_for_init(Square square, u64 occ) {
return sliding_attacks(square, occ, MASK_FILE[fileOf(square)]) |
sliding_attacks(square, occ, MASK_RANK[rankOf(square)]);
}
u64 ROOK_ATTACK_MASKS[64];
int ROOK_ATTACK_SHIFTS[64];
u64 ROOK_ATTACKS[64][4096];
const u64 ROOK_MAGICS[64] = {
0x0080001020400080, 0x0040001000200040, 0x0080081000200080, 0x0080040800100080,
0x0080020400080080, 0x0080010200040080, 0x0080008001000200, 0x0080002040800100,
0x0000800020400080, 0x0000400020005000, 0x0000801000200080, 0x0000800800100080,
0x0000800400080080, 0x0000800200040080, 0x0000800100020080, 0x0000800040800100,
0x0000208000400080, 0x0000404000201000, 0x0000808010002000, 0x0000808008001000,
0x0000808004000800, 0x0000808002000400, 0x0000010100020004, 0x0000020000408104,
0x0000208080004000, 0x0000200040005000, 0x0000100080200080, 0x0000080080100080,
0x0000040080080080, 0x0000020080040080, 0x0000010080800200, 0x0000800080004100,
0x0000204000800080, 0x0000200040401000, 0x0000100080802000, 0x0000080080801000,
0x0000040080800800, 0x0000020080800400, 0x0000020001010004, 0x0000800040800100,
0x0000204000808000, 0x0000200040008080, 0x0000100020008080, 0x0000080010008080,
0x0000040008008080, 0x0000020004008080, 0x0000010002008080, 0x0000004081020004,
0x0000204000800080, 0x0000200040008080, 0x0000100020008080, 0x0000080010008080,
0x0000040008008080, 0x0000020004008080, 0x0000800100020080, 0x0000800041000080,
0x00FFFCDDFCED714A, 0x007FFCDDFCED714A, 0x003FFFCDFFD88096, 0x0000040810002101,
0x0001000204080011, 0x0001000204000801, 0x0001000082000401, 0x0001FFFAABFAD1A2
};
//Initializes the magic lookup table for rooks
void initializeRookAttacks() {
u64 edges, subset, index;
for (Square sq = a1; sq <= h8; ++sq) {
edges = ((MASK_RANK[AFILE] | MASK_RANK[HFILE]) & ~MASK_RANK[rankOf(sq)]) |
((MASK_FILE[AFILE] | MASK_FILE[HFILE]) & ~MASK_FILE[fileOf(sq)]);
ROOK_ATTACK_MASKS[sq] = (MASK_RANK[rankOf(sq)]
^ MASK_FILE[fileOf(sq)]) & ~edges;
ROOK_ATTACK_SHIFTS[sq] = 64 - popcountll(ROOK_ATTACK_MASKS[sq]);
subset = 0;
do {
index = subset;
index = index * ROOK_MAGICS[sq];
index = index >> ROOK_ATTACK_SHIFTS[sq];
ROOK_ATTACKS[sq][index] = get_rook_attacks_for_init(sq, subset);
subset = (subset - ROOK_ATTACK_MASKS[sq]) & ROOK_ATTACK_MASKS[sq];
} while (subset);
}
}
//Returns the attacks bitboard for a rook at a given square, using the magic lookup table
constexpr u64 getRookAttacks(Square square, u64 occ) {
return ROOK_ATTACKS[square][((occ & ROOK_ATTACK_MASKS[square]) * ROOK_MAGICS[square])
>> ROOK_ATTACK_SHIFTS[square]];
}
//Returns the 'x-ray attacks' for a rook at a given square. X-ray attacks cover squares that are not immediately
//accessible by the rook, but become available when the immediate blockers are removed from the board
u64 getXrayRookAttacks(Square square, u64 occ, u64 blockers) {
u64 attacks = getRookAttacks(square, occ);
blockers &= attacks;
return attacks ^ getRookAttacks(square, occ ^ blockers);
}
//Returns bishop attacks from a given square, using the Hyperbola Quintessence Algorithm. Only used to initialize
//the magic lookup table
u64 getBishopAttacksForInit(Square square, u64 occ) {
return sliding_attacks(square, occ, MASK_DIAGONAL[diagonalOf(square)]) |
sliding_attacks(square, occ, MASK_ANTI_DIAGONAL[antiDiagonalOf(square)]);
}
u64 BISHOP_ATTACK_MASKS[64];
int BISHOP_ATTACK_SHIFTS[64];
u64 BISHOP_ATTACKS[64][512];
const u64 BISHOP_MAGICS[64] = {
0x0002020202020200, 0x0002020202020000, 0x0004010202000000, 0x0004040080000000,
0x0001104000000000, 0x0000821040000000, 0x0000410410400000, 0x0000104104104000,
0x0000040404040400, 0x0000020202020200, 0x0000040102020000, 0x0000040400800000,
0x0000011040000000, 0x0000008210400000, 0x0000004104104000, 0x0000002082082000,
0x0004000808080800, 0x0002000404040400, 0x0001000202020200, 0x0000800802004000,
0x0000800400A00000, 0x0000200100884000, 0x0000400082082000, 0x0000200041041000,
0x0002080010101000, 0x0001040008080800, 0x0000208004010400, 0x0000404004010200,
0x0000840000802000, 0x0000404002011000, 0x0000808001041000, 0x0000404000820800,
0x0001041000202000, 0x0000820800101000, 0x0000104400080800, 0x0000020080080080,
0x0000404040040100, 0x0000808100020100, 0x0001010100020800, 0x0000808080010400,
0x0000820820004000, 0x0000410410002000, 0x0000082088001000, 0x0000002011000800,
0x0000080100400400, 0x0001010101000200, 0x0002020202000400, 0x0001010101000200,
0x0000410410400000, 0x0000208208200000, 0x0000002084100000, 0x0000000020880000,
0x0000001002020000, 0x0000040408020000, 0x0004040404040000, 0x0002020202020000,
0x0000104104104000, 0x0000002082082000, 0x0000000020841000, 0x0000000000208800,
0x0000000010020200, 0x0000000404080200, 0x0000040404040400, 0x0002020202020200
};
//Initializes the magic lookup table for bishops
void initializeBishopAttacks() {
u64 edges, subset, index;
for (Square sq = a1; sq <= h8; ++sq) {
edges = ((MASK_RANK[AFILE] | MASK_RANK[HFILE]) & ~MASK_RANK[rankOf(sq)]) |
((MASK_FILE[AFILE] | MASK_FILE[HFILE]) & ~MASK_FILE[fileOf(sq)]);
BISHOP_ATTACK_MASKS[sq] = (MASK_DIAGONAL[diagonalOf(sq)]
^ MASK_ANTI_DIAGONAL[antiDiagonalOf(sq)]) & ~edges;
BISHOP_ATTACK_SHIFTS[sq] = 64 - popcountll(BISHOP_ATTACK_MASKS[sq]);
subset = 0;
do {
index = subset;
index = index * BISHOP_MAGICS[sq];
index = index >> BISHOP_ATTACK_SHIFTS[sq];
BISHOP_ATTACKS[sq][index] = getBishopAttacksForInit(sq, subset);
subset = (subset - BISHOP_ATTACK_MASKS[sq]) & BISHOP_ATTACK_MASKS[sq];
} while (subset);
}
}
//Returns the attacks bitboard for a bishop at a given square, using the magic lookup table
constexpr u64 getBishopAttacks(Square square, u64 occ) {
return BISHOP_ATTACKS[square][((occ & BISHOP_ATTACK_MASKS[square]) * BISHOP_MAGICS[square])
>> BISHOP_ATTACK_SHIFTS[square]];
}
//Returns the 'x-ray attacks' for a bishop at a given square. X-ray attacks cover squares that are not immediately
//accessible by the rook, but become available when the immediate blockers are removed from the board
u64 getXrayBishopAttacks(Square square, u64 occ, u64 blockers) {
u64 attacks = getBishopAttacks(square, occ);
blockers &= attacks;
return attacks ^ getBishopAttacks(square, occ ^ blockers);
}
u64 SQUARES_BETWEEN_BB[64][64];
//Initializes the lookup table for the bitboard of squares in between two given squares (0 if the
//two squares are not aligned)
void initializeSquaresBetween() {
u64 sqs;
for (Square sq1 = a1; sq1 <= h8; ++sq1)
for (Square sq2 = a1; sq2 <= h8; ++sq2) {
sqs = SQUARE_BB[sq1] | SQUARE_BB[sq2];
if (fileOf(sq1) == fileOf(sq2) || rankOf(sq1) == rankOf(sq2))
SQUARES_BETWEEN_BB[sq1][sq2] =
get_rook_attacks_for_init(sq1, sqs) & get_rook_attacks_for_init(sq2, sqs);
else if (diagonalOf(sq1) == diagonalOf(sq2) || antiDiagonalOf(sq1) == antiDiagonalOf(sq2))
SQUARES_BETWEEN_BB[sq1][sq2] =
getBishopAttacksForInit(sq1, sqs) & getBishopAttacksForInit(sq2, sqs);
}
}
u64 LINE[64][64];
u64 LINESEG[64][64]; // ADDITION, SEGMENTS OF A LINE BETWEEN SQUARES GIVEN, FOR FINDING PINNED PIECES.
//Initializes the lookup table for the bitboard of all squares along the line of two given squares (0 if the
//two squares are not aligned)
void initializeLine() {
for (Square sq1 = a1; sq1 <= h8; ++sq1) {
for (Square sq2 = a1; sq2 <= h8; ++sq2) {
if (fileOf(sq1) == fileOf(sq2) || rankOf(sq1) == rankOf(sq2))
LINE[sq1][sq2] =
get_rook_attacks_for_init(sq1, 0) & get_rook_attacks_for_init(sq2, 0)
| SQUARE_BB[sq1] | SQUARE_BB[sq2];
else if (diagonalOf(sq1) == diagonalOf(sq2) || antiDiagonalOf(sq1) == antiDiagonalOf(sq2))
LINE[sq1][sq2] =
getBishopAttacksForInit(sq1, 0) & getBishopAttacksForInit(sq2, 0)
| SQUARE_BB[sq1] | SQUARE_BB[sq2];
}
}
for (Square sq1 = a1; sq1 <= h8; ++sq1) {
for (Square sq2 = a1; sq2 <= h8; ++sq2) {
u64 blockers = (1ULL << sq1) | (1ULL << sq2);
if (fileOf(sq1) == fileOf(sq2) || rankOf(sq1) == rankOf(sq2))
LINESEG[sq1][sq2] =
get_rook_attacks_for_init(sq1, blockers) & get_rook_attacks_for_init(sq2, blockers)
| SQUARE_BB[sq1] | SQUARE_BB[sq2];
else if (diagonalOf(sq1) == diagonalOf(sq2) || antiDiagonalOf(sq1) == antiDiagonalOf(sq2))
LINESEG[sq1][sq2] =
getBishopAttacksForInit(sq1, blockers) & getBishopAttacksForInit(sq2, blockers)
| SQUARE_BB[sq1] | SQUARE_BB[sq2];
}
}
}
//Initializes lookup tables for rook moves, bishop moves, in-between squares, aligned squares and pseudolegal moves
void initializeAllDatabases() {
initializeRookAttacks();
initializeBishopAttacks();
initializeSquaresBetween();
initializeLine();
}
// Back to my code from here and below
struct MoveEvaluation {
Move move;
int eval;
constexpr MoveEvaluation() {
move = Move();
eval = -INF_INT;
}
constexpr MoveEvaluation(Move m, int eval) {
move = m;
this->eval = eval;
}
constexpr auto operator<=>(const MoveEvaluation& other) const { return eval <=> other.eval; }
};
struct MoveList {
array<Move, 218> moves;
int count;
constexpr MoveList() {
count = 0;
}
void add(Move m) {
moves[count++] = m;
}
Move get(int index) {
return moves[index];
}
int find(const Move entry) {
auto it = std::find(moves.begin(), moves.begin() + count, entry);
if (it != moves.begin() + count) {
return std::distance(moves.begin(), it);
}
return -1;
}
void sortByString(Board& board) {
array<string, 218> movesStr;
movesStr.fill("zzzz"); // Fill with values to be sorted to back.
for (int i = 0; i < count; ++i) {
movesStr[i] = moves[i].toString();
}
std::stable_sort(movesStr.begin(), movesStr.end());
for (auto& str : movesStr) {
if (str == "zzzz") {
str = "a1a1";
}
}
for (int i = 0; i < count; ++i) {
moves[i] = Move(movesStr[i], board);
}
}
};
struct Transposition {
u64 zobristKey;
Move bestMove;
i16 score;
u8 flag;
u8 depth;
Transposition() {
zobristKey = 0;
bestMove = Move();
flag = 0;
score = 0;
depth = 0;
}
Transposition(u64 zobristKey, Move bestMove, u8 flag, i16 score, u8 depth) {
this->zobristKey = zobristKey;
this->bestMove = bestMove;
this->flag = flag;
this->score = score;
this->depth = depth;
}
};
struct TranspositionTable {
private:
std::vector<Transposition> table;
public:
size_t size;
TranspositionTable(float sizeInMB = 16) {
resize(sizeInMB);
}
void clear() {
table.clear();
}
void resize(float newSizeMiB) {
// Find number of bytes allowed
size = newSizeMiB * 1024 * 1024;
// Divide by size of transposition entry
size /= sizeof(Transposition);
if (size == 0) size += 1;
IFDBG cout << "Using transposition table with " << formatNum(size) << " entries" << endl;
table.resize(size);
}
int index(u64 key, u64 size) {
return key % size;
}
void setEntry(u64 key, Transposition& entry) {
auto& loc = table[index(key, size)];
loc = entry;
}
Transposition* getEntry(u64 key) {
return &table[index(key, size)];
}
};
// ****** NNUE STUFF ******
constexpr i16 inputQuantizationValue = 255;
constexpr i16 hiddenQuantizationValue = 64;
constexpr i16 evalScale = 400;
constexpr size_t HL_SIZE = 128;
constexpr size_t OUTPUT_BUCKETS = 8;
constexpr int ReLU = 0;
constexpr int CReLU = 1;
constexpr int SCReLU = 2;
constexpr int activation = SCReLU;
using Accumulator = array<i16, HL_SIZE>;
class NNUE {
public:
alignas(32) array<i16, HL_SIZE * 768> weightsToHL;
alignas(32) array<i16, HL_SIZE> hiddenLayerBias;
alignas(32) array<array<i16, HL_SIZE * 2>, OUTPUT_BUCKETS> weightsToOut;
array<i16, OUTPUT_BUCKETS> outputBias;
constexpr i16 ReLU(const i16 x) {
if (x < 0) return 0;
return x;
}
constexpr i16 CReLU(const i16 x) {
i16 ans = x;
if (x < 0) ans = 0;
else if (x > inputQuantizationValue) ans = inputQuantizationValue;
return ans;
}
static int feature(Color perspective, Color color, PieceType piece, Square square) {
// Constructs a feature from the given perspective for a piece
// of the given type and color on the given square
int colorIndex = (perspective == color) ? 0 : 1;
int pieceIndex = static_cast<int>(piece);
int squareIndex = (perspective == BLACK) ? flipRank(square) : static_cast<int>(square);
return colorIndex * 64 * 6 + pieceIndex * 64 + squareIndex;
}
// Function from stockfish
template<typename IntType>
inline IntType read_little_endian(std::istream& stream) {
IntType result;
if (IsLittleEndian)
stream.read(reinterpret_cast<char*>(&result), sizeof(IntType));
else
{
std::uint8_t u[sizeof(IntType)];
std::make_unsigned_t<IntType> v = 0;
stream.read(reinterpret_cast<char*>(u), sizeof(IntType));
for (std::size_t i = 0; i < sizeof(IntType); ++i)
v = (v << 8) | u[sizeof(IntType) - i - 1];
std::memcpy(&result, &v, sizeof(IntType));
}
return result;
}
NNUE() {
weightsToHL.fill(1);
hiddenLayerBias.fill(0);
for (auto& w : weightsToOut) w.fill(1);