-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposition.h
More file actions
1017 lines (905 loc) · 44.7 KB
/
Copy pathposition.h
File metadata and controls
1017 lines (905 loc) · 44.7 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
/*
a chess library (bonus: you can integrate more piece types!) which
supports Chess960 and is decently fast enough
Copyright (C) 2025-2026 winapiadmin
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/>.
*/
#pragma once
#include "attacks.h"
#include "movegen.h"
#include "types.h"
#include "zobrist.h"
#include <algorithm>
#include <stdexcept>
#include <string>
#include <vector>
/// @file position.h
namespace chess {
namespace attacks {
/// @brief Scan for attacks along a ray and identify checkers and pins.
/// @tparam RayDir Direction index of the ray to scan.
/// @tparam FirstIncreases Whether the ray direction corresponds to increasing square indices (e.g. north/east) or decreasing
/// (south/west).
/// @param ksq King's square.
/// @param occ_masked Occupancy bitboard masked to the ray (i.e. only squares on the ray are considered occupied).
/// @param slider_mask Bitboard of potential slider attackers (rooks for orthogonal rays, bishops for diagonal rays).
/// @param occ_us Occupancy bitboard of the attacking side (used to detect pinned pieces).
/// @param checkers Output bitboard to accumulate discovered checkers.
/// @param pin_bb Output bitboard to accumulate discovered pinned pieces (bits set for squares of pinned pieces, not the
/// attackers).
/// @details This function uses the precomputed ray bitboards to efficiently find the first occupied square along the ray and
/// determine if it's a checker or a pinned piece. If the first occupied square is an enemy slider, it's a checker. If it's a
/// friendly piece, we check if there's another enemy slider behind it on the same ray, which would indicate that the friendly
/// piece is pinned.
/// @note This function assumes that the occupancy bitboards have already been masked to only include pieces on the relevant
/// ray, which allows it to use simple bit operations to find the first blocker and potential attackers without needing to
/// iterate over squares.
template <int RayDir, bool FirstIncreases>
inline void
scan_attacks_ray(Square ksq, Bitboard occ_masked, Bitboard slider_mask, Bitboard occ_us, Bitboard &checkers, Bitboard &pin_bb) {
const auto &ray = attacks::RAYS[RayDir][ksq];
Bitboard occ_on_ray = ray & occ_masked;
if (!occ_on_ray)
return;
int first_sq = FirstIncreases ? lsb(occ_on_ray) : msb(occ_on_ray);
Bitboard first_bb = 1ULL << first_sq;
if (first_bb & slider_mask) {
checkers |= first_bb;
} else if (first_bb & occ_us) {
Bitboard after = FirstIncreases ? occ_on_ray & ~((first_bb) | (first_bb - 1)) : occ_on_ray & (first_bb - 1);
if (after) {
int attacker_sq = FirstIncreases ? lsb(after) : msb(after);
if ((1ULL << attacker_sq) & slider_mask)
pin_bb |= movegen::between(ksq, static_cast<Square>(attacker_sq));
}
}
}
} // namespace attacks
/**
* Stores complete and incremental position state for supporting undo operations.
*
* Captures all necessary board state including piece placement, per-color occupancy,
* game rules (castling, en-passant, move counters), and incremental undo information
* (changed squares and pieces). Cached attack masks are saved to avoid recomputation
* on undo.
*/
template <typename Piece> struct alignas(64) HistoryEntry {
Bitboard pieces[7]{}; ///< Bitboards per piece type.
Bitboard occ[COLOR_NB]{}; ///< Occupancy per colour.
Color turn = COLOR_NB; ///< Side to move.
Move mv = Move::none(); ///< The move that led to this position.
Key hash = 0; ///< Zobrist hash.
uint8_t halfMoveClock = 0; ///< Half-move clock for 50/75-move rule.
uint16_t fullMoveNumber = 1; ///< Full-move number (starts at 1).
/// @brief Whether en-passant presence was included in the Zobrist hash.
bool epIncluded = false;
/// @brief Repetition counter originating from this saved state.
int8_t repetition = 0; ///< Repetition counter from this position.
/// @brief Number of plies since last null move.
uint8_t pliesFromNull = 0;
/// @brief En-passant target square.
Square enPassant = SQ_NONE; ///< En-passant target square.
/// @brief King's square for each colour in this saved state.
Square kings[COLOR_NB] = { SQ_NONE, SQ_NONE };
/// @brief Castling rights bitmask at this saved state.
CastlingRights castlingRights; ///< Castling rights bitmask.
/// @brief Incremental squares changed by the move (for undo).
Square incr_sqs[4] = { SQ_NONE, SQ_NONE, SQ_NONE, SQ_NONE };
/// @brief Incremental piece values for undo (parallel to incr_sqs).
Piece incr_pc[4] = { Piece::NO_PIECE, Piece::NO_PIECE, Piece::NO_PIECE, Piece::NO_PIECE };
/// @name Cached attack data (saved to avoid recomputation on undo)
/// @{
Bitboard saved_rook_pin{}; ///< Saved rook pin mask.
Bitboard saved_bishop_pin{}; ///< Saved bishop pin mask.
Bitboard saved_checkers{}; ///< Saved checkers bitboard.
Bitboard saved_check_mask{}; ///< Saved check mask.
/// @}
};
/// @enum CheckType
enum class CheckType { NO_CHECK, DIRECT_CHECK, DISCOVERY_CHECK };
/// @enum FENParsingMode
/// @brief FEN parsing mode for castling rights.
enum FENParsingMode { MODE_XFEN, MODE_SMK, MODE_AUTO };
/// @enum MoveGenType
/**
* @brief Bitmask flags controlling which pieces and move types to generate.
*
* Compile-time and runtime flags for filtering legal move generation.
* Piece flags (PAWN through KING) select which piece types to include.
* Move type flags (CAPTURE, QUIET) select move categories.
* PIECE_MASK combines all piece flags; ALL combines all flags.
*/
enum class MoveGenType : uint16_t {
NONE = 0,
PAWN = 1 << 1,
KNIGHT = 1 << 2,
BISHOP = 1 << 3,
ROOK = 1 << 4,
QUEEN = 1 << 5,
KING = 1 << 6,
PIECE_MASK = PAWN | KNIGHT | BISHOP | ROOK | QUEEN | KING,
CAPTURE = 1 << 7,
QUIET = 1 << 8,
ALL = PIECE_MASK | CAPTURE | QUIET
};
/**
* @brief Bitwise AND operation for MoveGenType flags.
* @param a First operand.
* @param b Second operand.
* @return Result of bitwise AND.
*/
template <typename MoveGenType> constexpr MoveGenType operator&(MoveGenType a, MoveGenType b) {
using U = std::underlying_type_t<MoveGenType>;
return static_cast<MoveGenType>(static_cast<U>(a) & static_cast<U>(b));
}
/**
* @brief Bitwise OR operation for MoveGenType flags.
* @param a First operand.
* @param b Second operand.
* @return Result of bitwise OR.
*/
template <typename MoveGenType> constexpr MoveGenType operator|(MoveGenType a, MoveGenType b) {
using U = std::underlying_type_t<MoveGenType>;
return static_cast<MoveGenType>(static_cast<U>(a) | static_cast<U>(b));
}
/**
* @class _Position
* @brief Chess position representation and move execution system.
* @tparam PieceC Piece-enum type (EnginePiece, PolyglotPiece, or ContiguousMappingPiece).
*
* Maintains board state including piece placement, Zobrist hashing, move history for undo,
* castling rights, en-passant state, and cached attack/pin/check masks. Supports both
* standard chess and Chess960 variants.
*/
template <typename PieceC = EnginePiece, typename = std::enable_if_t<is_piece_enum<PieceC>::value>> class _Position {
private:
std::vector<HistoryEntry<PieceC>> history;
std::vector<Key> rep_hashes_;
Bitboard _rook_pin{};
Bitboard _bishop_pin{};
Bitboard _checkers{};
Bitboard _check_mask{};
Bitboard _pin_mask{};
PieceC pieces_list[SQUARE_NB + 1] = {
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE,
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE,
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE,
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE,
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE,
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE,
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE,
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE,
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE,
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE,
PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE, PieceC::NO_PIECE
};
bool _chess960{};
/// @struct CastlingMeta
/// @brief Per-colour castling metadata for Chess960.
struct CastlingMeta {
Square king_start = SQ_NONE; ///< King's start square for castling.
Square rook_start_ks = SQ_NONE; ///< Rook start for kingside castling.
Square rook_start_qs = SQ_NONE; ///< Rook start for queenside castling.
std::array<Bitboard, 2> castling_paths{}; ///< Castling path bitboards [ks, qs].
} castling_meta_[2]{};
public:
/// @brief Standard starting FEN for classical chess.
static inline constexpr auto START_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
/// @brief Default FEN stub used for Chess960 tests (special castling format HA/ha).
static inline constexpr auto START_CHESS960_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w HAha - 0 1";
/// @brief Generate legal moves filtered by type.
/// @tparam type Bitmask of MoveGenType flags.
/// @tparam c Colour to move.
/// @tparam ListT Move-list type (Movelist or CountOnlyList).
/// @param out Output move list.
template <MoveGenType type = MoveGenType::ALL, Color c, typename ListT = Movelist> void legals(ListT &out) const {
constexpr auto raw = static_cast<uint16_t>(type);
constexpr uint16_t pieceBits = raw & static_cast<uint16_t>(MoveGenType::PIECE_MASK);
constexpr uint16_t modeBits =
raw & (static_cast<uint16_t>(MoveGenType::CAPTURE) | static_cast<uint16_t>(MoveGenType::QUIET));
constexpr uint16_t effectivePieces =
pieceBits ? pieceBits
: (raw == static_cast<uint16_t>(MoveGenType::NONE) ? 0 : static_cast<uint16_t>(MoveGenType::PIECE_MASK));
constexpr bool includeCaps = modeBits == 0 || (modeBits & static_cast<uint16_t>(MoveGenType::CAPTURE));
constexpr bool includeQuiet = modeBits == 0 || (modeBits & static_cast<uint16_t>(MoveGenType::QUIET));
constexpr bool captureOnly = includeCaps && !includeQuiet;
if constexpr (effectivePieces == 0 && modeBits != 0)
return;
if constexpr (effectivePieces & static_cast<uint16_t>(MoveGenType::PAWN)) {
movegen::genPawnSingleMoves<PieceC, c, captureOnly, ListT>(*this, out, _rook_pin, _bishop_pin, _check_mask);
if constexpr (includeQuiet)
movegen::genPawnDoubleMoves<PieceC, c, ListT>(*this, out, _pin_mask, _check_mask);
if constexpr (includeCaps)
movegen::genEP<PieceC, c, ListT>(*this, out);
}
if constexpr (effectivePieces & static_cast<uint16_t>(MoveGenType::KNIGHT)) {
movegen::genKnightMoves<PieceC, c, captureOnly, ListT>(*this, out, _pin_mask, _check_mask);
}
if constexpr (effectivePieces & static_cast<uint16_t>(MoveGenType::KING)) {
movegen::genKingMoves<PieceC, c, captureOnly, ListT>(*this, out, _pin_mask);
}
if constexpr (effectivePieces & static_cast<uint16_t>(MoveGenType::BISHOP)) {
movegen::genSlidingMoves<PieceC, c, BISHOP, captureOnly, ListT>(*this, out, _rook_pin, _bishop_pin, _check_mask);
}
if constexpr (effectivePieces & static_cast<uint16_t>(MoveGenType::ROOK)) {
movegen::genSlidingMoves<PieceC, c, ROOK, captureOnly, ListT>(*this, out, _rook_pin, _bishop_pin, _check_mask);
}
if constexpr (effectivePieces & static_cast<uint16_t>(MoveGenType::QUEEN)) {
movegen::genSlidingMoves<PieceC, c, QUEEN, captureOnly, ListT>(*this, out, _rook_pin, _bishop_pin, _check_mask);
}
}
/// @brief Count legal moves without storing them (uses CountOnlyList).
template <Color c> inline uint64_t count_legals() const noexcept {
CountOnlyList moves;
legals<MoveGenType::ALL, c>(moves);
return moves.size_;
}
/// @brief Generate legal moves (runtime colour dispatch).
template <MoveGenType type = MoveGenType::ALL, typename ListT = Movelist> inline void legals(ListT &out) const {
switch (side_to_move()) {
case WHITE:
legals<type, WHITE>(out);
return;
case BLACK:
legals<type, BLACK>(out);
return;
default:
UNREACHABLE();
return;
}
}
/// @brief Execute a move on the board.
/// @tparam Strict If true, validates that the move is legal.
template <bool Strict = true> void doMove(const Move &move);
/// @brief Snake-case alias for doMove().
template <bool Strict = true> void do_move(const Move &move) { doMove<Strict>(move); }
/// @brief Undo the last move. Returns saved HistoryEntry when RetAll=true.
/// @tparam RetAll If true, return the popped HistoryEntry.
/// @return The saved state if RetAll, otherwise void.
template <bool RetAll = false> inline auto undoMove() -> std::conditional_t<RetAll, HistoryEntry<PieceC>, void> {
pieces_list[state().incr_sqs[0]] = state().incr_pc[0];
pieces_list[state().incr_sqs[1]] = state().incr_pc[1];
pieces_list[state().incr_sqs[2]] = state().incr_pc[2];
pieces_list[state().incr_sqs[3]] = state().incr_pc[3];
rep_hashes_.pop_back();
_rook_pin = state().saved_rook_pin;
_bishop_pin = state().saved_bishop_pin;
_checkers = state().saved_checkers;
_check_mask = state().saved_check_mask;
_pin_mask = _rook_pin | _bishop_pin;
if constexpr (RetAll) {
HistoryEntry<PieceC> state_ = state();
history.pop_back();
return state_;
} else {
history.pop_back();
return;
}
}
/// @brief Undo the last move (snake_case). Returns saved HistoryEntry when RetAll=true.
template <bool RetAll = false> inline auto undo_move() -> std::conditional_t<RetAll, HistoryEntry<PieceC>, void> {
return undoMove<RetAll>();
}
/**
* Execute a null move, switching the side to move without placing any piece.
* Resets repetition and null-move tracking, and refreshes cached attack data.
*/
inline void doNullMove() {
history.push_back(state());
state().saved_rook_pin = _rook_pin;
state().saved_bishop_pin = _bishop_pin;
state().saved_checkers = _checkers;
state().saved_check_mask = _check_mask;
state().incr_sqs[0] = state().incr_sqs[1] = state().incr_sqs[2] = state().incr_sqs[3] = SQ_NONE;
state().incr_pc[0] = state().incr_pc[1] = state().incr_pc[2] = state().incr_pc[3] = PieceC::NO_PIECE;
state().hash ^= (ep_square() != SQ_NONE && state().epIncluded) ? zobrist::RandomEP[file_of(ep_square())] : 0;
state().epIncluded = false;
state().enPassant = SQ_NONE;
state().turn = ~state().turn;
state().hash ^= zobrist::RandomTurn;
rep_hashes_.push_back(state().hash);
state().fullMoveNumber += (state().turn == WHITE);
state().pliesFromNull = state().repetition = 0;
state().mv = Move::null();
state().halfMoveClock++;
refresh_attacks();
}
/// @brief Perform a null move (pass the turn).
[[deprecated("Pending to remove")]] inline void do_null_move() { doNullMove(); }
/// @name Occupancy queries
/// @{
/// @brief Combined occupancy (both colours).
[[nodiscard]] inline Bitboard pieces() const { return occ(); }
/// @brief Bitboard of a piece type for a colour (compile-time colour).
template <PieceType pt> [[nodiscard]] inline Bitboard pieces(Color c) const {
#if defined(_CHESSLIB_ERROR_MODE_ASSERT)
assert(c != COLOR_NB && "color is COLOR_NB");
#elif defined(_CHESSLIB_ERROR_MODE_THROW)
if (c == COLOR_NB)
throw std::runtime_error("color is COLOR_NB");
#endif
if constexpr (pt == PIECE_TYPE_NB || pt == ALL_PIECES)
return occ(c);
return state().pieces[pt] & state().occ[c];
}
/// @brief Bitboard of a piece type for a colour (runtime colour).
template <Color c> [[nodiscard]] inline Bitboard pieces(PieceType pt) const {
static_assert(c != COLOR_NB);
if (pt == PIECE_TYPE_NB || pt == ALL_PIECES)
return occ(c);
return state().pieces[pt] & state().occ[c];
}
/// @brief Bitboard of a piece type for a colour (compile-time both).
template <PieceType pt, Color c> [[nodiscard]] inline Bitboard pieces() const {
static_assert(c != COLOR_NB);
if constexpr (pt == PIECE_TYPE_NB || pt == ALL_PIECES)
return occ(c);
return state().pieces[pt] & state().occ[c];
}
/// @brief Bitboard of a piece type for a colour (runtime both).
[[nodiscard]] inline Bitboard pieces(PieceType pt, Color c) const {
#if defined(_CHESSLIB_ERROR_MODE_ASSERT)
assert(c != COLOR_NB && "color is COLOR_NB");
#elif defined(_CHESSLIB_ERROR_MODE_THROW)
if (c == COLOR_NB)
throw std::runtime_error("color is COLOR_NB");
#endif
switch (pt) {
case PIECE_TYPE_NB:
case ALL_PIECES:
return occ(c);
default:
return state().pieces[pt] & state().occ[c];
}
}
/// @brief Bitboard of a piece type (both colours).
[[nodiscard]] inline Bitboard pieces(PieceType pt) const {
switch (static_cast<int>(pt)) {
case PIECE_TYPE_NB:
case ALL_PIECES:
return occ();
default:
return state().pieces[pt];
}
}
/// @brief Union bitboard of multiple piece types.
template <typename... PTypes, typename = std::enable_if_t<(std::is_same_v<PTypes, PieceType> && ...)>>
[[nodiscard]] inline Bitboard pieces(PTypes... ptypes) const {
return (state().pieces[static_cast<int>(ptypes)] | ...);
}
/// @brief Union bitboard of multiple piece types for a colour.
template <typename... PTypes, typename = std::enable_if_t<(std::is_same_v<PTypes, PieceType> && ...)>>
[[nodiscard]] inline Bitboard pieces(Color c, PTypes... ptypes) const {
return (pieces(ptypes, c) | ...);
}
/// @}
/// @brief Get all pieces of a given colour attacking a target square.
/// @param colour Attacker colour.
/// @param square Attacked square.
/// @param occupied Occupancy bitboard.
/// @return Bitboard of attackers.
[[nodiscard]] inline Bitboard attackers(Color colour, Square square, Bitboard occupied) const {
auto queens = pieces<QUEEN>(colour);
auto atks = (attacks::pawn(~colour, square) & pieces<PAWN>(colour));
atks |= (attacks::knight(square) & pieces<KNIGHT>(colour));
atks |= (attacks::bishop(square, occupied) & (pieces<BISHOP>(colour) | queens));
atks |= (attacks::rook(square, occupied) & (pieces<ROOK>(colour) | queens));
atks |= (attacks::king(square) & pieces<KING>(colour));
return atks & occupied;
}
/**
* Test whether a square is attacked by the given colour.
* @returns `true` if the square is attacked by the given colour, `false` otherwise.
*/
[[nodiscard]] inline bool isAttacked(Square sq, Color by) const noexcept {
const Bitboard occ_bb = occ();
const Bitboard us_bb = occ(by);
Bitboard diag_attackers = pieces(PieceType::BISHOP, by) | pieces(PieceType::QUEEN, by);
Bitboard ortho_attackers = pieces(PieceType::ROOK, by) | pieces(PieceType::QUEEN, by);
return (attacks::pawn(~by, sq) & pieces(PieceType::PAWN, by)) ||
(attacks::knight(sq) & pieces(PieceType::KNIGHT, by)) || (attacks::king(sq) & pieces(PieceType::KING, by)) ||
(attacks::bishop(sq, occ_bb) & diag_attackers & us_bb) || (attacks::rook(sq, occ_bb) & ortho_attackers & us_bb);
}
/**
* Checks if a square is attacked by the given color.
* @param sq Square to check.
* @param by Color attacking the square.
* @return `true` if the square is attacked, `false` otherwise.
*/
[[nodiscard]] inline bool is_attacked(Square sq, Color by) const noexcept { return isAttacked(sq, by); }
/**
* Determines if a square is attacked by a specified color.
* @param sq Square to check
* @param by Color attacking the square.
* @param occupied The occupancy bitboard defining blocking positions for sliding pieces.
* @returns true if the square is attacked by the specified color, false otherwise.
*/
[[nodiscard]] inline bool isAttacked(Square sq, Color by, Bitboard occupied) const noexcept {
const Bitboard diag_attackers = pieces(PieceType::BISHOP, by) | pieces(PieceType::QUEEN, by);
const Bitboard ortho_attackers = pieces(PieceType::ROOK, by) | pieces(PieceType::QUEEN, by);
return (attacks::pawn(~by, sq) & pieces(PieceType::PAWN, by)) ||
(attacks::knight(sq) & pieces(PieceType::KNIGHT, by)) || (attacks::king(sq) & pieces(PieceType::KING, by)) ||
(attacks::bishop(sq, occupied) & diag_attackers) || (attacks::rook(sq, occupied) & ortho_attackers);
}
/**
* Test if a square is attacked by a specific color.
* @param sq Square to check.
* @param by Color of potential attackers.
* @param occupied Occupancy bitboard to use for attack calculations.
* @return true if the square is attacked by the specified color, false otherwise.
*/
[[nodiscard]] inline bool is_attacked(Square sq, Color by, Bitboard occupied) const noexcept {
return isAttacked(sq, by, occupied);
}
/// @brief Get attackers for a colour using the current occupancy.
[[nodiscard]] inline Bitboard attackers(Color colour, Square square) const { return attackers(colour, square, occ()); }
/// @brief Place a piece on the board (compile-time piece type).
template <PieceType pt> inline void placePiece(Square sq, Color c) {
if constexpr (pt != NO_PIECE_TYPE) {
Bitboard v = 1ULL << sq;
state().pieces[pt] |= v;
state().occ[c] |= v;
pieces_list[sq] = make_piece<PieceC>(pt, c);
state().hash ^= zobrist::RandomPiece[enum_idx<PieceC>()][(int)pieces_list[sq]][sq];
if constexpr (pt == KING)
state().kings[c] = sq;
}
}
/// @brief Remove a piece from the board (compile-time piece type).
template <PieceType pt> inline void removePiece(Square sq, Color c) {
if constexpr (pt != NO_PIECE_TYPE) {
Bitboard v = ~(1ULL << sq);
state().pieces[pt] &= v;
state().occ[c] &= v;
pieces_list[sq] = PieceC::NO_PIECE;
state().hash ^= zobrist::RandomPiece[enum_idx<PieceC>()][static_cast<int>(make_piece<PieceC>(pt, c))][sq];
if constexpr (pt == KING)
state().kings[c] = SQ_NONE;
}
}
/// @brief Place a piece (runtime piece type).
inline void placePiece(PieceType pt, Square sq, Color c) {
bool a = pt == KING;
Bitboard v = 1ULL << sq;
state().pieces[pt] |= v;
state().occ[c] |= v;
pieces_list[sq] = make_piece<PieceC>(pt, c);
state().hash ^= zobrist::RandomPiece[enum_idx<PieceC>()][(int)pieces_list[sq]][sq];
state().kings[c] = a ? sq : state().kings[c];
}
/// @brief Remove a piece (runtime piece type).
inline void removePiece(PieceType pt, Square sq, Color c) {
bool a = pt == KING;
if (pt != NO_PIECE_TYPE) {
Bitboard v = ~(1ULL << sq);
state().pieces[pt] &= v;
state().occ[c] &= v;
pieces_list[sq] = PieceC::NO_PIECE;
state().hash ^= zobrist::RandomPiece[enum_idx<PieceC>()][static_cast<int>(make_piece<PieceC>(pt, c))][sq];
state().kings[c] = a ? SQ_NONE : state().kings[c];
}
}
/// @brief Occupancy of a single colour.
[[nodiscard]] inline Bitboard occ(Color c) const {
ASSUME(c != COLOR_NB);
return state().occ[c];
}
/// @brief Combined occupancy.
[[nodiscard]] inline Bitboard occ() const { return state().occ[0] | state().occ[1]; }
/// @brief Piece on a square.
NO_SIDE_EFFECTS FORCEINLINE FLATTEN PieceC piece_on(Square s) const {
#if defined(_CHESSLIB_ERROR_MODE_ASSERT)
assert(chess::is_valid(s) && "sq is out-of-bounds");
#elif defined(_CHESSLIB_ERROR_MODE_THROW)
if (!chess::is_valid(s))
throw std::runtime_error("sq is out-of-bounds");
#endif
#if !defined(_DEBUG) || defined(NDEBUG)
return pieces_list[s];
#else
PieceC _p2 = PieceC::NO_PIECE;
Bitboard mask = (1ULL << s);
if (((state().occ[WHITE] | state().occ[BLACK]) & mask) == 0) {
_p2 = PieceC::NO_PIECE;
} else {
bool c = (state().occ[WHITE] & mask) != 0;
for (PieceType pt : { PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING }) {
bool is_p = (state().pieces[(int)pt] & mask) != 0;
if (is_p) {
_p2 = make_piece<PieceC>(pt, c ? WHITE : BLACK);
break;
}
}
}
auto p = pieces_list[s];
#if defined(_CHESSLIB_ERROR_MODE_ASSERT)
assert(p == _p2 && "Inconsistient piece map");
#elif defined(_CHESSLIB_ERROR_MODE_THROW)
if (p != _p2)
throw std::runtime_error("Inconsistient piece map");
#endif
return p;
#endif
}
/**
* Occupancy bitboard for a given color.
* @param c The color whose occupancy to retrieve.
* @returns The bitboard of occupied squares for the given color.
*/
[[nodiscard]] inline Bitboard us(Color c) const { return occ(c); }
/// @brief Zobrist hash of the current position.
[[nodiscard]] inline uint64_t hash() const { return state().hash; }
/// @brief Current side to move.
[[nodiscard]] inline Color side_to_move() const { return state().turn; }
/// @brief Current en-passant target square, or SQ_NONE.
[[nodiscard]] inline Square ep_square() const { return state().enPassant; }
/**
* Finds the lowest-indexed piece of the specified type for a given color.
* @param c The color to query.
* @returns The square of the lowest-indexed piece.
*/
template <PieceType pt> [[nodiscard]] inline Square square(Color c) const {
return static_cast<Square>(lsb(pieces<pt>(c)));
}
/**
* Retrieve the square occupied by the king for the given color.
* @param c The color.
* @returns The square of the king for color `c`.
*/
[[nodiscard]] inline Square kingSq(Color c) const { return state().kings[c]; }
/**
* Returns the king's square for the given color.
*/
[[nodiscard]] inline Square king_sq(Color c) const { return kingSq(c); }
[[nodiscard]] inline Bitboard checkers() const { return _checkers; }
/// @brief Combined pin mask.
[[nodiscard]] inline Bitboard pin_mask() const { return _pin_mask; }
/// @brief Construct from a FEN string.
inline _Position(std::string fen = START_FEN, bool chess960 = false, FENParsingMode xfen = MODE_AUTO) {
history.reserve(6144);
history.emplace_back();
rep_hashes_.reserve(6144);
setFEN(fen, chess960, xfen);
}
/// @brief Check whether a move is a capture.
[[nodiscard]] inline bool is_capture(Move mv) const {
return mv.type_of() == EN_PASSANT || (mv.type_of() != CASTLING && piece_on(mv.to_sq()) != PieceC::NO_PIECE);
}
/**
* Determines if a move captures a piece.
* @returns `true` if the move captures a piece, `false` otherwise.
*/
[[nodiscard]] inline bool isCapture(Move mv) const { return is_capture(mv); }
/// @brief Whether the move resets the 50-move clock (capture or pawn move).
[[nodiscard]] inline bool is_zeroing(Move mv) const { return is_capture(mv) || at<PieceType>(mv.from_sq()) == PAWN; }
/**
* Queries the piece at a square.
* @return The piece type at the given square.
*/
[[nodiscard]] inline PieceC piece_at(Square sq) const { return piece_on(sq); }
/// @brief Export position to FEN.
[[nodiscard]] std::string fen(bool xfen = true) const;
/**
* @brief Full move number, starting from 1.
*/
/**
* @brief Full move number, starting from 1.
*/
/**
* @brief Half-move clock for the 50/75-move rule.
*/
[[nodiscard]] inline uint16_t fullmoveNumber() const { return state().fullMoveNumber; }
/// @brief Full move number (snake_case wrapper).
[[nodiscard]] inline uint16_t fullmove_number() const { return state().fullMoveNumber; }
/// @brief Half-move clock for 50/75-move rule.
[[nodiscard]] inline uint8_t rule50_count() const { return state().halfMoveClock; }
/// @brief Castling rights for a specific colour.
[[nodiscard]] inline CastlingRights castlingRights(Color c) const {
return state().castlingRights & (c == WHITE ? WHITE_CASTLING : BLACK_CASTLING);
}
/**
* Castling rights bitmask for both colors.
*/
[[nodiscard]] inline CastlingRights castlingRights() const { return state().castlingRights; }
/// @brief Whether a move is a castling move.
[[nodiscard]] inline bool is_castling(Move mv) const { return mv.type_of() == CASTLING; }
/// @brief Raw Zobrist hash.
uint64_t zobrist() const;
/**
* Extract a property from a square.
*
* The returned type depends on the template parameter:
* - `PieceType`: returns the piece type at the square.
* - `Color`: returns the color of the piece at the square.
* - `PieceC` (default): returns the piece at the square.
* @tparam T The property type to extract. Defaults to `PieceC`.
* @param sq The square to query.
* @return The requested property at the square.
*/
template <typename T = PieceC> inline T at(Square sq) const {
if constexpr (std::is_same_v<T, PieceType>)
return piece_of(piece_on(sq));
else if constexpr (std::is_same_v<T, Color>)
return color_of(piece_on(sq));
else
return piece_on(sq);
}
/// @brief Get the castling rights with only the active rook squares set.
CastlingRights clean_castling_rights() const;
/// @brief Set position from a FEN string. Returns true on success.
bool setFEN(const std::string &str, bool chess960 = false, FENParsingMode xfen = MODE_AUTO);
/// @brief Snake-case wrapper for setFEN().
inline bool set_fen(const std::string &str, bool chess960 = false, FENParsingMode xfen = MODE_AUTO) {
return setFEN(str, chess960, xfen);
}
/// @brief Parse a UCI move string for this position.
Move parse_uci(std::string) const;
/// @brief Parse and execute a UCI move.
Move push_uci(std::string);
/// @brief Compute the valid en-passant square (if any).
Square _valid_ep_square() const;
/// @name Piece counts
/// @{
/// @brief Count pieces of a given compile-time piece type (both colours).
template <PieceType pt> inline int count() const { return popcount(pieces(pt)); }
/// @brief Count pieces of compile-time piece type `pt` for colour `c`.
template <PieceType pt, Color c> inline int count() const { return popcount(pieces<pt, c>()); }
/// @brief Count pieces of piece type `pt` for runtime colour `c`.
template <PieceType pt> inline int count(Color c) const { return popcount(pieces<pt>(c)); }
/// @brief Count pieces of runtime piece type `pt` for colour `c`.
inline int count(PieceType pt, Color c) const { return popcount(pieces(pt, c)); }
/// @}
/// @brief Ply count from the start of the game.
inline int ply() const { return 2 * (state().fullMoveNumber - 1) + (side_to_move() == BLACK); }
/// @brief Test for draw by insufficient material.
bool is_insufficient_material() const;
/// @brief Whether a colour has any non-pawn, non-king material.
inline bool hasNonPawnMaterial(Color c) const { return bool(us(c) & ~(pieces(PAWN) | pieces(KING)) & occ(c)); }
/// @brief Whether the side to move is in check.
inline bool is_check() const { return checkers() != 0LL; }
/// @name Castling-right queries
/// @{
inline bool has_castling_rights(Color c) const { return castlingRights(c) != 0; }
inline bool has_kingside_castling_rights(Color c) const { return (castlingRights(c) & KING_SIDE) != 0; }
inline bool has_queenside_castling_rights(Color c) const { return (castlingRights(c) & QUEEN_SIDE) != 0; }
/// @}
/**
* Determines if the position has been repeated at least the specified number of times.
* @param ply The repetition count threshold.
* @returns `true` if the repetition count plus one is at least `ply`, `false` otherwise.
*/
inline bool is_repetition(int ply) const { return state().repetition + 1 >= ply; }
/// @brief Repetition counter for current position.
inline int repetition_count() const { return state().repetition; }
/// @brief Whether the position is a draw (50-move or repetition).
inline bool is_draw(int ply) const { return rule50_count() > 99 || is_repetition(ply); }
/// @brief Whether there has been at least one repetition since the last capture or pawn move.
inline bool has_repeated() const {
auto idx = history.size() - 1;
int end = std::min({ static_cast<int>(rule50_count()),
static_cast<int>(state().pliesFromNull),
static_cast<int>(history.size()) - 1 });
while (end-- >= 4) {
if (history[idx].repetition)
return true;
idx--;
}
return false;
}
/**
* Determines if the half-move clock is at least n.
* @param n The threshold to check against.
* @return true if the half-move clock is greater than or equal to n, false otherwise.
*/
inline bool _is_halfmoves(int n) const { return rule50_count() >= n; }
/// @brief Whether the position uses Chess960 castling rules.
inline bool chess960() const { return _chess960; }
/// @brief Whether the seventy-five move rule applies.
inline bool is_seventyfive_moves() const { return _is_halfmoves(150); }
/// @brief Whether the fifty-move rule applies.
inline bool is_fifty_moves() const { return _is_halfmoves(100); }
/// @brief Whether fivefold repetition has occurred.
inline bool is_fivefold_repetition() const { return is_repetition(5); }
/// @brief Whether a square is attacked by a colour (with optional custom occupancy).
[[deprecated("Future migration to isAttacked due to incompatible API")]]
inline bool is_attacked_by(Color color, Square sq, Bitboard occupied = 0) const {
Bitboard occ_bb = occupied ? occupied : occ();
return isAttacked(sq, color, occ_bb);
}
/// @brief Whether the previous move left the opponent in check.
inline bool was_into_check() const {
bool atk = false;
Bitboard bb = pieces<KING>(~side_to_move());
while (!atk && bb) {
atk |= is_attacked((Square)pop_lsb(bb), side_to_move());
}
return atk != 0;
}
/// @brief Get attackers mask for a colour to a square.
inline Bitboard attackers_mask(Color color, Square square, Bitboard occupied) const {
auto queens = pieces<QUEEN>(color);
auto atks = (attacks::pawn(~color, square) & pieces<PAWN>(color));
atks |= (attacks::knight(square) & pieces<KNIGHT>(color));
atks |= (attacks::bishop(square, occupied) & (pieces<BISHOP>(color) | queens));
atks |= (attacks::rook(square, occupied) & (pieces<ROOK>(color) | queens));
atks |= (attacks::king(square) & pieces<KING>(color));
return atks & occ(color);
}
/// @brief Check whether any square on path is attacked (for castling through check).
inline bool _attacked_for_king(Bitboard path, Bitboard occupied) const {
Bitboard b = 0;
while (!b && path) {
b |= attackers_mask(~side_to_move(), static_cast<Square>(pop_lsb(path)), occupied);
}
return b != 0;
}
/// @brief Whether the current side is checkmated.
inline bool is_checkmate() const {
Movelist moves;
legals(moves);
return is_check() && !moves.size();
}
/// @brief Whether the current side is stalemated.
inline bool is_stalemate() const {
Movelist moves;
legals(moves);
return !is_check() && !moves.size();
}
/// @brief Compute the material-only key (excludes turn, EP, castling).
inline Key material_key() const {
return hash() ^ (zobrist::RandomTurn * ~side_to_move()) ^ (zobrist::RandomCastle[castlingRights()]) ^
(state().epIncluded ? zobrist::RandomEP[file_of(ep_square())] : zobrist::RandomEP[FILE_NB]);
}
/// @brief Validate position consistency.
template <bool Strict = false> bool is_valid() const;
/// @brief Classify check type for a move.
CheckType givesCheck(Move move) const;
/**
* @brief Determine the check type resulting from a move.
* @return The check type induced by the move: `NO_CHECK`, `DIRECT_CHECK`, or `DISCOVERY_CHECK`.
*/
[[nodiscard]] inline CheckType gives_check(Move move) const { return givesCheck(move); }
/**
* @brief Checks if a draw is available under the 50-move rule.
*/
[[nodiscard]] inline bool isHalfMoveDraw() const noexcept { return rule50_count() >= 100; }
/// @brief Whether the 50-move rule draw applies (snake_case wrapper).
[[nodiscard]] inline bool is_half_move_draw() const noexcept { return isHalfMoveDraw(); }
/**
* Returns the castling path bitboard for the specified color and side.
*
* @param c The color to query castling information for.
* @param isKingSide `true` for kingside castling, `false` for queenside.
* @returns A bitboard representing the squares involved in the castling path for the given color and side.
*/
[[nodiscard]] inline Bitboard getCastlingPath(Color c, bool isKingSide) const {
return castling_meta_[c].castling_paths[isKingSide];
}
/**
* Returns the castling path bitboard for the specified color and side.
* @returns Bitboard of squares along the castling path.
*/
[[nodiscard]] inline Bitboard get_castling_path(Color c, bool isKingSide) const { return getCastlingPath(c, isKingSide); }
/**
* Retrieve the castling metadata for a color.
* @return The castling metadata for the specified color.
*/
[[nodiscard]] inline auto getCastlingMetadata(Color c) const { return castling_meta_[c]; }
/**
* Castling metadata for a color.
* @param c Color.
*/
[[nodiscard]] inline auto get_castling_metadata(Color c) const { return getCastlingMetadata(c); }
private:
/// @brief Compute pin masks for the king at sq.
void pinMasks(Color c, Square sq, Bitboard &rook_pin, Bitboard &bishop_pin) const {
Bitboard occ_opp = occ(~c);
Bitboard occ_us = occ(c);
Bitboard opp_queens = pieces(QUEEN, ~c) & occ_opp;
Bitboard opp_bishops = (pieces<BISHOP>(~c) | opp_queens);
Bitboard bishop_atks = attacks::slider<BISHOP>(sq, occ_opp) & opp_bishops;
Bitboard opp_rooks = (pieces<ROOK>(~c) | opp_queens);
Bitboard rook_atks = attacks::slider<ROOK>(sq, occ_opp) & opp_rooks;
rook_pin = 0;
bishop_pin = 0;
while (bishop_atks) {
auto possible = movegen::between(sq, Square(pop_lsb(bishop_atks)));
Bitboard tmp = possible & occ_us;
if (tmp && (tmp & (tmp - 1)) == 0)
bishop_pin |= possible;
}
while (rook_atks) {
auto possible = movegen::between(sq, Square(pop_lsb(rook_atks)));
Bitboard tmp = possible & occ_us;
if (tmp && (tmp & (tmp - 1)) == 0)
rook_pin |= possible;
}
}
/**
* Recompute cached pins, checkers, and check mask for the side to move.
*
* Detects pinned pieces and checking pieces, then updates the check mask accordingly.
*/
inline void refresh_attacks() {
const Color c = side_to_move();
const Square ksq = kingSq(c);
const Bitboard occ_all = occ();
const Bitboard occ_us = occ(c);
Bitboard bishop_pin = 0, rook_pin = 0, checkers = 0;
// Directional scan from the king: check each ray for first/second occupied squares.
// This avoids iterating over all enemy sliders and calling movegen::between() per piece.
const Bitboard diag_sliders = pieces<BISHOP>(~c) | pieces<QUEEN>(~c);
const Bitboard ortho_sliders = pieces<ROOK>(~c) | pieces<QUEEN>(~c);
// Use precomputed rays and direction-aware nearest-blocker extraction.
const Bitboard occ_masked = occ_all;
// Diagonals: NE,NW,SE,SW
attacks::scan_attacks_ray<attacks::RD_NE, true>(ksq, occ_masked, diag_sliders, occ_us, checkers, bishop_pin);
attacks::scan_attacks_ray<attacks::RD_NW, true>(ksq, occ_masked, diag_sliders, occ_us, checkers, bishop_pin);
attacks::scan_attacks_ray<attacks::RD_SE, false>(ksq, occ_masked, diag_sliders, occ_us, checkers, bishop_pin);
attacks::scan_attacks_ray<attacks::RD_SW, false>(ksq, occ_masked, diag_sliders, occ_us, checkers, bishop_pin);
// Orthogonals: N,S,E,W
attacks::scan_attacks_ray<attacks::RD_NORTH, true>(ksq, occ_masked, ortho_sliders, occ_us, checkers, rook_pin);
attacks::scan_attacks_ray<attacks::RD_SOUTH, false>(ksq, occ_masked, ortho_sliders, occ_us, checkers, rook_pin);
attacks::scan_attacks_ray<attacks::RD_EAST, true>(ksq, occ_masked, ortho_sliders, occ_us, checkers, rook_pin);
attacks::scan_attacks_ray<attacks::RD_WEST, false>(ksq, occ_masked, ortho_sliders, occ_us, checkers, rook_pin);
// Pawn and knight checkers (precomputed tables, no magic lookups)
checkers |= (attacks::pawn(c, ksq) & pieces<PAWN>(~c));
checkers |= (attacks::knight(ksq) & pieces<KNIGHT>(~c));
_bishop_pin = bishop_pin;
_rook_pin = rook_pin;
_pin_mask = rook_pin | bishop_pin;
_checkers = checkers;
if (!_checkers) {
_check_mask = ~0ULL;
} else if ((_checkers & (_checkers - 1)) == 0) {
auto sq = static_cast<Square>(lsb(_checkers));
_check_mask = 1ULL << sq | movegen::between(ksq, sq);
} else {
_check_mask = 0ULL;
}
}
inline const auto &state() const { return history.back(); }
inline auto &state() { return history.back(); }
public:
/// @brief Copy constructor (deep copy of position state).
inline _Position(const _Position &other)
: history(other.history), rep_hashes_(other.rep_hashes_), _chess960(other._chess960),
castling_meta_{ other.castling_meta_[0], other.castling_meta_[1] } {
std::copy(std::begin(other.pieces_list), std::end(other.pieces_list), std::begin(pieces_list));
// Copy cached attack/pin/check masks from the source position so the copy
// is an exact snapshot. This avoids subtle inconsistencies with incremental saved state
// and is much cheaper than recomputing everything.
_rook_pin = other._rook_pin;
_bishop_pin = other._bishop_pin;
_checkers = other._checkers;
_check_mask = other._check_mask;
_pin_mask = other._pin_mask;
}
// @brief get size of history
// @return size of history
inline size_t history_count() const { return history.size(); }
};