diff --git a/.gitignore b/.gitignore index 52d905e..74eaf9f 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,6 @@ obj/ Eleanor # Other -.vscode \ No newline at end of file +.vscode +Scripts/game.pgn +data.binpack \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 57c3b17..0000000 --- a/README.md +++ /dev/null @@ -1,65 +0,0 @@ -![Eleanor](https://i.ibb.co/T1ZV9wN/91dea356-a725-45fd-b7a2-cd92afddcba4-1.jpg) -# Eleanor is a chess engine -## Features - -- Bitboard board representation -- Magic Bitboards -- Legal move generation -- Precalculated attack tables -- Storing moves in a 16 bit word -- Copy/make moving -- Simple evaluation (material and piece-square tables, MVV-LVA) -- Principal Variation Search -- Move ordering -- Time management -- UCI - -## Installation - -> Prerequisites: -> - A C++ compiler -> - Access to `make` command - - 1. Clone the repo to your PC - - 2. Run the command `make` in the root directory - > You can specify the compiler with the flag `CXX` - > and the executable name with `EXE`. - > By default they are `g++` and `Eleanor` respectively. - -3. Run the executable - -## How to use -There are some commands that you can use the engine with. - -- **`position`**: Set the current position of the board with [FEN](https://www.chess.com/terms/fen-chess). -`position [FEN]` or `position startpos` can be used. -- **`ucinewgame`** resets the position and game state -- **`quit`** terminates the program -- **`go`** is the command that asks what is the best move in the current position (search), -but we have to give it some parameters: -`wtime` `btime` `winc` `binc` -The first letter tells the color of player -wtime sets the remaining time of the white player -and winc sets the increments for the white player. -**It's important that these parameters are given in milliseconds!** -- **`stop`** stops the current search -- **`bench`** tests the search speed of the engine on a set of positions - -Also, the engine can be connected to any GUI software that has UCI support. - -## Sources I used -[Chess Programming Wiki](https://www.chessprogramming.org/Main_Page "Chess Programming Wiki") - -[Maksim Korzh's chess engine in C series](https://www.youtube.com/watch?v=QUNP-UjujBM&list=PLmN0neTso3Jxh8ZIylk74JpwfiWNI76Cs "Maksim Korzh's chess engine in C series") - -[Stockfish discord helping community](https://discord.com/invite/GWDRS3kU6R "Stockfish discord community") - -[Logo is generated by AI](https://deepai.org/ "Logo is generated by AI") - -
- -**The project is still in progress and developed constantly. Contributions are highly appreciated.** - -###### Last edited: 2025-01-23 - diff --git a/Scripts/game.pgn b/Scripts/game.pgn new file mode 100644 index 0000000..d73d958 --- /dev/null +++ b/Scripts/game.pgn @@ -0,0 +1,45 @@ +[Event "?"] +[Site "?"] +[Date "2025.04.01"] +[Round "1"] +[White "Eleanor-base"] +[Black "Eleanor-dev"] +[Result "1-0"] +[FEN "2r5/1k6/2p4p/4p3/3b1p1B/5B1P/2R5/7K b - - 0 1"] +[GameDuration "00:00:05"] +[GameEndTime "2025-04-01T18:10:20.331 Central Europe Daylight Time"] +[GameStartTime "2025-04-01T18:10:14.365 Central Europe Daylight Time"] +[PlyCount "58"] +[SetUp "1"] +[Termination "abandoned"] +[TimeControl "2.53+0.03"] + +1... Kb6 {-0.43 11/0 127 176492} 2. Kg2 {+0.45 10/0 117 182773} +Kb5 {-0.43 10/0 139 43190} 3. Bf2 {+0.48 10/0 94 154681} +Rg8+ {-0.41 10/0 104 181006} 4. Kf1 {+0.43 11/0 137 107880} +c5 {-0.42 11/0 114 186919} 5. Ke2 {+0.42 10/0 131 26558} +Rd8 {-0.31 11/0 126 178073} 6. Rd2 {+0.36 8/0 129 64726} +c4 {+0.11 11/0 124 101858} 7. Bxd4 {-0.11 11/0 86 135900} +Rxd4 {+0.10 11/0 124 121262} 8. Rxd4 {-0.01 13/0 117 207646} +exd4 {0.00 14/0 95 197856} 9. h4 {0.00 13/0 105 197264} +Kb4 {0.00 14/0 91 195163} 10. Kd2 {0.00 13/0 111 105382} +Kc5 {0.00 13/0 109 62420} 11. h5 {0.00 14/0 78 150612} Kb4 {0.00 16/0 79 181784} +12. Bd1 {0.00 15/0 86 193192} Kc5 {0.00 16/0 97 111839} +13. Kc2 {0.00 17/0 90 192373} Kb4 {0.00 17/0 95 120438} +14. Bf3 {0.00 17/0 76 176571} Kc5 {0.00 17/0 101 66844} +15. Ba8 {0.00 18/0 75 165249} Kb4 {0.00 18/0 86 198233} +16. Bf3 {0.00 18/0 77 183908} d3+ {+0.01 16/0 69 164278} +17. Kd2 {-0.03 16/0 81 145118} Kb3 {0.00 17/0 84 107987} +18. Be4 {0.00 16/0 61 125373} f3 {+0.09 17/0 75 163654} +19. Bxd3 {-0.01 16/0 86 109653} cxd3 {+0.57 18/0 55 140500} +20. Kxd3 {-0.97 22/0 73 227257} f2 {+0.98 22/0 71 204108} +21. Ke2 {-0.99 20/0 81 29772} Kc4 {+1.48 22/0 62 180691} +22. Kxf2 {-2.11 23/0 59 175088} Kd4 {+2.51 27/0 52 189697} +23. Kf3 {-3.34 26/0 62 187791} Ke5 {+2.50 32/0 48 167062} +24. Ke3 {-2.24 28/0 54 178563} Kf5 {+2.15 31/0 72 166014} +25. Kf3 {-2.22 32/0 52 188757} Kg5 {0.00 35/0 49 143292} +26. Ke4 {-2.09 32/0 62 209505} Kxh5 {0.00 39/0 48 159744} +27. Kf5 {-2.09 33/0 70 226933} Kh4 {0.00 52/0 46 161548} +28. Kf4 {0.00 37/0 51 178144} h5 {0.00 64/0 29 95868} +29. Kf3 {0.00 51/0 46 165319} Kh3 {0.00 64/0 15 14259} +30. Kf4 {0.00 52/0 64 186059, Black disconnects} 1-0 \ No newline at end of file diff --git a/Scripts/pgntouci.py b/Scripts/pgntouci.py new file mode 100644 index 0000000..76a3223 --- /dev/null +++ b/Scripts/pgntouci.py @@ -0,0 +1,19 @@ +########################################## +# convert pgn to uci +########################################## +import chess +import chess.pgn + +pgn = open("game.pgn") + +game = chess.pgn.read_game(pgn) + +board = game.board() + +moves = "position fen " + board.fen() + " moves" + +for move in game.mainline_moves(): + board.push(move) + moves += " " + move.uci() + +print(moves) \ No newline at end of file diff --git a/source/benchmark.cpp b/source/benchmark.cpp index fce2932..120024e 100644 --- a/source/benchmark.cpp +++ b/source/benchmark.cpp @@ -63,7 +63,7 @@ constexpr std::array fenPositions = { void RunBenchmark() { Board board; - int depth = 8; + int depth = BENCH_DEPTH; int ply = 0; benchStarted = true; searchStopped = false; @@ -80,7 +80,7 @@ void RunBenchmark() { Stopwatch sw; for (int i = 0; i < fenPositions.size(); i++) { board.SetByFen(fenPositions[i]); - PVS(board, depth, -inf, inf, ply); + SearchPosition(board, SearchParams()); } std::cout << nodes << " nodes " << int(nodes/sw.GetElapsedSec()) << " nps" << std::endl; diff --git a/source/benchmark.h b/source/benchmark.h index 69c9c98..b40f633 100644 --- a/source/benchmark.h +++ b/source/benchmark.h @@ -1,4 +1,6 @@ #pragma once #include +constexpr int BENCH_DEPTH = 8; + void RunBenchmark(); diff --git a/source/board.cpp b/source/board.cpp index 6b1736f..dbedc09 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -222,6 +222,7 @@ void Board::Promote(int square, int pieceType, int color, bool isCapture) { } bool Board::MakeMove(Move move) { + Board save = *this; // Null Move if (!move) { int newEpTarget = noEPTarget; @@ -347,7 +348,10 @@ bool Board::MakeMove(Move move) { MOVEGEN::GenThreatMaps(*this); sideToMove = !sideToMove; - if (InCheck()) return false; + if (InCheck()) { + *this = save; + return false; + } sideToMove = !sideToMove; if (attackerColor == Black) fullMoves++; diff --git a/source/board.h b/source/board.h index 4223eca..9b5f369 100644 --- a/source/board.h +++ b/source/board.h @@ -9,8 +9,8 @@ constexpr int noEPTarget = -1; constexpr int MAX_MOVES = 218; -inline int positionIndex = 0; -inline U64 positionHistory[1000]; +thread_local inline int positionIndex = 0; +thread_local inline U64 positionHistory[1000]; class Board { public: diff --git a/source/datagen.cpp b/source/datagen.cpp new file mode 100644 index 0000000..0f300a0 --- /dev/null +++ b/source/datagen.cpp @@ -0,0 +1,311 @@ +#include +#include +#include +#include +#include +#include +#include +#include "datagen.h" +#include "movegen.h" +#include "evaluate.h" +#include "search.h" +#include "movegen.h" +#include "stopwatch.h" + +#ifdef _WIN32 +#include +#endif + +#ifdef _WIN32 +static void HideCursor() { + HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + CONSOLE_CURSOR_INFO cursorInfo; + GetConsoleCursorInfo(hConsole, &cursorInfo); + cursorInfo.bVisible = FALSE; + SetConsoleCursorInfo(hConsole, &cursorInfo); +} + +static void ShowCursor() { + HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + CONSOLE_CURSOR_INFO cursorInfo; + GetConsoleCursorInfo(hConsole, &cursorInfo); + cursorInfo.bVisible = TRUE; + SetConsoleCursorInfo(hConsole, &cursorInfo); +} +#endif + +static void HideCursorLinux() { + std::cout << "\033[?25l"; +} + +static void ShowCursorLinux() { + std::cout << "\033[?25h"; +} + +namespace DATAGEN { + +std::mutex mutex; + +static void PlayRandMoves(Board &board) { + std::random_device dev; + std::mt19937 rng(dev()); + + for (int count = 0; count < RAND_MOVES; count++) { + MOVEGEN::GenerateMoves(board); + std::uniform_int_distribution dist(0, board.currentMoveIndex - 1); + + bool isLegal = board.MakeMove(board.moveList[dist(rng)]); + if (!isLegal) count--; + } + + MOVEGEN::GenerateMoves(board); +} + +static bool IsGameOver(Board &board) { + bool isDraw = SEARCH::IsDraw(board); + if (isDraw) return true; + + int moveSeen = 0; + + for (int i = 0; i < board.currentMoveIndex; i++) { + Board copy = board; + bool isLegal = copy.MakeMove(board.moveList[i]); + + if (!isLegal) continue; + positionIndex--; + moveSeen++; + } + + if (moveSeen == 0) return true; + return false; +} + +std::ostream &operator<<(std::ostream &os, const MarlinFormat &format) { + os.write(reinterpret_cast(&format), sizeof(MarlinFormat)); + return os; +} + +std::istream &operator>>(std::istream &is, MarlinFormat &format) { + is.read(reinterpret_cast(&format), sizeof(MarlinFormat)); + return is; +} + +std::ostream &operator<<(std::ostream &os, const ScoredMove &move) { + os.write(reinterpret_cast(&move), sizeof(ScoredMove)); + return os; +} + +std::istream &operator>>(std::istream &is, ScoredMove &move) { + is.read(reinterpret_cast(&move), sizeof(ScoredMove)); + return is; +} + +std::ostream &operator<<(std::ostream &os, const Game &game) { + os << game.format; + + uint32_t moveCount = game.moves.size(); + os.write(reinterpret_cast(&moveCount), sizeof(moveCount)); + + for (const auto &move : game.moves) { + os << move; + } + + return os; +} + +std::istream &operator>>(std::istream &is, Game &game) { + is >> game.format; + + uint32_t moveCount; + is.read(reinterpret_cast(&moveCount), sizeof(moveCount)); + + game.moves.resize(moveCount); + for (auto &move : game.moves) { + is >> move; + } + + return is; +} + +static void WriteToFile(const Game &game, const std::string &filename) { + std::lock_guard lock(mutex); + // Create a buffer to store the serialized data [prevents corruption] + std::vector buffer; + + const size_t formatSize = sizeof(MarlinFormat); + buffer.resize(formatSize + sizeof(uint32_t) * game.moves.size() + sizeof(uint32_t)); + + std::memcpy(buffer.data(), &game.format, formatSize); + + size_t offset = formatSize; + + for (const auto &move : game.moves) { + std::memcpy(buffer.data() + offset, &move, sizeof(ScoredMove)); + offset += sizeof(ScoredMove); + } + + uint32_t zero = 0; + std::memcpy(buffer.data() + offset, &zero, sizeof(zero)); + + std::ofstream file(filename, std::ios::binary | std::ios::out | std::ios::app); + if (!file) throw std::runtime_error("Failed to open file for writing"); + + file.write(buffer.data(), buffer.size()); + + file.close(); +} + +void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads) { + double elapsed = stopwatch.GetElapsedSec(); + double positionsPerSec = elapsed > 0 ? positions / elapsed : 0; + + int positionsInThousands = static_cast(round(positions / 1000.0)); + int targetInThousands = static_cast(round(targetPositions / 1000.0)); + + std::cout << "\033[H"; + + int width = 60; + + std::string title = "Eleanor - Datagen"; + int titlePadding = (width - title.length()) / 2; + std::cout << std::setw(titlePadding + title.length()) << title << std::endl; + + std::cout << std::string(width, '=') << std::endl; + + std::cout << std::endl; + + std::cout << std::fixed << std::setprecision(0); + + std::ostringstream datagenTextStream; + datagenTextStream << std::fixed << std::setprecision(2) + << "Positions processed: " << positions / 1000.0 << "K | Target: " << targetPositions / 1000.0 << "K"; + std::string datagenText = datagenTextStream.str(); + int datagenPadding = (width - datagenText.length()) / 2; + std::cout << std::setw(datagenPadding + datagenText.length()) << datagenText << std::endl; + + std::cout << std::endl; + + std::string elapsedText = "Elapsed Time: " + std::to_string(static_cast(round(elapsed))) + " sec"; + int elapsedPadding = (width - elapsedText.length()) / 2; + std::cout << std::setw(elapsedPadding + elapsedText.length()) << elapsedText << std::endl; + + std::string positionsPerSecText = "Positions/sec: " + std::to_string(static_cast(round(positionsPerSec))); + int positionsPerSecPadding = (width - positionsPerSecText.length()) / 2; + std::cout << std::setw(positionsPerSecPadding + positionsPerSecText.length()) << positionsPerSecText << std::endl; + + std::cout << std::endl; + + std::string threadsText = "Threads: " + std::to_string(static_cast(threads)); + int threadsTextPadding = (width - threadsText.length()) / 2; + std::cout << std::setw(threadsTextPadding + threadsText.length()) << threadsText << std::endl; + + std::cout << std::endl; + + int barWidth = 50; + double progress = (double)positions / targetPositions; + int pos = (int)(progress * barWidth); + + std::string progressBar = "["; + for (int i = 0; i < barWidth; ++i) { + if (i < pos) { + progressBar += "="; + } else if (i == pos) { + progressBar += ">"; + } else { + progressBar += " "; + } + } + progressBar += "] " + std::to_string(static_cast(round(progress * 100.0))) + " %"; + + int progressPadding = (width - progressBar.length()) / 2; + std::cout << std::setw(progressPadding + progressBar.length()) << progressBar << std::endl; + + std::cout << std::endl; + + std::cout << std::string(width, '-') << std::endl; +} + +void PlayGame(std::atomic& positions, int targetPositions) { + while (positions.load(std::memory_order_relaxed) < targetPositions) { + Game game; + Board board; + + uint8_t wdl = 1; + positionIndex = 0; + std::memset(SEARCH::killerMoves, 0, sizeof(SEARCH::killerMoves)); + SEARCH::history.Clear(); + + PlayRandMoves(board); + + int staticEval = HCE::Evaluate(board); + + SEARCH::SearchResults safeResults; + + MOVEGEN::GenerateMoves(board); + + while (!IsGameOver(board)) { + SEARCH::SearchResults results = SEARCH::SearchPosition(board, SearchParams()); + + if (!results.bestMove) break; + safeResults = results; + + game.moves.push_back(ScoredMove(results.bestMove.ConvertToViriMoveFormat(), UTILS::ConvertToWhiteRelative(board, results.score))); + board.MakeMove(results.bestMove); + MOVEGEN::GenerateMoves(board); + + // Increment positions, but do not exceed target + if (positions.load(std::memory_order_relaxed) < targetPositions) { + positions.fetch_add(1, std::memory_order_relaxed); + + if (std::abs(safeResults.score) >= std::abs(SEARCH::MATE_SCORE) - SEARCH::MAX_PLY) { + wdl = board.sideToMove ? 2 : 0; + } + + + } + } + game.format.packFrom(board, UTILS::ConvertToWhiteRelative(board, staticEval), wdl); + WriteToFile(game, "data.binpack"); + } +} + +void Run(int targetPositions, int threads) { + #ifdef _WIN32 + system("cls"); + HideCursor(); + #else + std::cout << "\033[2J\033[H"; + HideCursorLinux(); + #endif + + Stopwatch stopwatch; + + std::atomic positions = 0; + + for (int i = 0; i < threads; i++) { + auto worker = std::thread(PlayGame, std::ref(positions), targetPositions * 1000); + worker.detach(); + } + + int lastPrintedPosition = 0; + double lastPrintedTime = stopwatch.GetElapsedSec(); + + while (positions.load(std::memory_order_relaxed) < targetPositions * 1000) { + // Print progress every second + double currentTime = stopwatch.GetElapsedSec(); + if (currentTime - lastPrintedTime >= 1) { + lastPrintedTime = currentTime; + PrintProgress(positions, targetPositions * 1000, stopwatch, threads); + } + } + + PrintProgress(positions, targetPositions * 1000, stopwatch, threads); + + #ifdef _WIN32 + ShowCursor(); + #else + ShowCursorLinux(); + #endif +} + +} \ No newline at end of file diff --git a/source/datagen.h b/source/datagen.h new file mode 100644 index 0000000..28003ea --- /dev/null +++ b/source/datagen.h @@ -0,0 +1,81 @@ +#pragma once +#include "board.h" +#include "utils.h" +#include + +namespace DATAGEN { + +constexpr int SOFT_NODES = 5000; +constexpr int HARD_NODES = 100000; +constexpr int RAND_MOVES = 8; + +struct MarlinFormat { + uint64_t occupancy; // 8 bytes: Bitboard representing all occupied squares (includes all pieces) + std::array pieces; // 16 bytes: 64 squares stored in 4-bit format (2 squares per byte) + uint8_t stmEPSquare; // 1 byte: STM (side to move) in bit 7, EP square in bits 0-5 + uint8_t halfmoveClock; // 1 byte: Halfmove counter for the 50-move rule (incremented after each move) + uint16_t fullmoveNumber; // 2 bytes: Full move counter, starting at 1 (increments after Black's move) + int16_t eval; // 2 bytes: Search score (e.g., centipawns, positive = White advantage) + uint8_t wdl; // 1 byte: 0 = white loss, 1 = draw, 2 = white win + uint8_t extra; // 1 byte: Reserved for future use or additional data + + void packFrom(Board& board, int16_t eval, uint8_t wdl) { + const uint8_t stm = board.sideToMove == Black ? (1 << 7) : 0; + + occupancy = board.occupied; + pieces = UTILS::CompressPieces(board); + stmEPSquare = stm | (board.enPassantTarget == noEPTarget ? 64 : board.enPassantTarget); + + halfmoveClock = board.halfMoves; + fullmoveNumber = board.fullMoves; + this->eval = eval; + this->wdl = wdl; + extra = 0; + } + + void writeToFile(const std::string& filename) const { + std::ofstream outFile(filename, std::ios::binary); + if (!outFile) { + std::cerr << "Error opening file for writing!" << std::endl; + return; + } + + outFile.write(reinterpret_cast(&occupancy), sizeof(occupancy)); + outFile.write(reinterpret_cast(&pieces), sizeof(pieces)); + outFile.write(reinterpret_cast(&stmEPSquare), sizeof(stmEPSquare)); + outFile.write(reinterpret_cast(&halfmoveClock), sizeof(halfmoveClock)); + outFile.write(reinterpret_cast(&fullmoveNumber), sizeof(fullmoveNumber)); + outFile.write(reinterpret_cast(&eval), sizeof(eval)); + outFile.write(reinterpret_cast(&wdl), sizeof(wdl)); + outFile.write(reinterpret_cast(&extra), sizeof(extra)); + + outFile.close(); + } +}; + +struct ScoredMove { + uint16_t move; + int16_t score; + + ScoredMove() : move(0), score(0) {} + + ScoredMove(uint16_t m, int16_t s) { + move = m; + score = s; + } +}; + +struct Game { + MarlinFormat format; + std::vector moves; + + Game(){}; + + Game(MarlinFormat f, std::vector m) { + format = f; + moves = m; + } +}; + +void Run(int targetPositions, int threads); +} \ No newline at end of file diff --git a/source/main.cpp b/source/main.cpp index 000c9d5..486cee2 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -4,6 +4,7 @@ #include "utils.h" #include "benchmark.h" #include "search.h" +#include "datagen.h" int main(int argc, char* argv[]) { MOVEGEN::initLeaperAttacks(); @@ -16,6 +17,17 @@ int main(int argc, char* argv[]) { if (argc > 1) { if (std::string(argv[1]) == "bench") { RunBenchmark(); + } else if (std::string(argv[1]) == "datagen") { + int positions = 1; + int threads = 1; + if (argc > 2) { + positions = std::stoi(argv[2]); + + if (argc > 3) { + threads = std::stoi(argv[3]); + } + } + DATAGEN::Run(positions, threads); } } else { UCILoop(board); diff --git a/source/move.h b/source/move.h index 6a0e7aa..ac7b9b7 100644 --- a/source/move.h +++ b/source/move.h @@ -76,6 +76,56 @@ public: } } + uint16_t ConvertToViriMoveFormat() { + uint16_t viriMove = 0; + int flags = GetFlags(); + + // Define masks for different parts of the move + const uint16_t FROM_MASK = 0x3F; // 6 bits for the 'from' square (0-63) + const uint16_t TO_MASK = 0x3F; // 6 bits for the 'to' square (0-63) + const uint16_t MOVE_TYPE_MASK = 0x3 << 12; // 2 bits for the move type (castling, en passant, promotion, etc.) + const uint16_t PROMO_PIECE_MASK = 0x3 << 14; // 2 bits for the promotion piece (knight, bishop, etc.) + + // Set 'from' and 'to' squares + viriMove |= (MoveFrom() & FROM_MASK); // Mask the 'from' square + viriMove |= (MoveTo() & TO_MASK) << 6; // Mask the 'to' square + + // Determine move type (bits 12-13) + uint16_t moveType = 0; + uint16_t promoPiece = 0; + + if (flags == kingCastle || flags == queenCastle) { + moveType = 1; // Castling + } + else if (flags == epCapture) { + moveType = 2; // En passant + } + else if (flags >= knightPromotion && flags <= queenPromoCapture) { + moveType = 3; // Promotion + // Set promo piece (bits 14-15) + if (flags == knightPromotion || flags == knightPromoCapture) { + promoPiece = 1; // Knight + } + else if (flags == bishopPromotion || flags == bishopPromoCapture) { + promoPiece = 2; // Bishop + } + else if (flags == rookPromotion || flags == rookPromoCapture) { + promoPiece = 3; // Rook + } + else if (flags == queenPromotion || flags == queenPromoCapture) { + promoPiece = 4; // Queen + } + } + + // Apply move type (bits 12-13) using mask + viriMove |= (moveType & MOVE_TYPE_MASK); + + // Apply promotion piece (bits 14-15) using mask + viriMove |= (promoPiece & PROMO_PIECE_MASK); + + return viriMove; + } + operator uint16_t() { return m_move; } diff --git a/source/search.cpp b/source/search.cpp index e8ef5a1..0b76e9d 100644 --- a/source/search.cpp +++ b/source/search.cpp @@ -5,18 +5,21 @@ #include #include "tt.h" #include "stopwatch.h" +#include "datagen.h" +#include "benchmark.h" namespace SEARCH { -U64 nodes = 0; -bool benchStarted = false; +thread_local U64 nodes = 0; +thread_local U64 nodesToGo = 0; +thread_local bool benchStarted = false; -static inline int timeToSearch = 0; -static inline bool doingNullMove = false; +thread_local static inline int timeToSearch = 0; +thread_local static inline bool doingNullMove = false; -inline PVLine pvLine; +thread_local inline PVLine pvLine; -Stopwatch sw; +thread_local Stopwatch sw; void InitLMRTable() { for (int depth = 0; depth <= MAX_DEPTH; depth++) { @@ -122,6 +125,10 @@ static bool IsInsuffMat(Board &board) { && !(board.pieces[Pawn] | board.pieces[Queen] | board.pieces[Rook])); } +bool IsDraw(Board &board) { + return IsFifty(board) || IsInsuffMat(board) || IsThreefold(board); +} + static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int ply) { int reduction = 0; @@ -133,14 +140,22 @@ static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int return reduction; } +template static SearchResults Quiescence(Board board, int alpha, int beta, int ply) { - if (!benchStarted && nodes % 1024 == 0) { - if (sw.GetElapsedMS() >= timeToSearch) { + if constexpr (mode != nodesMode) { + if (!benchStarted && nodes % 1024 == 0) { + if (sw.GetElapsedMS() >= timeToSearch) { + StopSearch(); + return 0; + } + } + } else { + if (nodes > nodesToGo) { StopSearch(); return 0; } } - + int bestScore = HCE::Evaluate(board); TTEntry *entry = TT.GetRawEntry(board.hashKey); @@ -167,7 +182,7 @@ static SearchResults Quiescence(Board board, int alpha, int beta, int ply) { Board copy = board; int isLegal = copy.MakeMove(board.moveList[i]); if (!isLegal) continue; - int score = -Quiescence(copy, -beta, -alpha, ply + 1).score; + int score = -Quiescence(copy, -beta, -alpha, ply + 1).score; positionIndex--; if (score >= beta) { @@ -187,10 +202,24 @@ static SearchResults Quiescence(Board board, int alpha, int beta, int ply) { return results; } -template +template SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { - if (!benchStarted && nodes % 1024 == 0) { - if (sw.GetElapsedMS() >= timeToSearch) { + if constexpr (mode != bench || mode != nodesMode) { + if (nodes % 1024 == 0) { + if constexpr (mode == normal) { + if (sw.GetElapsedMS() >= timeToSearch) { + StopSearch(); + return 0; + } + } else if constexpr (mode == datagen) { + if (nodes >= DATAGEN::HARD_NODES) { + StopSearch(); + return 0; + } + } + } + } else if constexpr (mode == nodesMode) { + if (nodes > nodesToGo) { StopSearch(); return 0; } @@ -208,7 +237,7 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { } } - if (depth <= 0) return Quiescence(board, alpha, beta, ply); + if (depth <= 0) return Quiescence(board, alpha, beta, ply); const int staticEval = HCE::Evaluate(board); @@ -228,7 +257,7 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { // Always legal so we dont check it doingNullMove = true; - int score = -PVS(copy, depth - 3, -beta, -beta + 1, ply + 1).score; + int score = -PVS(copy, depth - 3, -beta, -beta + 1, ply + 1).score; doingNullMove = false; if (searchStopped) return 0; @@ -275,25 +304,28 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { // First move (suspected PV node) if (!moveSeen) { // Full search - score = -PVS(copy, newDepth, -beta, -alpha, ply + 1).score; + score = -PVS(copy, newDepth, -beta, -alpha, ply + 1).score; } else if (reductions) { // Null-window search with reductions - score = -PVS(copy, newDepth - reductions, -alpha-1, -alpha, ply + 1).score; + score = -PVS(copy, newDepth - reductions, -alpha-1, -alpha, ply + 1).score; if (score > alpha) { // Null-window search now without the reduction - score = -PVS(copy, newDepth, -alpha-1, -alpha, ply + 1).score; + score = -PVS(copy, newDepth, -alpha-1, -alpha, ply + 1).score; } } else { // Null-window search - score = -PVS(copy, newDepth, -alpha-1, -alpha, ply + 1).score; + score = -PVS(copy, newDepth, -alpha-1, -alpha, ply + 1).score; } // Check if we need to do full window re-search if (moveSeen && score > alpha && score < beta) { - score = -PVS(copy, newDepth, -beta, -alpha, ply + 1).score; + score = -PVS(copy, newDepth, -beta, -alpha, ply + 1).score; } + moveSeen++; + positionIndex--; + if (searchStopped) return 0; if (currMove.IsQuiet()) { @@ -301,9 +333,6 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { seenQuietsCount++; } - moveSeen++; - positionIndex--; - // Fail high (beta cutoff) if (score >= beta) { if (!currMove.IsCapture()) { @@ -347,6 +376,7 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { } // Iterative deepening +template static SearchResults ID(Board &board, SearchParams params) { int fullTime = board.sideToMove ? params.btime : params.wtime; int inc = board.sideToMove ? params.binc : params.winc; @@ -354,6 +384,12 @@ static SearchResults ID(Board &board, SearchParams params) { SearchResults safeResults; safeResults.score = -inf; + int toDepth = MAX_DEPTH; + + if constexpr (mode == bench) { + toDepth = BENCH_DEPTH; + } + int alpha = -inf; int beta = inf; @@ -362,13 +398,14 @@ static SearchResults ID(Board &board, SearchParams params) { int ply = 0; int elapsed = 0; + sw.Restart(); - for (int depth = 1; depth <= MAX_DEPTH; depth++) { + for (int depth = 1; depth <= toDepth; depth++) { timeToSearch = std::max((fullTime / 20) + (inc / 2), 4); int softTime = timeToSearch * 0.65; - SearchResults currentResults = PVS(board, depth, alpha, beta, ply); + SearchResults currentResults = PVS(board, depth, alpha, beta, ply); elapsed = sw.GetElapsedMS(); // If we fell outside the window, try again with full width @@ -396,19 +433,28 @@ static SearchResults ID(Board &board, SearchParams params) { safeResults = currentResults; } - std::cout << "info "; - std::cout << "depth " << depth; - std::cout << " time " << elapsed; - std::cout << " score cp " << safeResults.score; - std::cout << " nodes " << nodes << " nps " << int(nodes/sw.GetElapsedSec()); - std::cout << " hashfull " << TT.GetUsedPercentage(); - std::cout << " pv "; - pvLine.Print(0); - std::cout << std::endl; - - if (sw.GetElapsedMS() >= softTime) { - StopSearch(); - break; + if constexpr (mode == normal || mode == nodesMode) { + std::cout << "info "; + std::cout << "depth " << depth; + std::cout << " time " << elapsed; + std::cout << " score cp " << UTILS::ConvertToWhiteRelative(board, safeResults.score); + std::cout << " nodes " << nodes << " nps " << int(nodes/sw.GetElapsedSec()); + std::cout << " hashfull " << TT.GetUsedPercentage(); + std::cout << " pv "; + pvLine.Print(0); + std::cout << std::endl; + + if constexpr (mode == normal) { + if (sw.GetElapsedMS() >= softTime) { + StopSearch(); + break; + } + } + } else if constexpr (mode == datagen) { + if (nodes >= DATAGEN::SOFT_NODES) { + StopSearch(); + break; + } } } } @@ -416,19 +462,43 @@ static SearchResults ID(Board &board, SearchParams params) { return safeResults; } -void SearchPosition(Board &board, SearchParams params) { +template +SearchResults SearchPosition(Board &board, SearchParams params) { searchStopped = false; - nodes = 0; + if constexpr (mode != bench) { + nodes = 0; + + if constexpr (mode == nodesMode) { + nodesToGo = params.nodes; + } + } pvLine.Clear(); - SearchResults results = ID(board, params); + SearchResults results = ID(board, params); + + if constexpr (mode != normal) return results; std::cout << "bestmove "; results.bestMove.PrintMove(); std::cout << std::endl; + + return results; } void StopSearch() { searchStopped = true; } + +template SearchResults PVS(Board, int, int, int, int); +template SearchResults PVS(Board, int, int, int, int); +template SearchResults PVS(Board, int, int, int, int); +template SearchResults PVS(Board, int, int, int, int); +template SearchResults PVS(Board, int, int, int, int); +template SearchResults PVS(Board, int, int, int, int); + +template SearchResults SearchPosition(Board &board, SearchParams params); +template SearchResults SearchPosition(Board &board, SearchParams params); +template SearchResults SearchPosition(Board &board, SearchParams params); +template SearchResults SearchPosition(Board &board, SearchParams params); + } diff --git a/source/search.h b/source/search.h index f286246..71336a4 100644 --- a/source/search.h +++ b/source/search.h @@ -7,19 +7,27 @@ namespace SEARCH { +enum searchMode { + normal, + bench, + datagen, + nodesMode +}; + constexpr int MATE_SCORE = -99000; constexpr int MAX_DEPTH = 64; +constexpr int MAX_PLY = 128; constexpr int MAX_HISTORY = 16384; -extern U64 nodes; -extern bool benchStarted; +thread_local extern U64 nodes; +thread_local extern bool benchStarted; constexpr int inf = 100000; -inline bool searchStopped = false; +thread_local inline bool searchStopped = false; -// [id][ply] -inline int killerMoves[2][64]; +// [id][ply] +thread_local inline int killerMoves[2][MAX_PLY]; inline int lmrTable[MAX_DEPTH+1][MAX_MOVES]; @@ -67,12 +75,12 @@ public: } }; -inline History history; +thread_local inline History history; class PVLine { private: - int length[MAX_DEPTH] = {}; - Move table[MAX_DEPTH][MAX_DEPTH] = {}; + int length[MAX_PLY] = {}; + Move table[MAX_PLY][MAX_PLY] = {}; public: void SetLength(int ply) { length[ply] = ply; @@ -101,12 +109,15 @@ public: } }; -template +template SearchResults PVS(Board board, int depth, int alpha, int beta, int ply); -void SearchPosition(Board &board, SearchParams params); +template +SearchResults SearchPosition(Board &board, SearchParams params); void StopSearch(); +bool IsDraw(Board &board); + constexpr int moveScoreTable[6][6] = { 105, 205, 305, 405, 505, 605, 104, 204, 304, 404, 504, 604, diff --git a/source/tt.h b/source/tt.h index e8607c4..a6e4136 100644 --- a/source/tt.h +++ b/source/tt.h @@ -21,7 +21,7 @@ constexpr U64 maxHash = (64* 1000000) / sizeof(TTEntry); // 5 MB constexpr U64 defaultHash = (5 * 1000000) / sizeof(TTEntry); -inline U64 hashSize = defaultHash; +thread_local inline U64 hashSize = defaultHash; constexpr int invalidEntry = 111111; @@ -61,4 +61,4 @@ public: void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move besteMove); }; -inline TTable TT; +thread_local inline TTable TT; diff --git a/source/uci.cpp b/source/uci.cpp index d1ae052..53d8121 100644 --- a/source/uci.cpp +++ b/source/uci.cpp @@ -76,14 +76,20 @@ static void ParseGo(Board &board, std::string &command) { params.winc = ReadParam("winc", command); params.binc = ReadParam("binc", command); params.movesToGo = ReadParam("movestogo", command); + params.nodes = ReadParam("nodes", command); if (command.find("movetime") != std::string::npos) { params.wtime = ReadParam("movetime", command); params.btime = ReadParam("movetime", command); } - - auto worker = std::thread(SEARCH::SearchPosition, std::ref(board), params); - worker.detach(); + + if (params.nodes) { + auto worker = std::thread(SEARCH::SearchPosition, std::ref(board), params); + worker.detach(); + } else { + auto worker = std::thread(SEARCH::SearchPosition, std::ref(board), params); + worker.detach(); + } } static void SetOption(std::string &command) { diff --git a/source/uci.h b/source/uci.h index 11a231e..1f2553d 100644 --- a/source/uci.h +++ b/source/uci.h @@ -9,6 +9,7 @@ public: int winc = 0; int binc = 0; int movesToGo = 0; + int nodes = 0; SearchParams(){} }; diff --git a/source/utils.cpp b/source/utils.cpp index a9b645c..4a5bb6f 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -146,4 +146,44 @@ Move parseMove(Board &board, std::string_view str) { return Move(from, to, flag); } + +std::array CompressPieces(Board board) { + const uint8_t UNMOVED_ROOK = 6; + std::array compressed{}; + + Bitboard occupancy = board.occupied; + int index = 0; + + while (occupancy) { + int square = occupancy.getLS1BIndex(); + int pieceType = board.GetPieceType(square); + int pieceColor = board.GetPieceColor(square); + int pieceCode = pieceType; + + if (pieceType == Rook) { + if ((square == a1 && (board.castlingRights & whiteQueenRight)) + || (square == h1 && (board.castlingRights & whiteKingRight)) + || (square == a8 && (board.castlingRights & blackQueenRight)) + || (square == h8 && (board.castlingRights & blackKingRight))) + pieceCode = UNMOVED_ROOK; + } + + pieceCode |= (pieceColor << 3); // Shift the color to the 3rd bit (bit 3) + + int byteIndex = index / 2; + int bitShift = (index % 2) * 4; + + compressed[byteIndex] |= (pieceCode & 0x0F) << bitShift; + + index++; + occupancy.PopBit(square); + } + + return compressed; } + +int ConvertToWhiteRelative(Board &board, int score) { + return board.sideToMove == White ? score : -score; +} + +} \ No newline at end of file diff --git a/source/utils.h b/source/utils.h index 0156f55..37aa02b 100644 --- a/source/utils.h +++ b/source/utils.h @@ -29,4 +29,9 @@ std::vector split(std::string_view str, char delim); int parseSquare(std::string_view str); Move parseMove(Board &board, std::string_view str); + +std::array CompressPieces(Board board); + +int ConvertToWhiteRelative(Board &board, int score); + }