diff --git a/Chess/InplaceVector.h b/Chess/InplaceVector.h new file mode 100644 index 0000000..2d89d91 --- /dev/null +++ b/Chess/InplaceVector.h @@ -0,0 +1,99 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace SimpleChessEngine { + +template +using SmallestSizeType = std::conditional_t< + capacity <= std::numeric_limits::max(), std::uint8_t, + std::conditional_t::max(), + std::uint16_t, std::size_t>>; + +template + requires std::is_trivially_copyable_v && + std::is_trivially_default_constructible_v +class InplaceVector { + public: + using value_type = T; + using size_type = SmallestSizeType; + using difference_type = std::ptrdiff_t; + using reference = T&; + using const_reference = const T&; + using pointer = T*; + using const_pointer = const T*; + using iterator = T*; + using const_iterator = const T*; + + constexpr InplaceVector() noexcept = default; + + [[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; } + [[nodiscard]] constexpr size_type size() const noexcept { return size_; } + [[nodiscard]] constexpr bool empty() const noexcept { return size_ == 0; } + + [[nodiscard]] constexpr iterator begin() noexcept { return elements_.data(); } + [[nodiscard]] constexpr const_iterator begin() const noexcept { + return elements_.data(); + } + [[nodiscard]] constexpr iterator end() noexcept { return begin() + size_; } + [[nodiscard]] constexpr const_iterator end() const noexcept { + return begin() + size_; + } + + [[nodiscard]] constexpr reference operator[](size_type index) noexcept { + assert(index < size_); + return elements_[index]; + } + [[nodiscard]] constexpr const_reference operator[]( + size_type index) const noexcept { + assert(index < size_); + return elements_[index]; + } + [[nodiscard]] constexpr reference front() noexcept { return (*this)[0]; } + [[nodiscard]] constexpr const_reference front() const noexcept { + return (*this)[0]; + } + [[nodiscard]] constexpr reference back() noexcept { + assert(!empty()); + return *(end() - 1); + } + [[nodiscard]] constexpr const_reference back() const noexcept { + assert(!empty()); + return *(end() - 1); + } + + constexpr reference unchecked_push_back(const T& value) noexcept { + assert(size_ < N); + return elements_[size_++] = value; + } + + constexpr reference unchecked_push_front(const T& value) noexcept { + assert(size_ < N); + const T inserted = value; + std::move_backward(begin(), end(), end() + 1); + ++size_; + return front() = inserted; + } + + template + friend constexpr size_type erase_if(InplaceVector& vector, + Predicate predicate) { + const auto kept_end = + std::remove_if(vector.begin(), vector.end(), predicate); + const auto erased = static_cast(vector.end() - kept_end); + vector.size_ = static_cast(kept_end - vector.begin()); + return erased; + } + + private: + std::array elements_; + size_type size_ = 0; +}; + +} // namespace SimpleChessEngine diff --git a/Chess/MoveGenerator.cpp b/Chess/MoveGenerator.cpp index eb7fc1d..b7e8f81 100644 --- a/Chess/MoveGenerator.cpp +++ b/Chess/MoveGenerator.cpp @@ -9,17 +9,18 @@ namespace SimpleChessEngine { template <> void MoveGenerator::GenerateMovesForPiece( - PseudoLegalMove*& moves, Position& position, Bitboard target) const; + PseudoLegalMoves& moves, Position& position, Bitboard target) const; -template MoveGenerator::Moves MoveGenerator::GenerateMoves< +template MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves< MoveGenerator::Type::kAll>(Position& position) const; -template MoveGenerator::Moves MoveGenerator::GenerateMoves< +template MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves< MoveGenerator::Type::kQuiescence>(Position& position) const; + MoveGenerator::~MoveGenerator() = default; -void MoveGenerator::GenerateCastling(PseudoLegalMove*& moves, - const Position& position) { +void MoveGenerator::GenerateCastling(PseudoLegalMoves& moves, + const Position& position) { if (position.IsUnderCheck()) { return; } @@ -33,14 +34,15 @@ void MoveGenerator::GenerateCastling(PseudoLegalMove*& moves, const auto side_idx = static_cast(castling_side); const auto king_to = kKingCastlingDestination[color_idx][side_idx]; - *moves++ = PseudoLegalMove( - Move::Make(king_square, king_to)); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(king_square, king_to))); } } } template -void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, +void MoveGenerator::GenerateMovesForPiece(PseudoLegalMoves& moves, + Position& position, const Bitboard target) const { static_assert(piece != Piece::kPawn && piece != Piece::kKing); @@ -52,7 +54,7 @@ void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, Position& pos template <> void MoveGenerator::GenerateMovesForPiece( - PseudoLegalMove*& moves, Position& position, const Bitboard target) const { + PseudoLegalMoves& moves, Position& position, const Bitboard target) const { const auto us = position.GetSideToMove(); const auto us_idx = static_cast(us); const auto them = Flip(us); @@ -77,7 +79,7 @@ void MoveGenerator::GenerateMovesForPiece( while (push.Any()) { const auto to = push.PopFirstBit(); const auto from = Shift(to, opposite_direction); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } auto double_push = Shift(double_push_pawns, direction) & valid_squares; @@ -86,7 +88,7 @@ void MoveGenerator::GenerateMovesForPiece( while (double_push.Any()) { const auto to = double_push.PopFirstBit(); const auto from = Shift(Shift(to, opposite_direction), opposite_direction); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } const auto attacks = @@ -113,7 +115,7 @@ void MoveGenerator::GenerateMovesForPiece( while (attack_squares.Any()) { const auto to = attack_squares.PopFirstBit(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } } @@ -126,7 +128,7 @@ void MoveGenerator::GenerateMovesForPiece( if (attack_to.Any()) { const auto to = en_croissant_square.value(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = PseudoLegalMove(Move::Make(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move::Make(from, to))); } } } @@ -140,14 +142,14 @@ void MoveGenerator::GenerateMovesForPiece( const auto to = promotion_push.PopFirstBit(); const auto from = Shift(to, opposite_direction); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kQueen)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kKnight)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kRook)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kBishop)); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kQueen))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kKnight))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kRook))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kBishop))); } for (size_t attack_direction = 0; attack_direction < attacks.size(); @@ -159,21 +161,22 @@ void MoveGenerator::GenerateMovesForPiece( const auto to = attack_squares.PopFirstBit(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kQueen)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kKnight)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kRook)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kBishop)); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kQueen))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kKnight))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kRook))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kBishop))); } } } template -PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, - PseudoLegalMove* moves) const { +MoveGenerator::PseudoLegalMoves MoveGenerator::GeneratePseudoLegalMoves( + Position& position) const { + PseudoLegalMoves moves; const auto us = position.GetSideToMove(); const auto them = Flip(us); auto target = ~position.GetPieces(us); @@ -199,24 +202,17 @@ PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, target &= ray; pawn_target &= ray; } - auto* pawn_begin = moves; GenerateMovesForPiece(moves, position, pawn_target & ~position.GetPieces(us)); - auto* pawn_end = moves; - moves = pawn_begin; - for (auto* p = pawn_begin; p != pawn_end; ++p) { - if constexpr (type == Type::kQuiets) { - if (p->IsEnPassant()) continue; - } - if (p->IsEnPassant() && checkers.Any()) { - const auto captured = - static_cast(p->To() + (us == Player::kWhite ? -8 : 8)); - if (!checkers.Test(captured) && - !Between(king_square, checkers.GetFirstBit()).Test(p->To())) - continue; - } - *moves++ = *p; - } + erase_if(moves, [&](const PseudoLegalMove move) { + if (!move.IsEnPassant()) return false; + if constexpr (type == Type::kQuiets) return true; + if (checkers.None()) return false; + const auto captured = + static_cast(move.To() + (us == Player::kWhite ? -8 : 8)); + return !checkers.Test(captured) && + !Between(king_square, checkers.GetFirstBit()).Test(move.To()); + }); auto generate = [&]() { GenerateMovesForPiece(moves, position, target); }; @@ -233,40 +229,43 @@ PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, } template -MoveGenerator::Moves MoveGenerator::GenerateMoves(Position& position) const { - std::array moves; - auto* end = GeneratePseudoLegal(position, moves.data()); +MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves( + Position& position) const { + const auto pseudo_legal = GeneratePseudoLegalMoves(position); position.ComputePins(position.GetSideToMove()); - Moves legal; - legal.reserve(end - moves.data()); - for (auto* p = moves.data(); p != end; ++p) { - if (position.IsLegal(*p)) legal.push_back(LegalMove(static_cast(*p))); + LegalMoves legal; + for (const auto move : pseudo_legal) { + if (position.IsLegal(move)) { + legal.unchecked_push_back(LegalMove(static_cast(move))); + } } return legal; } bool MoveGenerator::HasLegalMove(Position& position) const { - std::array moves; - auto* end = GeneratePseudoLegal(position, moves.data()); + const auto pseudo_legal = GeneratePseudoLegalMoves(position); position.ComputePins(position.GetSideToMove()); - return std::any_of(moves.data(), end, - [&position](Move move) { - return position.IsLegal(move); - }); + return std::ranges::any_of(pseudo_legal, + [&position](const PseudoLegalMove move) { + return position.IsLegal(move); + }); } -template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal( - Position&, PseudoLegalMove*) const; -template PseudoLegalMove* -MoveGenerator::GeneratePseudoLegal(Position&, - PseudoLegalMove*) const; -template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal( - Position&, PseudoLegalMove*) const; -template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal< - MoveGenerator::Type::kQuiescence>(Position&, PseudoLegalMove*) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; template <> -void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, +void MoveGenerator::GenerateMovesForPiece(PseudoLegalMoves& moves, Position& position, Bitboard target) const { GenerateMovesFromSquare( @@ -275,7 +274,8 @@ void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, } template -void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& position, +void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMoves& moves, + Position& position, const BitIndex from, Bitboard target) const { assert(position.GetPieceAt(from) == piece); @@ -289,7 +289,7 @@ void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& p while (valid_moves.Any()) { const auto to = valid_moves.PopFirstBit(); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } } } // namespace SimpleChessEngine diff --git a/Chess/MoveGenerator.h b/Chess/MoveGenerator.h index 8092ac1..661fefb 100644 --- a/Chess/MoveGenerator.h +++ b/Chess/MoveGenerator.h @@ -1,8 +1,9 @@ #pragma once +#include #include -#include +#include "InplaceVector.h" #include "Move.h" #include "Position.h" @@ -21,12 +22,14 @@ class MoveGenerator { kQuiets = 8 }; - static constexpr size_t kMaxMovesPerPosition = 256; + static constexpr std::size_t kMaxMovesPerPosition = 256; + + using PseudoLegalMoves = InplaceVector; + using LegalMoves = InplaceVector; + MoveGenerator() = default; ~MoveGenerator(); - using Moves = std::vector; - /** * \brief Generates all possible moves for a given position. * @@ -35,16 +38,11 @@ class MoveGenerator { * \return All possible moves for the given position. */ template - [[nodiscard]] Moves GenerateMoves(Position& position) const; - - template - [[nodiscard, gnu::always_inline]] Moves GenerateLegalMoves(Position& position) const { - return GenerateMoves(position); - } + [[nodiscard]] LegalMoves GenerateLegalMoves(Position& position) const; template - [[nodiscard]] PseudoLegalMove* GeneratePseudoLegal(Position& position, - PseudoLegalMove* moves) const; + [[nodiscard]] PseudoLegalMoves GeneratePseudoLegalMoves( + Position& position) const; [[nodiscard]] bool HasLegalMove(Position& position) const; @@ -59,7 +57,7 @@ class MoveGenerator { * \return All possible moves for the given square. */ template - void GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, + void GenerateMovesForPiece(PseudoLegalMoves& moves, Position& position, Bitboard target) const; /** @@ -74,10 +72,11 @@ class MoveGenerator { * \return All possible moves for the given square and piece. */ template - void GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& position, BitIndex from, - Bitboard target) const; + void GenerateMovesFromSquare(PseudoLegalMoves& moves, Position& position, + BitIndex from, Bitboard target) const; - static void GenerateCastling(PseudoLegalMove*& moves, const Position& position); + static void GenerateCastling(PseudoLegalMoves& moves, + const Position& position); }; } // namespace SimpleChessEngine diff --git a/Chess/MovePicker.cpp b/Chess/MovePicker.cpp index fa320f3..e5f210d 100644 --- a/Chess/MovePicker.cpp +++ b/Chess/MovePicker.cpp @@ -1,7 +1,7 @@ #include "MovePicker.h" #include -#include +#include #include "Position.h" #include "Searcher.h" @@ -28,19 +28,16 @@ constexpr int PromotionRank(Piece promotion) { } } // namespace -void MovePicker::PartialInsertionSort(ScoredMove* begin, ScoredMove* end, - std::int64_t limit) { - if (begin == end) return; - for (auto *sorted_end = begin, *p = begin + 1; p < end; ++p) { - if (p->score >= limit) { - const auto tmp = *p; - *p = *++sorted_end; - auto* q = sorted_end; - for (; q != begin && (q - 1)->score < tmp.score; --q) { - *q = *(q - 1); - } - *q = tmp; +void MovePicker::SortByScore(ScoredRange moves) { + if (moves.empty()) return; + for (auto next = std::next(moves.begin()); next != moves.end(); ++next) { + const ScoredMove inserted = *next; + auto slot = next; + for (; slot != moves.begin() && std::prev(slot)->score < inserted.score; + --slot) { + *slot = *std::prev(slot); } + *slot = inserted; } } @@ -61,27 +58,21 @@ void MovePicker::InitPicker(Position& position, const Searcher* searcher, } void MovePicker::Generate(bool quiet) { - std::array generated; - auto* begin = generated.data(); - PseudoLegalMove* end; - const MoveGenerator generator; - if (quiet) { - end = generator.GeneratePseudoLegal( - *position_, begin); - } else if (!searcher_ && evasions_) { - end = generator.GeneratePseudoLegal(*position_, - begin); - } else if (!searcher_) { - end = generator.GeneratePseudoLegal( - *position_, begin); - } else { - end = generator.GeneratePseudoLegal( - *position_, begin); - } + const auto generated = [this, quiet] { + using enum MoveGenerator::Type; + const MoveGenerator generator; + if (quiet) return generator.GeneratePseudoLegalMoves(*position_); + if (!searcher_ && evasions_) { + return generator.GeneratePseudoLegalMoves(*position_); + } + if (!searcher_) { + return generator.GeneratePseudoLegalMoves(*position_); + } + return generator.GeneratePseudoLegalMoves(*position_); + }(); current_ = quiet ? bad_end_ : 0; end_ = current_; - for (auto* p = begin; p != end; ++p) { - const auto move = *p; + for (const auto move : generated) { if (move == tt_move_ || move == excluded_move_ || (quiet && std::ranges::find(killers_, move) != killers_.end())) continue; @@ -103,8 +94,7 @@ void MovePicker::Generate(bool quiet) { moves_[end_++] = {move, score}; } if (searcher_) { - PartialInsertionSort(moves_.data() + current_, moves_.data() + end_, - std::numeric_limits::min()); + SortByScore({moves_.begin() + current_, moves_.begin() + end_}); } } @@ -168,10 +158,11 @@ MaybeLegalMove MovePicker::SelectNextMove() { !position_->IsLegal(move, blockers_)) continue; if (!move.IsQuiet(*position_)) { - auto* found = std::find_if( - moves_.data(), moves_.data() + bad_end_, - [move](const auto& data) { return data.move == move; }); - if (found == moves_.data() + bad_end_) continue; + const ScoredRange bad_captures{moves_.begin(), + moves_.begin() + bad_end_}; + const auto found = + std::ranges::find(bad_captures, move, &ScoredMove::move); + if (found == bad_captures.end()) continue; found->move = Move::None(); } killers_[index] = move; diff --git a/Chess/MovePicker.h b/Chess/MovePicker.h index 55cd295..5210cf0 100644 --- a/Chess/MovePicker.h +++ b/Chess/MovePicker.h @@ -2,6 +2,7 @@ #include #include #include +#include #include "Evaluation.h" #include "Move.h" @@ -40,12 +41,15 @@ class MovePicker { std::int64_t score; }; - static void PartialInsertionSort(ScoredMove* begin, ScoredMove* end, - std::int64_t limit); + using ScoredMoves = + std::array; + using ScoredRange = std::ranges::subrange; + + static void SortByScore(ScoredRange moves); void Generate(bool quiet); [[nodiscard]] LegalMove Emit(LegalMove move); - std::array moves_; + ScoredMoves moves_; std::array killers_{}; Position* position_ = nullptr; const Searcher* searcher_ = nullptr; diff --git a/Chess/Position.cpp b/Chess/Position.cpp index 69b8468..10433b2 100644 --- a/Chess/Position.cpp +++ b/Chess/Position.cpp @@ -1,5 +1,6 @@ #include "Position.h" +#include #include #include "Attacks.h" @@ -516,11 +517,10 @@ bool Position::IsPseudoLegal(const Move &move) { const auto to = move.To(); if (!GetPieces(side_to_move_).Test(from)) return false; if (!move.IsNormal()) { - std::array moves; - const auto *end = - MoveGenerator{}.GeneratePseudoLegal( - *this, moves.data()); - return std::find(static_cast(moves.data()), end, move) != end; + return std::ranges::contains( + MoveGenerator{}.GeneratePseudoLegalMoves( + *this), + move); } if ((move.Raw() & 0x3000) || from == to || GetPieces(side_to_move_).Test(to)) return false; diff --git a/Chess/Searcher.h b/Chess/Searcher.h index 6b25369..9f3ba37 100644 --- a/Chess/Searcher.h +++ b/Chess/Searcher.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -136,7 +137,10 @@ class Searcher { [[nodiscard]] std::uint64_t GetRootEffort(const Move &move) const; [[nodiscard]] RootScore GetRootScore(const Move &move) const; - [[nodiscard]] MoveGenerator::Moves GetPrincipalVariation( + using PrincipalVariation = + InplaceVector::max()>; + + [[nodiscard]] PrincipalVariation GetPrincipalVariation( Depth max_depth, Position position) const; private: @@ -216,9 +220,9 @@ inline const Position &Searcher::GetPosition() const { return current_position_; inline const Move &Searcher::GetCurrentBestMove() const { return best_move_; } -inline MoveGenerator::Moves Searcher::GetPrincipalVariation(Depth max_depth, - Position position) const { - MoveGenerator::Moves answer; +inline Searcher::PrincipalVariation Searcher::GetPrincipalVariation( + Depth max_depth, Position position) const { + PrincipalVariation answer; for (Depth i = 0; i < max_depth; ++i) { const auto hashed_node = best_moves_->GetNode(position); if (!hashed_node.IsOccupied()) break; @@ -228,7 +232,7 @@ inline MoveGenerator::Moves Searcher::GetPrincipalVariation(Depth max_depth, if (found == legal_moves.end()) break; position.DoMove(*found); - answer.push_back(*found); + answer.unchecked_push_back(*found); } return answer; } diff --git a/Chess/SimpleChessEngine.h b/Chess/SimpleChessEngine.h index 8884d6a..41db835 100644 --- a/Chess/SimpleChessEngine.h +++ b/Chess/SimpleChessEngine.h @@ -215,7 +215,7 @@ class ChessEngine { }; void PrintInfo(const DebugInfo& info, Eval eval, Depth current_depth, - const MoveGenerator::Moves& principal_variation, + const Searcher::PrincipalVariation& principal_variation, std::chrono::duration search_time) { if (!reporting_) return; PrintInfo(ScoreInfo{eval}); @@ -277,7 +277,7 @@ inline void SimpleChessEngine::ChessEngine::ComputeBestMove( } const auto legal_moves = - MoveGenerator{}.GenerateMoves(position_); + MoveGenerator{}.GenerateLegalMoves(position_); if (legal_moves.empty()) { finish(BestMoveInfo{Move::None(), std::nullopt}); return; @@ -301,7 +301,8 @@ inline void SimpleChessEngine::ChessEngine::ComputeBestMove( DebugInfo info; Eval eval = position_.Evaluate(); EBFsInfo ebfs; - MoveGenerator::Moves principal_variation{legal_best_move}; + Searcher::PrincipalVariation principal_variation; + principal_variation.unchecked_push_back(legal_best_move); Depth trusted_depth = 0; Depth current_depth = initial_depth_; Depth last_best_move_depth = 0; @@ -352,7 +353,7 @@ inline void SimpleChessEngine::ChessEngine::ComputeBestMove( pv_position.DoMove(legal_best_move); principal_variation = searcher_.GetPrincipalVariation( static_cast(searched_depth - 1), std::move(pv_position)); - principal_variation.insert(principal_variation.begin(), legal_best_move); + principal_variation.unchecked_push_front(legal_best_move); ponder_move_ = principal_variation.size() > 1 ? std::optional{principal_variation[1]} : std::nullopt; diff --git a/Chess/UciCommunicator.h b/Chess/UciCommunicator.h index 51e2b96..4edf230 100644 --- a/Chess/UciCommunicator.h +++ b/Chess/UciCommunicator.h @@ -156,7 +156,7 @@ class SearchThread { Position position = info.position; if (MoveGenerator{} - .GenerateMoves(position) + .GenerateLegalMoves(position) .size() == 1) { optimum = std::min(optimum, kSingleMoveTime); } diff --git a/Tests/AspirationWindowTests.cpp b/Tests/AspirationWindowTests.cpp index 5fbf204..bdae08d 100644 --- a/Tests/AspirationWindowTests.cpp +++ b/Tests/AspirationWindowTests.cpp @@ -281,9 +281,10 @@ TEST(AspirationSearch, FindsQueenSacrificeMateAtCompletedDepthEight) { TEST(AspirationSearch, PrintsCompletedDepthWhenPvIsShorter) { auto position = PositionFactory{}(); - MoveGenerator::Moves moves{CheckedMove(position, "e2e4")}; + Searcher::PrincipalVariation moves; + moves.unchecked_push_back(CheckedMove(position, "e2e4")); position.DoMove(moves.front()); - moves.push_back(CheckedMove(position, "e7e5")); + moves.unchecked_push_back(CheckedMove(position, "e7e5")); std::ostringstream output; output << PrincipalVariationInfo{18, moves}; EXPECT_EQ(output.str(), "info depth 18 pv e2e4 e7e5\n"); diff --git a/Tests/HistoryPersistenceTests.cpp b/Tests/HistoryPersistenceTests.cpp index 44461ad..c1da97f 100644 --- a/Tests/HistoryPersistenceTests.cpp +++ b/Tests/HistoryPersistenceTests.cpp @@ -75,7 +75,7 @@ TEST(HistoryPersistence, SecondGoDecaysButterflyAndPreservesContinuation) { auto position = searcher.GetPosition(); const auto side = static_cast(position.GetSideToMove()); for (const auto move : - MoveGenerator{}.GenerateMoves(position)) { + MoveGenerator{}.GenerateLegalMoves(position)) { EXPECT_EQ(searcher.GetQuietScore(move, 2), expected[side][move.From()][move.To()]); } diff --git a/Tests/InplaceVectorTests.cpp b/Tests/InplaceVectorTests.cpp new file mode 100644 index 0000000..ab2a892 --- /dev/null +++ b/Tests/InplaceVectorTests.cpp @@ -0,0 +1,49 @@ +#include + +#include +#include + +#include "InplaceVector.h" + +using namespace SimpleChessEngine; + +static_assert(std::ranges::contiguous_range>); +static_assert(std::ranges::contiguous_range>); +static_assert([] { + InplaceVector values; + for (int value = 0; value < 256; ++value) values.unchecked_push_back(value); + if (values.size() != values.capacity() || values.back() != 255) return false; + const auto removed = erase_if(values, [](int value) { return value % 2 == 0; }); + return removed == 128 && values.size() == 128 && values.front() == 1 && + std::as_const(values).back() == 255; +}()); + +TEST(InplaceVector, BackRefersToLastElementAfterErasure) { + InplaceVector values; + values.unchecked_push_back(1); + values.unchecked_push_back(2); + values.unchecked_push_back(3); + values.back() = 4; + EXPECT_EQ(erase_if(values, [](int value) { return value == 4; }), 1); + EXPECT_EQ(std::as_const(values).back(), 2); + EXPECT_EQ(values.size(), 2); +} + +static_assert([] { + InplaceVector values; + values.unchecked_push_back(1); + values.unchecked_push_back(2); + values.unchecked_push_front(values.back()); + return values.size() == 3 && values.front() == 2 && values[1] == 1 && + values.back() == 2; +}()); + +TEST(InplaceVector, PushFrontPreservesAliasedValue) { + InplaceVector values; + values.unchecked_push_back(1); + values.unchecked_push_back(2); + values.unchecked_push_front(values.back()); + EXPECT_EQ(values.front(), 2); + EXPECT_EQ(values[1], 1); + EXPECT_EQ(values.back(), 2); +} diff --git a/Tests/NullMovePruningTests.cpp b/Tests/NullMovePruningTests.cpp index ff42a3d..2332a76 100644 --- a/Tests/NullMovePruningTests.cpp +++ b/Tests/NullMovePruningTests.cpp @@ -179,7 +179,7 @@ TEST_F(NullMovePruning, AcceptsConvertedMinimumBetaInclusively) { TEST_F(NullMovePruning, StaticEvalAtBetaSetsImprovingForLaterPruning) { auto position = PositionFactory{}(); const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); ASSERT_EQ(moves.size(), 20u); for (const Eval gap : {0, -1}) { const auto beta = position.Evaluate() - gap; diff --git a/Tests/QuiescenceTTTests.cpp b/Tests/QuiescenceTTTests.cpp index abb9b03..a8f696d 100644 --- a/Tests/QuiescenceTTTests.cpp +++ b/Tests/QuiescenceTTTests.cpp @@ -104,7 +104,7 @@ TEST(QuiescenceTT, QuietTtMoveIsIgnoredOutsideCheck) { TEST(QuiescenceTT, CaptureTtMoveIsSearchedFirstAndStored) { auto position = PositionFactory{}("k7/8/8/3p4/3R3p/8/8/K7 w - - 0 1"); const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); ASSERT_GT(moves.size(), 1u); const auto tt_move = moves.back(); ASSERT_TRUE(position.StaticExchangeEvaluation(tt_move, 1)); @@ -128,7 +128,7 @@ TEST(QuiescenceTT, QuietEvasionTtMoveIsSearchedFirstAndStored) { auto position = PositionFactory{}("k3r3/8/8/8/8/8/P7/4K3 w - - 0 1"); ASSERT_TRUE(position.IsUnderCheck()); const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); ASSERT_GT(moves.size(), 1u); const auto tt_move = moves.back(); ASSERT_TRUE(tt_move.IsQuiet(position)); diff --git a/Tests/SearchCorrectnessTests.cpp b/Tests/SearchCorrectnessTests.cpp index e0cfc2a..df3b8fa 100644 --- a/Tests/SearchCorrectnessTests.cpp +++ b/Tests/SearchCorrectnessTests.cpp @@ -417,11 +417,11 @@ TEST(ProbCut, TacticalPickerOrdersCapturesAndOmitsQuietsAndUnderpromotions) { Searcher searcher(position); MovePicker picker; picker.InitProbCut(position, &searcher, 1); - std::vector moves; + MoveGenerator::LegalMoves moves; for (auto next = picker.SelectProbCutMove(-2000); next; next = picker.SelectProbCutMove(-2000)) { const auto& move = *next; - moves.push_back(move); + moves.unchecked_push_back(move); EXPECT_FALSE(move.IsQuiet(position)); EXPECT_TRUE(!move.IsPromotion() || move.PromotionPiece() == Piece::kQueen); const auto before = position; diff --git a/Tests/StagedMovePickerTests.cpp b/Tests/StagedMovePickerTests.cpp index 404f526..1d8e810 100644 --- a/Tests/StagedMovePickerTests.cpp +++ b/Tests/StagedMovePickerTests.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include "MoveGenerator.h" @@ -41,11 +42,12 @@ TEST(StagedMovePicker, PseudoLegalValidationMatchesGenerator) { for (const auto* fen : kPositions) { SCOPED_TRACE(fen); auto position = PositionFactory{}(fen); - std::array generated; - auto* end = MoveGenerator{}.GeneratePseudoLegal( - position, generated.data()); std::set expected; - for (auto* p = generated.data(); p != end; ++p) expected.insert(p->Raw()); + for (const auto move : + MoveGenerator{}.GeneratePseudoLegalMoves( + position)) { + expected.insert(move.Raw()); + } for (unsigned raw = 0; raw < 65536; ++raw) { EXPECT_EQ(position.IsPseudoLegal(Move(static_cast(raw))), expected.contains(raw)) @@ -59,17 +61,17 @@ TEST(StagedMovePicker, CaptureAndQuietStagesPartitionLegalMoves) { SCOPED_TRACE(fen); auto position = PositionFactory{}(fen); const auto expected = LegalSet(position); - std::array generated; - auto* middle = - MoveGenerator{}.GeneratePseudoLegal( - position, generated.data()); - auto* end = - MoveGenerator{}.GeneratePseudoLegal( - position, middle); + const MoveGenerator generator; + const auto captures = + generator.GeneratePseudoLegalMoves( + position); + const auto quiets = + generator.GeneratePseudoLegalMoves( + position); std::set actual; - for (auto* p = generated.data(); p != end; ++p) { - if (!position.IsLegal(*p)) continue; - EXPECT_TRUE(actual.insert(p->Raw()).second); + for (const auto move : std::views::concat(captures, quiets)) { + if (!position.IsLegal(move)) continue; + EXPECT_TRUE(actual.insert(move.Raw()).second); } EXPECT_EQ(actual, expected); } @@ -133,8 +135,8 @@ TEST(StagedMovePicker, QuiescenceTtMoveComesFirstWithoutDuplicates) { auto position = PositionFactory{}(fen); const auto expected = position.IsUnderCheck() - ? MoveGenerator{}.GenerateMoves(position) - : MoveGenerator{}.GenerateMoves( + ? MoveGenerator{}.GenerateLegalMoves(position) + : MoveGenerator{}.GenerateLegalMoves( position); for (const auto tt_move : expected) { if (!position.IsUnderCheck() && !tt_move.IsEnPassant() && diff --git a/Tests/TypedMoveTests.cpp b/Tests/TypedMoveTests.cpp index 085d7e1..5105033 100644 --- a/Tests/TypedMoveTests.cpp +++ b/Tests/TypedMoveTests.cpp @@ -91,9 +91,6 @@ TEST(TypedMoves, AcceptsEveryGeneratedLegalMove) { "4k3/8/8/8/8/8/8/6KR w H - 0 1"}) { auto position = PositionFactory{}(fen); const auto moves = MoveGenerator{}.GenerateLegalMoves(position); - const auto raw_moves = MoveGenerator{}.GenerateMoves(position); - ASSERT_EQ(moves.size(), raw_moves.size()); - for (size_t i = 0; i < moves.size(); ++i) EXPECT_EQ(moves[i], raw_moves[i]); for (const auto move : moves) { const Move raw = move; const PseudoLegalMove degraded = move; diff --git a/Tests/UciInfoTests.cpp b/Tests/UciInfoTests.cpp index 9014560..f86ceda 100644 --- a/Tests/UciInfoTests.cpp +++ b/Tests/UciInfoTests.cpp @@ -16,7 +16,10 @@ TEST(PrincipalVariationInfo, ReportsIterationDepthForShortPV) { const auto first = CheckedMove(position, "e2e4"); position.DoMove(first); const auto second = CheckedMove(position, "e7e5"); - output << PrincipalVariationInfo{14, {first, second}}; + Searcher::PrincipalVariation pv; + pv.unchecked_push_back(first); + pv.unchecked_push_back(second); + output << PrincipalVariationInfo{14, pv}; EXPECT_EQ(output.str(), "info depth 14 pv e2e4 e7e5\n"); } diff --git a/Tests/tablebase_search_test.py b/Tests/tablebase_search_test.py index 2d81e19..fc61bea 100644 --- a/Tests/tablebase_search_test.py +++ b/Tests/tablebase_search_test.py @@ -68,7 +68,7 @@ def wait_for(self, pattern: str, timeout: float = 3.0) -> str: def ready(self) -> None: self.send("isready") - self.wait_for("readyok") + self.wait_for("readyok", timeout=60) def search(self, fen: str, control: str, invalid: bool = False, root_hit: bool = False) -> None: diff --git a/Tools/TablebaseBenchmark.cpp b/Tools/TablebaseBenchmark.cpp index c880b1e..c2738c9 100644 --- a/Tools/TablebaseBenchmark.cpp +++ b/Tools/TablebaseBenchmark.cpp @@ -75,7 +75,7 @@ int main(int argc, char** argv) { continue; } const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); const auto root_move = tablebase->RootMove(position); if (tablebase->ProbeWdl(position) && root_move && std::ranges::find(moves, *root_move) != moves.end()) {