-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.c
3359 lines (2960 loc) · 98.9 KB
/
net.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* net.c: Net game.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#ifdef NO_TGMATH_H
# include <math.h>
#else
# include <tgmath.h>
#endif
#include "puzzles.h"
#include "tree234.h"
/*
* The standard user interface for Net simply has left- and
* right-button mouse clicks in a square rotate it one way or the
* other. We also provide, by #ifdef, a separate interface based on
* rotational dragging motions. I initially developed this for the
* Mac on the basis that it might work better than the click
* interface with only one mouse button available, but in fact
* found it to be quite strange and unintuitive. Apparently it
* works better on stylus-driven platforms such as Palm and
* PocketPC, though, so we enable it by default there.
*/
#ifdef STYLUS_BASED
#define USE_DRAGGING
#endif
/* Direction and other bitfields */
#define R 0x01
#define U 0x02
#define L 0x04
#define D 0x08
#define LOCKED 0x10
#define ACTIVE 0x20
#define RERR (R << 6)
#define UERR (U << 6)
#define LERR (L << 6)
#define DERR (D << 6)
#define ERR(dir) ((dir) << 6)
/* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
#define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
#define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
#define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
#define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
((n)&3) == 1 ? A(x) : \
((n)&3) == 2 ? F(x) : C(x) )
/* X and Y displacements */
#define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
#define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
/* Bit count */
#define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
(((x) & 0x02) >> 1) + ((x) & 0x01) )
#define PREFERRED_TILE_SIZE 32
#define TILE_SIZE (ds->tilesize)
#define LINE_THICK ((TILE_SIZE+47)/48)
#ifdef SMALL_SCREEN
#define WINDOW_OFFSET 4
#else
#define WINDOW_OFFSET 16
#endif
#define ROTATE_TIME 0.13F
#define FLASH_FRAME 0.07F
enum {
COL_BACKGROUND,
COL_LOCKED,
COL_BORDER,
COL_WIRE,
COL_ENDPOINT,
COL_POWERED,
COL_BARRIER,
COL_ERR,
NCOLOURS
};
struct game_params {
int width;
int height;
bool wrapping;
bool unique;
float barrier_probability;
};
typedef struct game_immutable_state {
int refcount;
unsigned char *barriers;
} game_immutable_state;
struct game_state {
int width, height;
bool wrapping, completed;
int last_rotate_x, last_rotate_y, last_rotate_dir;
bool used_solve;
unsigned char *tiles;
struct game_immutable_state *imm;
};
#define OFFSETWH(x2,y2,x1,y1,dir,width,height) \
( (x2) = ((x1) + width + X((dir))) % width, \
(y2) = ((y1) + height + Y((dir))) % height)
#define OFFSET(x2,y2,x1,y1,dir,state) \
OFFSETWH(x2,y2,x1,y1,dir,(state)->width,(state)->height)
#define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
#define tile(state, x, y) index(state, (state)->tiles, x, y)
#define barrier(state, x, y) index(state, (state)->imm->barriers, x, y)
struct xyd {
int x, y, direction;
};
static int xyd_cmp(const void *av, const void *bv) {
const struct xyd *a = (const struct xyd *)av;
const struct xyd *b = (const struct xyd *)bv;
if (a->x < b->x)
return -1;
if (a->x > b->x)
return +1;
if (a->y < b->y)
return -1;
if (a->y > b->y)
return +1;
if (a->direction < b->direction)
return -1;
if (a->direction > b->direction)
return +1;
return 0;
}
static int xyd_cmp_nc(void *av, void *bv) { return xyd_cmp(av, bv); }
static struct xyd *new_xyd(int x, int y, int direction)
{
struct xyd *xyd = snew(struct xyd);
xyd->x = x;
xyd->y = y;
xyd->direction = direction;
return xyd;
}
/* ----------------------------------------------------------------------
* Manage game parameters.
*/
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->width = 5;
ret->height = 5;
ret->wrapping = false;
ret->unique = true;
ret->barrier_probability = 0.0;
return ret;
}
static const struct game_params net_presets[] = {
{5, 5, false, true, 0.0},
{7, 7, false, true, 0.0},
{9, 9, false, true, 0.0},
{11, 11, false, true, 0.0},
#ifndef SMALL_SCREEN
{13, 11, false, true, 0.0},
#endif
{5, 5, true, true, 0.0},
{7, 7, true, true, 0.0},
{9, 9, true, true, 0.0},
{11, 11, true, true, 0.0},
#ifndef SMALL_SCREEN
{13, 11, true, true, 0.0},
#endif
};
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char str[80];
if (i < 0 || i >= lenof(net_presets))
return false;
ret = snew(game_params);
*ret = net_presets[i];
sprintf(str, "%dx%d%s", ret->width, ret->height,
ret->wrapping ? " wrapping" : "");
*name = dupstr(str);
*params = ret;
return true;
}
static void free_params(game_params *params)
{
sfree(params);
}
static game_params *dup_params(const game_params *params)
{
game_params *ret = snew(game_params);
*ret = *params; /* structure copy */
return ret;
}
static void decode_params(game_params *ret, char const *string)
{
char const *p = string;
ret->width = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
if (*p == 'x') {
p++;
ret->height = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
} else {
ret->height = ret->width;
}
while (*p) {
if (*p == 'w') {
p++;
ret->wrapping = true;
} else if (*p == 'b') {
p++;
ret->barrier_probability = (float)atof(p);
while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
} else if (*p == 'a') {
p++;
ret->unique = false;
} else
p++; /* skip any other gunk */
}
}
static char *encode_params(const game_params *params, bool full)
{
char ret[400];
int len;
len = sprintf(ret, "%dx%d", params->width, params->height);
if (params->wrapping)
ret[len++] = 'w';
if (full && params->barrier_probability)
len += sprintf(ret+len, "b%g", params->barrier_probability);
if (full && !params->unique)
ret[len++] = 'a';
assert(len < lenof(ret));
ret[len] = '\0';
return dupstr(ret);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(6, config_item);
ret[0].name = "Width";
ret[0].type = C_STRING;
sprintf(buf, "%d", params->width);
ret[0].u.string.sval = dupstr(buf);
ret[1].name = "Height";
ret[1].type = C_STRING;
sprintf(buf, "%d", params->height);
ret[1].u.string.sval = dupstr(buf);
ret[2].name = "Walls wrap around";
ret[2].type = C_BOOLEAN;
ret[2].u.boolean.bval = params->wrapping;
ret[3].name = "Barrier probability";
ret[3].type = C_STRING;
sprintf(buf, "%g", params->barrier_probability);
ret[3].u.string.sval = dupstr(buf);
ret[4].name = "Ensure unique solution";
ret[4].type = C_BOOLEAN;
ret[4].u.boolean.bval = params->unique;
ret[5].name = NULL;
ret[5].type = C_END;
return ret;
}
static game_params *custom_params(const config_item *cfg)
{
game_params *ret = snew(game_params);
ret->width = atoi(cfg[0].u.string.sval);
ret->height = atoi(cfg[1].u.string.sval);
ret->wrapping = cfg[2].u.boolean.bval;
ret->barrier_probability = (float)atof(cfg[3].u.string.sval);
ret->unique = cfg[4].u.boolean.bval;
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
if (params->width <= 0 || params->height <= 0)
return "Width and height must both be greater than zero";
if (params->width <= 1 && params->height <= 1)
return "At least one of width and height must be greater than one";
if (params->width > INT_MAX / params->height)
return "Width times height must not be unreasonably large";
if (params->barrier_probability < 0)
return "Barrier probability may not be negative";
if (params->barrier_probability > 1)
return "Barrier probability may not be greater than 1";
/*
* Specifying either grid dimension as 2 in a wrapping puzzle
* makes it actually impossible to ensure a unique puzzle
* solution.
*
* Proof:
*
* Without loss of generality, let us assume the puzzle _width_
* is 2, so we can conveniently discuss rows without having to
* say `rows/columns' all the time. (The height may be 2 as
* well, but that doesn't matter.)
*
* In each row, there are two edges between tiles: the inner
* edge (running down the centre of the grid) and the outer
* edge (the identified left and right edges of the grid).
*
* Lemma: In any valid 2xn puzzle there must be at least one
* row in which _exactly one_ of the inner edge and outer edge
* is connected.
*
* Proof: No row can have _both_ inner and outer edges
* connected, because this would yield a loop. So the only
* other way to falsify the lemma is for every row to have
* _neither_ the inner nor outer edge connected. But this
* means there is no connection at all between the left and
* right columns of the puzzle, so there are two disjoint
* subgraphs, which is also disallowed. []
*
* Given such a row, it is always possible to make the
* disconnected edge connected and the connected edge
* disconnected without changing the state of any other edge.
* (This is easily seen by case analysis on the various tiles:
* left-pointing and right-pointing endpoints can be exchanged,
* likewise T-pieces, and a corner piece can select its
* horizontal connectivity independently of its vertical.) This
* yields a distinct valid solution.
*
* Thus, for _every_ row in which exactly one of the inner and
* outer edge is connected, there are two valid states for that
* row, and hence the total number of solutions of the puzzle
* is at least 2^(number of such rows), and in particular is at
* least 2 since there must be at least one such row. []
*/
if (full && params->unique && params->wrapping &&
(params->width == 2 || params->height == 2))
return "No wrapping puzzle with a width or height of 2 can have"
" a unique solution";
return NULL;
}
/* ----------------------------------------------------------------------
* Solver used to assure solution uniqueness during generation.
*/
/*
* Test cases I used while debugging all this were
*
* ./net --generate 1 13x11w#12300
* which expands under the non-unique grid generation rules to
* 13x11w:5eaade1bd222664436d5e2965c12656b1129dd825219e3274d558d5eb2dab5da18898e571d5a2987be79746bd95726c597447d6da96188c513add829da7681da954db113d3cd244
* and has two ambiguous areas.
*
* An even better one is
* 13x11w#507896411361192
* which expands to
* 13x11w:b7125b1aec598eb31bd58d82572bc11494e5dee4e8db2bdd29b88d41a16bdd996d2996ddec8c83741a1e8674e78328ba71737b8894a9271b1cd1399453d1952e43951d9b712822e
* and has an ambiguous area _and_ a situation where loop avoidance
* is a necessary deductive technique.
*
* Then there's
* 48x25w#820543338195187
* becoming
* 48x25w:255989d14cdd185deaa753a93821a12edc1ab97943ac127e2685d7b8b3c48861b2192416139212b316eddd35de43714ebc7628d753db32e596284d9ec52c5a7dc1b4c811a655117d16dc28921b2b4161352cab1d89d18bc836b8b891d55ea4622a1251861b5bc9a8aa3e5bcd745c95229ca6c3b5e21d5832d397e917325793d7eb442dc351b2db2a52ba8e1651642275842d8871d5534aabc6d5b741aaa2d48ed2a7dbbb3151ddb49d5b9a7ed1ab98ee75d613d656dbba347bc514c84556b43a9bc65a3256ead792488b862a9d2a8a39b4255a4949ed7dbd79443292521265896b4399c95ede89d7c8c797a6a57791a849adea489359a158aa12e5dacce862b8333b7ebea7d344d1a3c53198864b73a9dedde7b663abb1b539e1e8853b1b7edb14a2a17ebaae4dbe63598a2e7e9a2dbdad415bc1d8cb88cbab5a8c82925732cd282e641ea3bd7d2c6e776de9117a26be86deb7c82c89524b122cb9397cd1acd2284e744ea62b9279bae85479ababe315c3ac29c431333395b24e6a1e3c43a2da42d4dce84aadd5b154aea555eaddcbd6e527d228c19388d9b424d94214555a7edbdeebe569d4a56dc51a86bd9963e377bb74752bd5eaa5761ba545e297b62a1bda46ab4aee423ad6c661311783cc18786d4289236563cb4a75ec67d481c14814994464cd1b87396dee63e5ab6e952cc584baa1d4c47cb557ec84dbb63d487c8728118673a166846dd3a4ebc23d6cb9c5827d96b4556e91899db32b517eda815ae271a8911bd745447121dc8d321557bc2a435ebec1bbac35b1a291669451174e6aa2218a4a9c5a6ca31ebc45d84e3a82c121e9ced7d55e9a
* which has a spot (far right) where slightly more complex loop
* avoidance is required.
*/
struct todo {
bool *marked;
int *buffer;
int buflen;
int head, tail;
};
static struct todo *todo_new(int maxsize)
{
struct todo *todo = snew(struct todo);
todo->marked = snewn(maxsize, bool);
memset(todo->marked, 0, maxsize);
todo->buflen = maxsize + 1;
todo->buffer = snewn(todo->buflen, int);
todo->head = todo->tail = 0;
return todo;
}
static void todo_free(struct todo *todo)
{
sfree(todo->marked);
sfree(todo->buffer);
sfree(todo);
}
static void todo_add(struct todo *todo, int index)
{
if (todo->marked[index])
return; /* already on the list */
todo->marked[index] = true;
todo->buffer[todo->tail++] = index;
if (todo->tail == todo->buflen)
todo->tail = 0;
}
static int todo_get(struct todo *todo) {
int ret;
if (todo->head == todo->tail)
return -1; /* list is empty */
ret = todo->buffer[todo->head++];
if (todo->head == todo->buflen)
todo->head = 0;
todo->marked[ret] = false;
return ret;
}
/*
* Return values: -1 means puzzle was proved inconsistent, 0 means we
* failed to narrow down to a unique solution, +1 means we solved it
* fully.
*/
static int net_solver(int w, int h, unsigned char *tiles,
unsigned char *barriers, bool wrapping)
{
unsigned char *tilestate;
unsigned char *edgestate;
int *deadends;
DSF *equivalence;
struct todo *todo;
int i, j, x, y;
int area;
bool done_something;
/*
* Set up the solver's data structures.
*/
/*
* tilestate stores the possible orientations of each tile.
* There are up to four of these, so we'll index the array in
* fours. tilestate[(y * w + x) * 4] and its three successive
* members give the possible orientations, clearing to 255 from
* the end as things are ruled out.
*
* In this loop we also count up the area of the grid (which is
* not _necessarily_ equal to w*h, because there might be one
* or more blank squares present. This will never happen in a
* grid generated _by_ this program, but it's worth keeping the
* solver as general as possible.)
*/
tilestate = snewn(w * h * 4, unsigned char);
area = 0;
for (i = 0; i < w*h; i++) {
tilestate[i * 4] = tiles[i] & 0xF;
for (j = 1; j < 4; j++) {
if (tilestate[i * 4 + j - 1] == 255 ||
A(tilestate[i * 4 + j - 1]) == tilestate[i * 4])
tilestate[i * 4 + j] = 255;
else
tilestate[i * 4 + j] = A(tilestate[i * 4 + j - 1]);
}
if (tiles[i] != 0)
area++;
}
/*
* edgestate stores the known state of each edge. It is 0 for
* unknown, 1 for open (connected) and 2 for closed (not
* connected).
*
* In principle we need only worry about each edge once each,
* but in fact it's easier to track each edge twice so that we
* can reference it from either side conveniently. Also I'm
* going to allocate _five_ bytes per tile, rather than the
* obvious four, so that I can index edgestate[(y*w+x) * 5 + d]
* where d is 1,2,4,8 and they never overlap.
*/
edgestate = snewn((w * h - 1) * 5 + 9, unsigned char);
memset(edgestate, 0, (w * h - 1) * 5 + 9);
/*
* deadends tracks which edges have dead ends on them. It is
* indexed by tile and direction: deadends[(y*w+x) * 5 + d]
* tells you whether heading out of tile (x,y) in direction d
* can reach a limited amount of the grid. Values are area+1
* (no dead end known) or less than that (can reach _at most_
* this many other tiles by heading this way out of this tile).
*/
deadends = snewn((w * h - 1) * 5 + 9, int);
for (i = 0; i < (w * h - 1) * 5 + 9; i++)
deadends[i] = area+1;
/*
* equivalence tracks which sets of tiles are known to be
* connected to one another, so we can avoid creating loops by
* linking together tiles which are already linked through
* another route.
*
* This is a disjoint set forest structure: equivalence[i]
* contains the index of another member of the equivalence
* class containing i, or contains i itself for precisely one
* member in each such class. To find a representative member
* of the equivalence class containing i, you keep replacing i
* with equivalence[i] until it stops changing; then you go
* _back_ along the same path and point everything on it
* directly at the representative member so as to speed up
* future searches. Then you test equivalence between tiles by
* finding the representative of each tile and seeing if
* they're the same; and you create new equivalence (merge
* classes) by finding the representative of each tile and
* setting equivalence[one]=the_other.
*/
equivalence = dsf_new(w * h);
/*
* On a non-wrapping grid, we instantly know that all the edges
* round the edge are closed.
*/
if (!wrapping) {
for (i = 0; i < w; i++) {
edgestate[i * 5 + 2] = edgestate[((h-1) * w + i) * 5 + 8] = 2;
}
for (i = 0; i < h; i++) {
edgestate[(i * w + w-1) * 5 + 1] = edgestate[(i * w) * 5 + 4] = 2;
}
}
/*
* If we have barriers available, we can mark those edges as
* closed too.
*/
if (barriers) {
for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
int d;
for (d = 1; d <= 8; d += d) {
if (barriers[y*w+x] & d) {
int x2, y2;
/*
* In principle the barrier list should already
* contain each barrier from each side, but
* let's not take chances with our internal
* consistency.
*/
OFFSETWH(x2, y2, x, y, d, w, h);
edgestate[(y*w+x) * 5 + d] = 2;
edgestate[(y2*w+x2) * 5 + F(d)] = 2;
}
}
}
}
/*
* Since most deductions made by this solver are local (the
* exception is loop avoidance, where joining two tiles
* together on one side of the grid can theoretically permit a
* fresh deduction on the other), we can address the scaling
* problem inherent in iterating repeatedly over the entire
* grid by instead working with a to-do list.
*/
todo = todo_new(w * h);
/*
* Main deductive loop.
*/
done_something = true; /* prevent instant termination! */
while (1) {
int index;
/*
* Take a tile index off the todo list and process it.
*/
index = todo_get(todo);
if (index == -1) {
/*
* If we have run out of immediate things to do, we
* have no choice but to scan the whole grid for
* longer-range things we've missed. Hence, I now add
* every square on the grid back on to the to-do list.
* I also set `done_something' to false at this point;
* if we later come back here and find it still false,
* we will know we've scanned the entire grid without
* finding anything new to do, and we can terminate.
*/
if (!done_something)
break;
for (i = 0; i < w*h; i++)
todo_add(todo, i);
done_something = false;
index = todo_get(todo);
}
y = index / w;
x = index % w;
{
int d, ourclass = dsf_canonify(equivalence, y*w+x);
int deadendmax[9];
deadendmax[1] = deadendmax[2] = deadendmax[4] = deadendmax[8] = 0;
for (i = j = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
bool valid;
int nnondeadends, nondeadends[4], deadendtotal;
int nequiv, equiv[5];
int val = tilestate[(y*w+x) * 4 + i];
valid = true;
nnondeadends = deadendtotal = 0;
equiv[0] = ourclass;
nequiv = 1;
for (d = 1; d <= 8; d += d) {
/*
* Immediately rule out this orientation if it
* conflicts with any known edge.
*/
if ((edgestate[(y*w+x) * 5 + d] == 1 && !(val & d)) ||
(edgestate[(y*w+x) * 5 + d] == 2 && (val & d)))
valid = false;
if (val & d) {
/*
* Count up the dead-end statistics.
*/
if (deadends[(y*w+x) * 5 + d] <= area) {
deadendtotal += deadends[(y*w+x) * 5 + d];
} else {
nondeadends[nnondeadends++] = d;
}
/*
* Ensure we aren't linking to any tiles,
* through edges not already known to be
* open, which create a loop.
*/
if (edgestate[(y*w+x) * 5 + d] == 0) {
int c, k, x2, y2;
OFFSETWH(x2, y2, x, y, d, w, h);
c = dsf_canonify(equivalence, y2*w+x2);
for (k = 0; k < nequiv; k++)
if (c == equiv[k])
break;
if (k == nequiv)
equiv[nequiv++] = c;
else
valid = false;
}
}
}
if (nnondeadends == 0) {
/*
* If this orientation links together dead-ends
* with a total area of less than the entire
* grid, it is invalid.
*
* (We add 1 to deadendtotal because of the
* tile itself, of course; one tile linking
* dead ends of size 2 and 3 forms a subnetwork
* with a total area of 6, not 5.)
*/
if (deadendtotal > 0 && deadendtotal+1 < area)
valid = false;
} else if (nnondeadends == 1) {
/*
* If this orientation links together one or
* more dead-ends with precisely one
* non-dead-end, then we may have to mark that
* non-dead-end as a dead end going the other
* way. However, it depends on whether all
* other orientations share the same property.
*/
deadendtotal++;
if (deadendmax[nondeadends[0]] < deadendtotal)
deadendmax[nondeadends[0]] = deadendtotal;
} else {
/*
* If this orientation links together two or
* more non-dead-ends, then we can rule out the
* possibility of putting in new dead-end
* markings in those directions.
*/
int k;
for (k = 0; k < nnondeadends; k++)
deadendmax[nondeadends[k]] = area+1;
}
if (valid)
tilestate[(y*w+x) * 4 + j++] = val;
#ifdef SOLVER_DIAGNOSTICS
else
printf("ruling out orientation %x at %d,%d\n", val, x, y);
#endif
}
if (j == 0) {
/* If we've ruled out all possible orientations for a
* tile, then our puzzle has no solution at all. */
return -1;
}
if (j < i) {
done_something = true;
/*
* We have ruled out at least one tile orientation.
* Make sure the rest are blanked.
*/
while (j < 4)
tilestate[(y*w+x) * 4 + j++] = 255;
}
/*
* Now go through the tile orientations again and see
* if we've deduced anything new about any edges.
*/
{
int a, o;
a = 0xF; o = 0;
for (i = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
a &= tilestate[(y*w+x) * 4 + i];
o |= tilestate[(y*w+x) * 4 + i];
}
for (d = 1; d <= 8; d += d)
if (edgestate[(y*w+x) * 5 + d] == 0) {
int x2, y2, d2;
OFFSETWH(x2, y2, x, y, d, w, h);
d2 = F(d);
if (a & d) {
/* This edge is open in all orientations. */
#ifdef SOLVER_DIAGNOSTICS
printf("marking edge %d,%d:%d open\n", x, y, d);
#endif
edgestate[(y*w+x) * 5 + d] = 1;
edgestate[(y2*w+x2) * 5 + d2] = 1;
dsf_merge(equivalence, y*w+x, y2*w+x2);
done_something = true;
todo_add(todo, y2*w+x2);
} else if (!(o & d)) {
/* This edge is closed in all orientations. */
#ifdef SOLVER_DIAGNOSTICS
printf("marking edge %d,%d:%d closed\n", x, y, d);
#endif
edgestate[(y*w+x) * 5 + d] = 2;
edgestate[(y2*w+x2) * 5 + d2] = 2;
done_something = true;
todo_add(todo, y2*w+x2);
}
}
}
/*
* Now check the dead-end markers and see if any of
* them has lowered from the real ones.
*/
for (d = 1; d <= 8; d += d) {
int x2, y2, d2;
OFFSETWH(x2, y2, x, y, d, w, h);
d2 = F(d);
if (deadendmax[d] > 0 &&
deadends[(y2*w+x2) * 5 + d2] > deadendmax[d]) {
#ifdef SOLVER_DIAGNOSTICS
printf("setting dead end value %d,%d:%d to %d\n",
x2, y2, d2, deadendmax[d]);
#endif
deadends[(y2*w+x2) * 5 + d2] = deadendmax[d];
done_something = true;
todo_add(todo, y2*w+x2);
}
}
}
}
/*
* Mark all completely determined tiles as locked.
*/
j = +1;
for (i = 0; i < w*h; i++) {
if (tilestate[i * 4 + 1] == 255) {
assert(tilestate[i * 4 + 0] != 255);
tiles[i] = tilestate[i * 4] | LOCKED;
} else {
tiles[i] &= ~LOCKED;
j = 0;
}
}
/*
* Free up working space.
*/
todo_free(todo);
sfree(tilestate);
sfree(edgestate);
sfree(deadends);
dsf_free(equivalence);
return j;
}
/* ----------------------------------------------------------------------
* Randomly select a new game description.
*/
/*
* Function to randomly perturb an ambiguous section in a grid, to
* attempt to ensure unique solvability.
*/
static void perturb(int w, int h, unsigned char *tiles, bool wrapping,
random_state *rs, int startx, int starty, int startd)
{
struct xyd *perimeter, *perim2, *loop[2], looppos[2];
int nperim, perimsize, nloop[2], loopsize[2];
int x, y, d, i;
/*
* We know that the tile at (startx,starty) is part of an
* ambiguous section, and we also know that its neighbour in
* direction startd is fully specified. We begin by tracing all
* the way round the ambiguous area.
*/
nperim = perimsize = 0;
perimeter = NULL;
x = startx;
y = starty;
d = startd;
#ifdef PERTURB_DIAGNOSTICS
printf("perturb %d,%d:%d\n", x, y, d);
#endif
do {
int x2, y2, d2;
if (nperim >= perimsize) {
perimsize = perimsize * 3 / 2 + 32;
perimeter = sresize(perimeter, perimsize, struct xyd);
}
perimeter[nperim].x = x;
perimeter[nperim].y = y;
perimeter[nperim].direction = d;
nperim++;
#ifdef PERTURB_DIAGNOSTICS
printf("perimeter: %d,%d:%d\n", x, y, d);
#endif
/*
* First, see if we can simply turn left from where we are
* and find another locked square.
*/
d2 = A(d);
OFFSETWH(x2, y2, x, y, d2, w, h);
if ((!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1)) ||
(tiles[y2*w+x2] & LOCKED)) {
d = d2;
} else {
/*
* Failing that, step left into the new square and look
* in front of us.
*/
x = x2;
y = y2;
OFFSETWH(x2, y2, x, y, d, w, h);
if ((wrapping || (abs(x2-x) <= 1 && abs(y2-y) <= 1)) &&
!(tiles[y2*w+x2] & LOCKED)) {
/*
* And failing _that_, we're going to have to step
* forward into _that_ square and look right at the
* same locked square as we started with.
*/
x = x2;
y = y2;
d = C(d);
}
}
} while (x != startx || y != starty || d != startd);
/*
* Our technique for perturbing this ambiguous area is to
* search round its edge for a join we can make: that is, an
* edge on the perimeter which is (a) not currently connected,
* and (b) connecting it would not yield a full cross on either
* side. Then we make that join, search round the network to
* find the loop thus constructed, and sever the loop at a
* randomly selected other point.
*/
perim2 = snewn(nperim, struct xyd);
memcpy(perim2, perimeter, nperim * sizeof(struct xyd));
/* Shuffle the perimeter, so as to search it without directional bias. */
shuffle(perim2, nperim, sizeof(*perim2), rs);
for (i = 0; i < nperim; i++) {
int x2, y2;
x = perim2[i].x;
y = perim2[i].y;
d = perim2[i].direction;
OFFSETWH(x2, y2, x, y, d, w, h);
if (!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1))
continue; /* can't link across non-wrapping border */
if (tiles[y*w+x] & d)
continue; /* already linked in this direction! */
if (((tiles[y*w+x] | d) & 15) == 15)
continue; /* can't turn this tile into a cross */
if (((tiles[y2*w+x2] | F(d)) & 15) == 15)
continue; /* can't turn other tile into a cross */
/*
* We've found the point at which we're going to make a new
* link.
*/
#ifdef PERTURB_DIAGNOSTICS
printf("linking %d,%d:%d\n", x, y, d);
#endif
tiles[y*w+x] |= d;
tiles[y2*w+x2] |= F(d);
break;
}
sfree(perim2);
if (i == nperim) {
sfree(perimeter);
return; /* nothing we can do! */
}
/*
* Now we've constructed a new link, we need to find the entire
* loop of which it is a part.
*
* In principle, this involves doing a complete search round
* the network. However, I anticipate that in the vast majority
* of cases the loop will be quite small, so what I'm going to
* do is make _two_ searches round the network in parallel, one
* keeping its metaphorical hand on the left-hand wall while
* the other keeps its hand on the right. As soon as one of
* them gets back to its starting point, I abandon the other.
*/
for (i = 0; i < 2; i++) {
loopsize[i] = nloop[i] = 0;
loop[i] = NULL;
looppos[i].x = x;
looppos[i].y = y;
looppos[i].direction = d;
}
while (1) {
for (i = 0; i < 2; i++) {
int x2, y2, j;
x = looppos[i].x;
y = looppos[i].y;
d = looppos[i].direction;
OFFSETWH(x2, y2, x, y, d, w, h);
/*
* Add this path segment to the loop, unless it exactly
* reverses the previous one on the loop in which case
* we take it away again.
*/
#ifdef PERTURB_DIAGNOSTICS
printf("looppos[%d] = %d,%d:%d\n", i, x, y, d);