Merge branch 'master' into derm4
[pachi/peepo.git] / board.h
blob7c259cc0540c98379a0d22f8762f95f7106baf3e
1 /* probdist.h must be included before the include goard since we require
2 * proper including order. */
3 #include "probdist.h"
5 #ifndef ZZGO_BOARD_H
6 #define ZZGO_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 features_gamma;
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_GAMMA 1 // incremental probability distribution (requires BOARD_TRAITS, BOARD_PAT3)
39 #define BOARD_MAX_MOVES (BOARD_MAX_SIZE * BOARD_MAX_SIZE)
40 #define BOARD_MAX_GROUPS (BOARD_MAX_SIZE * BOARD_MAX_SIZE / 2)
43 /* Some engines might normalize their reading and skip symmetrical
44 * moves. We will tell them how can they do it. */
45 struct board_symmetry {
46 /* Playground is in this rectangle. */
47 int x1, x2, y1, y2;
48 /* d == 0: Full rectangle
49 * d == 1: Top triangle */
50 int d;
51 /* General symmetry type. */
52 /* Note that the above is redundant to this, but just provided
53 * for easier usage. */
54 enum {
55 SYM_FULL,
56 SYM_DIAG_UP,
57 SYM_DIAG_DOWN,
58 SYM_HORIZ,
59 SYM_VERT,
60 SYM_NONE
61 } type;
65 typedef uint64_t hash_t;
66 #define PRIhash PRIx64
68 /* XXX: This really belongs in pattern3.h, unfortunately that would mean
69 * a dependency hell. */
70 typedef uint16_t hash3_t; // 3x3 pattern hash
73 /* Note that "group" is only chain of stones that is solidly
74 * connected for us. */
75 typedef coord_t group_t;
77 struct group {
78 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
79 * don't care. */
80 /* _Combination_ of these two values can make some difference
81 * in performance - fine-tune. */
82 #define GROUP_KEEP_LIBS 10
83 // refill lib[] only when we hit this; this must be at least 2!
84 // Moggy requires at least 3 - see below for semantic impact.
85 #define GROUP_REFILL_LIBS 5
86 coord_t lib[GROUP_KEEP_LIBS];
87 /* libs is only LOWER BOUND for the number of real liberties!!!
88 * It denotes only number of items in lib[], thus you can rely
89 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
90 int libs;
93 struct neighbor_colors {
94 char colors[S_MAX];
98 /* Point traits bitmap; we update this information incrementally,
99 * it can be used e.g. for fast pattern.h features matching. */
100 struct btraits {
101 /* Number of neighbors we can capture. 0=this move is
102 * not capturing, 1..4=this many neighbors we can capture
103 * (can be multiple neighbors of same group). */
104 unsigned cap:3;
105 /* Number of 1-stone neighbors we can capture. */
106 unsigned cap1:3;
107 /* Whether it is SAFE to play here. This is essentially just
108 * cached result of board_safe_to_play(). (Of course the concept
109 * of "safety" is not perfect here, but it's the cheapest
110 * reasonable thing we can do.) */
111 bool safe:1;
112 /* Whether we need to re-compute this coordinate; used to
113 * weed out duplicates. Maintained only for S_BLACK. */
114 bool dirty:1;
118 /* You should treat this struct as read-only. Always call functions below if
119 * you want to change it. */
121 struct board {
122 int size; /* Including S_OFFBOARD margin - see below. */
123 int size2; /* size^2 */
124 int bits2; /* ceiling(log2(size2)) */
125 int captures[S_MAX];
126 float komi;
127 int handicap;
128 /* The ruleset is currently almost never taken into account;
129 * the board implementation is basically Chinese rules (handicap
130 * stones compensation) w/ suicide (or you can look at it as
131 * New Zealand w/o handi stones compensation), while the engine
132 * enforces no-suicide, making for real Chinese rules. */
133 enum {
134 RULES_CHINESE, /* default value */
135 RULES_AGA,
136 RULES_NEW_ZEALAND,
137 RULES_JAPANESE,
138 } rules;
140 /* Iterator offsets for foreach_neighbor*() */
141 int nei8[8], dnei[4];
143 int moves;
144 struct move last_move;
145 struct move last_move2; /* second-to-last move */
146 /* Whether we tried to add a hash twice; board_play*() can
147 * set this, but it will still carry out the move as well! */
148 bool superko_violation;
150 /* The following two structures are goban maps and are indexed by
151 * coord.pos. The map is surrounded by a one-point margin from
152 * S_OFFBOARD stones in order to speed up some internal loops.
153 * Some of the foreach iterators below might include these points;
154 * you need to handle them yourselves, if you need to. */
156 /* Stones played on the board */
157 enum stone *b; /* enum stone */
158 /* Group id the stones are part of; 0 == no group */
159 group_t *g;
160 /* Positions of next stones in the stone group; 0 == last stone */
161 coord_t *p;
162 /* Neighboring colors; numbers of neighbors of index color */
163 struct neighbor_colors *n;
164 /* Zobrist hash for each position */
165 hash_t *h;
166 #ifdef BOARD_SPATHASH
167 /* For spatial hashes, we use only 24 bits. */
168 /* [0] is d==1, we don't keep hash for d==0. */
169 /* We keep hashes for black-to-play ([][0]) and white-to-play
170 * ([][1], reversed stone colors since we match all patterns as
171 * black-to-play). */
172 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
173 #endif
174 #ifdef BOARD_PAT3
175 /* 3x3 pattern code for each position; see pattern3.h for encoding
176 * specification. The information is only valid for empty points. */
177 hash3_t *pat3;
178 #endif
179 #ifdef BOARD_TRAITS
180 /* Incrementally matched point traits information, black-to-play
181 * ([][0]) and white-to-play ([][1]). */
182 /* The information is only valid for empty points. */
183 struct btraits (*t)[2];
184 #endif
185 #ifdef BOARD_GAMMA
186 /* Relative probabilities of moves being played next, computed by
187 * multiplying gammas of the appropriate pattern features based on
188 * pat3 and traits (see pattern.h). The probability distribution
189 * is maintained over the full board grid. */
190 /* - Always invalid moves are guaranteed to have zero probability.
191 * - Self-eye-filling moves will always have zero probability.
192 * - Ko-prohibited moves might have non-zero probability.
193 * - FEAT_CONTIGUITY is not accounted for in the probability. */
194 struct probdist prob[2];
195 #endif
196 /* Cached information on x-y coordinates so that we avoid division. */
197 uint8_t (*coord)[2];
199 /* Group information - indexed by gid (which is coord of base group stone) */
200 struct group *gi;
202 /* Positions of free positions - queue (not map) */
203 /* Note that free position here is any valid move; including single-point eyes!
204 * However, pass is not included. */
205 coord_t *f; int flen;
207 #ifdef WANT_BOARD_C
208 /* Queue of capturable groups */
209 group_t *c; int clen;
210 #endif
212 #ifdef BOARD_TRAITS
213 /* Queue of positions that need their traits updated */
214 coord_t *tq; int tqlen;
215 #endif
217 /* Symmetry information */
218 struct board_symmetry symmetry;
220 /* Last ko played on the board. */
221 struct move last_ko;
222 int last_ko_age;
224 /* Basic ko check */
225 struct move ko;
227 /* Engine-specific state; persistent through board development,
228 * is reset only at clear_board. */
229 void *es;
231 /* Playout-specific state; persistent through board development,
232 * but its lifetime is maintained in play_random_game(); it should
233 * not be set outside of it. */
234 void *ps;
236 #ifdef BOARD_GAMMA
237 /* Gamma values for probability distribution; user must setup
238 * this pointer before any move is played, using board_gamma_set(). */
239 struct features_gamma *gamma;
240 /* Whether to compute the 'safe' trait using board_safe_to_play()
241 * (false) or is_bad_selfatari() (true, much slower). */
242 bool precise_selfatari;
243 #endif
246 /* --- PRIVATE DATA --- */
248 /* For superko check: */
250 /* Board "history" - hashes encountered. Size of the hash should be
251 * >> board_size^2. */
252 #define history_hash_bits 12
253 #define history_hash_mask ((1 << history_hash_bits) - 1)
254 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
255 #define history_hash_next(i) ((i + 1) & history_hash_mask)
256 hash_t history_hash[1 << history_hash_bits];
257 /* Hash of current board position. */
258 hash_t hash;
259 /* Hash of current board position quadrants. */
260 hash_t qhash[4];
263 #ifdef BOARD_SIZE
264 /* Avoid unused variable warnings */
265 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
266 #define board_size2(b_) (board_size(b_) * board_size(b_))
267 #else
268 #define board_size(b_) ((b_)->size)
269 #define board_size2(b_) ((b_)->size2)
270 #endif
272 #if BOARD_SIZE == 19
273 # define board_bits2(b_) 9
274 #elif BOARD_SIZE == 13
275 # define board_bits2(b_) 8
276 #elif BOARD_SIZE == 9
277 # define board_bits2(b_) 7
278 #else
279 # define board_bits2(b_) ((b_)->bits2)
280 #endif
282 #define board_at(b_, c) ((b_)->b[c])
283 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
285 #define group_at(b_, c) ((b_)->g[c])
286 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
288 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
289 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
290 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
291 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
292 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
293 #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))
295 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
297 #define groupnext_at(b_, c) ((b_)->p[c])
298 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
300 #define group_base(g_) (g_)
301 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
302 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
303 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
304 /* board_group_other_lib() makes sense only for groups with two liberties. */
305 #define board_group_other_lib(b_, g_, l_) (board_group_info(b_, g_).lib[board_group_info(b_, g_).lib[0] != (l_) ? 0 : 1])
307 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
309 struct board *board_init(void);
310 struct board *board_copy(struct board *board2, struct board *board1);
311 void board_done_noalloc(struct board *board);
312 void board_done(struct board *board);
313 /* size here is without the S_OFFBOARD margin. */
314 void board_resize(struct board *board, int size);
315 void board_clear(struct board *board);
317 struct FILE;
318 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
319 void board_print(struct board *board, FILE *f);
320 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
322 /* Place given handicap on the board; coordinates are printed to f. */
323 void board_handicap(struct board *board, int stones, FILE *f);
325 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
326 int board_play(struct board *board, struct move *m);
327 /* Like above, but plays random move; the move coordinate is recorded
328 * to *coord. This method will never fill your own eye. pass is played
329 * when no move can be played. You can impose extra restrictions if you
330 * supply your own permit function; the permit function can also modify
331 * the move coordinate to redirect the move elsewhere. */
332 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
333 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
335 /* Returns true if given move can be played. */
336 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
337 static bool board_is_valid_move(struct board *b, struct move *m);
338 /* Returns true if ko was just taken. */
339 static bool board_playing_ko_threat(struct board *b);
340 /* Returns 0 or ID of neighboring group in atari. */
341 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
342 /* Returns true if the move is not obvious self-atari. */
343 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
345 /* Adjust symmetry information as if given coordinate has been played. */
346 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
347 /* Associate a set of feature gamma values (for pd building) with the board. */
348 void board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari);
349 /* Force re-compute of a probability distribution item. */
350 void board_gamma_update(struct board *b, coord_t coord, enum stone color);
352 /* Returns true if given coordinate has all neighbors of given color or the edge. */
353 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
354 /* Returns true if given coordinate could be a false eye; this check makes
355 * sense only if you already know the coordinate is_eyelike(). */
356 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
357 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
358 * at least tries to). */
359 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
360 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
361 enum stone board_get_one_point_eye(struct board *board, coord_t c);
363 /* board_official_score() is the scoring method for yielding score suitable
364 * for external presentation. For fast scoring of entirely filled boards
365 * (e.g. playouts), use board_fast_score(). */
366 /* Positive: W wins */
367 /* Compare number of stones + 1pt eyes. */
368 float board_fast_score(struct board *board);
369 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
370 struct move_queue;
371 float board_official_score(struct board *board, struct move_queue *mq);
373 /** Iterators */
375 #define foreach_point(board_) \
376 do { \
377 coord_t c = 0; \
378 for (; c < board_size(board_) * board_size(board_); c++)
379 #define foreach_point_and_pass(board_) \
380 do { \
381 coord_t c = pass; \
382 for (; c < board_size(board_) * board_size(board_); c++)
383 #define foreach_point_end \
384 } while (0)
386 #define foreach_free_point(board_) \
387 do { \
388 int fmax__ = (board_)->flen; \
389 for (int f__ = 0; f__ < fmax__; f__++) { \
390 coord_t c = (board_)->f[f__];
391 #define foreach_free_point_end \
393 } while (0)
395 #define foreach_in_group(board_, group_) \
396 do { \
397 struct board *board__ = board_; \
398 coord_t c = group_base(group_); \
399 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
400 do {
401 #define foreach_in_group_end \
402 c = c2; c2 = groupnext_at(board__, c2); \
403 } while (c != 0); \
404 } while (0)
406 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
407 * on S_OFFBOARD coordinates. */
408 #define foreach_neighbor(board_, coord_, loop_body) \
409 do { \
410 struct board *board__ = board_; \
411 coord_t coord__ = coord_; \
412 coord_t c; \
413 c = coord__ - 1; do { loop_body } while (0); \
414 c = coord__ - board_size(board__); do { loop_body } while (0); \
415 c = coord__ + 1; do { loop_body } while (0); \
416 c = coord__ + board_size(board__); do { loop_body } while (0); \
417 } while (0)
419 #define foreach_8neighbor(board_, coord_) \
420 do { \
421 int fn__i; \
422 coord_t c = (coord_); \
423 for (fn__i = 0; fn__i < 8; fn__i++) { \
424 c += (board_)->nei8[fn__i];
425 #define foreach_8neighbor_end \
427 } while (0)
429 #define foreach_diag_neighbor(board_, coord_) \
430 do { \
431 int fn__i; \
432 coord_t c = (coord_); \
433 for (fn__i = 0; fn__i < 4; fn__i++) { \
434 c += (board_)->dnei[fn__i];
435 #define foreach_diag_neighbor_end \
437 } while (0)
440 static inline bool
441 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
443 return (neighbor_count_at(board, coord, eye_color)
444 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
447 static inline bool
448 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
450 if (board_at(board, coord) != S_NONE)
451 return false;
452 if (!board_is_eyelike(board, coord, stone_other(color)))
453 return true;
454 /* Play within {true,false} eye-ish formation */
455 if (board->ko.coord == coord && board->ko.color == color)
456 return false;
457 #ifdef BOARD_TRAITS
458 /* XXX: Disallows suicide. */
459 return trait_at(board, coord, color).cap > 0;
460 #else
461 int groups_in_atari = 0;
462 foreach_neighbor(board, coord, {
463 group_t g = group_at(board, c);
464 groups_in_atari += (board_group_info(board, g).libs == 1);
466 return !!groups_in_atari;
467 #endif
470 static inline bool
471 board_is_valid_move(struct board *board, struct move *m)
473 return board_is_valid_play(board, m->color, m->coord);
476 static inline bool
477 board_playing_ko_threat(struct board *b)
479 return !is_pass(b->ko.coord);
482 static inline group_t
483 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
485 #ifdef BOARD_TRAITS
486 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
487 #endif
488 foreach_neighbor(b, coord, {
489 group_t g = group_at(b, c);
490 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
491 return g;
492 /* We return first match. */
494 return 0;
497 static inline bool
498 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
500 /* number of free neighbors */
501 int libs = immediate_liberty_count(b, coord);
502 if (libs > 1)
503 return true;
505 #ifdef BOARD_TRAITS
506 /* number of capturable enemy groups */
507 if (trait_at(b, coord, color).cap > 0)
508 return true; // XXX: We don't account for snapback.
509 /* number of non-capturable friendly groups */
510 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
511 if (noncap_ours < 1)
512 return false;
513 /*#else see below */
514 #endif
516 /* ok, but we need to check if they don't have just two libs. */
517 coord_t onelib = -1;
518 foreach_neighbor(b, coord, {
519 #ifndef BOARD_TRAITS
520 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
521 return true; // can capture; no snapback check
522 #endif
523 if (board_at(b, c) != color) continue;
524 group_t g = group_at(b, c);
525 if (board_group_info(b, g).libs == 1) continue; // in atari
526 if (board_group_info(b, g).libs == 2) { // two liberties
527 if (libs > 0) return true; // we already have one real liberty
528 /* we might be connecting two 2-lib groups, which is ok;
529 * so remember the other liberty and just make sure it's
530 * not the same one */
531 if (onelib >= 0 && c != onelib) return true;
532 onelib = board_group_other_lib(b, g, c);
533 continue;
535 // many liberties
536 return true;
538 // no good support group
539 return false;
542 #endif