Pachi Shuhaku 8.00
[pachi/pachi-r6144.git] / gtp.c
blob0e409928ce4bdf5bc9ad793f09d850c2b2b4f651
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 "final_score\n"
95 "final_status_list\n"
96 "undo\n"
97 "pachi-result\n"
98 "kgs-chat\n"
99 "time_left\n"
100 "time_settings\n"
101 "kgs-time_settings";
104 /* Return true if cmd is a valid gtp command. */
105 bool
106 gtp_is_valid(char *cmd)
108 if (!cmd || !*cmd) return false;
109 char *s = strcasestr(known_commands, cmd);
110 if (!s) return false;
111 if (s != known_commands && s[-1] != '\n') return false;
113 int len = strlen(cmd);
114 return s[len] == '\0' || s[len] == '\n';
117 /* XXX: THIS IS TOTALLY INSECURE!!!!
118 * Even basic input checking is missing. */
120 enum parse_code
121 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
123 #define next_tok(to_) \
124 to_ = next; \
125 next = next + strcspn(next, " \t\r\n"); \
126 if (*next) { \
127 *next = 0; next++; \
128 next += strspn(next, " \t\r\n"); \
131 if (strchr(buf, '#'))
132 *strchr(buf, '#') = 0;
134 char *cmd, *next = buf;
135 next_tok(cmd);
137 int id = -1;
138 if (isdigit(*cmd)) {
139 id = atoi(cmd);
140 next_tok(cmd);
143 if (!*cmd)
144 return P_OK;
146 if (!strcasecmp(cmd, "protocol_version")) {
147 gtp_reply(id, "2", NULL);
148 return P_OK;
150 } else if (!strcasecmp(cmd, "name")) {
151 /* KGS hack */
152 gtp_reply(id, "Pachi ", engine->name, NULL);
153 return P_OK;
155 } else if (!strcasecmp(cmd, "echo")) {
156 gtp_reply(id, next, NULL);
157 return P_OK;
159 } else if (!strcasecmp(cmd, "version")) {
160 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, NULL);
161 return P_OK;
163 } else if (!strcasecmp(cmd, "list_commands")) {
164 gtp_reply(id, known_commands, NULL);
165 return P_OK;
167 } else if (!strcasecmp(cmd, "known_command")) {
168 char *arg;
169 next_tok(arg);
170 if (gtp_is_valid(arg)) {
171 gtp_reply(id, "true", NULL);
172 } else {
173 gtp_reply(id, "false", NULL);
175 return P_OK;
178 if (engine->notify && gtp_is_valid(cmd)) {
179 char *reply;
180 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
181 if (c == P_NOREPLY) {
182 id = NO_REPLY;
183 } else if (c == P_DONE_OK) {
184 gtp_reply(id, reply, NULL);
185 return P_OK;
186 } else if (c == P_DONE_ERROR) {
187 gtp_error(id, reply, NULL);
188 /* This is an internal error for the engine, but
189 * it is still OK from main's point of view. */
190 return P_OK;
191 } else if (c != P_OK) {
192 return c;
196 if (!strcasecmp(cmd, "quit")) {
197 gtp_reply(id, NULL);
198 exit(0);
200 } else if (!strcasecmp(cmd, "boardsize")) {
201 char *arg;
202 next_tok(arg);
203 int size = atoi(arg);
204 if (size < 1 || size > BOARD_MAX_SIZE) {
205 gtp_error(id, "illegal board size", NULL);
206 return P_OK;
208 board_resize(board, size);
209 gtp_reply(id, NULL);
211 } else if (!strcasecmp(cmd, "clear_board")) {
212 board_clear(board);
213 if (DEBUGL(1) && debug_boardprint)
214 board_print(board, stderr);
215 gtp_reply(id, NULL);
216 return P_ENGINE_RESET;
218 } else if (!strcasecmp(cmd, "kgs-game_over")) {
219 /* The game may not be really over, just adjourned.
220 * Do not clear the board to avoid illegal moves
221 * if the game is resumed immediately after. KGS
222 * may start directly with genmove on resumption. */
223 if (DEBUGL(1)) {
224 fprintf(stderr, "game is over\n");
225 fflush(stderr);
227 /* Sleep before replying, so that kgs doesn't
228 * start another game immediately. */
229 sleep(GAME_OVER_SLEEP);
230 gtp_reply(id, NULL);
232 } else if (!strcasecmp(cmd, "komi")) {
233 char *arg;
234 next_tok(arg);
235 sscanf(arg, PRIfloating, &board->komi);
237 if (DEBUGL(1 && debug_boardprint))
238 board_print(board, stderr);
239 gtp_reply(id, NULL);
241 } else if (!strcasecmp(cmd, "kgs-rules")) {
242 char *arg;
243 next_tok(arg);
244 if (!strcasecmp(arg, "japanese")) {
245 board->rules = RULES_JAPANESE;
246 } else if (!strcasecmp(arg, "chinese")) {
247 board->rules = RULES_CHINESE;
248 } else if (!strcasecmp(arg, "aga")) {
249 board->rules = RULES_AGA;
250 } else if (!strcasecmp(arg, "new_zealand")) {
251 board->rules = RULES_NEW_ZEALAND;
252 } else {
253 gtp_error(id, "unknown rules", NULL);
254 return P_OK;
256 gtp_reply(id, NULL);
258 } else if (!strcasecmp(cmd, "play")) {
259 struct move m;
261 char *arg;
262 next_tok(arg);
263 m.color = str2stone(arg);
264 next_tok(arg);
265 coord_t *c = str2coord(arg, board_size(board));
266 m.coord = *c; coord_done(c);
267 char *reply = NULL;
269 if (DEBUGL(1))
270 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
272 // This is where kgs starts the timer, not at genmove!
273 time_start_timer(&ti[stone_other(m.color)]);
275 if (engine->notify_play)
276 reply = engine->notify_play(engine, board, &m);
277 if (board_play(board, &m) < 0) {
278 if (DEBUGL(0)) {
279 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
280 board_print(board, stderr);
282 gtp_error(id, "illegal move", NULL);
283 } else {
284 if (DEBUGL(1) && debug_boardprint)
285 board_print_custom(board, stderr, engine->printhook);
286 gtp_reply(id, reply, NULL);
289 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
290 char *arg;
291 next_tok(arg);
292 enum stone color = str2stone(arg);
293 coord_t *c = NULL;
295 if (!ti[color].len.t.timer_start) {
296 /* First game move. */
297 time_start_timer(&ti[color]);
300 coord_t cf = pass;
301 if (board->fbook)
302 cf = fbook_check(board);
303 if (!is_pass(cf)) {
304 c = coord_copy(cf);
305 } else {
306 c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
308 struct move m = { *c, color };
309 if (board_play(board, &m) < 0) {
310 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
311 abort();
313 char *str = coord2str(*c, board);
314 if (DEBUGL(1))
315 fprintf(stderr, "playing move %s\n", str);
316 if (DEBUGL(1) && debug_boardprint) {
317 board_print_custom(board, stderr, engine->printhook);
319 gtp_reply(id, str, NULL);
320 free(str); coord_done(c);
322 /* Account for spent time. If our GTP peer keeps our clock, this will
323 * be overriden by next time_left GTP command properly. */
324 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
325 * should be absolutely rare situation and we will just spend a little
326 * less time than we could on next few moves.) */
327 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
328 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
330 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
331 char *arg;
332 next_tok(arg);
333 enum stone color = str2stone(arg);
334 void *stats;
335 int stats_size;
337 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
338 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
339 &stats, &stats_size);
340 if (!reply) {
341 gtp_error(id, "genmoves error", NULL);
342 return P_OK;
344 if (DEBUGL(3))
345 fprintf(stderr, "proposing moves %s\n", reply);
346 if (DEBUGL(4) && debug_boardprint)
347 board_print_custom(board, stderr, engine->printhook);
348 gtp_reply(id, reply, NULL);
349 if (stats_size > 0) {
350 double start = time_now();
351 fwrite(stats, 1, stats_size, stdout);
352 fflush(stdout);
353 if (DEBUGVV(2))
354 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
355 stats_size, (time_now() - start)*1000);
358 } else if (!strcasecmp(cmd, "set_free_handicap")) {
359 struct move m;
360 m.color = S_BLACK;
362 char *arg;
363 next_tok(arg);
364 do {
365 coord_t *c = str2coord(arg, board_size(board));
366 m.coord = *c; coord_done(c);
367 if (DEBUGL(1))
368 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
370 if (board_play(board, &m) < 0) {
371 if (DEBUGL(0))
372 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
373 gtp_error(id, "illegal move", NULL);
375 board->handicap++;
376 next_tok(arg);
377 } while (*arg);
378 if (DEBUGL(1) && debug_boardprint)
379 board_print(board, stderr);
380 gtp_reply(id, NULL);
382 /* TODO: Engine should choose free handicap; however, it tends to take
383 * overly long to think it all out, and unless it's clever its
384 * handicap stones won't be of much help. ;-) */
385 } else if (!strcasecmp(cmd, "place_free_handicap")
386 || !strcasecmp(cmd, "fixed_handicap")) {
387 char *arg;
388 next_tok(arg);
389 int stones = atoi(arg);
391 gtp_prefix('=', id);
392 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
393 if (DEBUGL(1) && debug_boardprint)
394 board_print(board, stderr);
395 if (id == NO_REPLY) return P_OK;
396 putchar('\n');
397 gtp_flush();
399 } else if (!strcasecmp(cmd, "final_score")) {
400 struct move_queue q = { .moves = 0 };
401 if (engine->dead_group_list)
402 engine->dead_group_list(engine, board, &q);
403 floating_t score = board_official_score(board, &q);
404 char str[64];
405 if (DEBUGL(1))
406 fprintf(stderr, "counted score %.1f\n", score);
407 if (score == 0) {
408 gtp_reply(id, "0", NULL);
409 } else if (score > 0) {
410 snprintf(str, 64, "W+%.1f", score);
411 gtp_reply(id, str, NULL);
412 } else {
413 snprintf(str, 64, "B+%.1f", -score);
414 gtp_reply(id, str, NULL);
417 /* XXX: This is a huge hack. */
418 } else if (!strcasecmp(cmd, "final_status_list")) {
419 if (id == NO_REPLY) return P_OK;
420 char *arg;
421 next_tok(arg);
422 struct move_queue q = { .moves = 0 };
423 if (engine->dead_group_list)
424 engine->dead_group_list(engine, board, &q);
425 /* else we return empty list - i.e. engine not supporting
426 * this assumes all stones alive at the game end. */
427 if (!strcasecmp(arg, "dead")) {
428 gtp_prefix('=', id);
429 for (unsigned int i = 0; i < q.moves; i++) {
430 foreach_in_group(board, q.move[i]) {
431 printf("%s ", coord2sstr(c, board));
432 } foreach_in_group_end;
433 putchar('\n');
435 if (!q.moves)
436 putchar('\n');
437 gtp_flush();
438 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
439 gtp_prefix('=', id);
440 bool printed_group = false;
441 foreach_point(board) { // foreach_group, effectively
442 group_t g = group_at(board, c);
443 if (!g || g != c) continue;
445 for (unsigned int i = 0; i < q.moves; i++) {
446 if (q.move[i] == g)
447 goto next_group;
449 foreach_in_group(board, g) {
450 printf("%s ", coord2sstr(c, board));
451 } foreach_in_group_end;
452 putchar('\n');
453 printed_group = true;
454 next_group:;
455 } foreach_point_end;
456 if (!printed_group)
457 putchar('\n');
458 gtp_flush();
459 } else {
460 gtp_error(id, "illegal status specifier", NULL);
463 } else if (!strcasecmp(cmd, "undo")) {
464 if (board_undo(board) < 0) {
465 if (DEBUGL(1)) {
466 fprintf(stderr, "undo on non-pass move %s\n", coord2sstr(board->last_move.coord, board));
467 board_print(board, stderr);
469 gtp_error(id, "cannot undo", NULL);
470 return P_OK;
472 char *reply = NULL;
473 if (engine->undo)
474 reply = engine->undo(engine, board);
475 if (DEBUGL(1) && debug_boardprint)
476 board_print(board, stderr);
477 gtp_reply(id, reply, NULL);
479 /* Custom commands for handling UCT opening tbook */
480 } else if (!strcasecmp(cmd, "uct_gentbook")) {
481 /* Board must be initialized properly, as if for genmove;
482 * makes sense only as 'uct_gentbook b'. */
483 char *arg;
484 next_tok(arg);
485 enum stone color = str2stone(arg);
486 if (uct_gentbook(engine, board, &ti[color], color))
487 gtp_reply(id, NULL);
488 else
489 gtp_error(id, "error generating tbook", NULL);
491 } else if (!strcasecmp(cmd, "uct_dumptbook")) {
492 char *arg;
493 next_tok(arg);
494 enum stone color = str2stone(arg);
495 uct_dumptbook(engine, board, color);
496 gtp_reply(id, NULL);
498 } else if (!strcasecmp(cmd, "uct_evaluate")) {
499 char *arg;
500 next_tok(arg);
501 enum stone color = str2stone(arg);
503 gtp_prefix('=', id);
504 /* Iterate through the list of all free coordinates
505 * and call uct_evaluate() for each. uct_evaluate()
506 * will throw NAN in case of invalid moves and such. */
507 for (int i = 0; i < board->flen; i++) {
508 floating_t val = uct_evaluate(engine, board, &ti[color], board->f[i], color);
509 if (isnan(val))
510 continue;
511 printf("%s %1.3f\n", coord2sstr(board->f[i], board), (double) val);
513 gtp_flush();
515 } else if (!strcasecmp(cmd, "pachi-result")) {
516 /* More detailed result of the last genmove. */
517 /* For UCT, the output format is: = color move playouts winrate dynkomi */
518 char *reply = NULL;
519 if (engine->result)
520 reply = engine->result(engine, board);
521 if (reply)
522 gtp_reply(id, reply, NULL);
523 else
524 gtp_error(id, "unknown pachi-result command", NULL);
526 } else if (!strcasecmp(cmd, "kgs-chat")) {
527 char *loc;
528 next_tok(loc);
529 char *src;
530 next_tok(src);
531 char *msg;
532 next_tok(msg);
533 char *reply = NULL;
534 if (engine->chat)
535 reply = engine->chat(engine, board, msg);
536 if (reply)
537 gtp_reply(id, reply, NULL);
538 else
539 gtp_error(id, "unknown kgs-chat command", NULL);
541 } else if (!strcasecmp(cmd, "time_left")) {
542 char *arg;
543 next_tok(arg);
544 enum stone color = str2stone(arg);
545 next_tok(arg);
546 int time = atoi(arg);
547 next_tok(arg);
548 int stones = atoi(arg);
549 if (!ti[color].ignore_gtp) {
550 time_left(&ti[color], time, stones);
551 } else {
552 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
555 gtp_reply(id, NULL);
557 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
558 char *time_system;
559 char *arg;
560 if (!strcasecmp(cmd, "kgs-time_settings")) {
561 next_tok(time_system);
562 } else {
563 time_system = "canadian";
566 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
567 if (!strcasecmp(time_system, "none")) {
568 main_time = -1;
569 } else if (!strcasecmp(time_system, "absolute")) {
570 next_tok(arg);
571 main_time = atoi(arg);
572 } else if (!strcasecmp(time_system, "byoyomi")) {
573 next_tok(arg);
574 main_time = atoi(arg);
575 next_tok(arg);
576 byoyomi_time = atoi(arg);
577 next_tok(arg);
578 byoyomi_periods = atoi(arg);
579 } else if (!strcasecmp(time_system, "canadian")) {
580 next_tok(arg);
581 main_time = atoi(arg);
582 next_tok(arg);
583 byoyomi_time = atoi(arg);
584 next_tok(arg);
585 byoyomi_stones = atoi(arg);
588 if (DEBUGL(1))
589 fprintf(stderr, "time_settings %d %d/%d*%d\n",
590 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
591 if (!ti[S_BLACK].ignore_gtp) {
592 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
593 ti[S_WHITE] = ti[S_BLACK];
594 } else {
595 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
598 gtp_reply(id, NULL);
600 } else {
601 gtp_error(id, "unknown command", NULL);
602 return P_UNKNOWN_COMMAND;
604 return P_OK;
606 #undef next_tok