Pattern Probability Table: Introduce basic infrastructure
[pachi/t.git] / gtp.c
blobf4ddac05c4bd4006e301682b416f34c234b6a817
1 #define DEBUG
2 #include <assert.h>
3 #include <ctype.h>
4 #include <math.h>
5 #include <stdarg.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <unistd.h>
11 #include "board.h"
12 #include "debug.h"
13 #include "engine.h"
14 #include "fbook.h"
15 #include "gtp.h"
16 #include "mq.h"
17 #include "uct/uct.h"
18 #include "version.h"
19 #include "timeinfo.h"
21 #define NO_REPLY (-2)
23 /* Sleep 5 seconds after a game ends to give time to kill the program. */
24 #define GAME_OVER_SLEEP 5
26 void
27 gtp_prefix(char prefix, int id)
29 if (id == NO_REPLY) return;
30 if (id >= 0)
31 printf("%c%d ", prefix, id);
32 else
33 printf("%c ", prefix);
36 void
37 gtp_flush(void)
39 putchar('\n');
40 fflush(stdout);
43 void
44 gtp_output(char prefix, int id, va_list params)
46 if (id == NO_REPLY) return;
47 gtp_prefix(prefix, id);
48 char *s;
49 while ((s = va_arg(params, char *))) {
50 fputs(s, stdout);
52 putchar('\n');
53 gtp_flush();
56 void
57 gtp_reply(int id, ...)
59 va_list params;
60 va_start(params, id);
61 gtp_output('=', id, params);
62 va_end(params);
65 void
66 gtp_error(int id, ...)
68 va_list params;
69 va_start(params, id);
70 gtp_output('?', id, params);
71 va_end(params);
74 /* List of known gtp commands. The internal command pachi-genmoves is not exported,
75 * it should only be used between master and slaves of the distributed engine. */
76 static char *known_commands =
77 "protocol_version\n"
78 "echo\n"
79 "name\n"
80 "version\n"
81 "list_commands\n"
82 "known_command\n"
83 "quit\n"
84 "boardsize\n"
85 "clear_board\n"
86 "kgs-game_over\n"
87 "komi\n"
88 "kgs-rules\n"
89 "play\n"
90 "genmove\n"
91 "kgs-genmove_cleanup\n"
92 "set_free_handicap\n"
93 "place_free_handicap\n"
94 "fixed_handicap\n"
95 "final_score\n"
96 "final_status_list\n"
97 "undo\n"
98 "pachi-result\n"
99 "kgs-chat\n"
100 "time_left\n"
101 "time_settings\n"
102 "kgs-time_settings";
105 /* Return true if cmd is a valid gtp command. */
106 bool
107 gtp_is_valid(char *cmd)
109 if (!cmd || !*cmd) return false;
110 char *s = strcasestr(known_commands, cmd);
111 if (!s) return false;
112 if (s != known_commands && s[-1] != '\n') return false;
114 int len = strlen(cmd);
115 return s[len] == '\0' || s[len] == '\n';
118 /* XXX: THIS IS TOTALLY INSECURE!!!!
119 * Even basic input checking is missing. */
121 enum parse_code
122 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
124 #define next_tok(to_) \
125 to_ = next; \
126 next = next + strcspn(next, " \t\r\n"); \
127 if (*next) { \
128 *next = 0; next++; \
129 next += strspn(next, " \t\r\n"); \
132 if (strchr(buf, '#'))
133 *strchr(buf, '#') = 0;
135 char *cmd, *next = buf;
136 next_tok(cmd);
138 int id = -1;
139 if (isdigit(*cmd)) {
140 id = atoi(cmd);
141 next_tok(cmd);
144 if (!*cmd)
145 return P_OK;
147 if (!strcasecmp(cmd, "protocol_version")) {
148 gtp_reply(id, "2", NULL);
149 return P_OK;
151 } else if (!strcasecmp(cmd, "name")) {
152 /* KGS hack */
153 gtp_reply(id, "Pachi ", engine->name, NULL);
154 return P_OK;
156 } else if (!strcasecmp(cmd, "echo")) {
157 gtp_reply(id, next, NULL);
158 return P_OK;
160 } else if (!strcasecmp(cmd, "version")) {
161 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, NULL);
162 return P_OK;
164 } else if (!strcasecmp(cmd, "list_commands")) {
165 gtp_reply(id, known_commands, NULL);
166 return P_OK;
168 } else if (!strcasecmp(cmd, "known_command")) {
169 char *arg;
170 next_tok(arg);
171 if (gtp_is_valid(arg)) {
172 gtp_reply(id, "true", NULL);
173 } else {
174 gtp_reply(id, "false", NULL);
176 return P_OK;
179 if (engine->notify && gtp_is_valid(cmd)) {
180 char *reply;
181 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
182 if (c == P_NOREPLY) {
183 id = NO_REPLY;
184 } else if (c == P_DONE_OK) {
185 gtp_reply(id, reply, NULL);
186 return P_OK;
187 } else if (c == P_DONE_ERROR) {
188 gtp_error(id, reply, NULL);
189 /* This is an internal error for the engine, but
190 * it is still OK from main's point of view. */
191 return P_OK;
192 } else if (c != P_OK) {
193 return c;
197 if (!strcasecmp(cmd, "quit")) {
198 gtp_reply(id, NULL);
199 exit(0);
201 } else if (!strcasecmp(cmd, "boardsize")) {
202 char *arg;
203 next_tok(arg);
204 int size = atoi(arg);
205 if (size < 1 || size > BOARD_MAX_SIZE) {
206 gtp_error(id, "illegal board size", NULL);
207 return P_OK;
209 board_resize(board, size);
210 board_clear(board);
211 gtp_reply(id, NULL);
213 } else if (!strcasecmp(cmd, "clear_board")) {
214 board_clear(board);
215 if (DEBUGL(1) && debug_boardprint)
216 board_print(board, stderr);
217 gtp_reply(id, NULL);
218 return P_ENGINE_RESET;
220 } else if (!strcasecmp(cmd, "kgs-game_over")) {
221 /* The game may not be really over, just adjourned.
222 * Do not clear the board to avoid illegal moves
223 * if the game is resumed immediately after. KGS
224 * may start directly with genmove on resumption. */
225 if (DEBUGL(1)) {
226 fprintf(stderr, "game is over\n");
227 fflush(stderr);
229 /* Sleep before replying, so that kgs doesn't
230 * start another game immediately. */
231 sleep(GAME_OVER_SLEEP);
232 gtp_reply(id, NULL);
234 } else if (!strcasecmp(cmd, "komi")) {
235 char *arg;
236 next_tok(arg);
237 sscanf(arg, PRIfloating, &board->komi);
239 if (DEBUGL(1) && debug_boardprint)
240 board_print(board, stderr);
241 gtp_reply(id, NULL);
243 } else if (!strcasecmp(cmd, "kgs-rules")) {
244 char *arg;
245 next_tok(arg);
246 if (!strcasecmp(arg, "japanese")) {
247 board->rules = RULES_JAPANESE;
248 } else if (!strcasecmp(arg, "chinese")) {
249 board->rules = RULES_CHINESE;
250 } else if (!strcasecmp(arg, "aga")) {
251 board->rules = RULES_AGA;
252 } else if (!strcasecmp(arg, "new_zealand")) {
253 board->rules = RULES_NEW_ZEALAND;
254 } else {
255 gtp_error(id, "unknown rules", NULL);
256 return P_OK;
258 gtp_reply(id, NULL);
260 } else if (!strcasecmp(cmd, "play")) {
261 struct move m;
263 char *arg;
264 next_tok(arg);
265 m.color = str2stone(arg);
266 next_tok(arg);
267 coord_t *c = str2coord(arg, board_size(board));
268 m.coord = *c; coord_done(c);
269 char *reply = NULL;
271 if (DEBUGL(1))
272 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
274 // This is where kgs starts the timer, not at genmove!
275 time_start_timer(&ti[stone_other(m.color)]);
277 if (engine->notify_play)
278 reply = engine->notify_play(engine, board, &m);
279 if (board_play(board, &m) < 0) {
280 if (DEBUGL(0)) {
281 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
282 board_print(board, stderr);
284 gtp_error(id, "illegal move", NULL);
285 } else {
286 if (DEBUGL(1) && debug_boardprint)
287 board_print_custom(board, stderr, engine->printhook);
288 gtp_reply(id, reply, NULL);
291 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
292 char *arg;
293 next_tok(arg);
294 enum stone color = str2stone(arg);
295 coord_t *c = NULL;
297 if (!ti[color].len.t.timer_start) {
298 /* First game move. */
299 time_start_timer(&ti[color]);
302 coord_t cf = pass;
303 if (board->fbook)
304 cf = fbook_check(board);
305 if (!is_pass(cf)) {
306 c = coord_copy(cf);
307 } else {
308 c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
310 struct move m = { *c, color };
311 if (board_play(board, &m) < 0) {
312 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
313 abort();
315 char *str = coord2str(*c, board);
316 if (DEBUGL(1))
317 fprintf(stderr, "playing move %s\n", str);
318 if (DEBUGL(1) && debug_boardprint) {
319 board_print_custom(board, stderr, engine->printhook);
321 gtp_reply(id, str, NULL);
322 free(str); coord_done(c);
324 /* Account for spent time. If our GTP peer keeps our clock, this will
325 * be overriden by next time_left GTP command properly. */
326 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
327 * should be absolutely rare situation and we will just spend a little
328 * less time than we could on next few moves.) */
329 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
330 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
332 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
333 char *arg;
334 next_tok(arg);
335 enum stone color = str2stone(arg);
336 void *stats;
337 int stats_size;
339 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
340 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
341 &stats, &stats_size);
342 if (!reply) {
343 gtp_error(id, "genmoves error", NULL);
344 return P_OK;
346 if (DEBUGL(3))
347 fprintf(stderr, "proposing moves %s\n", reply);
348 if (DEBUGL(4) && debug_boardprint)
349 board_print_custom(board, stderr, engine->printhook);
350 gtp_reply(id, reply, NULL);
351 if (stats_size > 0) {
352 double start = time_now();
353 fwrite(stats, 1, stats_size, stdout);
354 fflush(stdout);
355 if (DEBUGVV(2))
356 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
357 stats_size, (time_now() - start)*1000);
360 } else if (!strcasecmp(cmd, "set_free_handicap")) {
361 struct move m;
362 m.color = S_BLACK;
364 char *arg;
365 next_tok(arg);
366 do {
367 coord_t *c = str2coord(arg, board_size(board));
368 m.coord = *c; coord_done(c);
369 if (DEBUGL(1))
370 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
372 if (board_play(board, &m) < 0) {
373 if (DEBUGL(0))
374 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
375 gtp_error(id, "illegal move", NULL);
377 board->handicap++;
378 next_tok(arg);
379 } while (*arg);
380 if (DEBUGL(1) && debug_boardprint)
381 board_print(board, stderr);
382 gtp_reply(id, NULL);
384 /* TODO: Engine should choose free handicap; however, it tends to take
385 * overly long to think it all out, and unless it's clever its
386 * handicap stones won't be of much help. ;-) */
387 } else if (!strcasecmp(cmd, "place_free_handicap")
388 || !strcasecmp(cmd, "fixed_handicap")) {
389 char *arg;
390 next_tok(arg);
391 int stones = atoi(arg);
393 gtp_prefix('=', id);
394 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
395 if (DEBUGL(1) && debug_boardprint)
396 board_print(board, stderr);
397 if (id == NO_REPLY) return P_OK;
398 putchar('\n');
399 gtp_flush();
401 } else if (!strcasecmp(cmd, "final_score")) {
402 struct move_queue q = { .moves = 0 };
403 if (engine->dead_group_list)
404 engine->dead_group_list(engine, board, &q);
405 floating_t score = board_official_score(board, &q);
406 char str[64];
407 if (DEBUGL(1))
408 fprintf(stderr, "counted score %.1f\n", score);
409 if (score == 0) {
410 gtp_reply(id, "0", NULL);
411 } else if (score > 0) {
412 snprintf(str, 64, "W+%.1f", score);
413 gtp_reply(id, str, NULL);
414 } else {
415 snprintf(str, 64, "B+%.1f", -score);
416 gtp_reply(id, str, NULL);
419 /* XXX: This is a huge hack. */
420 } else if (!strcasecmp(cmd, "final_status_list")) {
421 if (id == NO_REPLY) return P_OK;
422 char *arg;
423 next_tok(arg);
424 struct move_queue q = { .moves = 0 };
425 if (engine->dead_group_list)
426 engine->dead_group_list(engine, board, &q);
427 /* else we return empty list - i.e. engine not supporting
428 * this assumes all stones alive at the game end. */
429 if (!strcasecmp(arg, "dead")) {
430 gtp_prefix('=', id);
431 for (unsigned int i = 0; i < q.moves; i++) {
432 foreach_in_group(board, q.move[i]) {
433 printf("%s ", coord2sstr(c, board));
434 } foreach_in_group_end;
435 putchar('\n');
437 if (!q.moves)
438 putchar('\n');
439 gtp_flush();
440 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
441 gtp_prefix('=', id);
442 bool printed_group = false;
443 foreach_point(board) { // foreach_group, effectively
444 group_t g = group_at(board, c);
445 if (!g || g != c) continue;
447 for (unsigned int i = 0; i < q.moves; i++) {
448 if (q.move[i] == g)
449 goto next_group;
451 foreach_in_group(board, g) {
452 printf("%s ", coord2sstr(c, board));
453 } foreach_in_group_end;
454 putchar('\n');
455 printed_group = true;
456 next_group:;
457 } foreach_point_end;
458 if (!printed_group)
459 putchar('\n');
460 gtp_flush();
461 } else {
462 gtp_error(id, "illegal status specifier", NULL);
465 } else if (!strcasecmp(cmd, "undo")) {
466 if (board_undo(board) < 0) {
467 if (DEBUGL(1)) {
468 fprintf(stderr, "undo on non-pass move %s\n", coord2sstr(board->last_move.coord, board));
469 board_print(board, stderr);
471 gtp_error(id, "cannot undo", NULL);
472 return P_OK;
474 char *reply = NULL;
475 if (engine->undo)
476 reply = engine->undo(engine, board);
477 if (DEBUGL(1) && debug_boardprint)
478 board_print(board, stderr);
479 gtp_reply(id, reply, NULL);
481 /* Custom commands for handling UCT opening tbook */
482 } else if (!strcasecmp(cmd, "uct_gentbook")) {
483 /* Board must be initialized properly, as if for genmove;
484 * makes sense only as 'uct_gentbook b'. */
485 char *arg;
486 next_tok(arg);
487 enum stone color = str2stone(arg);
488 if (uct_gentbook(engine, board, &ti[color], color))
489 gtp_reply(id, NULL);
490 else
491 gtp_error(id, "error generating tbook", NULL);
493 } else if (!strcasecmp(cmd, "uct_dumptbook")) {
494 char *arg;
495 next_tok(arg);
496 enum stone color = str2stone(arg);
497 uct_dumptbook(engine, board, color);
498 gtp_reply(id, NULL);
500 } else if (!strcasecmp(cmd, "uct_evaluate")) {
501 char *arg;
502 next_tok(arg);
503 enum stone color = str2stone(arg);
505 gtp_prefix('=', id);
506 /* Iterate through the list of all free coordinates
507 * and call uct_evaluate() for each. uct_evaluate()
508 * will throw NAN in case of invalid moves and such. */
509 foreach_free_point(board) {
510 if (!board_coord_in_symmetry(board, c))
511 continue;
512 floating_t val = uct_evaluate(engine, board, &ti[color], c, color);
513 if (isnan(val))
514 continue;
515 printf("%s %1.3f\n", coord2sstr(c, board), (double) val);
516 } foreach_free_point_end;
517 gtp_flush();
519 } else if (!strcasecmp(cmd, "pachi-result")) {
520 /* More detailed result of the last genmove. */
521 /* For UCT, the output format is: = color move playouts winrate dynkomi */
522 char *reply = NULL;
523 if (engine->result)
524 reply = engine->result(engine, board);
525 if (reply)
526 gtp_reply(id, reply, NULL);
527 else
528 gtp_error(id, "unknown pachi-result command", NULL);
530 } else if (!strcasecmp(cmd, "kgs-chat")) {
531 char *loc;
532 next_tok(loc);
533 char *src;
534 next_tok(src);
535 char *msg;
536 next_tok(msg);
537 char *reply = NULL;
538 if (engine->chat)
539 reply = engine->chat(engine, board, msg);
540 if (reply)
541 gtp_reply(id, reply, NULL);
542 else
543 gtp_error(id, "unknown kgs-chat command", NULL);
545 } else if (!strcasecmp(cmd, "time_left")) {
546 char *arg;
547 next_tok(arg);
548 enum stone color = str2stone(arg);
549 next_tok(arg);
550 int time = atoi(arg);
551 next_tok(arg);
552 int stones = atoi(arg);
553 if (!ti[color].ignore_gtp) {
554 time_left(&ti[color], time, stones);
555 } else {
556 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
559 gtp_reply(id, NULL);
561 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
562 char *time_system;
563 char *arg;
564 if (!strcasecmp(cmd, "kgs-time_settings")) {
565 next_tok(time_system);
566 } else {
567 time_system = "canadian";
570 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
571 if (!strcasecmp(time_system, "none")) {
572 main_time = -1;
573 } else if (!strcasecmp(time_system, "absolute")) {
574 next_tok(arg);
575 main_time = atoi(arg);
576 } else if (!strcasecmp(time_system, "byoyomi")) {
577 next_tok(arg);
578 main_time = atoi(arg);
579 next_tok(arg);
580 byoyomi_time = atoi(arg);
581 next_tok(arg);
582 byoyomi_periods = atoi(arg);
583 } else if (!strcasecmp(time_system, "canadian")) {
584 next_tok(arg);
585 main_time = atoi(arg);
586 next_tok(arg);
587 byoyomi_time = atoi(arg);
588 next_tok(arg);
589 byoyomi_stones = atoi(arg);
592 if (DEBUGL(1))
593 fprintf(stderr, "time_settings %d %d/%d*%d\n",
594 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
595 if (!ti[S_BLACK].ignore_gtp) {
596 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
597 ti[S_WHITE] = ti[S_BLACK];
598 } else {
599 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
602 gtp_reply(id, NULL);
604 } else {
605 gtp_error(id, "unknown command", NULL);
606 return P_UNKNOWN_COMMAND;
608 return P_OK;
610 #undef next_tok