diff options
| author | Aargh Rai <aargh.rai+git@gmail.com> | 2026-07-10 16:01:57 +0530 |
|---|---|---|
| committer | Aargh Rai <aargh.rai+git@gmail.com> | 2026-07-10 16:01:57 +0530 |
| commit | a14da2fe3864712dab4e7c4cfb5c323026d668de (patch) | |
| tree | 418c8c8ff44a611cbe1c1269b10926527046e232 /src | |
| parent | 2761f8a533e2b025f209222a1e4ec70b91c7e8ee (diff) | |
moving header files to include directory & moving resources in it's own directory
i know currently there is race condition, but the code is getting too
messy, i will continue to this after i make a vis tool to analyse how i
should split up files & stuff
the code rn needs intense restructing for it to make any more progress
Diffstat (limited to 'src')
34 files changed, 186 insertions, 1587 deletions
diff --git a/src/bitboard.h b/src/bitboard.h deleted file mode 100644 index ecd8c35..0000000 --- a/src/bitboard.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef BITBOARD_H -#define BITBOARD_H - -#include "ints.h" -#include <stdbool.h> - -typedef u64 bitboard_t; - -enum { - WHITE_KING, - WHITE_QUEEN, - WHITE_ROOK, - WHITE_BISHOP, - WHITE_KNIGHT, - WHITE_PAWN, - BLACK_KING, - BLACK_QUEEN, - BLACK_ROOK, - BLACK_BISHOP, - BLACK_KNIGHT, - BLACK_PAWN, - PIECE_TYPE_COUNT, -}; - -enum { - WHITE_SHORT_CASTLE = 1 << 0, - WHITE_LONG_CASTLE = 1 << 1, - BLACK_SHORT_CASTLE = 1 << 2, - BLACK_LONG_CASTLE = 1 << 3, -}; - -enum { - WHITE_TURN, - BLACK_TURN, -}; - -#define BITMASK_RANK_1 255ULL -#define BITMASK_RANK_2 65280ULL -#define BITMASK_RANK_3 16711680ULL -#define BITMASK_RANK_4 4278190080ULL -#define BITMASK_RANK_5 1095216660480ULL -#define BITMASK_RANK_6 280375465082880ULL -#define BITMASK_RANK_7 71776119061217280ULL -#define BITMASK_RANK_8 18374686479671623680ULL -#define BITMASK_FILE_A 72340172838076673ULL -#define BITMASK_FILE_B 144680345676153346ULL -#define BITMASK_FILE_C 289360691352306692ULL -#define BITMASK_FILE_D 578721382704613384ULL -#define BITMASK_FILE_E 1157442765409226768ULL -#define BITMASK_FILE_F 2314885530818453536ULL -#define BITMASK_FILE_G 4629771061636907072ULL -#define BITMASK_FILE_H 9259542123273814144ULL - -#define occupied_by(bitboard, index) (bitboard & ((bitboard_t)1 << index)) - -typedef struct { - bitboard_t bitboards[PIECE_TYPE_COUNT]; - u8 castling; - u8 turn; - u8 passantable_file; - u16 halfmove_clock; - u16 fullmove_clock; -} position_t; - -position_t position_starting(); -void assert_valid_position(position_t position); -bool check_valid_position(position_t position); -#define whites(position) \ - position.bitboards[WHITE_KING] | \ - position.bitboards[WHITE_QUEEN] | \ - position.bitboards[WHITE_ROOK] | \ - position.bitboards[WHITE_BISHOP] | \ - position.bitboards[WHITE_KNIGHT] | \ - position.bitboards[WHITE_PAWN] - -#define blacks(position) \ - position.bitboards[BLACK_KING] | \ - position.bitboards[BLACK_QUEEN] | \ - position.bitboards[BLACK_ROOK] | \ - position.bitboards[BLACK_BISHOP] | \ - position.bitboards[BLACK_KNIGHT] | \ - position.bitboards[BLACK_PAWN] - - -void print_bitboard(bitboard_t bitboard); - -#endif // BITBOARD_H diff --git a/src/engine.c b/src/engine.c index a063520..dc1f54e 100644 --- a/src/engine.c +++ b/src/engine.c @@ -2,49 +2,60 @@ #include <string.h> #include <unistd.h> #include <pthread.h> +#include "fcntl.h" #include "bitboard.h" -#include "engine/moves.h" +#include "moves.h" #include "fen.h" -#include "fcntl.h" #include "uci.h" #include "ipc.h" -// TODO: implement break conditions from the go command struct thread_args { int id; int stop; position_t position; + struct go_args *go_args; struct engine_message *message; }; + void *engine_thread(void *_args) { + printf("NIGGGGA\n"); struct thread_args *args = (struct thread_args*)_args; + args->stop = 0; - int k = 0; - while (k < 10) { - if (args->stop) continue; + int depth = 0; + while (true) { struct engine_message *message = args->message; - - k++; - message->depth = 69; + message->depth = depth++; message->multipv = args->id; message->pv = comm_moves_init(); + + // pseudo engine work + for (volatile int k = 0; k < 1000000000; k++) {} + add_comm_move(&message->pv, (struct uci_move) { 14, 24 }); - if (k == 10) { + if (args->stop || !should_continue(message, args->go_args)) { message->best_move = (struct uci_move) { 12, 24 }; message->ponder = (struct uci_move) { 42, 54 }; + message->next = NULL; + message->ready = 1; + break; } message->next = malloc(sizeof(struct engine_message*)); + message->next->ready = 0; message->ready = 1; args->message = message->next; } + + args->stop = 2; } struct threads { pthread_t *threads; struct thread_args* args; + struct go_args *go_args; engine_messages *engine_messages; size_t count; size_t capacity; @@ -53,24 +64,25 @@ struct threads { }; void increase_threads(struct threads *threads, size_t change) { + int old_capacity = threads->capacity; if (threads->count + change > threads->capacity) { - threads->capacity = threads->count + change + 16; // TODO: maybe round it to the upper power of 2 + threads->capacity = threads->count + change + 16; } threads->threads = threads->threads == NULL - ? malloc(sizeof(*threads->threads) * threads->capacity) - : realloc(threads->threads, sizeof(*threads->threads) * threads->capacity); + ? malloc(sizeof(pthread_t) * threads->capacity) + : realloc(threads->threads, sizeof(pthread_t) * threads->capacity); threads->args = threads->args == NULL - ? malloc(sizeof(*threads->args) * threads->capacity) - : realloc(threads->args, sizeof(*threads->args) * threads->capacity); + ? malloc(sizeof(struct thread_args) * threads->capacity) + : realloc(threads->args, sizeof(struct thread_args) * threads->capacity); threads->engine_messages->data = threads->engine_messages->data == NULL - ? malloc(sizeof(*threads->engine_messages->data) * threads->capacity) + ? malloc(sizeof(struct engine_message*) * threads->capacity) : realloc( - threads->engine_messages->data, - sizeof(*threads->engine_messages->data) * threads->capacity - ); + threads->engine_messages->data, + sizeof(struct engine_message*) * threads->capacity + ); for (int i = threads->count; i < threads->count + change; i++) { threads->engine_messages->data[i] = malloc(sizeof(struct engine_message)); @@ -79,6 +91,7 @@ void increase_threads(struct threads *threads, size_t change) { i, 0, threads->sharing_position, + threads->go_args, threads->engine_messages->data[i], }; pthread_create( @@ -94,7 +107,9 @@ void increase_threads(struct threads *threads, size_t change) { void decrease_threads(struct threads *threads, size_t change) { for (int i = 0; i < change; i++) { - free(threads->engine_messages->data[threads->count - i - 1]); + struct engine_message *item = threads->engine_messages->data[i]; + threads->engine_messages->data[i] = NULL; + free(item); pthread_cancel(threads->threads[threads->count - i - 1]); } threads->count -= change; @@ -102,17 +117,33 @@ void decrease_threads(struct threads *threads, size_t change) { } void set_threads(struct threads *threads, size_t new_size) { - if (new_size > threads->count) { + if (new_size >= threads->count) { increase_threads(threads, new_size - threads->count); } else { decrease_threads(threads, threads->count - new_size); } } +void send_stop_signal(struct threads *threads) { + for (int i = 0; i < threads->count; i++) { + if (threads->args[i].stop) continue; + threads->args[i].stop = 1; + } +} +bool all_stopped(struct threads *threads) { + if (threads->count == 0) return false; + for (int i = 0; i < threads->count; i++) { + if (threads->args[i].stop == 2) continue; + return false; + } + return true; +} + // TODO: someday fix that some structs have typedef, some dont int main(int argc, char** argv) { comms *comms = malloc(sizeof(*comms)); comms->engine_messages = malloc(sizeof(*comms->engine_messages)); + comms->engine_messages->data = NULL; comms->uci_state_initialized = 0; pthread_t uci_thread; @@ -123,24 +154,44 @@ int main(int argc, char** argv) { struct threads engine_threads = {0}; engine_threads.engine_messages = comms->engine_messages; - int initialized = 0; while (1) { if (atomic_load(&comms->state.quit)) break; - if (!atomic_load(&comms->state.go)) continue; - - if (initialized == 0) { + if (atomic_load(&comms->state.cleanup)) { + set_threads(&engine_threads, 0); + for (int i = 0; i < engine_threads.count; i++) { + engine_threads.args[i].stop = -1; + } + } + if (atomic_load(&comms->state.go)) { + printf("going\n"); engine_threads.sharing_position = comms->state.position; + engine_threads.go_args = (struct go_args*)comms->state.go_args; set_threads(&engine_threads, comms->state.threads); - initialized = 1; + atomic_store(&comms->state.go, 0); + atomic_store(&comms->state.go_ready_receive, 1); + } + if (atomic_load(&comms->state.stop)) { + printf("stopping\n"); + send_stop_signal(&engine_threads); + if (!all_stopped(&engine_threads)) continue; + set_threads(&engine_threads, 0); + for (int i = 0; i < engine_threads.count; i++) { + engine_threads.args[i].stop = -1; + } + atomic_store(&comms->state.stop, 0); } } + pthread_cancel(uci_thread); set_threads(&engine_threads, 0); free(engine_threads.threads); free(engine_threads.args); - free(comms->engine_messages); + for (int i = 0; i < engine_threads.count; i++) { + free(engine_threads.engine_messages->data[i]); + } free(comms->engine_messages->data); + free(comms->engine_messages); free(comms); return 0; } diff --git a/src/engine/moves.c b/src/engine/moves.c index 797e770..56bb47d 100644 --- a/src/engine/moves.c +++ b/src/engine/moves.c @@ -1,5 +1,6 @@ #include "moves.h" -#include "../bitboard.h" +#include "bitboard.h" + #include "moves/vec.c" #include "moves/king.c" #include "moves/knight.c" @@ -7,6 +8,7 @@ #include "moves/rook.c" #include "moves/bishop.c" #include "moves/queen.c" + #include <assert.h> void get_moves(moves_t* moves, position_t position) { diff --git a/src/engine/moves.h b/src/engine/moves.h deleted file mode 100644 index 86c4844..0000000 --- a/src/engine/moves.h +++ /dev/null @@ -1,81 +0,0 @@ -#ifndef MOVES_H -#define MOVES_H - -#include "../ints.h" -#include "../bitboard.h" - -typedef u8 square_t; - -// think about the chess move notation -// e4, Nf6, Qh3+, Qe1#, a8=Q, i need to store the information needed to -// recreate this in move_t -enum { - MOVE_CAPTURE = 1, - MOVE_SHORT_CASTLE = 1 << 1, - MOVE_LONG_CASTLE = 1 << 2, - - // technically these promotation flags can be compressed to only use 2 bits.. - MOVE_PROMOTE_Q = 1 << 3, // 1 << 5 - MOVE_PROMOTE_R = 1 << 4, // 2 << 5 - MOVE_PROMOTE_B = 1 << 5, // 3 << 5 - MOVE_PROMOTE_N = 1 << 6, // 4 << 5 ? nvm it uses 3 - MOVE_EN_PASSANT = 1 << 7, - MOVE_CHECK = 1 << 8, -}; - -typedef struct { - square_t from; - square_t to; - u16 flags; -} move_t; -void position_make_move(position_t* position, move_t* move); - -typedef struct { - move_t* moves; - u32 length; - u32 capacity; -} moves_t; - -moves_t moves_init(); -moves_t moves_init_wcapacity(u32 capacity); -moves_t moves_empty(); - -struct add_move_params { - u16 flags; -}; -#define add_move(moves, from, to, ...) _add_move(\ - moves, \ - from, \ - to, \ - (struct add_move_params) { .flags = 0, __VA_ARGS__ }\ -) -void _add_move( - moves_t* moves, - square_t from, - square_t to, - struct add_move_params params -); - -void get_pawn_moves(moves_t* moves, position_t position); -void get_knight_moves(moves_t* moves, position_t position); -void get_king_moves(moves_t* moves, position_t position); -void get_rook_moves(moves_t* moves, position_t position); -void get_bishop_moves(moves_t* moves, position_t position); -void get_queen_moves(moves_t* moves, position_t position); - -void get_moves(moves_t* moves, position_t position); - -void __forloop_rook_moves_gen( - moves_t* moves, - bitboard_t friendly_type, - bitboard_t friendly_pieces, - bitboard_t enemy_pieces -); -void __forloop_bishop_moves_gen( - moves_t* moves, - bitboard_t friendly_type, - bitboard_t friendly_pieces, - bitboard_t enemy_pieces -); - -#endif // !MOVES_H diff --git a/src/engine/moves/bishop.c b/src/engine/moves/bishop.c index c51d405..b69be57 100644 --- a/src/engine/moves/bishop.c +++ b/src/engine/moves/bishop.c @@ -1,4 +1,4 @@ -#include "../moves.h" +#include "moves.h" void __forloop_bishop_moves_gen( moves_t* moves, diff --git a/src/engine/moves/king.c b/src/engine/moves/king.c index e954ae5..1775e7f 100644 --- a/src/engine/moves/king.c +++ b/src/engine/moves/king.c @@ -1,4 +1,4 @@ -#include "../moves.h" +#include "moves.h" #include <stdio.h> void get_king_moves(moves_t* moves, position_t position) { diff --git a/src/engine/moves/knight.c b/src/engine/moves/knight.c index 20d072f..e7615f0 100644 --- a/src/engine/moves/knight.c +++ b/src/engine/moves/knight.c @@ -1,4 +1,4 @@ -#include "../moves.h" +#include "moves.h" bitboard_t knight_moves[64] = { 132096ULL, diff --git a/src/engine/moves/pawn.c b/src/engine/moves/pawn.c index 0b8993f..d9757f4 100644 --- a/src/engine/moves/pawn.c +++ b/src/engine/moves/pawn.c @@ -1,4 +1,4 @@ -#include "../moves.h" +#include "moves.h" #define add_promote_moves(other_flags) \ add_move(moves, from, to, .flags = other_flags | MOVE_PROMOTE_Q); \ diff --git a/src/engine/moves/queen.c b/src/engine/moves/queen.c index 9e6e5c4..bdf96fc 100644 --- a/src/engine/moves/queen.c +++ b/src/engine/moves/queen.c @@ -1,4 +1,4 @@ -#include "../moves.h" +#include "moves.h" void get_queen_moves(moves_t* moves, position_t position) { assert_valid_position(position); diff --git a/src/engine/moves/rook.c b/src/engine/moves/rook.c index dfd9c32..3e0ac95 100644 --- a/src/engine/moves/rook.c +++ b/src/engine/moves/rook.c @@ -1,4 +1,4 @@ -#include "../moves.h" +#include "moves.h" void __forloop_rook_moves_gen( moves_t* moves, diff --git a/src/engine/moves/vec.c b/src/engine/moves/vec.c index 6a5f3c6..9ded70d 100644 --- a/src/engine/moves/vec.c +++ b/src/engine/moves/vec.c @@ -1,4 +1,4 @@ -#include "../moves.h" +#include "moves.h" #include <assert.h> #include <stdlib.h> diff --git a/src/fen.h b/src/fen.h deleted file mode 100644 index d45240e..0000000 --- a/src/fen.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef FEN_H -#define FEN_H - -#include "bitboard.h" - -struct fen_load { - bool failed; - position_t position; -}; -struct fen_load load_fen(const char* fen); - -#endif // FEN_H diff --git a/src/ints.h b/src/ints.h deleted file mode 100644 index 4a0cfe3..0000000 --- a/src/ints.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef INTS_H -#define INTS_H - -#include <stdint.h> -#include <inttypes.h> - -typedef uint8_t u8; -typedef uint16_t u16; -typedef uint32_t u32; -typedef uint64_t u64; -typedef __uint128_t u128; -typedef int8_t i8; -typedef int16_t i16; -typedef int32_t i32; -typedef int64_t i64; -typedef __int128_t i128; -typedef float f32; -typedef double f64; - -#endif // !INTS_H @@ -22,6 +22,24 @@ void add_comm_move(comm_moves *moves, struct uci_move move) { moves->moves[moves->count++] = move; } + +bool should_continue(struct engine_message *message, struct go_args* go) { + int depth; + int nodes; + int mate; + if (go->depth && (go->depth >= message->depth)) { + return false; + } + if (go->nodes && (go->nodes >= message->nodes)) { + message->node_limit = true; + return false; + } + if (go->mate && message->mate && (go->mate <= message->mate)) { + return false; + } + return true; +} + #include "fen.c" #include "bitboard.c" diff --git a/src/ipc.h b/src/ipc.h deleted file mode 100644 index 35b109b..0000000 --- a/src/ipc.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef IPC_H -#define IPC_H - -// NOT TRUE IPC: I REALISED I AM STUPID AND COULD HAVE JUST USED THREADS - -#include <stdlib.h> -#include <sys/mman.h> - -#include "fen.h" -#include "uci/state.h" - -typedef struct { - struct uci_move *moves; - int count; - int capacity; -} comm_moves; - -struct engine_message { - int ready; - - int depth; - int seldepth; - int multipv; - int score_cp; - int nodes; - int nps; - int hashfull; - int tbhits; - int time; - comm_moves pv; - - struct uci_move best_move; - struct uci_move ponder; - - struct engine_message *next; -}; - -typedef struct { - struct engine_message **data; - int count; -} engine_messages; - -enum { MESSAGE_FILLED, MESSAGE_READ, MESSAGE_PROCESSED }; -typedef struct { - engine_messages *engine_messages; - uci_state state; - int uci_state_initialized; - int uci_message_ready; - struct fen_load from_position; - comm_moves moves; -} comms; - -comm_moves comm_moves_init(); -void add_comm_move(comm_moves *moves, struct uci_move move); - -#endif // IPC_H diff --git a/src/log.c b/src/log.c deleted file mode 100644 index 64d738c..0000000 --- a/src/log.c +++ /dev/null @@ -1,29 +0,0 @@ -#include <stdio.h> -#include "ipc.c" -#include "unistd.h" - -int main(int argc, char** argv) { - mqd_t rx = mq_open("/logs", O_CREAT | O_RDONLY, 0666, &attr); - mqd_t _ = mq_open("/server_to_engine", O_CREAT, 0666, &attr); - _ = mq_open("/engine_to_server", O_CREAT, 0666, &attr); - - for (int i = 1; i < argc; i++) { - printf("Running: %s\n", argv[i]); - if (fork() == 0) { - char* new_argv[] = {argv[i], NULL}; - execvp(argv[i], new_argv); - } - } - - while (1) { - char* buf = read_queue(rx); - if (buf[0] == 'e') { - printf("[\x1b[31mERRO\x1b[0m] %s\n", buf + 1); - } else if (buf[0] == 'w') { - printf("[\x1b[1;33mWARN\x1b[0m] %s\n", buf + 1); - } else if (buf[0] == 'i') { - printf("[\x1b[32mINFO\x1b[0m] %s\n", buf + 1); - } - free(buf); - } -} diff --git a/src/logger/logger.c b/src/logger/logger.c deleted file mode 100644 index 9f1e612..0000000 --- a/src/logger/logger.c +++ /dev/null @@ -1,5 +0,0 @@ -#include "logger.h" - -void send_log(mqd_t target, const char* msg, int n) { - mq_send(target, msg, n, 0); -} diff --git a/src/logger/logger.h b/src/logger/logger.h deleted file mode 100644 index abcdb6d..0000000 --- a/src/logger/logger.h +++ /dev/null @@ -1,67 +0,0 @@ -#include <stdio.h> -#include <mqueue.h> - -#ifndef LOG_LEVEL - #define LOG_LEVEL 3 -#endif - -#ifndef HAS_LOG_MODULE -#ifndef LOG_MODULE - #define HAS_LOG_MODULE 0 - #define LOG_MODULE "" -#else - #define HAS_LOG_MODULE 1 -#endif -#endif - -#if LOG_LEVEL >= 3 -#define log_infof(...) do { \ - char log_buf[1024]; \ - int n = 1; \ - log_buf[0] = 'i'; \ - if (HAS_LOG_MODULE == 1) { \ - n = snprintf(log_buf + 1, 1023, "(%s) ", LOG_MODULE); \ - } \ - snprintf(log_buf + n, 1024 - n, __VA_ARGS__); \ - send_log(logging, log_buf, 1024); \ -} while(0); -#endif // LOG_LEVEL >= 3 - -#if LOG_LEVEL >= 2 -#define log_warnf(...) do { \ - char log_buf[1024]; \ - int n = 1; \ - log_buf[0] = 'w'; \ - if (HAS_LOG_MODULE == 1) { \ - n = snprintf(log_buf + 1, 1023, "(%s) ", LOG_MODULE); \ - } \ - snprintf(log_buf + n, 1024 - n, __VA_ARGS__); \ - send_log(logging, log_buf, 1024); \ -} while(0); -#endif // LOG_LEVEL >= 2 - -#if LOG_LEVEL >= 1 -#define log_errof(...) do { \ - char log_buf[1024]; \ - int n = 1; \ - log_buf[0] = 'e'; \ - if (HAS_LOG_MODULE == 1) { \ - n = snprintf(log_buf + 1, 1023, "(%s) ", LOG_MODULE); \ - } \ - snprintf(log_buf + n, 1024 - n, __VA_ARGS__); \ - send_log(logging, log_buf, 1024); \ -} while(0); -#endif // LOG_LEVEL >= 1 - - -#ifndef log_infof -#define log_infof(...) (void)0 -#endif -#ifndef log_warnf -#define log_warnf(...) (void)0 -#endif -#ifndef log_errof -#define log_errof(...) (void)0 -#endif - -void send_log(mqd_t target, const char* msg, int n); diff --git a/src/server.c b/src/server.c deleted file mode 100644 index 7ff9c87..0000000 --- a/src/server.c +++ /dev/null @@ -1,190 +0,0 @@ -#include <errno.h> -#include <sys/socket.h> -#include <sys/wait.h> -#include <assert.h> -#include <unistd.h> - -#define LOG_MODULE "server" -#include "logger/logger.h" -#include "string.h" - -#define PORT 3456 - -#include "server/base64.c" -#include "server/ws_key.c" -#include "server/comms.c" - -mqd_t logging, tx, rx; -int handle_client(int client); - -int main(void) { - logging = mq_open("/logs", O_WRONLY); - tx = mq_open("/server_to_engine", O_WRONLY); - rx = mq_open("/engine_to_server", O_RDONLY); - - int server_fd = socket(AF_INET, SOCK_STREAM, 0); - int opt = 1; - - setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); - struct sockaddr_in addr = { - .sin_family = AF_INET, - .sin_addr.s_addr = INADDR_ANY, - .sin_port = htons(PORT) - }; - - if (bind(server_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { - perror("bind"); - return 1; - } - - if (listen(server_fd, 16) < 0) { - perror("listen"); - return 1; - } - - log_infof("Listening on %d", PORT); - - // https://websocket.org/guides/websocket-protocol/ - while(1) { - int client = accept(server_fd, NULL, NULL); - - if (client < 0) continue; - char req[4096]; - - int n = recv(client, req, sizeof(req) - 1, 0); - if (n <= 0) { - log_infof("Client close"); - close(client); - continue; - } - - req[n] = 0; - - char *key = find_websocket_key(req); - - if (!key) { - close(client); - continue; - } - - char accept_key[128]; - - websocket_accept_key(key, accept_key); - char response[512]; - - snprintf( - response, - sizeof(response), - "HTTP/1.1 101 Switching Protocols\r\n" - "Upgrade: websocket\r\n" - "Connection: Upgrade\r\n" - "Sec-WebSocket-Accept: %s\r\n" - "\r\n", - accept_key - ); - - send(client, response, strlen(response), 0); - if (fork() == 0) { - log_infof("{%d} WebSocket connected", client); - while(1) { - if (handle_client(client)) continue; - else break; - } - log_infof("{%d} WebSocket disconnected", client); - close(client); - } - } -} - -int handle_client(int client) { - unsigned char hdr[2]; - int recvn; - - if ((recvn = recv(client, hdr, 2, MSG_WAITALL)) != 2) { - if (recvn == -1) { - char buf[256]; - if (strerror_r(errno, buf, sizeof(buf)) == 0) { - log_warnf("recv: %s", buf); - } - } - log_warnf("{%d} recv close %d", client, recvn); - return 0; - } - - unsigned opcode = hdr[0] & 0x0F; - unsigned len = hdr[1] & 0x7F; - log_infof( - "{%d} opcode=%u len=%u masked=%u", - client, - opcode, - hdr[1] & 0x7F, - !!(hdr[1] & 0x80) - ); - if (opcode == 0x8) { - unsigned char close_frame[2] = {0x88, 0x00}; - send(client, close_frame, 2, 0); - log_warnf("{%d} opcode 0x8 close", client); - return 0; - } - - if (opcode == 0x9) { - unsigned char pong[2] = {0x8A, 0x00}; - send(client, pong, 2, 0); - return 1; - } - - unsigned char mask[4]; - recvn = recv(client, mask, 4, MSG_WAITALL); - if (recvn == -1) { - char buf[256]; - if (strerror_r(errno, buf, sizeof(buf)) == 0) { - log_warnf("mask recv err: %s", buf); - } - } else { - char mask_hex[256] = {0}; - base64_encode(mask, 126, mask_hex); - log_infof("mask recv{%d}: %s", recvn, mask_hex); - } - - unsigned char payload[126]; - recvn = recv(client, payload, len, MSG_WAITALL); - if (recvn == -1) { - char buf[256]; - if (strerror_r(errno, buf, sizeof(buf)) == 0) { - log_warnf("payload recv err: %s", buf); - } - } else { - char payload_hex[256] = {0}; - base64_encode(payload, 126, payload_hex); - log_infof("payload recv{%d}: %s", recvn, payload_hex); - } - - for (unsigned i = 0; i < len; i++) - payload[i] ^= mask[i % 4]; - - payload[len] = 0; - char* payload_ptr = (char*)payload; - struct strs response = handle_input(logging, tx, rx, payload_ptr, len); - - unsigned char out[1024]; - out[0] = 0x81; - int shift; - for (int i = 0; i < response.count; i++) { - struct str item = response.data[i]; - assert(item.len <= 125); - - log_infof("Replying %d: %.*s", client, item.len, item.msg) - out[1] = item.len; - shift = 2; - memcpy(out + 2, item.msg, item.len); - send(client, out, item.len + 2, 0); - } - log_infof("Replying %d: END-TRANSMISSION", client) - char end_transmission[] = "END-TRANSMISSION"; - int n = strlen(end_transmission); - out[1] = n; - - memcpy(out + 2, end_transmission, n); - send(client, out, n + 2, 0); - return 1; -} diff --git a/src/server/base64.c b/src/server/base64.c deleted file mode 100644 index e3e0ef6..0000000 --- a/src/server/base64.c +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef BASE64_C -#define BASE64_C - -#include <stddef.h> - -static const char b64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - -void base64_encode( - const unsigned char *in, - size_t len, - char *out -) { - size_t i, j = 0; - - for (i = 0; i < len; i += 3) { - unsigned v = in[i] << 16; - - if (i + 1 < len) v |= in[i + 1] << 8; - if (i + 2 < len) v |= in[i + 2]; - - out[j++] = b64[(v >> 18) & 63]; - out[j++] = b64[(v >> 12) & 63]; - - out[j++] = (i + 1 < len) ? b64[(v >> 6) & 63] : '='; - out[j++] = (i + 2 < len) ? b64[v & 63] : '='; - } - - out[j] = 0; -} - -#endif // BASE64_C diff --git a/src/server/comms.c b/src/server/comms.c deleted file mode 100644 index 67e42a2..0000000 --- a/src/server/comms.c +++ /dev/null @@ -1,68 +0,0 @@ -#include <assert.h> -#include <string.h> -#include "../ipc.c" -#include "../logger/logger.h" - -struct str { - char msg[1023]; - int len; -}; - -void set_output(struct str* output, char* msg) { - int i = 0; - while (msg[i] != 0) { - assert(i < 1023); - output->msg[i] = msg[i]; - i++; - } - output->len = i; -} - -struct strs { - struct str* data; - int capacity; - int count; -}; - -struct strs init_strs() { - return (struct strs) { - .data = malloc(sizeof(struct str) * 10), - .count = 0, - .capacity = 10, - }; -} -void add_str(struct strs* strs, char* str) { - if (strs->count + 1 > strs->capacity) { - strs->capacity += 30; - strs->data = realloc(strs->data, sizeof(struct str) * strs->capacity); - } - - struct str item; - set_output(&item, str); - - strs->data[strs->count] = item; - strs->count++; -} - -struct strs handle_input(mqd_t logging, mqd_t tx, mqd_t rx, char* payload, int len) { - log_infof("after: %d", payload[len]); - send_queue(tx, payload, len + 1); - char* buf = read_queue(rx); - - struct strs output = init_strs(); - - if (strcmp(buf, "Sending") != 0) { - return output; - } - - while (1) { - char* buf = read_queue(rx); - if (strcmp(buf, "END-TRANSMISSION") == 0) { - free(buf); - break; - } - add_str(&output, buf); - free(buf); - } - return output; -} diff --git a/src/server/ws_key.c b/src/server/ws_key.c deleted file mode 100644 index 015605e..0000000 --- a/src/server/ws_key.c +++ /dev/null @@ -1,36 +0,0 @@ -#include <openssl/sha.h> -#include <netinet/in.h> -#include <arpa/inet.h> -#include <string.h> -#include <stdio.h> - -#include "./base64.c" - -static const char *GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - -void websocket_accept_key(const char *client_key, char *output) { - char buf[256]; - snprintf(buf, sizeof(buf), "%s%s", client_key, GUID); - - unsigned char hash[SHA_DIGEST_LENGTH]; - SHA1((unsigned char *)buf, strlen(buf), hash); - base64_encode(hash, SHA_DIGEST_LENGTH, output); -} - -char *find_websocket_key(char *req) { - char *p = strstr(req, "Sec-WebSocket-Key:"); - - if (!p) return NULL; - - p += strlen("Sec-WebSocket-Key:"); - - while (*p == ' ') p++; - - static char key[128]; - int i = 0; - while (*p && *p != '\r' && *p != '\n') - key[i++] = *p++; - - key[i] = 0; - return key; -} @@ -1,14 +1,14 @@ #include <stdio.h> #include <string.h> #include <stdbool.h> -#include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <assert.h> -#include "uci/state.h" -#include "uci/command.h" -#include "uci/response.h" +#include <stdlib.h> +#include "state.h" +#include "command.h" +#include "response.h" #include "uci.h" #include "ipc.h" diff --git a/src/uci.h b/src/uci.h deleted file mode 100644 index b3ee4cc..0000000 --- a/src/uci.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef UCI_H -#define UCI_H - -#include "ipc.h" - -void *uci(void *com); - -#endif // UCI_H diff --git a/src/uci/UCI-Protocol-Specification.txt b/src/uci/UCI-Protocol-Specification.txt deleted file mode 100644 index f28b730..0000000 --- a/src/uci/UCI-Protocol-Specification.txt +++ /dev/null @@ -1,544 +0,0 @@ -// Dowloaded from: http://download.shredderchess.com/div/uci.zip - -Description of the universal chess interface (UCI) April 2006 -================================================================= - -* The specification is independent of the operating system. For Windows, - the engine is a normal exe file, either a console or "real" windows application. - -* all communication is done via standard input and output with text commands, - -* The engine should boot and wait for input from the GUI, - the engine should wait for the "isready" or "setoption" command to set up its internal parameters - as the boot process should be as quick as possible. - -* the engine must always be able to process input from stdin, even while thinking. - -* all command strings the engine receives will end with '\n', - also all commands the GUI receives should end with '\n', - Note: '\n' can be 0x0d or 0x0a0d or any combination depending on your OS. - If you use Engine and GUI in the same OS this should be no problem if you communicate in text mode, - but be aware of this when for example running a Linux engine in a Windows GUI. - -* arbitrary white space between tokens is allowed - Example: "debug on\n" and " debug on \n" and "\t debug \t \t\ton\t \n" - all set the debug mode of the engine on. - -* The engine will always be in forced mode which means it should never start calculating - or pondering without receiving a "go" command first. - -* Before the engine is asked to search on a position, there will always be a position command - to tell the engine about the current position. - -* by default all the opening book handling is done by the GUI, - but there is an option for the engine to use its own book ("OwnBook" option, see below) - -* if the engine or the GUI receives an unknown command or token it should just ignore it and try to - parse the rest of the string in this line. - Examples: "joho debug on\n" should switch the debug mode on given that joho is not defined, - "debug joho on\n" will be undefined however. - -* if the engine receives a command which is not supposed to come, for example "stop" when the engine is - not calculating, it should also just ignore it. - - -Move format: ------------- - -The move format is in long algebraic notation. -A nullmove from the Engine to the GUI should be sent as 0000. -Examples: e2e4, e7e5, e1g1 (white short castling), e7e8q (for promotion) - - - -GUI to engine: --------------- - -These are all the command the engine gets from the interface. - -* uci - tell engine to use the uci (universal chess interface), - this will be sent once as a first command after program boot - to tell the engine to switch to uci mode. - After receiving the uci command the engine must identify itself with the "id" command - and send the "option" commands to tell the GUI which engine settings the engine supports if any. - After that the engine should send "uciok" to acknowledge the uci mode. - If no uciok is sent within a certain time period, the engine task will be killed by the GUI. - -* debug [ on | off ] - switch the debug mode of the engine on and off. - In debug mode the engine should send additional infos to the GUI, e.g. with the "info string" command, - to help debugging, e.g. the commands that the engine has received etc. - This mode should be switched off by default and this command can be sent - any time, also when the engine is thinking. - -* isready - this is used to synchronize the engine with the GUI. When the GUI has sent a command or - multiple commands that can take some time to complete, - this command can be used to wait for the engine to be ready again or - to ping the engine to find out if it is still alive. - E.g. this should be sent after setting the path to the tablebases as this can take some time. - This command is also required once before the engine is asked to do any search - to wait for the engine to finish initializing. - This command must always be answered with "readyok" and can be sent also when the engine is calculating - in which case the engine should also immediately answer with "readyok" without stopping the search. - -* setoption name <id> [value <x>] - this is sent to the engine when the user wants to change the internal parameters - of the engine. For the "button" type no value is needed. - One string will be sent for each parameter and this will only be sent when the engine is waiting. - The name and value of the option in <id> should not be case sensitive and can inlude spaces. - The substrings "value" and "name" should be avoided in <id> and <x> to allow unambiguous parsing, - for example do not use <name> = "draw value". - Here are some strings for the example below: - "setoption name Nullmove value true\n" - "setoption name Selectivity value 3\n" - "setoption name Style value Risky\n" - "setoption name Clear Hash\n" - "setoption name NalimovPath value c:\chess\tb\4;c:\chess\tb\5\n" - -* register - this is the command to try to register an engine or to tell the engine that registration - will be done later. This command should always be sent if the engine has sent "registration error" - at program startup. - The following tokens are allowed: - * later - the user doesn't want to register the engine now. - * name <x> - the engine should be registered with the name <x> - * code <y> - the engine should be registered with the code <y> - Example: - "register later" - "register name Stefan MK code 4359874324" - -* ucinewgame - this is sent to the engine when the next search (started with "position" and "go") will be from - a different game. This can be a new game the engine should play or a new game it should analyse but - also the next position from a testsuite with positions only. - If the GUI hasn't sent a "ucinewgame" before the first "position" command, the engine shouldn't - expect any further ucinewgame commands as the GUI is probably not supporting the ucinewgame command. - So the engine should not rely on this command even though all new GUIs should support it. - As the engine's reaction to "ucinewgame" can take some time the GUI should always send "isready" - after "ucinewgame" to wait for the engine to finish its operation. - -* position [fen <fenstring> | startpos ] moves <move1> .... <movei> - set up the position described in fenstring on the internal board and - play the moves on the internal chess board. - if the game was played from the start position the string "startpos" will be sent - Note: no "new" command is needed. However, if this position is from a different game than - the last position sent to the engine, the GUI should have sent a "ucinewgame" inbetween. - -* go - start calculating on the current position set up with the "position" command. - There are a number of commands that can follow this command, all will be sent in the same string. - If one command is not sent its value should be interpreted as it would not influence the search. - * searchmoves <move1> .... <movei> - restrict search to this moves only - Example: After "position startpos" and "go infinite searchmoves e2e4 d2d4" - the engine should only search the two moves e2e4 and d2d4 in the initial position. - * ponder - start searching in pondering mode. - Do not exit the search in ponder mode, even if it's mate! - This means that the last move sent in in the position string is the ponder move. - The engine can do what it wants to do, but after a "ponderhit" command - it should execute the suggested move to ponder on. This means that the ponder move sent by - the GUI can be interpreted as a recommendation about which move to ponder. However, if the - engine decides to ponder on a different move, it should not display any mainlines as they are - likely to be misinterpreted by the GUI because the GUI expects the engine to ponder - on the suggested move. - * wtime <x> - white has x msec left on the clock - * btime <x> - black has x msec left on the clock - * winc <x> - white increment per move in mseconds if x > 0 - * binc <x> - black increment per move in mseconds if x > 0 - * movestogo <x> - there are x moves to the next time control, - this will only be sent if x > 0, - if you don't get this and get the wtime and btime it's sudden death - * depth <x> - search x plies only. - * nodes <x> - search x nodes only, - * mate <x> - search for a mate in x moves - * movetime <x> - search exactly x mseconds - * infinite - search until the "stop" command. Do not exit the search without being told so in this mode! - -* stop - stop calculating as soon as possible, - don't forget the "bestmove" and possibly the "ponder" token when finishing the search - -* ponderhit - the user has played the expected move. This will be sent if the engine was told to ponder on the same move - the user has played. The engine should continue searching but switch from pondering to normal search. - -* quit - quit the program as soon as possible - - -Engine to GUI: --------------- - -* id - * name <x> - this must be sent after receiving the "uci" command to identify the engine, - e.g. "id name Shredder X.Y\n" - * author <x> - this must be sent after receiving the "uci" command to identify the engine, - e.g. "id author Stefan MK\n" - -* uciok - Must be sent after the id and optional options to tell the GUI that the engine - has sent all infos and is ready in uci mode. - -* readyok - This must be sent when the engine has received an "isready" command and has - processed all input and is ready to accept new commands now. - It is usually sent after a command that can take some time to be able to wait for the engine, - but it can be used anytime, even when the engine is searching, - and must always be answered with "isready". - -* bestmove <move1> [ ponder <move2> ] - the engine has stopped searching and found the move <move> best in this position. - the engine can send the move it likes to ponder on. The engine must not start pondering automatically. - this command must always be sent if the engine stops searching, also in pondering mode if there is a - "stop" command, so for every "go" command a "bestmove" command is needed! - Directly before that the engine should send a final "info" command with the final search information, - the the GUI has the complete statistics about the last search. - -* copyprotection - this is needed for copyprotected engines. After the uciok command the engine can tell the GUI, - that it will check the copy protection now. This is done by "copyprotection checking". - If the check is ok the engine should send "copyprotection ok", otherwise "copyprotection error". - If there is an error the engine should not function properly but should not quit alone. - If the engine reports "copyprotection error" the GUI should not use this engine - and display an error message instead! - The code in the engine can look like this - TellGUI("copyprotection checking\n"); - // ... check the copy protection here ... - if(ok) - TellGUI("copyprotection ok\n"); - else - TellGUI("copyprotection error\n"); - -* registration - this is needed for engines that need a username and/or a code to function with all features. - Analog to the "copyprotection" command the engine can send "registration checking" - after the uciok command followed by either "registration ok" or "registration error". - Also after every attempt to register the engine it should answer with "registration checking" - and then either "registration ok" or "registration error". - In contrast to the "copyprotection" command, the GUI can use the engine after the engine has - reported an error, but should inform the user that the engine is not properly registered - and might not use all its features. - In addition the GUI should offer to open a dialog to - enable registration of the engine. To try to register an engine the GUI can send - the "register" command. - The GUI has to always answer with the "register" command if the engine sends "registration error" - at engine startup (this can also be done with "register later") - and tell the user somehow that the engine is not registered. - This way the engine knows that the GUI can deal with the registration procedure and the user - will be informed that the engine is not properly registered. - -* info - the engine wants to send information to the GUI. This should be done whenever one of the info has changed. - The engine can send only selected infos or multiple infos with one info command, - e.g. "info currmove e2e4 currmovenumber 1" or - "info depth 12 nodes 123456 nps 100000". - Also all infos belonging to the pv should be sent together - e.g. "info depth 2 score cp 214 time 1242 nodes 2124 nps 34928 pv e2e4 e7e5 g1f3" - I suggest to start sending "currmove", "currmovenumber", "currline" and "refutation" only after one second - to avoid too much traffic. - Additional info: - * depth <x> - search depth in plies - * seldepth <x> - selective search depth in plies, - if the engine sends seldepth there must also be a "depth" present in the same string. - * time <x> - the time searched in ms, this should be sent together with the pv. - * nodes <x> - x nodes searched, the engine should send this info regularly - * pv <move1> ... <movei> - the best line found - * multipv <num> - this for the multi pv mode. - for the best move/pv add "multipv 1" in the string when you send the pv. - in k-best mode always send all k variants in k strings together. - * score - * cp <x> - the score from the engine's point of view in centipawns. - * mate <y> - mate in y moves, not plies. - If the engine is getting mated use negative values for y. - * lowerbound - the score is just a lower bound. - * upperbound - the score is just an upper bound. - * currmove <move> - currently searching this move - * currmovenumber <x> - currently searching move number x, for the first move x should be 1 not 0. - * hashfull <x> - the hash is x permill full, the engine should send this info regularly - * nps <x> - x nodes per second searched, the engine should send this info regularly - * tbhits <x> - x positions where found in the endgame table bases - * sbhits <x> - x positions where found in the shredder endgame databases - * cpuload <x> - the cpu usage of the engine is x permill. - * string <str> - any string str which will be displayed be the engine, - if there is a string command the rest of the line will be interpreted as <str>. - * refutation <move1> <move2> ... <movei> - move <move1> is refuted by the line <move2> ... <movei>, i can be any number >= 1. - Example: after move d1h5 is searched, the engine can send - "info refutation d1h5 g6h5" - if g6h5 is the best answer after d1h5 or if g6h5 refutes the move d1h5. - if there is no refutation for d1h5 found, the engine should just send - "info refutation d1h5" - The engine should only send this if the option "UCI_ShowRefutations" is set to true. - * currline <cpunr> <move1> ... <movei> - this is the current line the engine is calculating. <cpunr> is the number of the cpu if - the engine is running on more than one cpu. <cpunr> = 1,2,3.... - if the engine is just using one cpu, <cpunr> can be omitted. - If <cpunr> is greater than 1, always send all k lines in k strings together. - The engine should only send this if the option "UCI_ShowCurrLine" is set to true. - - -* option - This command tells the GUI which parameters can be changed in the engine. - This should be sent once at engine startup after the "uci" and the "id" commands - if any parameter can be changed in the engine. - The GUI should parse this and build a dialog for the user to change the settings. - Note that not every option needs to appear in this dialog as some options like - "Ponder", "UCI_AnalyseMode", etc. are better handled elsewhere or are set automatically. - If the user wants to change some settings, the GUI will send a "setoption" command to the engine. - Note that the GUI need not send the setoption command when starting the engine for every option if - it doesn't want to change the default value. - For all allowed combinations see the examples below, - as some combinations of this tokens don't make sense. - One string will be sent for each parameter. - * name <id> - The option has the name id. - Certain options have a fixed value for <id>, which means that the semantics of this option is fixed. - Usually those options should not be displayed in the normal engine options window of the GUI but - get a special treatment. "Pondering" for example should be set automatically when pondering is - enabled or disabled in the GUI options. The same for "UCI_AnalyseMode" which should also be set - automatically by the GUI. All those certain options have the prefix "UCI_" except for the - first 6 options below. If the GUI gets an unknown Option with the prefix "UCI_", it should just - ignore it and not display it in the engine's options dialog. - * <id> = Hash, type is spin - the value in MB for memory for hash tables can be changed, - this should be answered with the first "setoptions" command at program boot - if the engine has sent the appropriate "option name Hash" command, - which should be supported by all engines! - So the engine should use a very small hash first as default. - * <id> = NalimovPath, type string - this is the path on the hard disk to the Nalimov compressed format. - Multiple directories can be concatenated with ";" - * <id> = NalimovCache, type spin - this is the size in MB for the cache for the nalimov table bases - These last two options should also be present in the initial options exchange dialog - when the engine is booted if the engine supports it - * <id> = Ponder, type check - this means that the engine is able to ponder. - The GUI will send this whenever pondering is possible or not. - Note: The engine should not start pondering on its own if this is enabled, this option is only - needed because the engine might change its time management algorithm when pondering is allowed. - * <id> = OwnBook, type check - this means that the engine has its own book which is accessed by the engine itself. - if this is set, the engine takes care of the opening book and the GUI will never - execute a move out of its book for the engine. If this is set to false by the GUI, - the engine should not access its own book. - * <id> = MultiPV, type spin - the engine supports multi best line or k-best mode. the default value is 1 - * <id> = UCI_ShowCurrLine, type check, should be false by default, - the engine can show the current line it is calculating. see "info currline" above. - * <id> = UCI_ShowRefutations, type check, should be false by default, - the engine can show a move and its refutation in a line. see "info refutations" above. - * <id> = UCI_LimitStrength, type check, should be false by default, - The engine is able to limit its strength to a specific Elo number, - This should always be implemented together with "UCI_Elo". - * <id> = UCI_Elo, type spin - The engine can limit its strength in Elo within this interval. - If UCI_LimitStrength is set to false, this value should be ignored. - If UCI_LimitStrength is set to true, the engine should play with this specific strength. - This should always be implemented together with "UCI_LimitStrength". - * <id> = UCI_AnalyseMode, type check - The engine wants to behave differently when analysing or playing a game. - For example when playing it can use some kind of learning. - This is set to false if the engine is playing a game, otherwise it is true. - * <id> = UCI_Opponent, type string - With this command the GUI can send the name, title, elo and if the engine is playing a human - or computer to the engine. - The format of the string has to be [GM|IM|FM|WGM|WIM|none] [<elo>|none] [computer|human] <name> - Examples: - "setoption name UCI_Opponent value GM 2800 human Gary Kasparov" - "setoption name UCI_Opponent value none none computer Shredder" - * <id> = UCI_EngineAbout, type string - With this command, the engine tells the GUI information about itself, for example a license text, - usually it doesn't make sense that the GUI changes this text with the setoption command. - Example: - "option name UCI_EngineAbout type string default Shredder by Stefan Meyer-Kahlen, see www.shredderchess.com" - * <id> = UCI_ShredderbasesPath, type string - this is either the path to the folder on the hard disk containing the Shredder endgame databases or - the path and filename of one Shredder endgame datbase. - * <id> = UCI_SetPositionValue, type string - the GUI can send this to the engine to tell the engine to use a certain value in centipawns from white's - point of view if evaluating this specifix position. - The string can have the formats: - <value> + <fen> | clear + <fen> | clearall - - * type <t> - The option has type t. - There are 5 different types of options the engine can send - * check - a checkbox that can either be true or false - * spin - a spin wheel that can be an integer in a certain range - * combo - a combo box that can have different predefined strings as a value - * button - a button that can be pressed to send a command to the engine - * string - a text field that has a string as a value, - an empty string has the value "<empty>" - * default <x> - the default value of this parameter is x - * min <x> - the minimum value of this parameter is x - * max <x> - the maximum value of this parameter is x - * var <x> - a predefined value of this parameter is x - Examples: - Here are 5 strings for each of the 5 possible types of options - "option name Nullmove type check default true\n" - "option name Selectivity type spin default 2 min 0 max 4\n" - "option name Style type combo default Normal var Solid var Normal var Risky\n" - "option name NalimovPath type string default c:\\n" - "option name Clear Hash type button\n" - - - -Examples: ---------- - -This is how the communication when the engine boots can look like: - -GUI engine - -// tell the engine to switch to UCI mode -uci - -// engine identify - id name Shredder - id author Stefan MK - -// engine sends the options it can change -// the engine can change the hash size from 1 to 128 MB - option name Hash type spin default 1 min 1 max 128 - -// the engine supports Nalimov endgame tablebases - option name NalimovPath type string default <empty> - option name NalimovCache type spin default 1 min 1 max 32 - -// the engine can switch off Nullmove and set the playing style - option name Nullmove type check default true - option name Style type combo default Normal var Solid var Normal var Risky - -// the engine has sent all parameters and is ready - uciok - -// Note: here the GUI can already send a "quit" command if it just wants to find out -// details about the engine, so the engine should not initialize its internal -// parameters before here. -// now the GUI sets some values in the engine -// set hash to 32 MB -setoption name Hash value 32 - -// init tbs -setoption name NalimovCache value 1 -setoption name NalimovPath value d:\tb;c\tb - -// waiting for the engine to finish initializing -// this command and the answer is required here! -isready - -// engine has finished setting up the internal values - readyok - -// now we are ready to go - -// if the GUI is supporting it, tell the engine that is is -// searching on a game that it hasn't searched on before -ucinewgame - -// if the engine supports the "UCI_AnalyseMode" option and the next search is supposed to -// be an analysis, the GUI should set "UCI_AnalyseMode" to true if it is currently -// set to false with this engine -setoption name UCI_AnalyseMode value true - -// tell the engine to search infinite from the start position after 1.e4 e5 -position startpos moves e2e4 e7e5 -go infinite - -// the engine starts sending infos about the search to the GUI -// (only some examples are given) - - - info depth 1 seldepth 0 - info score cp 13 depth 1 nodes 13 time 15 pv f1b5 - info depth 2 seldepth 2 - info nps 15937 - info score cp 14 depth 2 nodes 255 time 15 pv f1c4 f8c5 - info depth 2 seldepth 7 nodes 255 - info depth 3 seldepth 7 - info nps 26437 - info score cp 20 depth 3 nodes 423 time 15 pv f1c4 g8f6 b1c3 - info nps 41562 - .... - - -// here the user has seen enough and asks to stop the searching -stop - -// the engine has finished searching and is sending the bestmove command -// which is needed for every "go" command sent to tell the GUI -// that the engine is ready again - bestmove g1f3 ponder d8f6 - - - -Chess960 -======== - -UCI could easily be extended to support Chess960 (also known as Fischer Random Chess). - -The engine has to tell the GUI that it is capable of playing Chess960 and the GUI has to tell -the engine that is should play according to the Chess960 rules. -This is done by the special engine option UCI_Chess960. If the engine knows about Chess960 -it should send the command 'option name UCI_Chess960 type check default false' -to the GUI at program startup. -Whenever a Chess960 game is played, the GUI should set this engine option to 'true'. - -Castling is different in Chess960 and the white king move when castling short is not always e1g1. -A king move could both be the castling king move or just a normal king move. -This is why castling moves are sent in the form king "takes" his own rook. -Example: e1h1 for the white short castle move in the normal chess start position. - -In EPD and FEN position strings specifying the castle rights with w and q is not enough as -there could be more than one rook on the right or left side of the king. -This is why the castle rights are specified with the letter of the castle rook's line. -Upper case letters for white's and lower case letters for black's castling rights. -Example: The normal chess position would be: -rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w AHah - - diff --git a/src/uci/command.c b/src/uci/command.c index d82c50c..02d6e0f 100644 --- a/src/uci/command.c +++ b/src/uci/command.c @@ -1,6 +1,6 @@ #include <assert.h> -#include <stdlib.h> #include <string.h> +#include <stdlib.h> #include "command.h" ucicmd ucicmd_init() { diff --git a/src/uci/command.h b/src/uci/command.h deleted file mode 100644 index ba9c51d..0000000 --- a/src/uci/command.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef UCI_COMMAND_H -#define UCI_COMMAND_H - -#define MAX_TOKEN_SIZE 32 - -typedef struct { - char root[MAX_TOKEN_SIZE]; - int args_count; - int args_capacity; - char* args; - bool empty; -} ucicmd; - -ucicmd ucicmd_init(); -void ucicmd_add(ucicmd* cmd, const char* token); -void ucicmd_set_root(ucicmd* cmd, const char* token); -void ucicmd_append_arg(ucicmd* cmd, const char* token); -char* ucicmd_get_arg(ucicmd cmd, int i); -void ucicmd_deinit(ucicmd cmd); - -#endif // UCI_COMMAND_H diff --git a/src/uci/draft-1.pdf b/src/uci/draft-1.pdf Binary files differdeleted file mode 100644 index 9c68adb..0000000 --- a/src/uci/draft-1.pdf +++ /dev/null diff --git a/src/uci/draft-2.pdf b/src/uci/draft-2.pdf Binary files differdeleted file mode 100644 index d0d4707..0000000 --- a/src/uci/draft-2.pdf +++ /dev/null diff --git a/src/uci/response.c b/src/uci/response.c index 6208a54..7ebe49c 100644 --- a/src/uci/response.c +++ b/src/uci/response.c @@ -3,8 +3,9 @@ #include <stdlib.h> #include "response.h" -#include "../fen.h" -#include "../bitboard.h" +#include "ipc.h" +#include "fen.h" +#include "bitboard.h" void apply_option(uci_state *state, char *name, char *buffer) { int settings_count = sizeof(state->option_settings)/sizeof(option_setting_t); @@ -212,6 +213,48 @@ void handle_idle( } else if (strcmp(cmd.root, "isready") == 0) { current_state = STATE_SYNC; } else if (strcmp(cmd.root, "go") == 0) { + state->go_args = malloc(sizeof(struct go_args)); + struct go_args *info = state->go_args; + for (int i = 0; i < cmd.args_count; i++) { + if (strcmp(ucicmd_get_arg(cmd, i), "searchmoves") == 0) { + info->searchmoves = comm_moves_init(); + for (i++; i < cmd.args_count; i++) { + char* move_str = ucicmd_get_arg(cmd, i); + if (move_str[1] < '0' || move_str[1] > '9') break; + + add_comm_move(&info->searchmoves, (struct uci_move) { + (move_str[0] - 'a') * 8 + (move_str[1] - '1'), + (move_str[2] - 'a') * 8 + (move_str[3] - '1') + }); + } + i--; + } else if (strcmp(ucicmd_get_arg(cmd, i), "ponder") == 0) { + info->ponder = true; + } else if (strcmp(ucicmd_get_arg(cmd, i), "wtime") == 0) { + info->wtime = atoi(ucicmd_get_arg(cmd, ++i)); + } else if (strcmp(ucicmd_get_arg(cmd, i), "btime") == 0) { + info->btime = atoi(ucicmd_get_arg(cmd, ++i)); + } else if (strcmp(ucicmd_get_arg(cmd, i), "winc") == 0) { + info->winc = atoi(ucicmd_get_arg(cmd, ++i)); + } else if (strcmp(ucicmd_get_arg(cmd, i), "binc") == 0) { + info->binc = atoi(ucicmd_get_arg(cmd, ++i)); + } else if (strcmp(ucicmd_get_arg(cmd, i), "movestogo") == 0) { + info->movestogo = atoi(ucicmd_get_arg(cmd, ++i)); + } else if (strcmp(ucicmd_get_arg(cmd, i), "depth") == 0) { + info->depth = atoi(ucicmd_get_arg(cmd, ++i)); + } else if (strcmp(ucicmd_get_arg(cmd, i), "nodes") == 0) { + info->nodes = atoi(ucicmd_get_arg(cmd, ++i)); + } else if (strcmp(ucicmd_get_arg(cmd, i), "mate") == 0) { + info->mate = atoi(ucicmd_get_arg(cmd, ++i)); + } else if (strcmp(ucicmd_get_arg(cmd, i), "movetime") == 0) { + info->movetime = atoi(ucicmd_get_arg(cmd, ++i)); + } else if (strcmp(ucicmd_get_arg(cmd, i), "infinite") == 0) { + info->infinite = true; + } else if (strcmp(ucicmd_get_arg(cmd, i), "perft") == 0) { + info->perft = atoi(ucicmd_get_arg(cmd, ++i)); + } + } + atomic_store(&state->go, 1); current_state = STATE_ACTIVE; } else { @@ -247,17 +290,31 @@ void handle_active( engine_messages* engine_messages, ucicmd cmd ) { + while (atomic_load(&state->go_ready_receive) == 0); + + bool ended = false; for (int i = 0; i < engine_messages->count; i++) { struct engine_message *old = engine_messages->data[i]; + if (old == NULL) continue; if (!old->ready) continue; old->ready = 0; printf( - "info depth %d seldepth %d multipv %d score cp %d nodes %d nps %d hashfull %d tbhits %d time %d pv", + "info depth %d seldepth %d multipv %d ", old->depth, old->seldepth, - old->multipv, - old->score_cp, + old->multipv + ); + if (old->mate) { + printf("mate %d ", old->mate); + } else { + printf("score cp %d ", old->score_cp); + } + if (old->node_limit) { + printf("upperbound "); + } + printf( + "nodes %d nps %d hashfull %d tbhits %d time %d pv", old->nodes, old->nps, old->hashfull, @@ -278,6 +335,7 @@ void handle_active( printf("\n"); if (old->best_move.from != 0 && old->best_move.to != 0) { + ended = true; printf( "bestmove %c%c%c%c", (old->best_move.from / 8) + 'a', @@ -300,8 +358,13 @@ void handle_active( engine_messages->data[i] = old->next; free(old->pv.moves); free(old); + + if (ended) { + printf("ENDED\n"); + atomic_store(&state->cleanup, 1); + current_state = STATE_IDLE; + } } - // TODO: this section will call the engine to analysis if (cmd.empty) { return; } @@ -316,9 +379,9 @@ void handle_active( void handle_halt(uci_state *state, ucicmd cmd) { // TIMEOUT NOTICE: THE FOLLOWING BLOCK SHOULDN'T TAKE MORE THAN 1 SECONDS - + + atomic_store(&state->stop, 1); // --- - printf("bestmove 0000\n"); // TODO: idk get it rn current_state = STATE_IDLE; } diff --git a/src/uci/response.h b/src/uci/response.h deleted file mode 100644 index 16652d2..0000000 --- a/src/uci/response.h +++ /dev/null @@ -1,19 +0,0 @@ -#include "command.h" -#include "state.h" -#include "../ipc.h" - -void handle_uci( - uci_state *state, - engine_messages* engine_message, - ucicmd cmd -); -void handle_initial(uci_state *state, ucicmd cmd); -void handle_idle(uci_state *state, ucicmd cmd); -void handle_sync(uci_state *state, ucicmd cmd); -void handle_ping(uci_state *state, ucicmd cmd); -void handle_active( - uci_state *state, - engine_messages* engine_message, - ucicmd cmd -); -void handle_halt(uci_state *state, ucicmd cmd); diff --git a/src/uci/state.c b/src/uci/state.c index f64b5cf..56e0b04 100644 --- a/src/uci/state.c +++ b/src/uci/state.c @@ -9,7 +9,7 @@ option_setting_t option_setting_combo( combo_t *combo ) { option_setting_t output = {0}; - memcpy(output.option_name, option_name, 32); + strncpy(output.option_name, option_name, 32); output.type = OPTION_COMBO; output.data.combo = (option_combo_setting_t) { combinations, @@ -29,7 +29,7 @@ option_setting_t option_setting_spin( spin_t *spin ) { option_setting_t output = {0}; - memcpy(output.option_name, option_name, 32); + strncpy(output.option_name, option_name, 32); output.type = OPTION_SPIN; output.data.spin = (option_spin_setting_t) { min, max, default_value }; output.value.spin = spin; @@ -43,7 +43,7 @@ option_setting_t option_setting_check( check_t *check ) { option_setting_t output = {0}; - memcpy(output.option_name, option_name, 32); + strncpy(output.option_name, option_name, 32); output.type = OPTION_CHECK; output.data.check_default = default_value; output.value.check = check; @@ -72,7 +72,7 @@ option_setting_t option_setting_button( button_t *button ) { option_setting_t output = {0}; - memcpy(output.option_name, option_name, 32); + strncpy(output.option_name, option_name, 32); output.type = OPTION_BUTTON; output.value.button = button; *button = false; diff --git a/src/uci/state.h b/src/uci/state.h deleted file mode 100644 index 9c59a3a..0000000 --- a/src/uci/state.h +++ /dev/null @@ -1,118 +0,0 @@ -#ifndef UCI_STATE_H -#define UCI_STATE_H - -#include <stdatomic.h> -#include "../fen.h" - -typedef struct { - char* data; - int length; -} str_t; - -typedef bool check_t; -typedef int spin_t; -typedef int combo_t; -// the button isn't actually a value thing -// it's more like an event. -// so we parse a button type, we set this to true, handle it -// then set it to false again -typedef bool button_t; - -typedef struct { - char** combination; - int count; - int default_index; -} option_combo_setting_t; -typedef struct { - int min; - int max; - int default_value; -} option_spin_setting_t; -enum { OPTION_SPIN, OPTION_COMBO, OPTION_CHECK, OPTION_STRING, OPTION_BUTTON }; -typedef struct { - char option_name[32]; - int type; - union { - option_combo_setting_t combo; - option_spin_setting_t spin; - bool check_default; - const char* string_default; - } data; - union { - combo_t *combo; - spin_t *spin; - check_t *check; - str_t *string; - button_t *button; - } value; -} option_setting_t; - -option_setting_t option_setting_combo( - char* option_name, - char** combinations, - int combinations_count, - int default_index, - combo_t *combo -); -option_setting_t option_setting_spin( - const char* option_name, - int min, - int max, - int default_value, - spin_t *spin -); -option_setting_t option_setting_check( - const char* option_name, - bool default_value, - check_t *check -); -option_setting_t option_setting_string( - const char* option_name, - const char* default_value, - str_t *string -); -option_setting_t option_setting_button( - const char* option_name, - button_t *button -); - -typedef struct { - char name[32]; - char author[32]; - bool debug; - - atomic_int go; - atomic_int quit; - - position_t position; - struct uci_move *moves; - int moves_count; - - option_setting_t option_settings[11]; - - // options - spin_t threads; - spin_t hash; - button_t clear_hash; - // str_t nalimovpath; - // spin_t nalimovcache; - // check_t ponder; - // check_t ownbook; - // spin_t multipv; - check_t uci_showcurrline; - check_t uci_showrefutations; - check_t uci_limitstrength; - spin_t uci_elo; - check_t uci_analysemode; - str_t uci_opponent; - str_t uci_engineabout; - // str_t uci_shredderbasespath; - str_t uci_setpositionvalue; -} uci_state; - -struct uci_move { - int from; - int to; -}; - -#endif // UCI_STATE_H diff --git a/src/uci/uci_min.txt b/src/uci/uci_min.txt deleted file mode 100644 index 58a85b6..0000000 --- a/src/uci/uci_min.txt +++ /dev/null @@ -1,140 +0,0 @@ -GUI to engine: -* uci -* debug [ on | off ] -* isready -* setoption name <id> [value <x>] - Here are some strings for the example below: - "setoption name Nullmove value true\n" - "setoption name Selectivity value 3\n" - "setoption name Style value Risky\n" - "setoption name Clear Hash\n" - "setoption name NalimovPath value c:\chess\tb\4;c:\chess\tb\5\n" - -* register - The following tokens are allowed: - * later - the user doesn't want to register the engine now. - * name <x> - the engine should be registered with the name <x> - * code <y> - the engine should be registered with the code <y> - Example: - "register later" - "register name Stefan MK code 4359874324" - -* ucinewgame -* position [fen <fenstring> | startpos ] moves <move1> .... <movei> -* go - * searchmoves <move1> .... <movei> - Example: After "position startpos" and "go infinite searchmoves e2e4 d2d4" - the engine should only search the two moves e2e4 and d2d4 in the initial position. - * ponder - * wtime <x> - * btime <x> - * winc <x> - * binc <x> - * movestogo <x> - * depth <x> - * nodes <x> - * mate <x> - * movetime <x> - * infinite -* stop -* ponderhit -* quit - - -Engine to GUI: -* id - * name <x> - e.g. "id name Shredder X.Y\n" - * author <x> - e.g. "id author Stefan MK\n" -* uciok -* readyok -* bestmove <move1> [ ponder <move2> ] -* copyprotection -* registration -* info - e.g. "info currmove e2e4 currmovenumber 1" or - "info depth 12 nodes 123456 nps 100000". - e.g. "info depth 2 score cp 214 time 1242 nodes 2124 nps 34928 pv e2e4 e7e5 g1f3" - Additional info: - * depth <x> - * seldepth <x> - * time <x> - * nodes <x> - * pv <move1> ... <movei> - * multipv <num> - * score - * cp <x> - * mate <y> - * lowerbound - * upperbound - * currmove <move> - * currmovenumber <x> - * hashfull <x> - * nps <x> - * tbhits <x> - * sbhits <x> - * cpuload <x> - * string <str> - * refutation <move1> <move2> ... <movei> - Example: after move d1h5 is searched, the engine can send - "info refutation d1h5 g6h5" - if g6h5 is the best answer after d1h5 or if g6h5 refutes the move d1h5. - if there is no refutation for d1h5 found, the engine should just send - "info refutation d1h5" - * currline <cpunr> <move1> ... <movei> - - -* option - * name <id> - * <id> = Hash, type is spin - * <id> = NalimovPath, type string - * <id> = NalimovCache, type spin - * <id> = Ponder, type check - * <id> = OwnBook, type check - * <id> = MultiPV, type spin - * <id> = UCI_ShowCurrLine, type check, should be false by default, - * <id> = UCI_ShowRefutations, type check, should be false by default, - * <id> = UCI_LimitStrength, type check, should be false by default, - * <id> = UCI_Elo, type spin - * <id> = UCI_AnalyseMode, type check - * <id> = UCI_Opponent, type string - Examples: - "setoption name UCI_Opponent value GM 2800 human Gary Kasparov" - "setoption name UCI_Opponent value none none computer Shredder" - * <id> = UCI_EngineAbout, type string - Example: - "option name UCI_EngineAbout type string default Shredder by Stefan Meyer-Kahlen, see www.shredderchess.com" - * <id> = UCI_ShredderbasesPath, type string - * <id> = UCI_SetPositionValue, type string - - * type <t> - * check - a checkbox that can either be true or false - * spin - a spin wheel that can be an integer in a certain range - * combo - a combo box that can have different predefined strings as a value - * button - a button that can be pressed to send a command to the engine - * string - a text field that has a string as a value, - an empty string has the value "<empty>" - * default <x> - the default value of this parameter is x - * min <x> - the minimum value of this parameter is x - * max <x> - the maximum value of this parameter is x - * var <x> - a predefined value of this parameter is x - Examples: - Here are 5 strings for each of the 5 possible types of options - "option name Nullmove type check default true\n" - "option name Selectivity type spin default 2 min 0 max 4\n" - "option name Style type combo default Normal var Solid var Normal var Risky\n" - "option name NalimovPath type string default c:\\n" - "option name Clear Hash type button\n" |
