tree_init: exit cleanly instead of core dump when running out of memory.
[pachi.git] / board.h
blob1afc39629bbbd226db6daa40e29240ca45be977c
1 #ifndef ZZGO_BOARD_H
2 #define ZZGO_BOARD_H
4 #include <inttypes.h>
5 #include <stdbool.h>
6 #include <stdint.h>
8 #include "stone.h"
9 #include "move.h"
10 #include "probdist.h"
11 #include "util.h"
13 struct features_gamma;
16 /* The board implementation has bunch of optional features.
17 * Turn them on below: */
19 #define WANT_BOARD_C // capturable groups queue
21 //#define BOARD_SIZE 9 // constant board size, allows better optimization
23 //#define BOARD_SPATHASH // incremental patternsp.h hashes
24 #define BOARD_SPATHASH_MAXD 3 // maximal diameter
26 #define BOARD_PAT3 // incremental 3x3 pattern codes
28 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
29 //#define BOARD_GAMMA 1 // incremental probability distribution (requires BOARD_TRAITS, BOARD_PAT3)
32 /* Allow board_play_random_move() to return pass even when
33 * there are other moves available. */
34 extern bool random_pass;
37 /* Some engines might normalize their reading and skip symmetrical
38 * moves. We will tell them how can they do it. */
39 struct board_symmetry {
40 /* Playground is in this rectangle. */
41 int x1, x2, y1, y2;
42 /* d == 0: Full rectangle
43 * d == 1: Top triangle */
44 int d;
45 /* General symmetry type. */
46 /* Note that the above is redundant to this, but just provided
47 * for easier usage. */
48 enum {
49 SYM_FULL,
50 SYM_DIAG_UP,
51 SYM_DIAG_DOWN,
52 SYM_HORIZ,
53 SYM_VERT,
54 SYM_NONE
55 } type;
59 typedef uint64_t hash_t;
60 #define PRIhash PRIx64
63 /* Note that "group" is only chain of stones that is solidly
64 * connected for us. */
65 typedef coord_t group_t;
67 struct group {
68 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
69 * don't care. */
70 /* _Combination_ of these two values can make some difference
71 * in performance - fine-tune. */
72 #define GROUP_KEEP_LIBS 10
73 // refill lib[] only when we hit this; this must be at least 2!
74 // Moggy requires at least 3 - see below for semantic impact.
75 #define GROUP_REFILL_LIBS 5
76 coord_t lib[GROUP_KEEP_LIBS];
77 /* libs is only LOWER BOUND for the number of real liberties!!!
78 * It denotes only number of items in lib[], thus you can rely
79 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
80 int libs;
83 struct neighbor_colors {
84 char colors[S_MAX];
88 /* Point traits bitmap; we update this information incrementally,
89 * it can be used e.g. for fast pattern.h features matching. */
90 struct btraits {
91 /* Number of neighbors we can capture. 0=this move is
92 * not capturing, 1..4=this many neighbors we can capture
93 * (can be multiple neighbors of same group). */
94 unsigned cap:3;
95 /* Whether it is SAFE to play here. This is essentially just
96 * cached result of board_safe_to_play(). (Of course the concept
97 * of "safety" is not perfect here, but it's the cheapest
98 * reasonable thing we can do.) */
99 bool safe:1;
100 /* Whether we need to re-compute this coordinate; used to
101 * weed out duplicates. Maintained only for S_BLACK. */
102 bool dirty:1;
106 /* You should treat this struct as read-only. Always call functions below if
107 * you want to change it. */
109 struct board {
110 int size; /* Including S_OFFBOARD margin - see below. */
111 int size2; /* size^2 */
112 int captures[S_MAX];
113 float komi;
114 int handicap;
115 /* The ruleset is currently almost never taken into account;
116 * the board implementation is basically Chinese rules (handicap
117 * stones compensation) w/ suicide (or you can look at it as
118 * New Zealand w/o handi stones compensation), while the engine
119 * enforces no-suicide, making for real Chinese rules. */
120 enum {
121 RULES_CHINESE, /* default value */
122 RULES_AGA,
123 RULES_NEW_ZEALAND,
124 RULES_JAPANESE,
125 } rules;
127 /* Iterator offsets for foreach_neighbor*() */
128 int nei8[8], dnei[4];
130 int moves;
131 struct move last_move;
132 struct move last_move2; /* second-to-last move */
133 /* Whether we tried to add a hash twice; board_play*() can
134 * set this, but it will still carry out the move as well! */
135 bool superko_violation;
137 /* The following two structures are goban maps and are indexed by
138 * coord.pos. The map is surrounded by a one-point margin from
139 * S_OFFBOARD stones in order to speed up some internal loops.
140 * Some of the foreach iterators below might include these points;
141 * you need to handle them yourselves, if you need to. */
143 /* Stones played on the board */
144 enum stone *b; /* enum stone */
145 /* Group id the stones are part of; 0 == no group */
146 group_t *g;
147 /* Positions of next stones in the stone group; 0 == last stone */
148 coord_t *p;
149 /* Neighboring colors; numbers of neighbors of index color */
150 struct neighbor_colors *n;
151 /* Zobrist hash for each position */
152 hash_t *h;
153 #ifdef BOARD_SPATHASH
154 /* For spatial hashes, we use only 24 bits. */
155 /* [0] is d==1, we don't keep hash for d==0. */
156 /* We keep hashes for black-to-play ([][0]) and white-to-play
157 * ([][1], reversed stone colors since we match all patterns as
158 * black-to-play). */
159 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
160 #endif
161 #ifdef BOARD_PAT3
162 /* 3x3 pattern code for each position; see pattern3.h for encoding
163 * specification. The information is only valid for empty points. */
164 uint16_t *pat3;
165 #endif
166 #ifdef BOARD_TRAITS
167 /* Incrementally matched point traits information, black-to-play
168 * ([][0]) and white-to-play ([][1]). */
169 /* The information is only valid for empty points. */
170 struct btraits (*t)[2];
171 #endif
172 #ifdef BOARD_GAMMA
173 /* Relative probabilities of moves being played next, computed by
174 * multiplying gammas of the appropriate pattern features based on
175 * pat3 and traits (see pattern.h). The probability distribution
176 * is maintained over the full board grid. */
177 /* - Always invalid moves are guaranteed to have zero probability.
178 * - Self-eye-filling moves will always have zero probability.
179 * - Ko-prohibited moves might have non-zero probability.
180 * - FEAT_CONTIGUITY is not accounted for in the probability. */
181 struct probdist prob[2];
182 #endif
184 /* Group information - indexed by gid (which is coord of base group stone) */
185 struct group *gi;
187 /* Positions of free positions - queue (not map) */
188 /* Note that free position here is any valid move; including single-point eyes! */
189 coord_t *f; int flen;
191 #ifdef WANT_BOARD_C
192 /* Queue of capturable groups */
193 group_t *c; int clen;
194 #endif
196 #ifdef BOARD_TRAITS
197 /* Queue of positions that need their traits updated */
198 coord_t *tq; int tqlen;
199 #endif
201 /* Symmetry information */
202 struct board_symmetry symmetry;
204 /* Last ko played on the board. */
205 struct move last_ko;
206 int last_ko_age;
208 /* Basic ko check */
209 struct move ko;
211 /* Engine-specific state; persistent through board development,
212 * is reset only at clear_board. */
213 void *es;
215 /* Playout-specific state; persistent through board development,
216 * but its lifetime is maintained in play_random_game(); it should
217 * not be set outside of it. */
218 void *ps;
220 #ifdef BOARD_GAMMA
221 /* Gamma values for probability distribution; user must setup
222 * this pointer before any move is played, using board_gamma_set(). */
223 struct features_gamma *gamma;
224 /* Whether to compute the 'safe' trait using board_safe_to_play()
225 * (false) or is_bad_selfatari() (true, much slower). */
226 bool precise_selfatari;
227 #endif
230 /* --- PRIVATE DATA --- */
232 /* For superko check: */
234 /* Board "history" - hashes encountered. Size of the hash should be
235 * >> board_size^2. */
236 #define history_hash_bits 12
237 #define history_hash_mask ((1 << history_hash_bits) - 1)
238 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
239 #define history_hash_next(i) ((i + 1) & history_hash_mask)
240 hash_t history_hash[1 << history_hash_bits];
241 /* Hash of current board position. */
242 hash_t hash;
245 #ifdef BOARD_SIZE
246 /* Avoid unused variable warnings */
247 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
248 #define board_size2(b_) (board_size(b_) * board_size(b_))
249 #else
250 #define board_size(b_) ((b_)->size)
251 #define board_size2(b_) ((b_)->size2)
252 #endif
254 #define board_at(b_, c) ((b_)->b[coord_raw(c)])
255 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
257 #define group_at(b_, c) ((b_)->g[coord_raw(c)])
258 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
260 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
261 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord_raw(coord)].colors[(enum stone) color])
262 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
263 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
264 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
265 #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))
267 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
269 #define groupnext_at(b_, c) ((b_)->p[coord_raw(c)])
270 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
272 #define group_base(g_) (g_)
273 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
274 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
275 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
277 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord_raw(coord)])
279 struct board *board_init(void);
280 struct board *board_copy(struct board *board2, struct board *board1);
281 void board_done_noalloc(struct board *board);
282 void board_done(struct board *board);
283 /* size here is without the S_OFFBOARD margin. */
284 void board_resize(struct board *board, int size);
285 void board_clear(struct board *board);
287 struct FILE;
288 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
289 void board_print(struct board *board, FILE *f);
290 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
292 /* Place given handicap on the board; coordinates are printed to f. */
293 void board_handicap(struct board *board, int stones, FILE *f);
295 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
296 int board_play(struct board *board, struct move *m);
297 /* Like above, but plays random move; the move coordinate is recorded
298 * to *coord. This method will never fill your own eye. pass is played
299 * when no move can be played. You can impose extra restrictions if you
300 * supply your own permit function. */
301 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
302 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
304 /* Returns true if given move can be played. */
305 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
306 static bool board_is_valid_move(struct board *b, struct move *m);
307 /* Returns true if ko was just taken. */
308 static bool board_playing_ko_threat(struct board *b);
309 /* Returns 0 or ID of neighboring group in atari. */
310 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
311 /* Returns true if the move is not obvious self-atari. */
312 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
314 /* Adjust symmetry information as if given coordinate has been played. */
315 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
316 /* Associate a set of feature gamma values (for pd building) with the board. */
317 void board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari);
318 /* Force re-compute of a probability distribution item. */
319 void board_gamma_update(struct board *b, coord_t coord, enum stone color);
321 /* Returns true if given coordinate has all neighbors of given color or the edge. */
322 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
323 /* Returns true if given coordinate could be a false eye; this check makes
324 * sense only if you already know the coordinate is_eyelike(). */
325 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
326 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
327 * at least tries to). */
328 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
329 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
330 enum stone board_get_one_point_eye(struct board *board, coord_t c);
332 /* board_official_score() is the scoring method for yielding score suitable
333 * for external presentation. For fast scoring of entirely filled boards
334 * (e.g. playouts), use board_fast_score(). */
335 /* Positive: W wins */
336 /* Compare number of stones + 1pt eyes. */
337 float board_fast_score(struct board *board);
338 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
339 struct move_queue;
340 float board_official_score(struct board *board, struct move_queue *mq);
342 /** Iterators */
344 #define foreach_point(board_) \
345 do { \
346 coord_t c; coord_pos(c, 0, (board_)); \
347 for (; coord_raw(c) < board_size(board_) * board_size(board_); coord_raw(c)++)
348 #define foreach_point_and_pass(board_) \
349 do { \
350 coord_t c; coord_pos(c, -1, (board_)); \
351 for (; coord_raw(c) < board_size(board_) * board_size(board_); coord_raw(c)++)
352 #define foreach_point_end \
353 } while (0)
355 #define foreach_in_group(board_, group_) \
356 do { \
357 struct board *board__ = board_; \
358 coord_t c = group_base(group_); \
359 coord_t c2 = c; coord_raw(c2) = groupnext_at(board__, c2); \
360 do {
361 #define foreach_in_group_end \
362 c = c2; coord_raw(c2) = groupnext_at(board__, c2); \
363 } while (coord_raw(c) != 0); \
364 } while (0)
366 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
367 * on S_OFFBOARD coordinates. */
368 #define foreach_neighbor(board_, coord_, loop_body) \
369 do { \
370 struct board *board__ = board_; \
371 coord_t coord__ = coord_; \
372 coord_t c; \
373 coord_pos(c, coord_raw(coord__) - 1, (board__)); do { loop_body } while (0); \
374 coord_pos(c, coord_raw(coord__) - board_size(board__), (board__)); do { loop_body } while (0); \
375 coord_pos(c, coord_raw(coord__) + 1, (board__)); do { loop_body } while (0); \
376 coord_pos(c, coord_raw(coord__) + board_size(board__), (board__)); do { loop_body } while (0); \
377 } while (0)
379 #define foreach_8neighbor(board_, coord_) \
380 do { \
381 int fn__i; \
382 coord_t c = (coord_); \
383 for (fn__i = 0; fn__i < 8; fn__i++) { \
384 c += (board_)->nei8[fn__i];
385 #define foreach_8neighbor_end \
387 } while (0)
389 #define foreach_diag_neighbor(board_, coord_) \
390 do { \
391 int fn__i; \
392 coord_t c = (coord_); \
393 for (fn__i = 0; fn__i < 4; fn__i++) { \
394 c += (board_)->dnei[fn__i];
395 #define foreach_diag_neighbor_end \
397 } while (0)
400 static inline bool
401 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
403 return (neighbor_count_at(board, coord, eye_color)
404 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
407 static inline bool
408 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
410 if (board_at(board, coord) != S_NONE)
411 return false;
412 if (!board_is_eyelike(board, coord, stone_other(color)))
413 return true;
414 /* Play within {true,false} eye-ish formation */
415 if (board->ko.coord == coord && board->ko.color == color)
416 return false;
417 #ifdef BOARD_TRAITS
418 /* XXX: Disallows suicide. */
419 return trait_at(board, coord, color).cap > 0;
420 #else
421 int groups_in_atari = 0;
422 foreach_neighbor(board, coord, {
423 group_t g = group_at(board, c);
424 groups_in_atari += (board_group_info(board, g).libs == 1);
426 return !!groups_in_atari;
427 #endif
430 static inline bool
431 board_is_valid_move(struct board *board, struct move *m)
433 return board_is_valid_play(board, m->color, m->coord);
436 static inline bool
437 board_playing_ko_threat(struct board *b)
439 return !is_pass(b->ko.coord);
442 static inline group_t
443 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
445 #ifdef BOARD_TRAITS
446 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
447 #endif
448 foreach_neighbor(b, coord, {
449 group_t g = group_at(b, c);
450 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
451 return g;
452 /* We return first match. */
454 return 0;
457 static inline bool
458 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
460 /* number of free neighbors */
461 int libs = immediate_liberty_count(b, coord);
462 if (libs > 1)
463 return true;
465 #ifdef BOARD_TRAITS
466 /* number of capturable enemy groups */
467 if (trait_at(b, coord, color).cap > 0)
468 return true; // XXX: We don't account for snapback.
469 /* number of non-capturable friendly groups */
470 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
471 if (noncap_ours < 1)
472 return false;
473 /*#else see below */
474 #endif
476 /* ok, but we need to check if they don't have just two libs. */
477 coord_t onelib = -1;
478 foreach_neighbor(b, coord, {
479 #ifndef BOARD_TRAITS
480 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
481 return true; // can capture; no snapback check
482 #endif
483 if (board_at(b, c) != color) continue;
484 group_t g = group_at(b, c);
485 if (board_group_info(b, g).libs == 1) continue; // in atari
486 if (board_group_info(b, g).libs == 2) { // two liberties
487 if (libs > 0) return true; // we already have one real liberty
488 // get the other liberty
489 coord_t lib = board_group_info(b, g).lib[0];
490 if (lib == coord) lib = board_group_info(b, g).lib[0];
491 /* we might be connecting two 2-lib groups, which is ok;
492 * so remember the other liberty and just make sure it's
493 * not the same one */
494 if (onelib >= 0 && lib != onelib) return true;
495 onelib = lib;
496 continue;
498 // many liberties
499 return true;
501 // no good support group
502 return false;
505 #endif