Merge pull request #28 from lemonsqueeze/dcnn
[pachi.git] / board.h
blobf34dccde4bee193e3b60c6cf282e54d2e28a6c3e
1 /* probdist.h must be included before the include goard since we require
2 * proper including order. */
3 #include "probdist.h"
5 #ifndef PACHI_BOARD_H
6 #define PACHI_BOARD_H
8 #include <inttypes.h>
9 #include <stdbool.h>
10 #include <stdint.h>
12 #include "util.h"
13 #include "stone.h"
14 #include "move.h"
16 struct fbook;
19 /* Maximum supported board size. (Without the S_OFFBOARD edges.) */
20 #define BOARD_MAX_SIZE 19
23 /* The board implementation has bunch of optional features.
24 * Turn them on below: */
26 #define WANT_BOARD_C // capturable groups queue
28 //#define BOARD_SIZE 9 // constant board size, allows better optimization
30 //#define BOARD_SPATHASH // incremental patternsp.h hashes
31 #define BOARD_SPATHASH_MAXD 3 // maximal diameter
33 #define BOARD_PAT3 // incremental 3x3 pattern codes
35 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
36 //#define BOARD_TRAIT_SAFE 1 // include btraits.safe (rather expensive, unused)
37 //#define BOARD_TRAIT_SAFE 2 // include btraits.safe based on full is_bad_selfatari()
40 #define BOARD_MAX_MOVES (BOARD_MAX_SIZE * BOARD_MAX_SIZE)
41 #define BOARD_MAX_GROUPS (BOARD_MAX_SIZE * BOARD_MAX_SIZE / 2)
43 enum e_sym {
44 SYM_FULL,
45 SYM_DIAG_UP,
46 SYM_DIAG_DOWN,
47 SYM_HORIZ,
48 SYM_VERT,
49 SYM_NONE
53 /* Some engines might normalize their reading and skip symmetrical
54 * moves. We will tell them how can they do it. */
55 struct board_symmetry {
56 /* Playground is in this rectangle. */
57 int x1, x2, y1, y2;
58 /* d == 0: Full rectangle
59 * d == 1: Top triangle */
60 int d;
61 /* General symmetry type. */
62 /* Note that the above is redundant to this, but just provided
63 * for easier usage. */
64 enum e_sym type;
68 typedef uint64_t hash_t;
69 #define PRIhash PRIx64
71 /* XXX: This really belongs in pattern3.h, unfortunately that would mean
72 * a dependency hell. */
73 typedef uint32_t hash3_t; // 3x3 pattern hash
76 /* Note that "group" is only chain of stones that is solidly
77 * connected for us. */
78 typedef coord_t group_t;
80 struct group {
81 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
82 * don't care. */
83 /* _Combination_ of these two values can make some difference
84 * in performance - fine-tune. */
85 #define GROUP_KEEP_LIBS 10
86 // refill lib[] only when we hit this; this must be at least 2!
87 // Moggy requires at least 3 - see below for semantic impact.
88 #define GROUP_REFILL_LIBS 5
89 coord_t lib[GROUP_KEEP_LIBS];
90 /* libs is only LOWER BOUND for the number of real liberties!!!
91 * It denotes only number of items in lib[], thus you can rely
92 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
93 int libs;
96 struct neighbor_colors {
97 char colors[S_MAX];
101 /* Point traits bitmap; we update this information incrementally,
102 * it can be used e.g. for fast pattern features matching. */
103 struct btraits {
104 /* Number of neighbors we can capture. 0=this move is
105 * not capturing, 1..4=this many neighbors we can capture
106 * (can be multiple neighbors of same group). */
107 unsigned cap:3;
108 /* Number of 1-stone neighbors we can capture. */
109 unsigned cap1:3;
110 #ifdef BOARD_TRAIT_SAFE
111 /* Whether it is SAFE to play here. This is essentially just
112 * cached result of board_safe_to_play(). (Of course the concept
113 * of "safety" is not perfect here, but it's the cheapest
114 * reasonable thing we can do.) */
115 bool safe:1;
116 #endif
117 /* Whether we need to re-compute this coordinate; used to
118 * weed out duplicates. Maintained only for S_BLACK. */
119 bool dirty:1;
123 /* You should treat this struct as read-only. Always call functions below if
124 * you want to change it. */
126 struct board {
127 int size; /* Including S_OFFBOARD margin - see below. */
128 int size2; /* size^2 */
129 int bits2; /* ceiling(log2(size2)) */
130 int captures[S_MAX];
131 floating_t komi;
132 int handicap;
133 /* The ruleset is currently almost never taken into account;
134 * the board implementation is basically Chinese rules (handicap
135 * stones compensation) w/ suicide (or you can look at it as
136 * New Zealand w/o handi stones compensation), while the engine
137 * enforces no-suicide, making for real Chinese rules.
138 * However, we accept suicide moves by the opponent, so we
139 * should work with rules allowing suicide, just not taking
140 * full advantage of them. */
141 enum go_ruleset {
142 RULES_CHINESE, /* default value */
143 RULES_AGA,
144 RULES_NEW_ZEALAND,
145 RULES_JAPANESE,
146 RULES_STONES_ONLY, /* do not count eyes */
147 /* http://home.snafu.de/jasiek/siming.html */
148 /* Simplified ING rules - RULES_CHINESE with handicaps
149 * counting as points and pass stones. Also should
150 * allow suicide, but Pachi will never suicide
151 * nevertheless. */
152 /* XXX: I couldn't find the point about pass stones
153 * in the rule text, but it is Robert Jasiek's
154 * interpretation of them... These rules were
155 * used e.g. at the EGC2012 13x13 tournament.
156 * They are not supported by KGS. */
157 RULES_SIMING,
158 } rules;
160 char *fbookfile;
161 struct fbook *fbook;
163 /* Iterator offsets for foreach_neighbor*() */
164 int nei8[8], dnei[4];
166 int moves;
167 struct move last_move;
168 struct move last_move2; /* second-to-last move */
169 struct move last_move3; /* just before last_move2, only set if last_move is pass */
170 struct move last_move4; /* just before last_move3, only set if last_move & last_move2 are pass */
171 /* Whether we tried to add a hash twice; board_play*() can
172 * set this, but it will still carry out the move as well! */
173 bool superko_violation;
175 /* The following two structures are goban maps and are indexed by
176 * coord.pos. The map is surrounded by a one-point margin from
177 * S_OFFBOARD stones in order to speed up some internal loops.
178 * Some of the foreach iterators below might include these points;
179 * you need to handle them yourselves, if you need to. */
181 /* Stones played on the board */
182 enum stone *b; /* enum stone */
183 /* Group id the stones are part of; 0 == no group */
184 group_t *g;
185 /* Positions of next stones in the stone group; 0 == last stone */
186 coord_t *p;
187 /* Neighboring colors; numbers of neighbors of index color */
188 struct neighbor_colors *n;
189 /* Zobrist hash for each position */
190 hash_t *h;
191 #ifdef BOARD_SPATHASH
192 /* For spatial hashes, we use only 24 bits. */
193 /* [0] is d==1, we don't keep hash for d==0. */
194 /* We keep hashes for black-to-play ([][0]) and white-to-play
195 * ([][1], reversed stone colors since we match all patterns as
196 * black-to-play). */
197 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
198 #endif
199 #ifdef BOARD_PAT3
200 /* 3x3 pattern code for each position; see pattern3.h for encoding
201 * specification. The information is only valid for empty points. */
202 hash3_t *pat3;
203 #endif
204 #ifdef BOARD_TRAITS
205 /* Incrementally matched point traits information, black-to-play
206 * ([][0]) and white-to-play ([][1]). */
207 /* The information is only valid for empty points. */
208 struct btraits (*t)[2];
209 #endif
210 /* Cached information on x-y coordinates so that we avoid division. */
211 uint8_t (*coord)[2];
213 /* Group information - indexed by gid (which is coord of base group stone) */
214 struct group *gi;
216 /* Positions of free positions - queue (not map) */
217 /* Note that free position here is any valid move; including single-point eyes!
218 * However, pass is not included. */
219 coord_t *f; int flen;
221 #ifdef WANT_BOARD_C
222 /* Queue of capturable groups */
223 group_t *c; int clen;
224 #endif
226 #ifdef BOARD_TRAITS
227 /* Queue of positions that need their traits updated */
228 coord_t *tq; int tqlen;
229 #endif
231 /* Symmetry information */
232 struct board_symmetry symmetry;
234 /* Last ko played on the board. */
235 struct move last_ko;
236 int last_ko_age;
238 /* Basic ko check */
239 struct move ko;
241 /* Engine-specific state; persistent through board development,
242 * is reset only at clear_board. */
243 void *es;
245 /* Playout-specific state; persistent through board development,
246 * but its lifetime is maintained in play_random_game(); it should
247 * not be set outside of it. */
248 void *ps;
251 /* --- PRIVATE DATA --- */
253 /* For superko check: */
255 /* Board "history" - hashes encountered. Size of the hash should be
256 * >> board_size^2. */
257 #define history_hash_bits 12
258 #define history_hash_mask ((1 << history_hash_bits) - 1)
259 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
260 #define history_hash_next(i) ((i + 1) & history_hash_mask)
261 hash_t history_hash[1 << history_hash_bits];
262 /* Hash of current board position. */
263 hash_t hash;
264 /* Hash of current board position quadrants. */
265 hash_t qhash[4];
268 #ifdef BOARD_SIZE
269 /* Avoid unused variable warnings */
270 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
271 #define board_size2(b_) (board_size(b_) * board_size(b_))
272 #define real_board_size(b_) (((b_) == (b_)) ? BOARD_SIZE : 0)
273 #else
274 #define board_size(b_) ((b_)->size)
275 #define board_size2(b_) ((b_)->size2)
276 #define real_board_size(b_) ((b_)->size - 2)
277 #endif
279 /* This is a shortcut for taking different action on smaller
280 * and large boards (e.g. picking different variable defaults).
281 * This is of course less optimal than fine-tuning dependency
282 * function of values on board size, but that is difficult and
283 * possibly not very rewarding if you are interested just in
284 * 9x9 and 19x19. */
285 #define board_large(b_) (board_size(b_)-2 >= 15)
286 #define board_small(b_) (board_size(b_)-2 <= 9)
288 #if BOARD_SIZE == 19
289 # define board_bits2(b_) 9
290 #elif BOARD_SIZE == 13
291 # define board_bits2(b_) 8
292 #elif BOARD_SIZE == 9
293 # define board_bits2(b_) 7
294 #else
295 # define board_bits2(b_) ((b_)->bits2)
296 #endif
298 #define board_at(b_, c) ((b_)->b[c])
299 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
301 #define group_at(b_, c) ((b_)->g[c])
302 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
304 /* Warning! Neighbor count is not kept up-to-date for S_NONE! */
305 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
306 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
307 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
308 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
309 #define immediate_liberty_count(b_, coord) (4 - neighbor_count_at(b_, coord, S_BLACK) - neighbor_count_at(b_, coord, S_WHITE) - neighbor_count_at(b_, coord, S_OFFBOARD))
311 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
313 #define groupnext_at(b_, c) ((b_)->p[c])
314 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
316 #define group_base(g_) (g_)
317 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
318 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
319 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
320 /* board_group_other_lib() makes sense only for groups with two liberties. */
321 #define board_group_other_lib(b_, g_, l_) (board_group_info(b_, g_).lib[board_group_info(b_, g_).lib[0] != (l_) ? 0 : 1])
323 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
325 struct board *board_init(char *fbookfile);
326 struct board *board_copy(struct board *board2, struct board *board1);
327 void board_done_noalloc(struct board *board);
328 void board_done(struct board *board);
329 /* size here is without the S_OFFBOARD margin. */
330 void board_resize(struct board *board, int size);
331 void board_clear(struct board *board);
333 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
334 void board_print(struct board *board, FILE *f);
335 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
337 /* Place given handicap on the board; coordinates are printed to f. */
338 void board_handicap(struct board *board, int stones, FILE *f);
340 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
341 int board_play(struct board *board, struct move *m);
342 /* Like above, but plays random move; the move coordinate is recorded
343 * to *coord. This method will never fill your own eye. pass is played
344 * when no move can be played. You can impose extra restrictions if you
345 * supply your own permit function; the permit function can also modify
346 * the move coordinate to redirect the move elsewhere. */
347 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
348 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
350 /*Undo, supported only for pass moves. Returns -1 on error, 0 otherwise. */
351 int board_undo(struct board *board);
353 /* Returns true if given move can be played. */
354 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
355 static bool board_is_valid_move(struct board *b, struct move *m);
356 /* Returns true if ko was just taken. */
357 static bool board_playing_ko_threat(struct board *b);
358 /* Returns 0 or ID of neighboring group in atari. */
359 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
360 /* Returns true if the move is not obvious self-atari. */
361 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
363 /* Determine number of stones in a group, up to @max stones. */
364 static int group_stone_count(struct board *b, group_t group, int max);
366 /* Adjust symmetry information as if given coordinate has been played. */
367 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
368 /* Check if coordinates are within symmetry base. (If false, they can
369 * be derived from the base.) */
370 static bool board_coord_in_symmetry(struct board *b, coord_t c);
372 /* Returns true if given coordinate has all neighbors of given color or the edge. */
373 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
374 /* Returns true if given coordinate could be a false eye; this check makes
375 * sense only if you already know the coordinate is_eyelike(). */
376 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
377 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
378 * at least tries to). */
379 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
380 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
381 enum stone board_get_one_point_eye(struct board *board, coord_t c);
383 /* board_official_score() is the scoring method for yielding score suitable
384 * for external presentation. For fast scoring of entirely filled boards
385 * (e.g. playouts), use board_fast_score(). */
386 /* Positive: W wins */
387 /* Compare number of stones + 1pt eyes. */
388 floating_t board_fast_score(struct board *board);
389 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
390 struct move_queue;
391 floating_t board_official_score(struct board *board, struct move_queue *mq);
393 /* Set board rules according to given string. Returns false in case
394 * of unknown ruleset name. */
395 bool board_set_rules(struct board *board, char *name);
397 /** Iterators */
399 #define foreach_point(board_) \
400 do { \
401 coord_t c = 0; \
402 for (; c < board_size(board_) * board_size(board_); c++)
403 #define foreach_point_and_pass(board_) \
404 do { \
405 coord_t c = pass; \
406 for (; c < board_size(board_) * board_size(board_); c++)
407 #define foreach_point_end \
408 } while (0)
410 #define foreach_free_point(board_) \
411 do { \
412 int fmax__ = (board_)->flen; \
413 for (int f__ = 0; f__ < fmax__; f__++) { \
414 coord_t c = (board_)->f[f__];
415 #define foreach_free_point_end \
417 } while (0)
419 #define foreach_in_group(board_, group_) \
420 do { \
421 struct board *board__ = board_; \
422 coord_t c = group_base(group_); \
423 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
424 do {
425 #define foreach_in_group_end \
426 c = c2; c2 = groupnext_at(board__, c2); \
427 } while (c != 0); \
428 } while (0)
430 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
431 * on S_OFFBOARD coordinates. */
432 #define foreach_neighbor(board_, coord_, loop_body) \
433 do { \
434 struct board *board__ = board_; \
435 coord_t coord__ = coord_; \
436 coord_t c; \
437 c = coord__ - board_size(board__); do { loop_body } while (0); \
438 c = coord__ - 1; do { loop_body } while (0); \
439 c = coord__ + 1; do { loop_body } while (0); \
440 c = coord__ + board_size(board__); do { loop_body } while (0); \
441 } while (0)
443 #define foreach_8neighbor(board_, coord_) \
444 do { \
445 int fn__i; \
446 coord_t c = (coord_); \
447 for (fn__i = 0; fn__i < 8; fn__i++) { \
448 c += (board_)->nei8[fn__i];
449 #define foreach_8neighbor_end \
451 } while (0)
453 #define foreach_diag_neighbor(board_, coord_) \
454 do { \
455 int fn__i; \
456 coord_t c = (coord_); \
457 for (fn__i = 0; fn__i < 4; fn__i++) { \
458 c += (board_)->dnei[fn__i];
459 #define foreach_diag_neighbor_end \
461 } while (0)
464 static inline bool
465 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
467 return (neighbor_count_at(board, coord, eye_color)
468 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
471 /* Group suicides allowed */
472 static inline bool
473 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
475 if (board_at(board, coord) != S_NONE)
476 return false;
477 if (!board_is_eyelike(board, coord, stone_other(color)))
478 return true;
479 /* Play within {true,false} eye-ish formation */
480 if (board->ko.coord == coord && board->ko.color == color)
481 return false;
482 #ifdef BOARD_TRAITS
483 /* XXX: Disallows suicide. */
484 return trait_at(board, coord, color).cap > 0;
485 #else
486 int groups_in_atari = 0;
487 foreach_neighbor(board, coord, {
488 group_t g = group_at(board, c);
489 groups_in_atari += (board_group_info(board, g).libs == 1);
491 return !!groups_in_atari;
492 #endif
495 /* Check group suicides, slower than board_is_valid_play() */
496 static inline bool
497 board_is_valid_play_no_suicide(struct board *board, enum stone color, coord_t coord)
499 if (board_at(board, coord) != S_NONE)
500 return false;
501 if (immediate_liberty_count(board, coord) >= 1)
502 return true;
503 if (board_is_eyelike(board, coord, stone_other(color)) &&
504 board->ko.coord == coord && board->ko.color == color)
505 return false;
507 // Capturing something ?
508 #ifdef BOARD_TRAITS
509 /* XXX: Disallows suicide. */
510 if (trait_at(board, coord, color).cap > 0)
511 return true;
512 #else
513 foreach_neighbor(board, coord, {
514 if (board_at(board, c) == stone_other(color) &&
515 board_group_info(board, group_at(board, c)).libs == 1)
516 return true;
518 #endif
520 // Neighbour with 2 libs ?
521 foreach_neighbor(board, coord, {
522 if (board_at(board, c) == color &&
523 board_group_info(board, group_at(board, c)).libs > 1)
524 return true;
527 return false; // Suicide
531 static inline bool
532 board_is_valid_move(struct board *board, struct move *m)
534 return board_is_valid_play(board, m->color, m->coord);
537 static inline bool
538 board_playing_ko_threat(struct board *b)
540 return !is_pass(b->ko.coord);
543 static inline group_t
544 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
546 #ifdef BOARD_TRAITS
547 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
548 #endif
549 foreach_neighbor(b, coord, {
550 group_t g = group_at(b, c);
551 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
552 return g;
553 /* We return first match. */
555 return 0;
558 static inline bool
559 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
561 /* number of free neighbors */
562 int libs = immediate_liberty_count(b, coord);
563 if (libs > 1)
564 return true;
566 #ifdef BOARD_TRAITS
567 /* number of capturable enemy groups */
568 if (trait_at(b, coord, color).cap > 0)
569 return true; // XXX: We don't account for snapback.
570 /* number of non-capturable friendly groups */
571 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
572 if (noncap_ours < 1)
573 return false;
574 /*#else see below */
575 #endif
577 /* ok, but we need to check if they don't have just two libs. */
578 coord_t onelib = -1;
579 foreach_neighbor(b, coord, {
580 #ifndef BOARD_TRAITS
581 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
582 return true; // can capture; no snapback check
583 #endif
584 if (board_at(b, c) != color) continue;
585 group_t g = group_at(b, c);
586 if (board_group_info(b, g).libs == 1) continue; // in atari
587 if (board_group_info(b, g).libs == 2) { // two liberties
588 if (libs > 0) return true; // we already have one real liberty
589 /* we might be connecting two 2-lib groups, which is ok;
590 * so remember the other liberty and just make sure it's
591 * not the same one */
592 if (onelib >= 0 && c != onelib) return true;
593 onelib = board_group_other_lib(b, g, c);
594 continue;
596 // many liberties
597 return true;
599 // no good support group
600 return false;
603 static inline int
604 group_stone_count(struct board *b, group_t group, int max)
606 int n = 0;
607 foreach_in_group(b, group) {
608 n++;
609 if (n >= max) return max;
610 } foreach_in_group_end;
611 return n;
614 static inline bool
615 board_coord_in_symmetry(struct board *b, coord_t c)
617 if (coord_y(c, b) < b->symmetry.y1 || coord_y(c, b) > b->symmetry.y2)
618 return false;
619 if (coord_x(c, b) < b->symmetry.x1 || coord_x(c, b) > b->symmetry.x2)
620 return false;
621 if (b->symmetry.d) {
622 int x = coord_x(c, b);
623 if (b->symmetry.type == SYM_DIAG_DOWN)
624 x = board_size(b) - 1 - x;
625 if (x > coord_y(c, b))
626 return false;
628 return true;
632 #endif