Board traits: Track the 'safe' trait usable for atariescape/selfatari detection
[pachi.git] / board.c
blob4158f11327059d040f3914b041e00dc8d76ce05a
1 #include <alloca.h>
2 #include <assert.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
7 #include "board.h"
8 #include "debug.h"
9 #include "mq.h"
10 #include "random.h"
12 #ifdef BOARD_SPATHASH
13 #include "patternsp.h"
14 #endif
15 #ifdef BOARD_PAT3
16 #include "pattern3.h"
17 #endif
19 bool random_pass = false;
22 #if 0
23 #define profiling_noinline __attribute__((noinline))
24 #else
25 #define profiling_noinline
26 #endif
28 #define gi_granularity 4
29 #define gi_allocsize(gids) ((1 << gi_granularity) + ((gids) >> gi_granularity) * (1 << gi_granularity))
32 static void
33 board_setup(struct board *b)
35 memset(b, 0, sizeof(*b));
37 struct move m = { pass, S_NONE };
38 b->last_move = b->last_move2 = b->last_ko = b->ko = m;
41 struct board *
42 board_init(void)
44 struct board *b = malloc(sizeof(struct board));
45 board_setup(b);
47 // Default setup
48 b->size = 9 + 2;
49 board_clear(b);
51 return b;
54 struct board *
55 board_copy(struct board *b2, struct board *b1)
57 memcpy(b2, b1, sizeof(struct board));
59 int bsize = board_size2(b2) * sizeof(*b2->b);
60 int gsize = board_size2(b2) * sizeof(*b2->g);
61 int fsize = board_size2(b2) * sizeof(*b2->f);
62 int nsize = board_size2(b2) * sizeof(*b2->n);
63 int psize = board_size2(b2) * sizeof(*b2->p);
64 int hsize = board_size2(b2) * 2 * sizeof(*b2->h);
65 int gisize = board_size2(b2) * sizeof(*b2->gi);
66 #ifdef WANT_BOARD_C
67 int csize = board_size2(b2) * sizeof(*b2->c);
68 #else
69 int csize = 0;
70 #endif
71 #ifdef BOARD_SPATHASH
72 int ssize = board_size2(b2) * sizeof(*b2->spathash);
73 #else
74 int ssize = 0;
75 #endif
76 #ifdef BOARD_PAT3
77 int p3size = board_size2(b2) * sizeof(*b2->pat3);
78 #else
79 int p3size = 0;
80 #endif
81 #ifdef BOARD_TRAITS
82 int tsize = board_size2(b2) * sizeof(*b2->t);
83 #else
84 int tsize = 0;
85 #endif
86 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize);
87 memcpy(x, b1->b, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize);
88 b2->b = x; x += bsize;
89 b2->g = x; x += gsize;
90 b2->f = x; x += fsize;
91 b2->p = x; x += psize;
92 b2->n = x; x += nsize;
93 b2->h = x; x += hsize;
94 b2->gi = x; x += gisize;
95 #ifdef WANT_BOARD_C
96 b2->c = x; x += csize;
97 #endif
98 #ifdef BOARD_SPATHASH
99 b2->spathash = x; x += ssize;
100 #endif
101 #ifdef BOARD_PAT3
102 b2->pat3 = x; x += p3size;
103 #endif
104 #ifdef BOARD_TRAITS
105 b2->t = x; x += tsize;
106 #endif
108 return b2;
111 void
112 board_done_noalloc(struct board *board)
114 if (board->b) free(board->b);
117 void
118 board_done(struct board *board)
120 board_done_noalloc(board);
121 free(board);
124 void
125 board_resize(struct board *board, int size)
127 #ifdef BOARD_SIZE
128 assert(board_size(board) == size + 2);
129 #else
130 board_size(board) = size + 2 /* S_OFFBOARD margin */;
131 board_size2(board) = board_size(board) * board_size(board);
132 #endif
133 if (board->b)
134 free(board->b);
136 int bsize = board_size2(board) * sizeof(*board->b);
137 int gsize = board_size2(board) * sizeof(*board->g);
138 int fsize = board_size2(board) * sizeof(*board->f);
139 int nsize = board_size2(board) * sizeof(*board->n);
140 int psize = board_size2(board) * sizeof(*board->p);
141 int hsize = board_size2(board) * 2 * sizeof(*board->h);
142 int gisize = board_size2(board) * sizeof(*board->gi);
143 #ifdef WANT_BOARD_C
144 int csize = board_size2(board) * sizeof(*board->c);
145 #else
146 int csize = 0;
147 #endif
148 #ifdef BOARD_SPATHASH
149 int ssize = board_size2(board) * sizeof(*board->spathash);
150 #else
151 int ssize = 0;
152 #endif
153 #ifdef BOARD_PAT3
154 int p3size = board_size2(board) * sizeof(*board->pat3);
155 #else
156 int p3size = 0;
157 #endif
158 #ifdef BOARD_TRAITS
159 int tsize = board_size2(board) * sizeof(*board->t);
160 #else
161 int tsize = 0;
162 #endif
163 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize);
164 memset(x, 0, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize);
165 board->b = x; x += bsize;
166 board->g = x; x += gsize;
167 board->f = x; x += fsize;
168 board->p = x; x += psize;
169 board->n = x; x += nsize;
170 board->h = x; x += hsize;
171 board->gi = x; x += gisize;
172 #ifdef WANT_BOARD_C
173 board->c = x; x += csize;
174 #endif
175 #ifdef BOARD_SPATHASH
176 board->spathash = x; x += ssize;
177 #endif
178 #ifdef BOARD_PAT3
179 board->pat3 = x; x += p3size;
180 #endif
181 #ifdef BOARD_TRAITS
182 board->t = x; x += tsize;
183 #endif
186 void
187 board_clear(struct board *board)
189 int size = board_size(board);
190 float komi = board->komi;
192 board_done_noalloc(board);
193 board_setup(board);
194 board_resize(board, size - 2 /* S_OFFBOARD margin */);
196 board->komi = komi;
198 /* Setup neighborhood iterators */
199 board->nei8[0] = -size - 1; // (-1,-1)
200 board->nei8[1] = 1;
201 board->nei8[2] = 1;
202 board->nei8[3] = size - 2; // (-1,0)
203 board->nei8[4] = 2;
204 board->nei8[5] = size - 2; // (-1,1)
205 board->nei8[6] = 1;
206 board->nei8[7] = 1;
207 board->dnei[0] = -size - 1;
208 board->dnei[1] = 2;
209 board->dnei[2] = size*2 - 2;
210 board->dnei[3] = 2;
212 /* Setup initial symmetry */
213 board->symmetry.d = 1;
214 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
215 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
216 board->symmetry.type = SYM_FULL;
218 /* Draw the offboard margin */
219 int top_row = board_size2(board) - board_size(board);
220 int i;
221 for (i = 0; i < board_size(board); i++)
222 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
223 for (i = 0; i <= top_row; i += board_size(board))
224 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
226 foreach_point(board) {
227 coord_t coord = c;
228 if (board_at(board, coord) == S_OFFBOARD)
229 continue;
230 foreach_neighbor(board, c, {
231 inc_neighbor_count_at(board, coord, board_at(board, c));
232 } );
233 } foreach_point_end;
235 /* First, pass is always a free position. */
236 board->f[board->flen++] = coord_raw(pass);
237 /* All positions are free! Except the margin. */
238 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
239 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
240 board->f[board->flen++] = i;
242 /* Initialize zobrist hashtable. */
243 foreach_point(board) {
244 int max = (sizeof(hash_t) << history_hash_bits);
245 /* fast_random() is 16-bit only */
246 board->h[coord_raw(c) * 2] = ((hash_t) fast_random(max))
247 | ((hash_t) fast_random(max) << 16)
248 | ((hash_t) fast_random(max) << 32)
249 | ((hash_t) fast_random(max) << 48);
250 if (!board->h[coord_raw(c) * 2])
251 /* Would be kinda "oops". */
252 board->h[coord_raw(c) * 2] = 1;
253 /* And once again for white */
254 board->h[coord_raw(c) * 2 + 1] = ((hash_t) fast_random(max))
255 | ((hash_t) fast_random(max) << 16)
256 | ((hash_t) fast_random(max) << 32)
257 | ((hash_t) fast_random(max) << 48);
258 if (!board->h[coord_raw(c) * 2 + 1])
259 board->h[coord_raw(c) * 2 + 1] = 1;
260 } foreach_point_end;
262 #ifdef BOARD_SPATHASH
263 /* Initialize spatial hashes. */
264 foreach_point(board) {
265 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
266 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
267 ptcoords_at(x, y, c, board, j);
268 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
269 pthashes[0][j][board_at(board, c)];
270 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
271 pthashes[0][j][stone_other(board_at(board, c))];
274 } foreach_point_end;
275 #endif
276 #ifdef BOARD_PAT3
277 /* Initialize 3x3 pattern codes. */
278 foreach_point(board) {
279 if (board_at(board, c) == S_NONE)
280 board->pat3[c] = pattern3_hash(board, c);
281 } foreach_point_end;
282 #endif
283 #ifdef BOARD_TRAITS
284 /* Initialize traits. */
285 foreach_point(board) {
286 trait_at(board, c, S_BLACK).cap = 0;
287 trait_at(board, c, S_BLACK).safe = true;
288 trait_at(board, c, S_WHITE).cap = 0;
289 trait_at(board, c, S_WHITE).safe = true;
290 } foreach_point_end;
291 #endif
295 static void
296 board_print_top(struct board *board, FILE *f, int c)
298 for (int i = 0; i < c; i++) {
299 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
300 fprintf(f, " ");
301 for (int x = 1; x < board_size(board) - 1; x++)
302 fprintf(f, "%c ", asdf[x - 1]);
303 fprintf(f, " ");
305 fprintf(f, "\n");
306 for (int i = 0; i < c; i++) {
307 fprintf(f, " +-");
308 for (int x = 1; x < board_size(board) - 1; x++)
309 fprintf(f, "--");
310 fprintf(f, "+");
312 fprintf(f, "\n");
315 static void
316 board_print_bottom(struct board *board, FILE *f, int c)
318 for (int i = 0; i < c; i++) {
319 fprintf(f, " +-");
320 for (int x = 1; x < board_size(board) - 1; x++)
321 fprintf(f, "--");
322 fprintf(f, "+");
324 fprintf(f, "\n");
327 static void
328 board_print_row(struct board *board, int y, FILE *f, board_cprint cprint)
330 fprintf(f, " %2d | ", y);
331 for (int x = 1; x < board_size(board) - 1; x++) {
332 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
333 fprintf(f, "%c)", stone2char(board_atxy(board, x, y)));
334 else
335 fprintf(f, "%c ", stone2char(board_atxy(board, x, y)));
337 fprintf(f, "|");
338 if (cprint) {
339 fprintf(f, " %2d | ", y);
340 for (int x = 1; x < board_size(board) - 1; x++) {
341 cprint(board, coord_xy(board, x, y), f);
343 fprintf(f, "|");
345 fprintf(f, "\n");
348 void
349 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
351 fprintf(f, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
352 board->moves, board->komi, board->handicap,
353 board->captures[S_BLACK], board->captures[S_WHITE]);
354 board_print_top(board, f, 1 + !!cprint);
355 for (int y = board_size(board) - 2; y >= 1; y--)
356 board_print_row(board, y, f, cprint);
357 board_print_bottom(board, f, 1 + !!cprint);
358 fprintf(f, "\n");
361 static void
362 cprint_group(struct board *board, coord_t c, FILE *f)
364 fprintf(f, "%d ", group_base(group_at(board, c)));
367 void
368 board_print(struct board *board, FILE *f)
370 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
374 /* Recompute some of the traits for given point from scratch. Note that
375 * some traits are updated incrementally elsewhere. */
376 static void
377 board_trait_recompute(struct board *board, coord_t coord)
379 #ifdef BOARD_TRAITS
380 trait_at(board, coord, S_BLACK).safe = board_safe_to_play(board, coord, S_BLACK);
381 trait_at(board, coord, S_WHITE).safe = board_safe_to_play(board, coord, S_WHITE);
382 if (DEBUGL(8)) {
383 fprintf(stderr, "traits[%s:%s lib=%d] (black cap=%d safe=%d) (white cap=%d safe=%d)\n",
384 coord2sstr(coord, board), stone2str(board_at(board, coord)), immediate_liberty_count(board, coord),
385 trait_at(board, coord, S_BLACK).cap, trait_at(board, coord, S_BLACK).safe,
386 trait_at(board, coord, S_WHITE).cap, trait_at(board, coord, S_WHITE).safe);
388 #endif
391 /* Update board hash with given coordinate. */
392 static void profiling_noinline
393 board_hash_update(struct board *board, coord_t coord, enum stone color)
395 board->hash ^= hash_at(board, coord, color);
396 if (DEBUGL(8))
397 fprintf(stderr, "board_hash_update(%d,%d,%d) ^ %"PRIhash" -> %"PRIhash"\n", color, coord_x(coord, board), coord_y(coord, board), hash_at(board, coord, color), board->hash);
399 #ifdef BOARD_SPATHASH
400 /* Gridcular metric is reflective, so we update all hashes
401 * of appropriate ditance in OUR circle. */
402 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
403 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
404 ptcoords_at(x, y, coord, board, j);
405 /* We either changed from S_NONE to color
406 * or vice versa; doesn't matter. */
407 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
408 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
409 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
410 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
413 #endif
415 #if defined(BOARD_PAT3)
416 /* @color is not what we need in case of capture. */
417 enum stone new_color = board_at(board, coord);
418 if (new_color == S_NONE)
419 board->pat3[coord] = pattern3_hash(board, coord);
420 foreach_8neighbor(board, coord) { // internally, the loop uses fn__i=[0..7]
421 if (board_at(board, c) != S_NONE)
422 continue;
423 board->pat3[c] &= ~(3 << (fn__i*2));
424 board->pat3[c] |= new_color << (fn__i*2);
425 #if 0
426 if (board_at(board, c) != S_OFFBOARD && pattern3_hash(board, c) != board->pat3[c]) {
427 board_print(board, stderr);
428 fprintf(stderr, "%s->%s %x != %x (%d-%d:%d)\n", coord2sstr(coord, board), coord2sstr(c, board), pattern3_hash(board, c), board->pat3[c], coord, c, fn__i);
429 assert(0);
431 #endif
432 } foreach_8neighbor_end;
433 #endif
436 /* Commit current board hash to history. */
437 static void profiling_noinline
438 board_hash_commit(struct board *board)
440 if (DEBUGL(8))
441 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
442 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
443 board->history_hash[board->hash & history_hash_mask] = board->hash;
444 } else {
445 hash_t i = board->hash;
446 while (board->history_hash[i & history_hash_mask]) {
447 if (board->history_hash[i & history_hash_mask] == board->hash) {
448 if (DEBUGL(5))
449 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
450 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
451 board->superko_violation = true;
452 return;
454 i = history_hash_next(i);
456 board->history_hash[i & history_hash_mask] = board->hash;
461 void
462 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
464 if (likely(symmetry->type == SYM_NONE)) {
465 /* Fully degenerated already. We do not support detection
466 * of restoring of symmetry, assuming that this is too rare
467 * a case to handle. */
468 return;
471 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
472 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
473 if (DEBUGL(6)) {
474 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
475 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
476 symmetry->d, symmetry->type, x, y);
479 switch (symmetry->type) {
480 case SYM_FULL:
481 if (x == t && y == t) {
482 /* Tengen keeps full symmetry. */
483 return;
485 /* New symmetry now? */
486 if (x == y) {
487 symmetry->type = SYM_DIAG_UP;
488 symmetry->x1 = symmetry->y1 = 1;
489 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
490 symmetry->d = 1;
491 } else if (dx == y) {
492 symmetry->type = SYM_DIAG_DOWN;
493 symmetry->x1 = symmetry->y1 = 1;
494 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
495 symmetry->d = 1;
496 } else if (x == t) {
497 symmetry->type = SYM_HORIZ;
498 symmetry->y1 = 1;
499 symmetry->y2 = board_size(b) - 1;
500 symmetry->d = 0;
501 } else if (y == t) {
502 symmetry->type = SYM_VERT;
503 symmetry->x1 = 1;
504 symmetry->x2 = board_size(b) - 1;
505 symmetry->d = 0;
506 } else {
507 break_symmetry:
508 symmetry->type = SYM_NONE;
509 symmetry->x1 = symmetry->y1 = 1;
510 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
511 symmetry->d = 0;
513 break;
514 case SYM_DIAG_UP:
515 if (x == y)
516 return;
517 goto break_symmetry;
518 case SYM_DIAG_DOWN:
519 if (dx == y)
520 return;
521 goto break_symmetry;
522 case SYM_HORIZ:
523 if (x == t)
524 return;
525 goto break_symmetry;
526 case SYM_VERT:
527 if (y == t)
528 return;
529 goto break_symmetry;
530 case SYM_NONE:
531 assert(0);
532 break;
535 if (DEBUGL(6)) {
536 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
537 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
538 symmetry->d, symmetry->type);
540 /* Whew. */
544 void
545 board_handicap_stone(struct board *board, int x, int y, FILE *f)
547 struct move m;
548 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
550 board_play(board, &m);
551 /* Simulate white passing; otherwise, UCT search can get confused since
552 * tree depth parity won't match the color to move. */
553 board->moves++;
555 char *str = coord2str(m.coord, board);
556 if (DEBUGL(1))
557 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
558 fprintf(f, "%s ", str);
559 free(str);
562 void
563 board_handicap(struct board *board, int stones, FILE *f)
565 int margin = 3 + (board_size(board) >= 13);
566 int min = margin;
567 int mid = board_size(board) / 2;
568 int max = board_size(board) - 1 - margin;
569 const int places[][2] = {
570 { min, min }, { max, max }, { max, min }, { min, max },
571 { min, mid }, { max, mid },
572 { mid, min }, { mid, max },
573 { mid, mid },
576 board->handicap = stones;
578 if (stones == 5 || stones == 7) {
579 board_handicap_stone(board, mid, mid, f);
580 stones--;
583 int i;
584 for (i = 0; i < stones; i++)
585 board_handicap_stone(board, places[i][0], places[i][1], f);
589 static void __attribute__((noinline))
590 check_libs_consistency(struct board *board, group_t g)
592 #ifdef DEBUG
593 if (!g) return;
594 struct group *gi = &board_group_info(board, g);
595 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
596 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
597 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
598 assert(0);
600 #endif
603 static void
604 board_capturable_add(struct board *board, group_t group, coord_t lib)
606 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
607 #ifdef BOARD_TRAITS
608 /* Increase capturable count trait of my last lib. */
609 enum stone capturing_color = stone_other(board_at(board, group));
610 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
611 foreach_neighbor(board, lib, {
612 if (DEBUGL(8) && group_at(board, c) == group)
613 fprintf(stderr, "%s[%d] %s cap bump bc of %s(%d) member %s\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap, stone2str(capturing_color), coord2sstr(group, board), board_group_info(board, group).libs, coord2sstr(c, board));
614 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group);
616 board_trait_recompute(board, lib);
617 #endif
619 #ifdef WANT_BOARD_C
620 /* Update the list of capturable groups. */
621 assert(group);
622 assert(board->clen < board_size2(board));
623 board->c[board->clen++] = group;
624 #endif
626 static void
627 board_capturable_rm(struct board *board, group_t group, coord_t lib)
629 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
630 #ifdef BOARD_TRAITS
631 /* Decrease capturable count trait of my previously-last lib. */
632 enum stone capturing_color = stone_other(board_at(board, group));
633 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
634 foreach_neighbor(board, lib, {
635 if (DEBUGL(8) && group_at(board, c) == group)
636 fprintf(stderr, "%s[%d] cap dump bc of %s(%d) member %s\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap, coord2sstr(group, board), board_group_info(board, group).libs, coord2sstr(c, board));
637 trait_at(board, lib, capturing_color).cap -= (group_at(board, c) == group);
639 board_trait_recompute(board, lib);
640 #endif
642 #ifdef WANT_BOARD_C
643 /* Update the list of capturable groups. */
644 for (int i = 0; i < board->clen; i++) {
645 if (unlikely(board->c[i] == group)) {
646 board->c[i] = board->c[--board->clen];
647 return;
650 fprintf(stderr, "rm of bad group %d\n", group_base(group));
651 assert(0);
652 #endif
655 static void
656 board_group_addlib(struct board *board, group_t group, coord_t coord)
658 if (DEBUGL(7)) {
659 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
660 group_base(group), coord2sstr(group_base(group), board),
661 board_group_info(board, group).libs, coord2sstr(coord, board));
664 check_libs_consistency(board, group);
666 struct group *gi = &board_group_info(board, group);
667 if (gi->libs < GROUP_KEEP_LIBS) {
668 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
669 #if 0
670 /* Seems extra branch just slows it down */
671 if (!gi->lib[i])
672 break;
673 #endif
674 if (unlikely(gi->lib[i] == coord))
675 return;
677 if (gi->libs == 0)
678 board_capturable_add(board, group, coord);
679 else if (gi->libs == 1)
680 board_capturable_rm(board, group, gi->lib[0]);
681 gi->lib[gi->libs++] = coord;
684 check_libs_consistency(board, group);
687 static void
688 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
690 /* Add extra liberty from the board to our liberty list. */
691 unsigned char watermark[board_size2(board) / 8];
692 memset(watermark, 0, sizeof(watermark));
693 #define watermark_get(c) (watermark[coord_raw(c) >> 3] & (1 << (coord_raw(c) & 7)))
694 #define watermark_set(c) watermark[coord_raw(c) >> 3] |= (1 << (coord_raw(c) & 7))
696 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
697 watermark_set(gi->lib[i]);
698 watermark_set(avoid);
700 foreach_in_group(board, group) {
701 coord_t coord2 = c;
702 foreach_neighbor(board, coord2, {
703 if (board_at(board, c) + watermark_get(c) != S_NONE)
704 continue;
705 watermark_set(c);
706 gi->lib[gi->libs++] = c;
707 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
708 return;
709 } );
710 } foreach_in_group_end;
711 #undef watermark_get
712 #undef watermark_set
715 static void
716 board_group_rmlib(struct board *board, group_t group, coord_t coord)
718 if (DEBUGL(7)) {
719 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
720 group_base(group), coord2sstr(group_base(group), board),
721 board_group_info(board, group).libs, coord2sstr(coord, board));
724 struct group *gi = &board_group_info(board, group);
725 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
726 #if 0
727 /* Seems extra branch just slows it down */
728 if (!gi->lib[i])
729 break;
730 #endif
731 if (likely(gi->lib[i] != coord))
732 continue;
734 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
735 gi->lib[gi->libs] = 0;
737 check_libs_consistency(board, group);
739 /* Postpone refilling lib[] until we need to. */
740 assert(GROUP_REFILL_LIBS > 1);
741 if (gi->libs > GROUP_REFILL_LIBS)
742 return;
743 if (gi->libs == GROUP_REFILL_LIBS)
744 board_group_find_extra_libs(board, group, gi, coord);
746 if (gi->libs == 1)
747 board_capturable_add(board, group, gi->lib[0]);
748 else if (gi->libs == 0)
749 board_capturable_rm(board, group, lib);
750 return;
753 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
754 * can call this multiple times per coord. */
755 check_libs_consistency(board, group);
756 return;
760 /* This is a low-level routine that doesn't maintain consistency
761 * of all the board data structures. */
762 static void
763 board_remove_stone(struct board *board, group_t group, coord_t c)
765 enum stone color = board_at(board, c);
766 board_at(board, c) = S_NONE;
767 group_at(board, c) = 0;
768 board_hash_update(board, c, color);
769 #ifdef BOARD_TRAITS
770 /* We mark as cannot-capture now. If this is a ko/snapback,
771 * we will get incremented later in board_group_addlib(). */
772 trait_at(board, c, S_BLACK).cap = 0;
773 trait_at(board, c, S_WHITE).cap = 0;
774 /* However, we do decide safety statically; we might get
775 * over-paranoid, but in that case the neighbor loop for
776 * stones removed next will repair the flag. */
777 /* We must do this update after the loop when our neighbor count is correct. */
778 board_trait_recompute(board, c);
779 #endif
781 /* Increase liberties of surrounding groups */
782 coord_t coord = c;
783 foreach_neighbor(board, coord, {
784 dec_neighbor_count_at(board, c, color);
785 board_trait_recompute(board, c);
786 group_t g = group_at(board, c);
787 if (g && g != group)
788 board_group_addlib(board, g, coord);
791 if (DEBUGL(6))
792 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
793 board->f[board->flen++] = coord_raw(c);
796 static int profiling_noinline
797 board_group_capture(struct board *board, group_t group)
799 int stones = 0;
801 foreach_in_group(board, group) {
802 board->captures[stone_other(board_at(board, c))]++;
803 board_remove_stone(board, group, c);
804 stones++;
805 } foreach_in_group_end;
807 if (board_group_info(board, group).libs == 1)
808 board_capturable_rm(board, group, board_group_info(board, group).lib[0]);
809 memset(&board_group_info(board, group), 0, sizeof(struct group));
811 return stones;
815 static void profiling_noinline
816 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
818 group_at(board, coord) = group;
819 groupnext_at(board, coord) = groupnext_at(board, prevstone);
820 groupnext_at(board, prevstone) = coord_raw(coord);
822 #ifdef BOARD_TRAITS
823 if (board_group_info(board, group).libs == 1) {
824 /* Our group is temporarily in atari; make sure the capturable
825 * counts also correspond to the newly added stone before we
826 * start adding liberties again so bump-dump ops match. */
827 enum stone capturing_color = stone_other(board_at(board, group));
828 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
829 coord_t lib = board_group_info(board, group).lib[0];
830 if (coord_is_adjecent(lib, coord, board)) {
831 if (DEBUGL(8)) fprintf(stderr, "add_to_group %s: %s[%d] bump\n", coord2sstr(group, board), coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
832 trait_at(board, lib, capturing_color).cap++;
833 board_trait_recompute(board, lib);
836 #endif
838 foreach_neighbor(board, coord, {
839 if (board_at(board, c) == S_NONE)
840 board_group_addlib(board, group, c);
843 if (DEBUGL(8))
844 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
845 coord_x(prevstone, board), coord_y(prevstone, board),
846 coord_x(coord, board), coord_y(coord, board),
847 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
848 group_base(group));
851 static void profiling_noinline
852 merge_groups(struct board *board, group_t group_to, group_t group_from)
854 if (DEBUGL(7))
855 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
856 group_base(group_from), group_base(group_to));
857 struct group *gi_from = &board_group_info(board, group_from);
858 struct group *gi_to = &board_group_info(board, group_to);
860 /* We do this early before the group info is rewritten. */
861 if (gi_from->libs == 1)
862 board_capturable_rm(board, group_from, gi_from->lib[0]);
864 if (DEBUGL(7))
865 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
867 if (gi_to->libs < GROUP_KEEP_LIBS) {
868 for (int i = 0; i < gi_from->libs; i++) {
869 for (int j = 0; j < gi_to->libs; j++)
870 if (gi_to->lib[j] == gi_from->lib[i])
871 goto next_from_lib;
872 if (gi_to->libs == 0)
873 board_capturable_add(board, group_to, gi_from->lib[i]);
874 else if (gi_to->libs == 1)
875 board_capturable_rm(board, group_to, gi_to->lib[0]);
876 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
877 if (gi_to->libs >= GROUP_KEEP_LIBS)
878 break;
879 next_from_lib:;
883 #ifdef BOARD_TRAITS
884 if (board_group_info(board, group_to).libs == 1) {
885 /* Our group is currently in atari; make sure we properly
886 * count in even the neighbors from the other group in the
887 * capturable counter. */
888 enum stone capturing_color = stone_other(board_at(board, group_to));
889 assert(capturing_color == S_BLACK || capturing_color == S_WHITE);
890 coord_t lib = board_group_info(board, group_to).lib[0];
891 foreach_neighbor(board, lib, {
892 if (DEBUGL(8) && group_at(board, c) == group_from) fprintf(stderr, "%s[%d] cap bump\n", coord2sstr(lib, board), trait_at(board, lib, capturing_color).cap);
893 trait_at(board, lib, capturing_color).cap += (group_at(board, c) == group_from);
895 board_trait_recompute(board, lib);
897 #endif
899 coord_t last_in_group;
900 foreach_in_group(board, group_from) {
901 last_in_group = c;
902 group_at(board, c) = group_to;
903 } foreach_in_group_end;
904 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
905 groupnext_at(board, group_base(group_to)) = group_base(group_from);
906 memset(gi_from, 0, sizeof(struct group));
908 if (DEBUGL(7))
909 fprintf(stderr, "board_play_raw: merged group: %d\n",
910 group_base(group_to));
913 static group_t profiling_noinline
914 new_group(struct board *board, coord_t coord)
916 group_t group = coord_raw(coord);
917 struct group *gi = &board_group_info(board, group);
918 foreach_neighbor(board, coord, {
919 if (board_at(board, c) == S_NONE)
920 /* board_group_addlib is ridiculously expensive for us */
921 #if GROUP_KEEP_LIBS < 4
922 if (gi->libs < GROUP_KEEP_LIBS)
923 #endif
924 gi->lib[gi->libs++] = c;
927 group_at(board, coord) = group;
928 groupnext_at(board, coord) = 0;
930 if (gi->libs == 1)
931 board_capturable_add(board, group, gi->lib[0]);
932 check_libs_consistency(board, group);
934 if (DEBUGL(8))
935 fprintf(stderr, "new_group: added %d,%d to group %d\n",
936 coord_x(coord, board), coord_y(coord, board),
937 group_base(group));
939 return group;
942 static inline group_t
943 play_one_neighbor(struct board *board,
944 coord_t coord, enum stone color, enum stone other_color,
945 coord_t c, group_t group)
947 enum stone ncolor = board_at(board, c);
948 group_t ngroup = group_at(board, c);
950 inc_neighbor_count_at(board, c, color);
951 /* We can be S_NONE, in that case we need to update the safety
952 * trait since we might be left with only one liberty. */
953 board_trait_recompute(board, c);
955 if (!ngroup)
956 return group;
958 board_group_rmlib(board, ngroup, coord);
959 if (DEBUGL(7))
960 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
961 group_base(ngroup), ncolor, color, other_color);
963 if (ncolor == color && ngroup != group) {
964 if (!group) {
965 group = ngroup;
966 add_to_group(board, group, c, coord);
967 } else {
968 merge_groups(board, group, ngroup);
970 } else if (ncolor == other_color) {
971 if (DEBUGL(8)) {
972 struct group *gi = &board_group_info(board, ngroup);
973 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
974 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
975 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
976 fprintf(stderr, "\n");
978 if (unlikely(board_group_captured(board, ngroup)))
979 board_group_capture(board, ngroup);
981 return group;
984 /* We played on a place with at least one liberty. We will become a member of
985 * some group for sure. */
986 static group_t profiling_noinline
987 board_play_outside(struct board *board, struct move *m, int f)
989 coord_t coord = m->coord;
990 enum stone color = m->color;
991 enum stone other_color = stone_other(color);
992 group_t group = 0;
994 board->f[f] = board->f[--board->flen];
995 if (DEBUGL(6))
996 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
998 #if defined(BOARD_TRAITS) && !defined(NDEBUG)
999 /* Sanity check that cap matches reality. */
1001 int a = 0;
1002 foreach_neighbor(board, coord, {
1003 group_t g = group_at(board, c);
1004 a += g && (board_at(board, c) == other_color && board_group_info(board, g).libs == 1);
1006 assert(a == trait_at(board, coord, color).cap);
1007 assert(board_safe_to_play(board, coord, color) == trait_at(board, coord, color).safe);
1009 #endif
1010 foreach_neighbor(board, coord, {
1011 group = play_one_neighbor(board, coord, color, other_color, c, group);
1014 board_at(board, coord) = color;
1015 if (unlikely(!group))
1016 group = new_group(board, coord);
1018 board->last_move2 = board->last_move;
1019 board->last_move = *m;
1020 board->moves++;
1021 board_hash_update(board, coord, color);
1022 board_symmetry_update(board, &board->symmetry, coord);
1023 struct move ko = { pass, S_NONE };
1024 board->ko = ko;
1026 return group;
1029 /* We played in an eye-like shape. Either we capture at least one of the eye
1030 * sides in the process of playing, or return -1. */
1031 static int profiling_noinline
1032 board_play_in_eye(struct board *board, struct move *m, int f)
1034 coord_t coord = m->coord;
1035 enum stone color = m->color;
1036 /* Check ko: Capture at a position of ko capture one move ago */
1037 if (unlikely(color == board->ko.color && coord_eq(coord, board->ko.coord))) {
1038 if (DEBUGL(5))
1039 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
1040 return -1;
1041 } else if (DEBUGL(6)) {
1042 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
1043 color, coord_x(coord, board), coord_y(coord, board),
1044 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1047 struct move ko = { pass, S_NONE };
1049 int captured_groups = 0;
1051 foreach_neighbor(board, coord, {
1052 group_t g = group_at(board, c);
1053 if (DEBUGL(7))
1054 fprintf(stderr, "board_check: group %d has %d libs\n",
1055 g, board_group_info(board, g).libs);
1056 captured_groups += (board_group_info(board, g).libs == 1);
1059 if (likely(captured_groups == 0)) {
1060 if (DEBUGL(5)) {
1061 if (DEBUGL(6))
1062 board_print(board, stderr);
1063 fprintf(stderr, "board_check: one-stone suicide\n");
1066 return -1;
1068 #ifdef BOARD_TRAITS
1069 /* We _will_ for sure capture something. */
1070 assert(trait_at(board, coord, color).cap > 0);
1071 assert(trait_at(board, coord, color).safe == board_safe_to_play(board, coord, color));
1072 #endif
1074 board->f[f] = board->f[--board->flen];
1075 if (DEBUGL(6))
1076 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1078 foreach_neighbor(board, coord, {
1079 inc_neighbor_count_at(board, c, color);
1080 /* Originally, this could not have changed any trait
1081 * since no neighbors were S_NONE, however by now some
1082 * of them might be removed from the board. */
1083 board_trait_recompute(board, c);
1085 group_t group = group_at(board, c);
1086 if (!group)
1087 continue;
1089 board_group_rmlib(board, group, coord);
1090 if (DEBUGL(7))
1091 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1092 group_base(group));
1094 if (board_group_captured(board, group)) {
1095 if (board_group_capture(board, group) == 1) {
1096 /* If we captured multiple groups at once,
1097 * we can't be fighting ko so we don't need
1098 * to check for that. */
1099 ko.color = stone_other(color);
1100 ko.coord = c;
1101 board->last_ko = ko;
1102 board->last_ko_age = board->moves;
1103 if (DEBUGL(5))
1104 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1109 board_at(board, coord) = color;
1110 group_t group = new_group(board, coord);
1112 board->last_move2 = board->last_move;
1113 board->last_move = *m;
1114 board->moves++;
1115 board_hash_update(board, coord, color);
1116 board_hash_commit(board);
1117 board_symmetry_update(board, &board->symmetry, coord);
1118 board->ko = ko;
1120 return !!group;
1123 static int __attribute__((flatten))
1124 board_play_f(struct board *board, struct move *m, int f)
1126 if (DEBUGL(7)) {
1127 fprintf(stderr, "board_play(): ---- Playing %d,%d\n", coord_x(m->coord, board), coord_y(m->coord, board));
1129 if (likely(!board_is_eyelike(board, &m->coord, stone_other(m->color)))) {
1130 /* NOT playing in an eye. Thus this move has to succeed. (This
1131 * is thanks to New Zealand rules. Otherwise, multi-stone
1132 * suicide might fail.) */
1133 group_t group = board_play_outside(board, m, f);
1134 if (unlikely(board_group_captured(board, group))) {
1135 board_group_capture(board, group);
1137 board_hash_commit(board);
1138 return 0;
1139 } else {
1140 return board_play_in_eye(board, m, f);
1145 board_play(struct board *board, struct move *m)
1147 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1148 board->last_move2 = board->last_move;
1149 board->last_move = *m;
1150 return 0;
1153 int f;
1154 for (f = 0; f < board->flen; f++)
1155 if (board->f[f] == coord_raw(m->coord))
1156 return board_play_f(board, m, f);
1158 if (DEBUGL(7))
1159 fprintf(stderr, "board_check: stone exists\n");
1160 return -1;
1164 static inline bool
1165 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1167 coord_raw(*coord) = b->f[f];
1168 if (unlikely(is_pass(*coord)))
1169 return random_pass;
1170 struct move m = { *coord, color };
1171 if (DEBUGL(6))
1172 fprintf(stderr, "trying random move %d: %d,%d\n", f, coord_x(*coord, b), coord_y(*coord, b));
1173 return (likely(!board_is_one_point_eye(b, coord, color)) /* bad idea to play into one, usually */
1174 && board_is_valid_move(b, &m)
1175 && (!permit || permit(permit_data, b, &m))
1176 && likely(board_play_f(b, &m, f) >= 0));
1179 void
1180 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1182 int base = fast_random(b->flen);
1183 coord_pos(*coord, base, b);
1184 if (likely(board_try_random_move(b, color, coord, base, permit, permit_data)))
1185 return;
1187 int f;
1188 for (f = base + 1; f < b->flen; f++)
1189 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1190 return;
1191 for (f = 0; f < base; f++)
1192 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1193 return;
1195 *coord = pass;
1199 bool
1200 board_is_false_eyelike(struct board *board, coord_t *coord, enum stone eye_color)
1202 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1204 /* XXX: We attempt false eye detection but we will yield false
1205 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1207 foreach_diag_neighbor(board, *coord) {
1208 color_diag_libs[(enum stone) board_at(board, c)]++;
1209 } foreach_diag_neighbor_end;
1210 /* For false eye, we need two enemy stones diagonally in the
1211 * middle of the board, or just one enemy stone at the edge
1212 * or in the corner. */
1213 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1214 return color_diag_libs[stone_other(eye_color)] >= 2;
1217 bool
1218 board_is_one_point_eye(struct board *board, coord_t *coord, enum stone eye_color)
1220 return board_is_eyelike(board, coord, eye_color)
1221 && !board_is_false_eyelike(board, coord, eye_color);
1224 enum stone
1225 board_get_one_point_eye(struct board *board, coord_t *coord)
1227 if (board_is_one_point_eye(board, coord, S_WHITE))
1228 return S_WHITE;
1229 else if (board_is_one_point_eye(board, coord, S_BLACK))
1230 return S_BLACK;
1231 else
1232 return S_NONE;
1236 float
1237 board_fast_score(struct board *board)
1239 int scores[S_MAX];
1240 memset(scores, 0, sizeof(scores));
1242 foreach_point(board) {
1243 enum stone color = board_at(board, c);
1244 if (color == S_NONE)
1245 color = board_get_one_point_eye(board, &c);
1246 scores[color]++;
1247 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1248 } foreach_point_end;
1250 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1253 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1255 /* One flood-fill iteration; returns true if next iteration
1256 * is required. */
1257 static bool
1258 board_tromp_taylor_iter(struct board *board, int *ownermap)
1260 bool needs_update = false;
1261 foreach_point(board) {
1262 /* Ignore occupied and already-dame positions. */
1263 if (board_at(board, c) != S_NONE || ownermap[c] == 3)
1264 continue;
1265 /* Count neighbors. */
1266 int nei[4] = {0};
1267 foreach_neighbor(board, c, {
1268 nei[ownermap[c]]++;
1270 /* If we have neighbors of both colors, or dame,
1271 * we are dame too. */
1272 if ((nei[1] && nei[2]) || nei[3]) {
1273 ownermap[c] = 3;
1274 /* Speed up the propagation. */
1275 foreach_neighbor(board, c, {
1276 if (board_at(board, c) == S_NONE)
1277 ownermap[c] = 3;
1279 needs_update = true;
1280 continue;
1282 /* If we have neighbors of one color, we are owned
1283 * by that color, too. */
1284 if (!ownermap[c] && (nei[1] || nei[2])) {
1285 int newowner = nei[1] ? 1 : 2;
1286 ownermap[c] = newowner;
1287 /* Speed up the propagation. */
1288 foreach_neighbor(board, c, {
1289 if (board_at(board, c) == S_NONE && !ownermap[c])
1290 ownermap[c] = newowner;
1292 needs_update = true;
1293 continue;
1295 } foreach_point_end;
1296 return needs_update;
1299 /* Tromp-Taylor Counting */
1300 float
1301 board_official_score(struct board *board, struct move_queue *q)
1304 /* A point P, not colored C, is said to reach C, if there is a path of
1305 * (vertically or horizontally) adjacent points of P's color from P to
1306 * a point of color C.
1308 * A player's score is the number of points of her color, plus the
1309 * number of empty points that reach only her color. */
1311 int ownermap[board_size2(board)];
1312 int s[4] = {0};
1313 const int o[4] = {0, 1, 2, 0};
1314 foreach_point(board) {
1315 ownermap[c] = o[board_at(board, c)];
1316 s[board_at(board, c)]++;
1317 } foreach_point_end;
1319 if (q) {
1320 /* Process dead groups. */
1321 for (int i = 0; i < q->moves; i++) {
1322 foreach_in_group(board, q->move[i]) {
1323 enum stone color = board_at(board, c);
1324 ownermap[c] = o[stone_other(color)];
1325 s[color]--; s[stone_other(color)]++;
1326 } foreach_in_group_end;
1330 /* We need to special-case empty board. */
1331 if (!s[S_BLACK] && !s[S_WHITE])
1332 return board->komi + board->handicap;
1334 while (board_tromp_taylor_iter(board, ownermap))
1335 /* Flood-fill... */;
1337 int scores[S_MAX];
1338 memset(scores, 0, sizeof(scores));
1340 foreach_point(board) {
1341 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1342 if (ownermap[c] == 3)
1343 continue;
1344 scores[ownermap[c]]++;
1345 } foreach_point_end;
1347 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];