Distributed engine: log number of replies and threads. Align time.
[pachi/pachi-r6144.git] / board.h
blobbc2e0bd9bfd5193a1bf72c8b46b55eb9a6dc09f4
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;
116 /* Iterator offsets for foreach_neighbor*() */
117 int nei8[8], dnei[4];
119 int moves;
120 struct move last_move;
121 struct move last_move2; /* second-to-last move */
122 /* Whether we tried to add a hash twice; board_play*() can
123 * set this, but it will still carry out the move as well! */
124 bool superko_violation;
126 /* The following two structures are goban maps and are indexed by
127 * coord.pos. The map is surrounded by a one-point margin from
128 * S_OFFBOARD stones in order to speed up some internal loops.
129 * Some of the foreach iterators below might include these points;
130 * you need to handle them yourselves, if you need to. */
132 /* Stones played on the board */
133 enum stone *b; /* enum stone */
134 /* Group id the stones are part of; 0 == no group */
135 group_t *g;
136 /* Positions of next stones in the stone group; 0 == last stone */
137 coord_t *p;
138 /* Neighboring colors; numbers of neighbors of index color */
139 struct neighbor_colors *n;
140 /* Zobrist hash for each position */
141 hash_t *h;
142 #ifdef BOARD_SPATHASH
143 /* For spatial hashes, we use only 24 bits. */
144 /* [0] is d==1, we don't keep hash for d==0. */
145 /* We keep hashes for black-to-play ([][0]) and white-to-play
146 * ([][1], reversed stone colors since we match all patterns as
147 * black-to-play). */
148 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
149 #endif
150 #ifdef BOARD_PAT3
151 /* 3x3 pattern code for each position; see pattern3.h for encoding
152 * specification. The information is only valid for empty points. */
153 uint16_t *pat3;
154 #endif
155 #ifdef BOARD_TRAITS
156 /* Incrementally matched point traits information, black-to-play
157 * ([][0]) and white-to-play ([][1]). */
158 /* The information is only valid for empty points. */
159 struct btraits (*t)[2];
160 #endif
161 #ifdef BOARD_GAMMA
162 /* Relative probabilities of moves being played next, computed by
163 * multiplying gammas of the appropriate pattern features based on
164 * pat3 and traits (see pattern.h). The probability distribution
165 * is maintained over the full board grid. */
166 /* - Always invalid moves are guaranteed to have zero probability.
167 * - Self-eye-filling moves will always have zero probability.
168 * - Ko-prohibited moves might have non-zero probability.
169 * - FEAT_CONTIGUITY is not accounted for in the probability. */
170 struct probdist prob[2];
171 #endif
173 /* Group information - indexed by gid (which is coord of base group stone) */
174 struct group *gi;
176 /* Positions of free positions - queue (not map) */
177 /* Note that free position here is any valid move; including single-point eyes! */
178 coord_t *f; int flen;
180 #ifdef WANT_BOARD_C
181 /* Queue of capturable groups */
182 group_t *c; int clen;
183 #endif
185 #ifdef BOARD_TRAITS
186 /* Queue of positions that need their traits updated */
187 coord_t *tq; int tqlen;
188 #endif
190 /* Symmetry information */
191 struct board_symmetry symmetry;
193 /* Last ko played on the board. */
194 struct move last_ko;
195 int last_ko_age;
197 /* Basic ko check */
198 struct move ko;
200 /* Engine-specific state; persistent through board development,
201 * is reset only at clear_board. */
202 void *es;
204 /* Playout-specific state; persistent through board development,
205 * but its lifetime is maintained in play_random_game(); it should
206 * not be set outside of it. */
207 void *ps;
209 #ifdef BOARD_GAMMA
210 /* Gamma values for probability distribution; user must setup
211 * this pointer before any move is played, using board_gamma_set(). */
212 struct features_gamma *gamma;
213 /* Whether to compute the 'safe' trait using board_safe_to_play()
214 * (false) or is_bad_selfatari() (true, much slower). */
215 bool precise_selfatari;
216 #endif
219 /* --- PRIVATE DATA --- */
221 /* For superko check: */
223 /* Board "history" - hashes encountered. Size of the hash should be
224 * >> board_size^2. */
225 #define history_hash_bits 12
226 #define history_hash_mask ((1 << history_hash_bits) - 1)
227 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
228 #define history_hash_next(i) ((i + 1) & history_hash_mask)
229 hash_t history_hash[1 << history_hash_bits];
230 /* Hash of current board position. */
231 hash_t hash;
234 #ifdef BOARD_SIZE
235 /* Avoid unused variable warnings */
236 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
237 #define board_size2(b_) (board_size(b_) * board_size(b_))
238 #else
239 #define board_size(b_) ((b_)->size)
240 #define board_size2(b_) ((b_)->size2)
241 #endif
243 #define board_at(b_, c) ((b_)->b[coord_raw(c)])
244 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
246 #define group_at(b_, c) ((b_)->g[coord_raw(c)])
247 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
249 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
250 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord_raw(coord)].colors[(enum stone) color])
251 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
252 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
253 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
254 #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))
256 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
258 #define groupnext_at(b_, c) ((b_)->p[coord_raw(c)])
259 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
261 #define group_base(g_) (g_)
262 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
263 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
264 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
266 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord_raw(coord)])
268 struct board *board_init(void);
269 struct board *board_copy(struct board *board2, struct board *board1);
270 void board_done_noalloc(struct board *board);
271 void board_done(struct board *board);
272 /* size here is without the S_OFFBOARD margin. */
273 void board_resize(struct board *board, int size);
274 void board_clear(struct board *board);
276 struct FILE;
277 typedef void (*board_cprint)(struct board *b, coord_t c, FILE *f);
278 void board_print(struct board *board, FILE *f);
279 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
281 /* Place given handicap on the board; coordinates are printed to f. */
282 void board_handicap(struct board *board, int stones, FILE *f);
284 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
285 int board_play(struct board *board, struct move *m);
286 /* Like above, but plays random move; the move coordinate is recorded
287 * to *coord. This method will never fill your own eye. pass is played
288 * when no move can be played. You can impose extra restrictions if you
289 * supply your own permit function. */
290 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
291 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
293 /* Returns true if given move can be played. */
294 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
295 static bool board_is_valid_move(struct board *b, struct move *m);
296 /* Returns true if ko was just taken. */
297 static bool board_playing_ko_threat(struct board *b);
298 /* Returns 0 or ID of neighboring group in atari. */
299 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
300 /* Returns true if the move is not obvious self-atari. */
301 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
303 /* Adjust symmetry information as if given coordinate has been played. */
304 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
305 /* Associate a set of feature gamma values (for pd building) with the board. */
306 void board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari);
307 /* Force re-compute of a probability distribution item. */
308 void board_gamma_update(struct board *b, coord_t coord, enum stone color);
310 /* Returns true if given coordinate has all neighbors of given color or the edge. */
311 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
312 /* Returns true if given coordinate could be a false eye; this check makes
313 * sense only if you already know the coordinate is_eyelike(). */
314 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
315 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
316 * at least tries to). */
317 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
318 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
319 enum stone board_get_one_point_eye(struct board *board, coord_t c);
321 /* board_official_score() is the scoring method for yielding score suitable
322 * for external presentation. For fast scoring of entirely filled boards
323 * (e.g. playouts), use board_fast_score(). */
324 /* Positive: W wins */
325 /* Compare number of stones + 1pt eyes. */
326 float board_fast_score(struct board *board);
327 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
328 struct move_queue;
329 float board_official_score(struct board *board, struct move_queue *mq);
331 /** Iterators */
333 #define foreach_point(board_) \
334 do { \
335 coord_t c; coord_pos(c, 0, (board_)); \
336 for (; coord_raw(c) < board_size(board_) * board_size(board_); coord_raw(c)++)
337 #define foreach_point_and_pass(board_) \
338 do { \
339 coord_t c; coord_pos(c, -1, (board_)); \
340 for (; coord_raw(c) < board_size(board_) * board_size(board_); coord_raw(c)++)
341 #define foreach_point_end \
342 } while (0)
344 #define foreach_in_group(board_, group_) \
345 do { \
346 struct board *board__ = board_; \
347 coord_t c = group_base(group_); \
348 coord_t c2 = c; coord_raw(c2) = groupnext_at(board__, c2); \
349 do {
350 #define foreach_in_group_end \
351 c = c2; coord_raw(c2) = groupnext_at(board__, c2); \
352 } while (coord_raw(c) != 0); \
353 } while (0)
355 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
356 * on S_OFFBOARD coordinates. */
357 #define foreach_neighbor(board_, coord_, loop_body) \
358 do { \
359 struct board *board__ = board_; \
360 coord_t coord__ = coord_; \
361 coord_t c; \
362 coord_pos(c, coord_raw(coord__) - 1, (board__)); do { loop_body } while (0); \
363 coord_pos(c, coord_raw(coord__) - board_size(board__), (board__)); do { loop_body } while (0); \
364 coord_pos(c, coord_raw(coord__) + 1, (board__)); do { loop_body } while (0); \
365 coord_pos(c, coord_raw(coord__) + board_size(board__), (board__)); do { loop_body } while (0); \
366 } while (0)
368 #define foreach_8neighbor(board_, coord_) \
369 do { \
370 int fn__i; \
371 coord_t c = (coord_); \
372 for (fn__i = 0; fn__i < 8; fn__i++) { \
373 c += (board_)->nei8[fn__i];
374 #define foreach_8neighbor_end \
376 } while (0)
378 #define foreach_diag_neighbor(board_, coord_) \
379 do { \
380 int fn__i; \
381 coord_t c = (coord_); \
382 for (fn__i = 0; fn__i < 4; fn__i++) { \
383 c += (board_)->dnei[fn__i];
384 #define foreach_diag_neighbor_end \
386 } while (0)
389 static inline bool
390 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
392 return (neighbor_count_at(board, coord, eye_color)
393 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
396 static inline bool
397 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
399 if (board_at(board, coord) != S_NONE)
400 return false;
401 if (!board_is_eyelike(board, coord, stone_other(color)))
402 return true;
403 /* Play within {true,false} eye-ish formation */
404 if (board->ko.coord == coord && board->ko.color == color)
405 return false;
406 #ifdef BOARD_TRAITS
407 /* XXX: Disallows suicide. */
408 return trait_at(board, coord, color).cap > 0;
409 #else
410 int groups_in_atari = 0;
411 foreach_neighbor(board, coord, {
412 group_t g = group_at(board, c);
413 groups_in_atari += (board_group_info(board, g).libs == 1);
415 return !!groups_in_atari;
416 #endif
419 static inline bool
420 board_is_valid_move(struct board *board, struct move *m)
422 return board_is_valid_play(board, m->color, m->coord);
425 static inline bool
426 board_playing_ko_threat(struct board *b)
428 return !is_pass(b->ko.coord);
431 static inline group_t
432 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
434 #ifdef BOARD_TRAITS
435 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
436 #endif
437 foreach_neighbor(b, coord, {
438 group_t g = group_at(b, c);
439 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
440 return g;
441 /* We return first match. */
443 return 0;
446 static inline bool
447 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
449 /* number of free neighbors */
450 int libs = immediate_liberty_count(b, coord);
451 if (libs > 1)
452 return true;
454 #ifdef BOARD_TRAITS
455 /* number of capturable enemy groups */
456 if (trait_at(b, coord, color).cap > 0)
457 return true; // XXX: We don't account for snapback.
458 /* number of non-capturable friendly groups */
459 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
460 if (noncap_ours < 1)
461 return false;
462 /*#else see below */
463 #endif
465 /* ok, but we need to check if they don't have just two libs. */
466 coord_t onelib = -1;
467 foreach_neighbor(b, coord, {
468 #ifndef BOARD_TRAITS
469 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
470 return true; // can capture; no snapback check
471 #endif
472 if (board_at(b, c) != color) continue;
473 group_t g = group_at(b, c);
474 if (board_group_info(b, g).libs == 1) continue; // in atari
475 if (board_group_info(b, g).libs == 2) { // two liberties
476 if (libs > 0) return true; // we already have one real liberty
477 // get the other liberty
478 coord_t lib = board_group_info(b, g).lib[0];
479 if (lib == coord) lib = board_group_info(b, g).lib[0];
480 /* we might be connecting two 2-lib groups, which is ok;
481 * so remember the other liberty and just make sure it's
482 * not the same one */
483 if (onelib >= 0 && lib != onelib) return true;
484 onelib = lib;
485 continue;
487 // many liberties
488 return true;
490 // no good support group
491 return false;
494 #endif