chiark / gitweb /
Another tweak to the solver to make it handle blank tiles correctly.
[sgt-puzzles.git] / net.c
1 /*
2  * net.c: Net game.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <ctype.h>
10 #include <math.h>
11
12 #include "puzzles.h"
13 #include "tree234.h"
14
15 #define PI 3.141592653589793238462643383279502884197169399
16
17 #define MATMUL(xr,yr,m,x,y) do { \
18     float rx, ry, xx = (x), yy = (y), *mat = (m); \
19     rx = mat[0] * xx + mat[2] * yy; \
20     ry = mat[1] * xx + mat[3] * yy; \
21     (xr) = rx; (yr) = ry; \
22 } while (0)
23
24 /* Direction and other bitfields */
25 #define R 0x01
26 #define U 0x02
27 #define L 0x04
28 #define D 0x08
29 #define LOCKED 0x10
30 #define ACTIVE 0x20
31 /* Corner flags go in the barriers array */
32 #define RU 0x10
33 #define UL 0x20
34 #define LD 0x40
35 #define DR 0x80
36
37 /* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
38 #define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
39 #define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
40 #define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
41 #define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
42                     ((n)&3) == 1 ? A(x) : \
43                     ((n)&3) == 2 ? F(x) : C(x) )
44
45 /* X and Y displacements */
46 #define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
47 #define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
48
49 /* Bit count */
50 #define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
51                    (((x) & 0x02) >> 1) + ((x) & 0x01) )
52
53 #define TILE_SIZE 32
54 #define TILE_BORDER 1
55 #define WINDOW_OFFSET 16
56
57 #define ROTATE_TIME 0.13F
58 #define FLASH_FRAME 0.07F
59
60 enum {
61     COL_BACKGROUND,
62     COL_LOCKED,
63     COL_BORDER,
64     COL_WIRE,
65     COL_ENDPOINT,
66     COL_POWERED,
67     COL_BARRIER,
68     NCOLOURS
69 };
70
71 struct game_params {
72     int width;
73     int height;
74     int wrapping;
75     int unique;
76     float barrier_probability;
77 };
78
79 struct game_aux_info {
80     int width, height;
81     unsigned char *tiles;
82 };
83
84 struct game_state {
85     int width, height, cx, cy, wrapping, completed;
86     int last_rotate_x, last_rotate_y, last_rotate_dir;
87     int used_solve, just_used_solve;
88     unsigned char *tiles;
89     unsigned char *barriers;
90 };
91
92 #define OFFSETWH(x2,y2,x1,y1,dir,width,height) \
93     ( (x2) = ((x1) + width + X((dir))) % width, \
94       (y2) = ((y1) + height + Y((dir))) % height)
95
96 #define OFFSET(x2,y2,x1,y1,dir,state) \
97         OFFSETWH(x2,y2,x1,y1,dir,(state)->width,(state)->height)
98
99 #define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
100 #define tile(state, x, y)     index(state, (state)->tiles, x, y)
101 #define barrier(state, x, y)  index(state, (state)->barriers, x, y)
102
103 struct xyd {
104     int x, y, direction;
105 };
106
107 static int xyd_cmp(const void *av, const void *bv) {
108     const struct xyd *a = (const struct xyd *)av;
109     const struct xyd *b = (const struct xyd *)bv;
110     if (a->x < b->x)
111         return -1;
112     if (a->x > b->x)
113         return +1;
114     if (a->y < b->y)
115         return -1;
116     if (a->y > b->y)
117         return +1;
118     if (a->direction < b->direction)
119         return -1;
120     if (a->direction > b->direction)
121         return +1;
122     return 0;
123 };
124
125 static int xyd_cmp_nc(void *av, void *bv) { return xyd_cmp(av, bv); }
126
127 static struct xyd *new_xyd(int x, int y, int direction)
128 {
129     struct xyd *xyd = snew(struct xyd);
130     xyd->x = x;
131     xyd->y = y;
132     xyd->direction = direction;
133     return xyd;
134 }
135
136 /* ----------------------------------------------------------------------
137  * Manage game parameters.
138  */
139 static game_params *default_params(void)
140 {
141     game_params *ret = snew(game_params);
142
143     ret->width = 5;
144     ret->height = 5;
145     ret->wrapping = FALSE;
146     ret->unique = TRUE;
147     ret->barrier_probability = 0.0;
148
149     return ret;
150 }
151
152 static int game_fetch_preset(int i, char **name, game_params **params)
153 {
154     game_params *ret;
155     char str[80];
156     static const struct { int x, y, wrap; } values[] = {
157         {5, 5, FALSE},
158         {7, 7, FALSE},
159         {9, 9, FALSE},
160         {11, 11, FALSE},
161         {13, 11, FALSE},
162         {5, 5, TRUE},
163         {7, 7, TRUE},
164         {9, 9, TRUE},
165         {11, 11, TRUE},
166         {13, 11, TRUE},
167     };
168
169     if (i < 0 || i >= lenof(values))
170         return FALSE;
171
172     ret = snew(game_params);
173     ret->width = values[i].x;
174     ret->height = values[i].y;
175     ret->wrapping = values[i].wrap;
176     ret->unique = TRUE;
177     ret->barrier_probability = 0.0;
178
179     sprintf(str, "%dx%d%s", ret->width, ret->height,
180             ret->wrapping ? " wrapping" : "");
181
182     *name = dupstr(str);
183     *params = ret;
184     return TRUE;
185 }
186
187 static void free_params(game_params *params)
188 {
189     sfree(params);
190 }
191
192 static game_params *dup_params(game_params *params)
193 {
194     game_params *ret = snew(game_params);
195     *ret = *params;                    /* structure copy */
196     return ret;
197 }
198
199 static void decode_params(game_params *ret, char const *string)
200 {
201     char const *p = string;
202
203     ret->width = atoi(p);
204     while (*p && isdigit((unsigned char)*p)) p++;
205     if (*p == 'x') {
206         p++;
207         ret->height = atoi(p);
208         while (*p && isdigit((unsigned char)*p)) p++;
209     } else {
210         ret->height = ret->width;
211     }
212
213     while (*p) {
214         if (*p == 'w') {
215             p++;
216             ret->wrapping = TRUE;
217         } else if (*p == 'b') {
218             p++;
219             ret->barrier_probability = atof(p);
220             while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
221         } else if (*p == 'a') {
222             p++;
223             ret->unique = FALSE;
224         } else
225             p++;                       /* skip any other gunk */
226     }
227 }
228
229 static char *encode_params(game_params *params, int full)
230 {
231     char ret[400];
232     int len;
233
234     len = sprintf(ret, "%dx%d", params->width, params->height);
235     if (params->wrapping)
236         ret[len++] = 'w';
237     if (full && params->barrier_probability)
238         len += sprintf(ret+len, "b%g", params->barrier_probability);
239     if (full && !params->unique)
240         ret[len++] = 'a';
241     assert(len < lenof(ret));
242     ret[len] = '\0';
243
244     return dupstr(ret);
245 }
246
247 static config_item *game_configure(game_params *params)
248 {
249     config_item *ret;
250     char buf[80];
251
252     ret = snewn(6, config_item);
253
254     ret[0].name = "Width";
255     ret[0].type = C_STRING;
256     sprintf(buf, "%d", params->width);
257     ret[0].sval = dupstr(buf);
258     ret[0].ival = 0;
259
260     ret[1].name = "Height";
261     ret[1].type = C_STRING;
262     sprintf(buf, "%d", params->height);
263     ret[1].sval = dupstr(buf);
264     ret[1].ival = 0;
265
266     ret[2].name = "Walls wrap around";
267     ret[2].type = C_BOOLEAN;
268     ret[2].sval = NULL;
269     ret[2].ival = params->wrapping;
270
271     ret[3].name = "Barrier probability";
272     ret[3].type = C_STRING;
273     sprintf(buf, "%g", params->barrier_probability);
274     ret[3].sval = dupstr(buf);
275     ret[3].ival = 0;
276
277     ret[4].name = "Ensure unique solution";
278     ret[4].type = C_BOOLEAN;
279     ret[4].sval = NULL;
280     ret[4].ival = params->unique;
281
282     ret[5].name = NULL;
283     ret[5].type = C_END;
284     ret[5].sval = NULL;
285     ret[5].ival = 0;
286
287     return ret;
288 }
289
290 static game_params *custom_params(config_item *cfg)
291 {
292     game_params *ret = snew(game_params);
293
294     ret->width = atoi(cfg[0].sval);
295     ret->height = atoi(cfg[1].sval);
296     ret->wrapping = cfg[2].ival;
297     ret->barrier_probability = (float)atof(cfg[3].sval);
298     ret->unique = cfg[4].ival;
299
300     return ret;
301 }
302
303 static char *validate_params(game_params *params)
304 {
305     if (params->width <= 0 && params->height <= 0)
306         return "Width and height must both be greater than zero";
307     if (params->width <= 0)
308         return "Width must be greater than zero";
309     if (params->height <= 0)
310         return "Height must be greater than zero";
311     if (params->width <= 1 && params->height <= 1)
312         return "At least one of width and height must be greater than one";
313     if (params->barrier_probability < 0)
314         return "Barrier probability may not be negative";
315     if (params->barrier_probability > 1)
316         return "Barrier probability may not be greater than 1";
317     return NULL;
318 }
319
320 /* ----------------------------------------------------------------------
321  * Solver used to assure solution uniqueness during generation. 
322  */
323
324 /*
325  * Test cases I used while debugging all this were
326  * 
327  *   ./net --generate 1 13x11w#12300
328  * which expands under the non-unique grid generation rules to
329  *   13x11w:5eaade1bd222664436d5e2965c12656b1129dd825219e3274d558d5eb2dab5da18898e571d5a2987be79746bd95726c597447d6da96188c513add829da7681da954db113d3cd244
330  * and has two ambiguous areas.
331  * 
332  * An even better one is
333  *   13x11w#507896411361192
334  * which expands to
335  *   13x11w:b7125b1aec598eb31bd58d82572bc11494e5dee4e8db2bdd29b88d41a16bdd996d2996ddec8c83741a1e8674e78328ba71737b8894a9271b1cd1399453d1952e43951d9b712822e
336  * and has an ambiguous area _and_ a situation where loop avoidance
337  * is a necessary deductive technique.
338  * 
339  * Then there's
340  *   48x25w#820543338195187
341  * becoming
342  *   48x25w:255989d14cdd185deaa753a93821a12edc1ab97943ac127e2685d7b8b3c48861b2192416139212b316eddd35de43714ebc7628d753db32e596284d9ec52c5a7dc1b4c811a655117d16dc28921b2b4161352cab1d89d18bc836b8b891d55ea4622a1251861b5bc9a8aa3e5bcd745c95229ca6c3b5e21d5832d397e917325793d7eb442dc351b2db2a52ba8e1651642275842d8871d5534aabc6d5b741aaa2d48ed2a7dbbb3151ddb49d5b9a7ed1ab98ee75d613d656dbba347bc514c84556b43a9bc65a3256ead792488b862a9d2a8a39b4255a4949ed7dbd79443292521265896b4399c95ede89d7c8c797a6a57791a849adea489359a158aa12e5dacce862b8333b7ebea7d344d1a3c53198864b73a9dedde7b663abb1b539e1e8853b1b7edb14a2a17ebaae4dbe63598a2e7e9a2dbdad415bc1d8cb88cbab5a8c82925732cd282e641ea3bd7d2c6e776de9117a26be86deb7c82c89524b122cb9397cd1acd2284e744ea62b9279bae85479ababe315c3ac29c431333395b24e6a1e3c43a2da42d4dce84aadd5b154aea555eaddcbd6e527d228c19388d9b424d94214555a7edbdeebe569d4a56dc51a86bd9963e377bb74752bd5eaa5761ba545e297b62a1bda46ab4aee423ad6c661311783cc18786d4289236563cb4a75ec67d481c14814994464cd1b87396dee63e5ab6e952cc584baa1d4c47cb557ec84dbb63d487c8728118673a166846dd3a4ebc23d6cb9c5827d96b4556e91899db32b517eda815ae271a8911bd745447121dc8d321557bc2a435ebec1bbac35b1a291669451174e6aa2218a4a9c5a6ca31ebc45d84e3a82c121e9ced7d55e9a
343  * which has a spot (far right) where slightly more complex loop
344  * avoidance is required.
345  */
346
347 static int dsf_canonify(int *dsf, int val)
348 {
349     int v2 = val;
350
351     while (dsf[val] != val)
352         val = dsf[val];
353
354     while (v2 != val) {
355         int tmp = dsf[v2];
356         dsf[v2] = val;
357         v2 = tmp;
358     }
359
360     return val;
361 }
362
363 static void dsf_merge(int *dsf, int v1, int v2)
364 {
365     v1 = dsf_canonify(dsf, v1);
366     v2 = dsf_canonify(dsf, v2);
367     dsf[v2] = v1;
368 }
369
370 struct todo {
371     unsigned char *marked;
372     int *buffer;
373     int buflen;
374     int head, tail;
375 };
376
377 static struct todo *todo_new(int maxsize)
378 {
379     struct todo *todo = snew(struct todo);
380     todo->marked = snewn(maxsize, unsigned char);
381     memset(todo->marked, 0, maxsize);
382     todo->buflen = maxsize + 1;
383     todo->buffer = snewn(todo->buflen, int);
384     todo->head = todo->tail = 0;
385     return todo;
386 }
387
388 static void todo_free(struct todo *todo)
389 {
390     sfree(todo->marked);
391     sfree(todo->buffer);
392     sfree(todo);
393 }
394
395 static void todo_add(struct todo *todo, int index)
396 {
397     if (todo->marked[index])
398         return;                        /* already on the list */
399     todo->marked[index] = TRUE;
400     todo->buffer[todo->tail++] = index;
401     if (todo->tail == todo->buflen)
402         todo->tail = 0;
403 }
404
405 static int todo_get(struct todo *todo) {
406     int ret;
407
408     if (todo->head == todo->tail)
409         return -1;                     /* list is empty */
410     ret = todo->buffer[todo->head++];
411     if (todo->head == todo->buflen)
412         todo->head = 0;
413     todo->marked[ret] = FALSE;
414
415     return ret;
416 }
417
418 static int net_solver(int w, int h, unsigned char *tiles,
419                       unsigned char *barriers, int wrapping)
420 {
421     unsigned char *tilestate;
422     unsigned char *edgestate;
423     int *deadends;
424     int *equivalence;
425     struct todo *todo;
426     int i, j, x, y;
427     int area;
428     int done_something;
429
430     /*
431      * Set up the solver's data structures.
432      */
433     
434     /*
435      * tilestate stores the possible orientations of each tile.
436      * There are up to four of these, so we'll index the array in
437      * fours. tilestate[(y * w + x) * 4] and its three successive
438      * members give the possible orientations, clearing to 255 from
439      * the end as things are ruled out.
440      * 
441      * In this loop we also count up the area of the grid (which is
442      * not _necessarily_ equal to w*h, because there might be one
443      * or more blank squares present. This will never happen in a
444      * grid generated _by_ this program, but it's worth keeping the
445      * solver as general as possible.)
446      */
447     tilestate = snewn(w * h * 4, unsigned char);
448     area = 0;
449     for (i = 0; i < w*h; i++) {
450         tilestate[i * 4] = tiles[i] & 0xF;
451         for (j = 1; j < 4; j++) {
452             if (tilestate[i * 4 + j - 1] == 255 ||
453                 A(tilestate[i * 4 + j - 1]) == tilestate[i * 4])
454                 tilestate[i * 4 + j] = 255;
455             else
456                 tilestate[i * 4 + j] = A(tilestate[i * 4 + j - 1]);
457         }
458         if (tiles[i] != 0)
459             area++;
460     }
461
462     /*
463      * edgestate stores the known state of each edge. It is 0 for
464      * unknown, 1 for open (connected) and 2 for closed (not
465      * connected).
466      * 
467      * In principle we need only worry about each edge once each,
468      * but in fact it's easier to track each edge twice so that we
469      * can reference it from either side conveniently. Also I'm
470      * going to allocate _five_ bytes per tile, rather than the
471      * obvious four, so that I can index edgestate[(y*w+x) * 5 + d]
472      * where d is 1,2,4,8 and they never overlap.
473      */
474     edgestate = snewn((w * h - 1) * 5 + 9, unsigned char);
475     memset(edgestate, 0, (w * h - 1) * 5 + 9);
476
477     /*
478      * deadends tracks which edges have dead ends on them. It is
479      * indexed by tile and direction: deadends[(y*w+x) * 5 + d]
480      * tells you whether heading out of tile (x,y) in direction d
481      * can reach a limited amount of the grid. Values are area+1
482      * (no dead end known) or less than that (can reach _at most_
483      * this many other tiles by heading this way out of this tile).
484      */
485     deadends = snewn((w * h - 1) * 5 + 9, int);
486     for (i = 0; i < (w * h - 1) * 5 + 9; i++)
487         deadends[i] = area+1;
488
489     /*
490      * equivalence tracks which sets of tiles are known to be
491      * connected to one another, so we can avoid creating loops by
492      * linking together tiles which are already linked through
493      * another route.
494      * 
495      * This is a disjoint set forest structure: equivalence[i]
496      * contains the index of another member of the equivalence
497      * class containing i, or contains i itself for precisely one
498      * member in each such class. To find a representative member
499      * of the equivalence class containing i, you keep replacing i
500      * with equivalence[i] until it stops changing; then you go
501      * _back_ along the same path and point everything on it
502      * directly at the representative member so as to speed up
503      * future searches. Then you test equivalence between tiles by
504      * finding the representative of each tile and seeing if
505      * they're the same; and you create new equivalence (merge
506      * classes) by finding the representative of each tile and
507      * setting equivalence[one]=the_other.
508      */
509     equivalence = snewn(w * h, int);
510     for (i = 0; i < w*h; i++)
511         equivalence[i] = i;            /* initially all distinct */
512
513     /*
514      * On a non-wrapping grid, we instantly know that all the edges
515      * round the edge are closed.
516      */
517     if (!wrapping) {
518         for (i = 0; i < w; i++) {
519             edgestate[i * 5 + 2] = edgestate[((h-1) * w + i) * 5 + 8] = 2;
520         }
521         for (i = 0; i < h; i++) {
522             edgestate[(i * w + w-1) * 5 + 1] = edgestate[(i * w) * 5 + 4] = 2;
523         }
524     }
525
526     /*
527      * If we have barriers available, we can mark those edges as
528      * closed too.
529      */
530     if (barriers) {
531         for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
532             int d;
533             for (d = 1; d <= 8; d += d) {
534                 if (barriers[y*w+x] & d) {
535                     int x2, y2;
536                     /*
537                      * In principle the barrier list should already
538                      * contain each barrier from each side, but
539                      * let's not take chances with our internal
540                      * consistency.
541                      */
542                     OFFSETWH(x2, y2, x, y, d, w, h);
543                     edgestate[(y*w+x) * 5 + d] = 2;
544                     edgestate[(y2*w+x2) * 5 + F(d)] = 2;
545                 }
546             }
547         }
548     }
549
550     /*
551      * Since most deductions made by this solver are local (the
552      * exception is loop avoidance, where joining two tiles
553      * together on one side of the grid can theoretically permit a
554      * fresh deduction on the other), we can address the scaling
555      * problem inherent in iterating repeatedly over the entire
556      * grid by instead working with a to-do list.
557      */
558     todo = todo_new(w * h);
559
560     /*
561      * Main deductive loop.
562      */
563     done_something = TRUE;             /* prevent instant termination! */
564     while (1) {
565         int index;
566
567         /*
568          * Take a tile index off the todo list and process it.
569          */
570         index = todo_get(todo);
571         if (index == -1) {
572             /*
573              * If we have run out of immediate things to do, we
574              * have no choice but to scan the whole grid for
575              * longer-range things we've missed. Hence, I now add
576              * every square on the grid back on to the to-do list.
577              * I also set `done_something' to FALSE at this point;
578              * if we later come back here and find it still FALSE,
579              * we will know we've scanned the entire grid without
580              * finding anything new to do, and we can terminate.
581              */
582             if (!done_something)
583                 break;
584             for (i = 0; i < w*h; i++)
585                 todo_add(todo, i);
586             done_something = FALSE;
587
588             index = todo_get(todo);
589         }
590
591         y = index / w;
592         x = index % w;
593         {
594             int d, ourclass = dsf_canonify(equivalence, y*w+x);
595             int deadendmax[9];
596
597             deadendmax[1] = deadendmax[2] = deadendmax[4] = deadendmax[8] = 0;
598
599             for (i = j = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
600                 int valid;
601                 int nnondeadends, nondeadends[4], deadendtotal;
602                 int nequiv, equiv[5];
603                 int val = tilestate[(y*w+x) * 4 + i];
604
605                 valid = TRUE;
606                 nnondeadends = deadendtotal = 0;
607                 equiv[0] = ourclass;
608                 nequiv = 1;
609                 for (d = 1; d <= 8; d += d) {
610                     /*
611                      * Immediately rule out this orientation if it
612                      * conflicts with any known edge.
613                      */
614                     if ((edgestate[(y*w+x) * 5 + d] == 1 && !(val & d)) ||
615                         (edgestate[(y*w+x) * 5 + d] == 2 && (val & d)))
616                         valid = FALSE;
617
618                     if (val & d) {
619                         /*
620                          * Count up the dead-end statistics.
621                          */
622                         if (deadends[(y*w+x) * 5 + d] <= area) {
623                             deadendtotal += deadends[(y*w+x) * 5 + d];
624                         } else {
625                             nondeadends[nnondeadends++] = d;
626                         }
627
628                         /*
629                          * Ensure we aren't linking to any tiles,
630                          * through edges not already known to be
631                          * open, which create a loop.
632                          */
633                         if (edgestate[(y*w+x) * 5 + d] == 0) {
634                             int c, k, x2, y2;
635                             
636                             OFFSETWH(x2, y2, x, y, d, w, h);
637                             c = dsf_canonify(equivalence, y2*w+x2);
638                             for (k = 0; k < nequiv; k++)
639                                 if (c == equiv[k])
640                                     break;
641                             if (k == nequiv)
642                                 equiv[nequiv++] = c;
643                             else
644                                 valid = FALSE;
645                         }
646                     }
647                 }
648
649                 if (nnondeadends == 0) {
650                     /*
651                      * If this orientation links together dead-ends
652                      * with a total area of less than the entire
653                      * grid, it is invalid.
654                      *
655                      * (We add 1 to deadendtotal because of the
656                      * tile itself, of course; one tile linking
657                      * dead ends of size 2 and 3 forms a subnetwork
658                      * with a total area of 6, not 5.)
659                      */
660                     if (deadendtotal > 0 && deadendtotal+1 < area)
661                         valid = FALSE;
662                 } else if (nnondeadends == 1) {
663                     /*
664                      * If this orientation links together one or
665                      * more dead-ends with precisely one
666                      * non-dead-end, then we may have to mark that
667                      * non-dead-end as a dead end going the other
668                      * way. However, it depends on whether all
669                      * other orientations share the same property.
670                      */
671                     deadendtotal++;
672                     if (deadendmax[nondeadends[0]] < deadendtotal)
673                         deadendmax[nondeadends[0]] = deadendtotal;
674                 } else {
675                     /*
676                      * If this orientation links together two or
677                      * more non-dead-ends, then we can rule out the
678                      * possibility of putting in new dead-end
679                      * markings in those directions.
680                      */
681                     int k;
682                     for (k = 0; k < nnondeadends; k++)
683                         deadendmax[nondeadends[k]] = area+1;
684                 }
685
686                 if (valid)
687                     tilestate[(y*w+x) * 4 + j++] = val;
688 #ifdef SOLVER_DIAGNOSTICS
689                 else
690                     printf("ruling out orientation %x at %d,%d\n", val, x, y);
691 #endif
692             }
693
694             assert(j > 0);             /* we can't lose _all_ possibilities! */
695
696             if (j < i) {
697                 done_something = TRUE;
698
699                 /*
700                  * We have ruled out at least one tile orientation.
701                  * Make sure the rest are blanked.
702                  */
703                 while (j < 4)
704                     tilestate[(y*w+x) * 4 + j++] = 255;
705             }
706
707             /*
708              * Now go through the tile orientations again and see
709              * if we've deduced anything new about any edges.
710              */
711             {
712                 int a, o;
713                 a = 0xF; o = 0;
714
715                 for (i = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
716                     a &= tilestate[(y*w+x) * 4 + i];
717                     o |= tilestate[(y*w+x) * 4 + i];
718                 }
719                 for (d = 1; d <= 8; d += d)
720                     if (edgestate[(y*w+x) * 5 + d] == 0) {
721                         int x2, y2, d2;
722                         OFFSETWH(x2, y2, x, y, d, w, h);
723                         d2 = F(d);
724                         if (a & d) {
725                             /* This edge is open in all orientations. */
726 #ifdef SOLVER_DIAGNOSTICS
727                             printf("marking edge %d,%d:%d open\n", x, y, d);
728 #endif
729                             edgestate[(y*w+x) * 5 + d] = 1;
730                             edgestate[(y2*w+x2) * 5 + d2] = 1;
731                             dsf_merge(equivalence, y*w+x, y2*w+x2);
732                             done_something = TRUE;
733                             todo_add(todo, y2*w+x2);
734                         } else if (!(o & d)) {
735                             /* This edge is closed in all orientations. */
736 #ifdef SOLVER_DIAGNOSTICS
737                             printf("marking edge %d,%d:%d closed\n", x, y, d);
738 #endif
739                             edgestate[(y*w+x) * 5 + d] = 2;
740                             edgestate[(y2*w+x2) * 5 + d2] = 2;
741                             done_something = TRUE;
742                             todo_add(todo, y2*w+x2);
743                         }
744                     }
745
746             }
747
748             /*
749              * Now check the dead-end markers and see if any of
750              * them has lowered from the real ones.
751              */
752             for (d = 1; d <= 8; d += d) {
753                 int x2, y2, d2;
754                 OFFSETWH(x2, y2, x, y, d, w, h);
755                 d2 = F(d);
756                 if (deadendmax[d] > 0 &&
757                     deadends[(y2*w+x2) * 5 + d2] > deadendmax[d]) {
758 #ifdef SOLVER_DIAGNOSTICS
759                     printf("setting dead end value %d,%d:%d to %d\n",
760                            x2, y2, d2, deadendmax[d]);
761 #endif
762                     deadends[(y2*w+x2) * 5 + d2] = deadendmax[d];
763                     done_something = TRUE;
764                     todo_add(todo, y2*w+x2);
765                 }
766             }
767
768         }
769     }
770
771     /*
772      * Mark all completely determined tiles as locked.
773      */
774     j = TRUE;
775     for (i = 0; i < w*h; i++) {
776         if (tilestate[i * 4 + 1] == 255) {
777             assert(tilestate[i * 4 + 0] != 255);
778             tiles[i] = tilestate[i * 4] | LOCKED;
779         } else {
780             tiles[i] &= ~LOCKED;
781             j = FALSE;
782         }
783     }
784
785     /*
786      * Free up working space.
787      */
788     todo_free(todo);
789     sfree(tilestate);
790     sfree(edgestate);
791     sfree(deadends);
792     sfree(equivalence);
793
794     return j;
795 }
796
797 /* ----------------------------------------------------------------------
798  * Randomly select a new game description.
799  */
800
801 /*
802  * Function to randomly perturb an ambiguous section in a grid, to
803  * attempt to ensure unique solvability.
804  */
805 static void perturb(int w, int h, unsigned char *tiles, int wrapping,
806                     random_state *rs, int startx, int starty, int startd)
807 {
808     struct xyd *perimeter, *perim2, *loop[2], looppos[2];
809     int nperim, perimsize, nloop[2], loopsize[2];
810     int x, y, d, i;
811
812     /*
813      * We know that the tile at (startx,starty) is part of an
814      * ambiguous section, and we also know that its neighbour in
815      * direction startd is fully specified. We begin by tracing all
816      * the way round the ambiguous area.
817      */
818     nperim = perimsize = 0;
819     perimeter = NULL;
820     x = startx;
821     y = starty;
822     d = startd;
823 #ifdef PERTURB_DIAGNOSTICS
824     printf("perturb %d,%d:%d\n", x, y, d);
825 #endif
826     do {
827         int x2, y2, d2;
828
829         if (nperim >= perimsize) {
830             perimsize = perimsize * 3 / 2 + 32;
831             perimeter = sresize(perimeter, perimsize, struct xyd);
832         }
833         perimeter[nperim].x = x;
834         perimeter[nperim].y = y;
835         perimeter[nperim].direction = d;
836         nperim++;
837 #ifdef PERTURB_DIAGNOSTICS
838         printf("perimeter: %d,%d:%d\n", x, y, d);
839 #endif
840
841         /*
842          * First, see if we can simply turn left from where we are
843          * and find another locked square.
844          */
845         d2 = A(d);
846         OFFSETWH(x2, y2, x, y, d2, w, h);
847         if ((!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1)) ||
848             (tiles[y2*w+x2] & LOCKED)) {
849             d = d2;
850         } else {
851             /*
852              * Failing that, step left into the new square and look
853              * in front of us.
854              */
855             x = x2;
856             y = y2;
857             OFFSETWH(x2, y2, x, y, d, w, h);
858             if ((wrapping || (abs(x2-x) <= 1 && abs(y2-y) <= 1)) &&
859                 !(tiles[y2*w+x2] & LOCKED)) {
860                 /*
861                  * And failing _that_, we're going to have to step
862                  * forward into _that_ square and look right at the
863                  * same locked square as we started with.
864                  */
865                 x = x2;
866                 y = y2;
867                 d = C(d);
868             }
869         }
870
871     } while (x != startx || y != starty || d != startd);
872
873     /*
874      * Our technique for perturbing this ambiguous area is to
875      * search round its edge for a join we can make: that is, an
876      * edge on the perimeter which is (a) not currently connected,
877      * and (b) connecting it would not yield a full cross on either
878      * side. Then we make that join, search round the network to
879      * find the loop thus constructed, and sever the loop at a
880      * randomly selected other point.
881      */
882     perim2 = snewn(nperim, struct xyd);
883     memcpy(perim2, perimeter, nperim * sizeof(struct xyd));
884     /* Shuffle the perimeter, so as to search it without directional bias. */
885     for (i = nperim; --i ;) {
886         int j = random_upto(rs, i+1);
887         struct xyd t;
888
889         t = perim2[j];
890         perim2[j] = perim2[i];
891         perim2[i] = t;
892     }
893     for (i = 0; i < nperim; i++) {
894         int x2, y2;
895
896         x = perim2[i].x;
897         y = perim2[i].y;
898         d = perim2[i].direction;
899
900         OFFSETWH(x2, y2, x, y, d, w, h);
901         if (!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1))
902             continue;            /* can't link across non-wrapping border */
903         if (tiles[y*w+x] & d)
904             continue;                  /* already linked in this direction! */
905         if (((tiles[y*w+x] | d) & 15) == 15)
906             continue;                  /* can't turn this tile into a cross */
907         if (((tiles[y2*w+x2] | F(d)) & 15) == 15)
908             continue;                  /* can't turn other tile into a cross */
909
910         /*
911          * We've found the point at which we're going to make a new
912          * link.
913          */
914 #ifdef PERTURB_DIAGNOSTICS      
915         printf("linking %d,%d:%d\n", x, y, d);
916 #endif
917         tiles[y*w+x] |= d;
918         tiles[y2*w+x2] |= F(d);
919
920         break;
921     }
922
923     if (i == nperim)
924         return;                        /* nothing we can do! */
925
926     /*
927      * Now we've constructed a new link, we need to find the entire
928      * loop of which it is a part.
929      * 
930      * In principle, this involves doing a complete search round
931      * the network. However, I anticipate that in the vast majority
932      * of cases the loop will be quite small, so what I'm going to
933      * do is make _two_ searches round the network in parallel, one
934      * keeping its metaphorical hand on the left-hand wall while
935      * the other keeps its hand on the right. As soon as one of
936      * them gets back to its starting point, I abandon the other.
937      */
938     for (i = 0; i < 2; i++) {
939         loopsize[i] = nloop[i] = 0;
940         loop[i] = NULL;
941         looppos[i].x = x;
942         looppos[i].y = y;
943         looppos[i].direction = d;
944     }
945     while (1) {
946         for (i = 0; i < 2; i++) {
947             int x2, y2, j;
948
949             x = looppos[i].x;
950             y = looppos[i].y;
951             d = looppos[i].direction;
952
953             OFFSETWH(x2, y2, x, y, d, w, h);
954
955             /*
956              * Add this path segment to the loop, unless it exactly
957              * reverses the previous one on the loop in which case
958              * we take it away again.
959              */
960 #ifdef PERTURB_DIAGNOSTICS
961             printf("looppos[%d] = %d,%d:%d\n", i, x, y, d);
962 #endif
963             if (nloop[i] > 0 &&
964                 loop[i][nloop[i]-1].x == x2 &&
965                 loop[i][nloop[i]-1].y == y2 &&
966                 loop[i][nloop[i]-1].direction == F(d)) {
967 #ifdef PERTURB_DIAGNOSTICS
968                 printf("removing path segment %d,%d:%d from loop[%d]\n",
969                        x2, y2, F(d), i);
970 #endif
971                 nloop[i]--;
972             } else {
973                 if (nloop[i] >= loopsize[i]) {
974                     loopsize[i] = loopsize[i] * 3 / 2 + 32;
975                     loop[i] = sresize(loop[i], loopsize[i], struct xyd);
976                 }
977 #ifdef PERTURB_DIAGNOSTICS
978                 printf("adding path segment %d,%d:%d to loop[%d]\n",
979                        x, y, d, i);
980 #endif
981                 loop[i][nloop[i]++] = looppos[i];
982             }
983
984 #ifdef PERTURB_DIAGNOSTICS
985             printf("tile at new location is %x\n", tiles[y2*w+x2] & 0xF);
986 #endif
987             d = F(d);
988             for (j = 0; j < 4; j++) {
989                 if (i == 0)
990                     d = A(d);
991                 else
992                     d = C(d);
993 #ifdef PERTURB_DIAGNOSTICS
994                 printf("trying dir %d\n", d);
995 #endif
996                 if (tiles[y2*w+x2] & d) {
997                     looppos[i].x = x2;
998                     looppos[i].y = y2;
999                     looppos[i].direction = d;
1000                     break;
1001                 }
1002             }
1003
1004             assert(j < 4);
1005             assert(nloop[i] > 0);
1006
1007             if (looppos[i].x == loop[i][0].x &&
1008                 looppos[i].y == loop[i][0].y &&
1009                 looppos[i].direction == loop[i][0].direction) {
1010 #ifdef PERTURB_DIAGNOSTICS
1011                 printf("loop %d finished tracking\n", i);
1012 #endif
1013
1014                 /*
1015                  * Having found our loop, we now sever it at a
1016                  * randomly chosen point - absolutely any will do -
1017                  * which is not the one we joined it at to begin
1018                  * with. Conveniently, the one we joined it at is
1019                  * loop[i][0], so we just avoid that one.
1020                  */
1021                 j = random_upto(rs, nloop[i]-1) + 1;
1022                 x = loop[i][j].x;
1023                 y = loop[i][j].y;
1024                 d = loop[i][j].direction;
1025                 OFFSETWH(x2, y2, x, y, d, w, h);
1026                 tiles[y*w+x] &= ~d;
1027                 tiles[y2*w+x2] &= ~F(d);
1028
1029                 break;
1030             }
1031         }
1032         if (i < 2)
1033             break;
1034     }
1035     sfree(loop[0]);
1036     sfree(loop[1]);
1037
1038     /*
1039      * Finally, we must mark the entire disputed section as locked,
1040      * to prevent the perturb function being called on it multiple
1041      * times.
1042      * 
1043      * To do this, we _sort_ the perimeter of the area. The
1044      * existing xyd_cmp function will arrange things into columns
1045      * for us, in such a way that each column has the edges in
1046      * vertical order. Then we can work down each column and fill
1047      * in all the squares between an up edge and a down edge.
1048      */
1049     qsort(perimeter, nperim, sizeof(struct xyd), xyd_cmp);
1050     x = y = -1;
1051     for (i = 0; i <= nperim; i++) {
1052         if (i == nperim || perimeter[i].x > x) {
1053             /*
1054              * Fill in everything from the last Up edge to the
1055              * bottom of the grid, if necessary.
1056              */
1057             if (x != -1) {
1058                 while (y < h) {
1059 #ifdef PERTURB_DIAGNOSTICS
1060                     printf("resolved: locking tile %d,%d\n", x, y);
1061 #endif
1062                     tiles[y * w + x] |= LOCKED;
1063                     y++;
1064                 }
1065                 x = y = -1;
1066             }
1067
1068             if (i == nperim)
1069                 break;
1070
1071             x = perimeter[i].x;
1072             y = 0;
1073         }
1074
1075         if (perimeter[i].direction == U) {
1076             x = perimeter[i].x;
1077             y = perimeter[i].y;
1078         } else if (perimeter[i].direction == D) {
1079             /*
1080              * Fill in everything from the last Up edge to here.
1081              */
1082             assert(x == perimeter[i].x && y <= perimeter[i].y);
1083             while (y <= perimeter[i].y) {
1084 #ifdef PERTURB_DIAGNOSTICS
1085                 printf("resolved: locking tile %d,%d\n", x, y);
1086 #endif
1087                 tiles[y * w + x] |= LOCKED;
1088                 y++;
1089             }
1090             x = y = -1;
1091         }
1092     }
1093
1094     sfree(perimeter);
1095 }
1096
1097 static char *new_game_desc(game_params *params, random_state *rs,
1098                            game_aux_info **aux)
1099 {
1100     tree234 *possibilities, *barriertree;
1101     int w, h, x, y, cx, cy, nbarriers;
1102     unsigned char *tiles, *barriers;
1103     char *desc, *p;
1104
1105     w = params->width;
1106     h = params->height;
1107
1108     cx = w / 2;
1109     cy = h / 2;
1110
1111     tiles = snewn(w * h, unsigned char);
1112     barriers = snewn(w * h, unsigned char);
1113
1114     begin_generation:
1115
1116     memset(tiles, 0, w * h);
1117     memset(barriers, 0, w * h);
1118
1119     /*
1120      * Construct the unshuffled grid.
1121      * 
1122      * To do this, we simply start at the centre point, repeatedly
1123      * choose a random possibility out of the available ways to
1124      * extend a used square into an unused one, and do it. After
1125      * extending the third line out of a square, we remove the
1126      * fourth from the possibilities list to avoid any full-cross
1127      * squares (which would make the game too easy because they
1128      * only have one orientation).
1129      * 
1130      * The slightly worrying thing is the avoidance of full-cross
1131      * squares. Can this cause our unsophisticated construction
1132      * algorithm to paint itself into a corner, by getting into a
1133      * situation where there are some unreached squares and the
1134      * only way to reach any of them is to extend a T-piece into a
1135      * full cross?
1136      * 
1137      * Answer: no it can't, and here's a proof.
1138      * 
1139      * Any contiguous group of such unreachable squares must be
1140      * surrounded on _all_ sides by T-pieces pointing away from the
1141      * group. (If not, then there is a square which can be extended
1142      * into one of the `unreachable' ones, and so it wasn't
1143      * unreachable after all.) In particular, this implies that
1144      * each contiguous group of unreachable squares must be
1145      * rectangular in shape (any deviation from that yields a
1146      * non-T-piece next to an `unreachable' square).
1147      * 
1148      * So we have a rectangle of unreachable squares, with T-pieces
1149      * forming a solid border around the rectangle. The corners of
1150      * that border must be connected (since every tile connects all
1151      * the lines arriving in it), and therefore the border must
1152      * form a closed loop around the rectangle.
1153      * 
1154      * But this can't have happened in the first place, since we
1155      * _know_ we've avoided creating closed loops! Hence, no such
1156      * situation can ever arise, and the naive grid construction
1157      * algorithm will guaranteeably result in a complete grid
1158      * containing no unreached squares, no full crosses _and_ no
1159      * closed loops. []
1160      */
1161     possibilities = newtree234(xyd_cmp_nc);
1162
1163     if (cx+1 < w)
1164         add234(possibilities, new_xyd(cx, cy, R));
1165     if (cy-1 >= 0)
1166         add234(possibilities, new_xyd(cx, cy, U));
1167     if (cx-1 >= 0)
1168         add234(possibilities, new_xyd(cx, cy, L));
1169     if (cy+1 < h)
1170         add234(possibilities, new_xyd(cx, cy, D));
1171
1172     while (count234(possibilities) > 0) {
1173         int i;
1174         struct xyd *xyd;
1175         int x1, y1, d1, x2, y2, d2, d;
1176
1177         /*
1178          * Extract a randomly chosen possibility from the list.
1179          */
1180         i = random_upto(rs, count234(possibilities));
1181         xyd = delpos234(possibilities, i);
1182         x1 = xyd->x;
1183         y1 = xyd->y;
1184         d1 = xyd->direction;
1185         sfree(xyd);
1186
1187         OFFSET(x2, y2, x1, y1, d1, params);
1188         d2 = F(d1);
1189 #ifdef DEBUG
1190         printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
1191                x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
1192 #endif
1193
1194         /*
1195          * Make the connection. (We should be moving to an as yet
1196          * unused tile.)
1197          */
1198         index(params, tiles, x1, y1) |= d1;
1199         assert(index(params, tiles, x2, y2) == 0);
1200         index(params, tiles, x2, y2) |= d2;
1201
1202         /*
1203          * If we have created a T-piece, remove its last
1204          * possibility.
1205          */
1206         if (COUNT(index(params, tiles, x1, y1)) == 3) {
1207             struct xyd xyd1, *xydp;
1208
1209             xyd1.x = x1;
1210             xyd1.y = y1;
1211             xyd1.direction = 0x0F ^ index(params, tiles, x1, y1);
1212
1213             xydp = find234(possibilities, &xyd1, NULL);
1214
1215             if (xydp) {
1216 #ifdef DEBUG
1217                 printf("T-piece; removing (%d,%d,%c)\n",
1218                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1219 #endif
1220                 del234(possibilities, xydp);
1221                 sfree(xydp);
1222             }
1223         }
1224
1225         /*
1226          * Remove all other possibilities that were pointing at the
1227          * tile we've just moved into.
1228          */
1229         for (d = 1; d < 0x10; d <<= 1) {
1230             int x3, y3, d3;
1231             struct xyd xyd1, *xydp;
1232
1233             OFFSET(x3, y3, x2, y2, d, params);
1234             d3 = F(d);
1235
1236             xyd1.x = x3;
1237             xyd1.y = y3;
1238             xyd1.direction = d3;
1239
1240             xydp = find234(possibilities, &xyd1, NULL);
1241
1242             if (xydp) {
1243 #ifdef DEBUG
1244                 printf("Loop avoidance; removing (%d,%d,%c)\n",
1245                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1246 #endif
1247                 del234(possibilities, xydp);
1248                 sfree(xydp);
1249             }
1250         }
1251
1252         /*
1253          * Add new possibilities to the list for moving _out_ of
1254          * the tile we have just moved into.
1255          */
1256         for (d = 1; d < 0x10; d <<= 1) {
1257             int x3, y3;
1258
1259             if (d == d2)
1260                 continue;              /* we've got this one already */
1261
1262             if (!params->wrapping) {
1263                 if (d == U && y2 == 0)
1264                     continue;
1265                 if (d == D && y2 == h-1)
1266                     continue;
1267                 if (d == L && x2 == 0)
1268                     continue;
1269                 if (d == R && x2 == w-1)
1270                     continue;
1271             }
1272
1273             OFFSET(x3, y3, x2, y2, d, params);
1274
1275             if (index(params, tiles, x3, y3))
1276                 continue;              /* this would create a loop */
1277
1278 #ifdef DEBUG
1279             printf("New frontier; adding (%d,%d,%c)\n",
1280                    x2, y2, "0RU3L567D9abcdef"[d]);
1281 #endif
1282             add234(possibilities, new_xyd(x2, y2, d));
1283         }
1284     }
1285     /* Having done that, we should have no possibilities remaining. */
1286     assert(count234(possibilities) == 0);
1287     freetree234(possibilities);
1288
1289     if (params->unique) {
1290         int prevn = -1;
1291
1292         /*
1293          * Run the solver to check unique solubility.
1294          */
1295         while (!net_solver(w, h, tiles, NULL, params->wrapping)) {
1296             int n = 0;
1297
1298             /*
1299              * We expect (in most cases) that most of the grid will
1300              * be uniquely specified already, and the remaining
1301              * ambiguous sections will be small and separate. So
1302              * our strategy is to find each individual such
1303              * section, and perform a perturbation on the network
1304              * in that area.
1305              */
1306             for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1307                 if (x+1 < w && ((tiles[y*w+x] ^ tiles[y*w+x+1]) & LOCKED)) {
1308                     n++;
1309                     if (tiles[y*w+x] & LOCKED)
1310                         perturb(w, h, tiles, params->wrapping, rs, x+1, y, L);
1311                     else
1312                         perturb(w, h, tiles, params->wrapping, rs, x, y, R);
1313                 }
1314                 if (y+1 < h && ((tiles[y*w+x] ^ tiles[(y+1)*w+x]) & LOCKED)) {
1315                     n++;
1316                     if (tiles[y*w+x] & LOCKED)
1317                         perturb(w, h, tiles, params->wrapping, rs, x, y+1, U);
1318                     else
1319                         perturb(w, h, tiles, params->wrapping, rs, x, y, D);
1320                 }
1321             }
1322
1323             /*
1324              * Now n counts the number of ambiguous sections we
1325              * have fiddled with. If we haven't managed to decrease
1326              * it from the last time we ran the solver, give up and
1327              * regenerate the entire grid.
1328              */
1329             if (prevn != -1 && prevn <= n)
1330                 goto begin_generation; /* (sorry) */
1331
1332             prevn = n;
1333         }
1334
1335         /*
1336          * The solver will have left a lot of LOCKED bits lying
1337          * around in the tiles array. Remove them.
1338          */
1339         for (x = 0; x < w*h; x++)
1340             tiles[x] &= ~LOCKED;
1341     }
1342
1343     /*
1344      * Now compute a list of the possible barrier locations.
1345      */
1346     barriertree = newtree234(xyd_cmp_nc);
1347     for (y = 0; y < h; y++) {
1348         for (x = 0; x < w; x++) {
1349
1350             if (!(index(params, tiles, x, y) & R) &&
1351                 (params->wrapping || x < w-1))
1352                 add234(barriertree, new_xyd(x, y, R));
1353             if (!(index(params, tiles, x, y) & D) &&
1354                 (params->wrapping || y < h-1))
1355                 add234(barriertree, new_xyd(x, y, D));
1356         }
1357     }
1358
1359     /*
1360      * Save the unshuffled grid in an aux_info.
1361      */
1362     {
1363         game_aux_info *solution;
1364
1365         solution = snew(game_aux_info);
1366         solution->width = w;
1367         solution->height = h;
1368         solution->tiles = snewn(w * h, unsigned char);
1369         memcpy(solution->tiles, tiles, w * h);
1370
1371         *aux = solution;
1372     }
1373
1374     /*
1375      * Now shuffle the grid.
1376      */
1377     for (y = 0; y < h; y++) {
1378         for (x = 0; x < w; x++) {
1379             int orig = index(params, tiles, x, y);
1380             int rot = random_upto(rs, 4);
1381             index(params, tiles, x, y) = ROT(orig, rot);
1382         }
1383     }
1384
1385     /*
1386      * And now choose barrier locations. (We carefully do this
1387      * _after_ shuffling, so that changing the barrier rate in the
1388      * params while keeping the random seed the same will give the
1389      * same shuffled grid and _only_ change the barrier locations.
1390      * Also the way we choose barrier locations, by repeatedly
1391      * choosing one possibility from the list until we have enough,
1392      * is designed to ensure that raising the barrier rate while
1393      * keeping the seed the same will provide a superset of the
1394      * previous barrier set - i.e. if you ask for 10 barriers, and
1395      * then decide that's still too hard and ask for 20, you'll get
1396      * the original 10 plus 10 more, rather than getting 20 new
1397      * ones and the chance of remembering your first 10.)
1398      */
1399     nbarriers = (int)(params->barrier_probability * count234(barriertree));
1400     assert(nbarriers >= 0 && nbarriers <= count234(barriertree));
1401
1402     while (nbarriers > 0) {
1403         int i;
1404         struct xyd *xyd;
1405         int x1, y1, d1, x2, y2, d2;
1406
1407         /*
1408          * Extract a randomly chosen barrier from the list.
1409          */
1410         i = random_upto(rs, count234(barriertree));
1411         xyd = delpos234(barriertree, i);
1412
1413         assert(xyd != NULL);
1414
1415         x1 = xyd->x;
1416         y1 = xyd->y;
1417         d1 = xyd->direction;
1418         sfree(xyd);
1419
1420         OFFSET(x2, y2, x1, y1, d1, params);
1421         d2 = F(d1);
1422
1423         index(params, barriers, x1, y1) |= d1;
1424         index(params, barriers, x2, y2) |= d2;
1425
1426         nbarriers--;
1427     }
1428
1429     /*
1430      * Clean up the rest of the barrier list.
1431      */
1432     {
1433         struct xyd *xyd;
1434
1435         while ( (xyd = delpos234(barriertree, 0)) != NULL)
1436             sfree(xyd);
1437
1438         freetree234(barriertree);
1439     }
1440
1441     /*
1442      * Finally, encode the grid into a string game description.
1443      * 
1444      * My syntax is extremely simple: each square is encoded as a
1445      * hex digit in which bit 0 means a connection on the right,
1446      * bit 1 means up, bit 2 left and bit 3 down. (i.e. the same
1447      * encoding as used internally). Each digit is followed by
1448      * optional barrier indicators: `v' means a vertical barrier to
1449      * the right of it, and `h' means a horizontal barrier below
1450      * it.
1451      */
1452     desc = snewn(w * h * 3 + 1, char);
1453     p = desc;
1454     for (y = 0; y < h; y++) {
1455         for (x = 0; x < w; x++) {
1456             *p++ = "0123456789abcdef"[index(params, tiles, x, y)];
1457             if ((params->wrapping || x < w-1) &&
1458                 (index(params, barriers, x, y) & R))
1459                 *p++ = 'v';
1460             if ((params->wrapping || y < h-1) &&
1461                 (index(params, barriers, x, y) & D))
1462                 *p++ = 'h';
1463         }
1464     }
1465     assert(p - desc <= w*h*3);
1466     *p = '\0';
1467
1468     sfree(tiles);
1469     sfree(barriers);
1470
1471     return desc;
1472 }
1473
1474 static void game_free_aux_info(game_aux_info *aux)
1475 {
1476     sfree(aux->tiles);
1477     sfree(aux);
1478 }
1479
1480 static char *validate_desc(game_params *params, char *desc)
1481 {
1482     int w = params->width, h = params->height;
1483     int i;
1484
1485     for (i = 0; i < w*h; i++) {
1486         if (*desc >= '0' && *desc <= '9')
1487             /* OK */;
1488         else if (*desc >= 'a' && *desc <= 'f')
1489             /* OK */;
1490         else if (*desc >= 'A' && *desc <= 'F')
1491             /* OK */;
1492         else if (!*desc)
1493             return "Game description shorter than expected";
1494         else
1495             return "Game description contained unexpected character";
1496         desc++;
1497         while (*desc == 'h' || *desc == 'v')
1498             desc++;
1499     }
1500     if (*desc)
1501         return "Game description longer than expected";
1502
1503     return NULL;
1504 }
1505
1506 /* ----------------------------------------------------------------------
1507  * Construct an initial game state, given a description and parameters.
1508  */
1509
1510 static game_state *new_game(game_params *params, char *desc)
1511 {
1512     game_state *state;
1513     int w, h, x, y;
1514
1515     assert(params->width > 0 && params->height > 0);
1516     assert(params->width > 1 || params->height > 1);
1517
1518     /*
1519      * Create a blank game state.
1520      */
1521     state = snew(game_state);
1522     w = state->width = params->width;
1523     h = state->height = params->height;
1524     state->cx = state->width / 2;
1525     state->cy = state->height / 2;
1526     state->wrapping = params->wrapping;
1527     state->last_rotate_dir = state->last_rotate_x = state->last_rotate_y = 0;
1528     state->completed = state->used_solve = state->just_used_solve = FALSE;
1529     state->tiles = snewn(state->width * state->height, unsigned char);
1530     memset(state->tiles, 0, state->width * state->height);
1531     state->barriers = snewn(state->width * state->height, unsigned char);
1532     memset(state->barriers, 0, state->width * state->height);
1533
1534     /*
1535      * Parse the game description into the grid.
1536      */
1537     for (y = 0; y < h; y++) {
1538         for (x = 0; x < w; x++) {
1539             if (*desc >= '0' && *desc <= '9')
1540                 tile(state, x, y) = *desc - '0';
1541             else if (*desc >= 'a' && *desc <= 'f')
1542                 tile(state, x, y) = *desc - 'a' + 10;
1543             else if (*desc >= 'A' && *desc <= 'F')
1544                 tile(state, x, y) = *desc - 'A' + 10;
1545             if (*desc)
1546                 desc++;
1547             while (*desc == 'h' || *desc == 'v') {
1548                 int x2, y2, d1, d2;
1549                 if (*desc == 'v')
1550                     d1 = R;
1551                 else
1552                     d1 = D;
1553
1554                 OFFSET(x2, y2, x, y, d1, state);
1555                 d2 = F(d1);
1556
1557                 barrier(state, x, y) |= d1;
1558                 barrier(state, x2, y2) |= d2;
1559
1560                 desc++;
1561             }
1562         }
1563     }
1564
1565     /*
1566      * Set up border barriers if this is a non-wrapping game.
1567      */
1568     if (!state->wrapping) {
1569         for (x = 0; x < state->width; x++) {
1570             barrier(state, x, 0) |= U;
1571             barrier(state, x, state->height-1) |= D;
1572         }
1573         for (y = 0; y < state->height; y++) {
1574             barrier(state, 0, y) |= L;
1575             barrier(state, state->width-1, y) |= R;
1576         }
1577     }
1578
1579     /*
1580      * Set up the barrier corner flags, for drawing barriers
1581      * prettily when they meet.
1582      */
1583     for (y = 0; y < state->height; y++) {
1584         for (x = 0; x < state->width; x++) {
1585             int dir;
1586
1587             for (dir = 1; dir < 0x10; dir <<= 1) {
1588                 int dir2 = A(dir);
1589                 int x1, y1, x2, y2, x3, y3;
1590                 int corner = FALSE;
1591
1592                 if (!(barrier(state, x, y) & dir))
1593                     continue;
1594
1595                 if (barrier(state, x, y) & dir2)
1596                     corner = TRUE;
1597
1598                 x1 = x + X(dir), y1 = y + Y(dir);
1599                 if (x1 >= 0 && x1 < state->width &&
1600                     y1 >= 0 && y1 < state->height &&
1601                     (barrier(state, x1, y1) & dir2))
1602                     corner = TRUE;
1603
1604                 x2 = x + X(dir2), y2 = y + Y(dir2);
1605                 if (x2 >= 0 && x2 < state->width &&
1606                     y2 >= 0 && y2 < state->height &&
1607                     (barrier(state, x2, y2) & dir))
1608                     corner = TRUE;
1609
1610                 if (corner) {
1611                     barrier(state, x, y) |= (dir << 4);
1612                     if (x1 >= 0 && x1 < state->width &&
1613                         y1 >= 0 && y1 < state->height)
1614                         barrier(state, x1, y1) |= (A(dir) << 4);
1615                     if (x2 >= 0 && x2 < state->width &&
1616                         y2 >= 0 && y2 < state->height)
1617                         barrier(state, x2, y2) |= (C(dir) << 4);
1618                     x3 = x + X(dir) + X(dir2), y3 = y + Y(dir) + Y(dir2);
1619                     if (x3 >= 0 && x3 < state->width &&
1620                         y3 >= 0 && y3 < state->height)
1621                         barrier(state, x3, y3) |= (F(dir) << 4);
1622                 }
1623             }
1624         }
1625     }
1626
1627     return state;
1628 }
1629
1630 static game_state *dup_game(game_state *state)
1631 {
1632     game_state *ret;
1633
1634     ret = snew(game_state);
1635     ret->width = state->width;
1636     ret->height = state->height;
1637     ret->cx = state->cx;
1638     ret->cy = state->cy;
1639     ret->wrapping = state->wrapping;
1640     ret->completed = state->completed;
1641     ret->used_solve = state->used_solve;
1642     ret->just_used_solve = state->just_used_solve;
1643     ret->last_rotate_dir = state->last_rotate_dir;
1644     ret->last_rotate_x = state->last_rotate_x;
1645     ret->last_rotate_y = state->last_rotate_y;
1646     ret->tiles = snewn(state->width * state->height, unsigned char);
1647     memcpy(ret->tiles, state->tiles, state->width * state->height);
1648     ret->barriers = snewn(state->width * state->height, unsigned char);
1649     memcpy(ret->barriers, state->barriers, state->width * state->height);
1650
1651     return ret;
1652 }
1653
1654 static void free_game(game_state *state)
1655 {
1656     sfree(state->tiles);
1657     sfree(state->barriers);
1658     sfree(state);
1659 }
1660
1661 static game_state *solve_game(game_state *state, game_aux_info *aux,
1662                               char **error)
1663 {
1664     game_state *ret;
1665
1666     if (!aux) {
1667         /*
1668          * Run the internal solver on the provided grid. This might
1669          * not yield a complete solution.
1670          */
1671         ret = dup_game(state);
1672         net_solver(ret->width, ret->height, ret->tiles,
1673                    ret->barriers, ret->wrapping);
1674     } else {
1675         assert(aux->width == state->width);
1676         assert(aux->height == state->height);
1677         ret = dup_game(state);
1678         memcpy(ret->tiles, aux->tiles, ret->width * ret->height);
1679         ret->used_solve = ret->just_used_solve = TRUE;
1680         ret->completed = TRUE;
1681     }
1682
1683     return ret;
1684 }
1685
1686 static char *game_text_format(game_state *state)
1687 {
1688     return NULL;
1689 }
1690
1691 /* ----------------------------------------------------------------------
1692  * Utility routine.
1693  */
1694
1695 /*
1696  * Compute which squares are reachable from the centre square, as a
1697  * quick visual aid to determining how close the game is to
1698  * completion. This is also a simple way to tell if the game _is_
1699  * completed - just call this function and see whether every square
1700  * is marked active.
1701  */
1702 static unsigned char *compute_active(game_state *state)
1703 {
1704     unsigned char *active;
1705     tree234 *todo;
1706     struct xyd *xyd;
1707
1708     active = snewn(state->width * state->height, unsigned char);
1709     memset(active, 0, state->width * state->height);
1710
1711     /*
1712      * We only store (x,y) pairs in todo, but it's easier to reuse
1713      * xyd_cmp and just store direction 0 every time.
1714      */
1715     todo = newtree234(xyd_cmp_nc);
1716     index(state, active, state->cx, state->cy) = ACTIVE;
1717     add234(todo, new_xyd(state->cx, state->cy, 0));
1718
1719     while ( (xyd = delpos234(todo, 0)) != NULL) {
1720         int x1, y1, d1, x2, y2, d2;
1721
1722         x1 = xyd->x;
1723         y1 = xyd->y;
1724         sfree(xyd);
1725
1726         for (d1 = 1; d1 < 0x10; d1 <<= 1) {
1727             OFFSET(x2, y2, x1, y1, d1, state);
1728             d2 = F(d1);
1729
1730             /*
1731              * If the next tile in this direction is connected to
1732              * us, and there isn't a barrier in the way, and it
1733              * isn't already marked active, then mark it active and
1734              * add it to the to-examine list.
1735              */
1736             if ((tile(state, x1, y1) & d1) &&
1737                 (tile(state, x2, y2) & d2) &&
1738                 !(barrier(state, x1, y1) & d1) &&
1739                 !index(state, active, x2, y2)) {
1740                 index(state, active, x2, y2) = ACTIVE;
1741                 add234(todo, new_xyd(x2, y2, 0));
1742             }
1743         }
1744     }
1745     /* Now we expect the todo list to have shrunk to zero size. */
1746     assert(count234(todo) == 0);
1747     freetree234(todo);
1748
1749     return active;
1750 }
1751
1752 struct game_ui {
1753     int cur_x, cur_y;
1754     int cur_visible;
1755     random_state *rs; /* used for jumbling */
1756 };
1757
1758 static game_ui *new_ui(game_state *state)
1759 {
1760     void *seed;
1761     int seedsize;
1762     game_ui *ui = snew(game_ui);
1763     ui->cur_x = state->width / 2;
1764     ui->cur_y = state->height / 2;
1765     ui->cur_visible = FALSE;
1766     get_random_seed(&seed, &seedsize);
1767     ui->rs = random_init(seed, seedsize);
1768     sfree(seed);
1769
1770     return ui;
1771 }
1772
1773 static void free_ui(game_ui *ui)
1774 {
1775     random_free(ui->rs);
1776     sfree(ui);
1777 }
1778
1779 /* ----------------------------------------------------------------------
1780  * Process a move.
1781  */
1782 static game_state *make_move(game_state *state, game_ui *ui,
1783                              int x, int y, int button)
1784 {
1785     game_state *ret, *nullret;
1786     int tx, ty, orig;
1787
1788     nullret = NULL;
1789
1790     if (button == LEFT_BUTTON ||
1791         button == MIDDLE_BUTTON ||
1792         button == RIGHT_BUTTON) {
1793
1794         if (ui->cur_visible) {
1795             ui->cur_visible = FALSE;
1796             nullret = state;
1797         }
1798
1799         /*
1800          * The button must have been clicked on a valid tile.
1801          */
1802         x -= WINDOW_OFFSET + TILE_BORDER;
1803         y -= WINDOW_OFFSET + TILE_BORDER;
1804         if (x < 0 || y < 0)
1805             return nullret;
1806         tx = x / TILE_SIZE;
1807         ty = y / TILE_SIZE;
1808         if (tx >= state->width || ty >= state->height)
1809             return nullret;
1810         if (x % TILE_SIZE >= TILE_SIZE - TILE_BORDER ||
1811             y % TILE_SIZE >= TILE_SIZE - TILE_BORDER)
1812             return nullret;
1813     } else if (button == CURSOR_UP || button == CURSOR_DOWN ||
1814                button == CURSOR_RIGHT || button == CURSOR_LEFT) {
1815         if (button == CURSOR_UP && ui->cur_y > 0)
1816             ui->cur_y--;
1817         else if (button == CURSOR_DOWN && ui->cur_y < state->height-1)
1818             ui->cur_y++;
1819         else if (button == CURSOR_LEFT && ui->cur_x > 0)
1820             ui->cur_x--;
1821         else if (button == CURSOR_RIGHT && ui->cur_x < state->width-1)
1822             ui->cur_x++;
1823         else
1824             return nullret;            /* no cursor movement */
1825         ui->cur_visible = TRUE;
1826         return state;                  /* UI activity has occurred */
1827     } else if (button == 'a' || button == 's' || button == 'd' ||
1828                button == 'A' || button == 'S' || button == 'D') {
1829         tx = ui->cur_x;
1830         ty = ui->cur_y;
1831         if (button == 'a' || button == 'A')
1832             button = LEFT_BUTTON;
1833         else if (button == 's' || button == 'S')
1834             button = MIDDLE_BUTTON;
1835         else if (button == 'd' || button == 'D')
1836             button = RIGHT_BUTTON;
1837         ui->cur_visible = TRUE;
1838     } else if (button == 'j' || button == 'J') {
1839         /* XXX should we have some mouse control for this? */
1840         button = 'J';   /* canonify */
1841         tx = ty = -1;   /* shut gcc up :( */
1842     } else
1843         return nullret;
1844
1845     /*
1846      * The middle button locks or unlocks a tile. (A locked tile
1847      * cannot be turned, and is visually marked as being locked.
1848      * This is a convenience for the player, so that once they are
1849      * sure which way round a tile goes, they can lock it and thus
1850      * avoid forgetting later on that they'd already done that one;
1851      * and the locking also prevents them turning the tile by
1852      * accident. If they change their mind, another middle click
1853      * unlocks it.)
1854      */
1855     if (button == MIDDLE_BUTTON) {
1856
1857         ret = dup_game(state);
1858         ret->just_used_solve = FALSE;
1859         tile(ret, tx, ty) ^= LOCKED;
1860         ret->last_rotate_dir = ret->last_rotate_x = ret->last_rotate_y = 0;
1861         return ret;
1862
1863     } else if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
1864
1865         /*
1866          * The left and right buttons have no effect if clicked on a
1867          * locked tile.
1868          */
1869         if (tile(state, tx, ty) & LOCKED)
1870             return nullret;
1871
1872         /*
1873          * Otherwise, turn the tile one way or the other. Left button
1874          * turns anticlockwise; right button turns clockwise.
1875          */
1876         ret = dup_game(state);
1877         ret->just_used_solve = FALSE;
1878         orig = tile(ret, tx, ty);
1879         if (button == LEFT_BUTTON) {
1880             tile(ret, tx, ty) = A(orig);
1881             ret->last_rotate_dir = +1;
1882         } else {
1883             tile(ret, tx, ty) = C(orig);
1884             ret->last_rotate_dir = -1;
1885         }
1886         ret->last_rotate_x = tx;
1887         ret->last_rotate_y = ty;
1888
1889     } else if (button == 'J') {
1890
1891         /*
1892          * Jumble all unlocked tiles to random orientations.
1893          */
1894         int jx, jy;
1895         ret = dup_game(state);
1896         ret->just_used_solve = FALSE;
1897         for (jy = 0; jy < ret->height; jy++) {
1898             for (jx = 0; jx < ret->width; jx++) {
1899                 if (!(tile(ret, jx, jy) & LOCKED)) {
1900                     int rot = random_upto(ui->rs, 4);
1901                     orig = tile(ret, jx, jy);
1902                     tile(ret, jx, jy) = ROT(orig, rot);
1903                 }
1904             }
1905         }
1906         ret->last_rotate_dir = 0; /* suppress animation */
1907         ret->last_rotate_x = ret->last_rotate_y = 0;
1908
1909     } else assert(0);
1910
1911     /*
1912      * Check whether the game has been completed.
1913      */
1914     {
1915         unsigned char *active = compute_active(ret);
1916         int x1, y1;
1917         int complete = TRUE;
1918
1919         for (x1 = 0; x1 < ret->width; x1++)
1920             for (y1 = 0; y1 < ret->height; y1++)
1921                 if ((tile(ret, x1, y1) & 0xF) && !index(ret, active, x1, y1)) {
1922                     complete = FALSE;
1923                     goto break_label;  /* break out of two loops at once */
1924                 }
1925         break_label:
1926
1927         sfree(active);
1928
1929         if (complete)
1930             ret->completed = TRUE;
1931     }
1932
1933     return ret;
1934 }
1935
1936 /* ----------------------------------------------------------------------
1937  * Routines for drawing the game position on the screen.
1938  */
1939
1940 struct game_drawstate {
1941     int started;
1942     int width, height;
1943     unsigned char *visible;
1944 };
1945
1946 static game_drawstate *game_new_drawstate(game_state *state)
1947 {
1948     game_drawstate *ds = snew(game_drawstate);
1949
1950     ds->started = FALSE;
1951     ds->width = state->width;
1952     ds->height = state->height;
1953     ds->visible = snewn(state->width * state->height, unsigned char);
1954     memset(ds->visible, 0xFF, state->width * state->height);
1955
1956     return ds;
1957 }
1958
1959 static void game_free_drawstate(game_drawstate *ds)
1960 {
1961     sfree(ds->visible);
1962     sfree(ds);
1963 }
1964
1965 static void game_size(game_params *params, int *x, int *y)
1966 {
1967     *x = WINDOW_OFFSET * 2 + TILE_SIZE * params->width + TILE_BORDER;
1968     *y = WINDOW_OFFSET * 2 + TILE_SIZE * params->height + TILE_BORDER;
1969 }
1970
1971 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
1972 {
1973     float *ret;
1974
1975     ret = snewn(NCOLOURS * 3, float);
1976     *ncolours = NCOLOURS;
1977
1978     /*
1979      * Basic background colour is whatever the front end thinks is
1980      * a sensible default.
1981      */
1982     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1983
1984     /*
1985      * Wires are black.
1986      */
1987     ret[COL_WIRE * 3 + 0] = 0.0F;
1988     ret[COL_WIRE * 3 + 1] = 0.0F;
1989     ret[COL_WIRE * 3 + 2] = 0.0F;
1990
1991     /*
1992      * Powered wires and powered endpoints are cyan.
1993      */
1994     ret[COL_POWERED * 3 + 0] = 0.0F;
1995     ret[COL_POWERED * 3 + 1] = 1.0F;
1996     ret[COL_POWERED * 3 + 2] = 1.0F;
1997
1998     /*
1999      * Barriers are red.
2000      */
2001     ret[COL_BARRIER * 3 + 0] = 1.0F;
2002     ret[COL_BARRIER * 3 + 1] = 0.0F;
2003     ret[COL_BARRIER * 3 + 2] = 0.0F;
2004
2005     /*
2006      * Unpowered endpoints are blue.
2007      */
2008     ret[COL_ENDPOINT * 3 + 0] = 0.0F;
2009     ret[COL_ENDPOINT * 3 + 1] = 0.0F;
2010     ret[COL_ENDPOINT * 3 + 2] = 1.0F;
2011
2012     /*
2013      * Tile borders are a darker grey than the background.
2014      */
2015     ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2016     ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2017     ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2018
2019     /*
2020      * Locked tiles are a grey in between those two.
2021      */
2022     ret[COL_LOCKED * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2023     ret[COL_LOCKED * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2024     ret[COL_LOCKED * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2025
2026     return ret;
2027 }
2028
2029 static void draw_thick_line(frontend *fe, int x1, int y1, int x2, int y2,
2030                             int colour)
2031 {
2032     draw_line(fe, x1-1, y1, x2-1, y2, COL_WIRE);
2033     draw_line(fe, x1+1, y1, x2+1, y2, COL_WIRE);
2034     draw_line(fe, x1, y1-1, x2, y2-1, COL_WIRE);
2035     draw_line(fe, x1, y1+1, x2, y2+1, COL_WIRE);
2036     draw_line(fe, x1, y1, x2, y2, colour);
2037 }
2038
2039 static void draw_rect_coords(frontend *fe, int x1, int y1, int x2, int y2,
2040                              int colour)
2041 {
2042     int mx = (x1 < x2 ? x1 : x2);
2043     int my = (y1 < y2 ? y1 : y2);
2044     int dx = (x2 + x1 - 2*mx + 1);
2045     int dy = (y2 + y1 - 2*my + 1);
2046
2047     draw_rect(fe, mx, my, dx, dy, colour);
2048 }
2049
2050 static void draw_barrier_corner(frontend *fe, int x, int y, int dir, int phase)
2051 {
2052     int bx = WINDOW_OFFSET + TILE_SIZE * x;
2053     int by = WINDOW_OFFSET + TILE_SIZE * y;
2054     int x1, y1, dx, dy, dir2;
2055
2056     dir >>= 4;
2057
2058     dir2 = A(dir);
2059     dx = X(dir) + X(dir2);
2060     dy = Y(dir) + Y(dir2);
2061     x1 = (dx > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
2062     y1 = (dy > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
2063
2064     if (phase == 0) {
2065         draw_rect_coords(fe, bx+x1, by+y1,
2066                          bx+x1-TILE_BORDER*dx, by+y1-(TILE_BORDER-1)*dy,
2067                          COL_WIRE);
2068         draw_rect_coords(fe, bx+x1, by+y1,
2069                          bx+x1-(TILE_BORDER-1)*dx, by+y1-TILE_BORDER*dy,
2070                          COL_WIRE);
2071     } else {
2072         draw_rect_coords(fe, bx+x1, by+y1,
2073                          bx+x1-(TILE_BORDER-1)*dx, by+y1-(TILE_BORDER-1)*dy,
2074                          COL_BARRIER);
2075     }
2076 }
2077
2078 static void draw_barrier(frontend *fe, int x, int y, int dir, int phase)
2079 {
2080     int bx = WINDOW_OFFSET + TILE_SIZE * x;
2081     int by = WINDOW_OFFSET + TILE_SIZE * y;
2082     int x1, y1, w, h;
2083
2084     x1 = (X(dir) > 0 ? TILE_SIZE : X(dir) == 0 ? TILE_BORDER : 0);
2085     y1 = (Y(dir) > 0 ? TILE_SIZE : Y(dir) == 0 ? TILE_BORDER : 0);
2086     w = (X(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
2087     h = (Y(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
2088
2089     if (phase == 0) {
2090         draw_rect(fe, bx+x1-X(dir), by+y1-Y(dir), w, h, COL_WIRE);
2091     } else {
2092         draw_rect(fe, bx+x1, by+y1, w, h, COL_BARRIER);
2093     }
2094 }
2095
2096 static void draw_tile(frontend *fe, game_state *state, int x, int y, int tile,
2097                       float angle, int cursor)
2098 {
2099     int bx = WINDOW_OFFSET + TILE_SIZE * x;
2100     int by = WINDOW_OFFSET + TILE_SIZE * y;
2101     float matrix[4];
2102     float cx, cy, ex, ey, tx, ty;
2103     int dir, col, phase;
2104
2105     /*
2106      * When we draw a single tile, we must draw everything up to
2107      * and including the borders around the tile. This means that
2108      * if the neighbouring tiles have connections to those borders,
2109      * we must draw those connections on the borders themselves.
2110      *
2111      * This would be terribly fiddly if we ever had to draw a tile
2112      * while its neighbour was in mid-rotate, because we'd have to
2113      * arrange to _know_ that the neighbour was being rotated and
2114      * hence had an anomalous effect on the redraw of this tile.
2115      * Fortunately, the drawing algorithm avoids ever calling us in
2116      * this circumstance: we're either drawing lots of straight
2117      * tiles at game start or after a move is complete, or we're
2118      * repeatedly drawing only the rotating tile. So no problem.
2119      */
2120
2121     /*
2122      * So. First blank the tile out completely: draw a big
2123      * rectangle in border colour, and a smaller rectangle in
2124      * background colour to fill it in.
2125      */
2126     draw_rect(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER,
2127               COL_BORDER);
2128     draw_rect(fe, bx+TILE_BORDER, by+TILE_BORDER,
2129               TILE_SIZE-TILE_BORDER, TILE_SIZE-TILE_BORDER,
2130               tile & LOCKED ? COL_LOCKED : COL_BACKGROUND);
2131
2132     /*
2133      * Draw an inset outline rectangle as a cursor, in whichever of
2134      * COL_LOCKED and COL_BACKGROUND we aren't currently drawing
2135      * in.
2136      */
2137     if (cursor) {
2138         draw_line(fe, bx+TILE_SIZE/8, by+TILE_SIZE/8,
2139                   bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2140                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2141         draw_line(fe, bx+TILE_SIZE/8, by+TILE_SIZE/8,
2142                   bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
2143                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2144         draw_line(fe, bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
2145                   bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2146                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2147         draw_line(fe, bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2148                   bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2149                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2150     }
2151
2152     /*
2153      * Set up the rotation matrix.
2154      */
2155     matrix[0] = (float)cos(angle * PI / 180.0);
2156     matrix[1] = (float)-sin(angle * PI / 180.0);
2157     matrix[2] = (float)sin(angle * PI / 180.0);
2158     matrix[3] = (float)cos(angle * PI / 180.0);
2159
2160     /*
2161      * Draw the wires.
2162      */
2163     cx = cy = TILE_BORDER + (TILE_SIZE-TILE_BORDER) / 2.0F - 0.5F;
2164     col = (tile & ACTIVE ? COL_POWERED : COL_WIRE);
2165     for (dir = 1; dir < 0x10; dir <<= 1) {
2166         if (tile & dir) {
2167             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
2168             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
2169             MATMUL(tx, ty, matrix, ex, ey);
2170             draw_thick_line(fe, bx+(int)cx, by+(int)cy,
2171                             bx+(int)(cx+tx), by+(int)(cy+ty),
2172                             COL_WIRE);
2173         }
2174     }
2175     for (dir = 1; dir < 0x10; dir <<= 1) {
2176         if (tile & dir) {
2177             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
2178             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
2179             MATMUL(tx, ty, matrix, ex, ey);
2180             draw_line(fe, bx+(int)cx, by+(int)cy,
2181                       bx+(int)(cx+tx), by+(int)(cy+ty), col);
2182         }
2183     }
2184
2185     /*
2186      * Draw the box in the middle. We do this in blue if the tile
2187      * is an unpowered endpoint, in cyan if the tile is a powered
2188      * endpoint, in black if the tile is the centrepiece, and
2189      * otherwise not at all.
2190      */
2191     col = -1;
2192     if (x == state->cx && y == state->cy)
2193         col = COL_WIRE;
2194     else if (COUNT(tile) == 1) {
2195         col = (tile & ACTIVE ? COL_POWERED : COL_ENDPOINT);
2196     }
2197     if (col >= 0) {
2198         int i, points[8];
2199
2200         points[0] = +1; points[1] = +1;
2201         points[2] = +1; points[3] = -1;
2202         points[4] = -1; points[5] = -1;
2203         points[6] = -1; points[7] = +1;
2204
2205         for (i = 0; i < 8; i += 2) {
2206             ex = (TILE_SIZE * 0.24F) * points[i];
2207             ey = (TILE_SIZE * 0.24F) * points[i+1];
2208             MATMUL(tx, ty, matrix, ex, ey);
2209             points[i] = bx+(int)(cx+tx);
2210             points[i+1] = by+(int)(cy+ty);
2211         }
2212
2213         draw_polygon(fe, points, 4, TRUE, col);
2214         draw_polygon(fe, points, 4, FALSE, COL_WIRE);
2215     }
2216
2217     /*
2218      * Draw the points on the border if other tiles are connected
2219      * to us.
2220      */
2221     for (dir = 1; dir < 0x10; dir <<= 1) {
2222         int dx, dy, px, py, lx, ly, vx, vy, ox, oy;
2223
2224         dx = X(dir);
2225         dy = Y(dir);
2226
2227         ox = x + dx;
2228         oy = y + dy;
2229
2230         if (ox < 0 || ox >= state->width || oy < 0 || oy >= state->height)
2231             continue;
2232
2233         if (!(tile(state, ox, oy) & F(dir)))
2234             continue;
2235
2236         px = bx + (int)(dx>0 ? TILE_SIZE + TILE_BORDER - 1 : dx<0 ? 0 : cx);
2237         py = by + (int)(dy>0 ? TILE_SIZE + TILE_BORDER - 1 : dy<0 ? 0 : cy);
2238         lx = dx * (TILE_BORDER-1);
2239         ly = dy * (TILE_BORDER-1);
2240         vx = (dy ? 1 : 0);
2241         vy = (dx ? 1 : 0);
2242
2243         if (angle == 0.0 && (tile & dir)) {
2244             /*
2245              * If we are fully connected to the other tile, we must
2246              * draw right across the tile border. (We can use our
2247              * own ACTIVE state to determine what colour to do this
2248              * in: if we are fully connected to the other tile then
2249              * the two ACTIVE states will be the same.)
2250              */
2251             draw_rect_coords(fe, px-vx, py-vy, px+lx+vx, py+ly+vy, COL_WIRE);
2252             draw_rect_coords(fe, px, py, px+lx, py+ly,
2253                              (tile & ACTIVE) ? COL_POWERED : COL_WIRE);
2254         } else {
2255             /*
2256              * The other tile extends into our border, but isn't
2257              * actually connected to us. Just draw a single black
2258              * dot.
2259              */
2260             draw_rect_coords(fe, px, py, px, py, COL_WIRE);
2261         }
2262     }
2263
2264     /*
2265      * Draw barrier corners, and then barriers.
2266      */
2267     for (phase = 0; phase < 2; phase++) {
2268         for (dir = 1; dir < 0x10; dir <<= 1)
2269             if (barrier(state, x, y) & (dir << 4))
2270                 draw_barrier_corner(fe, x, y, dir << 4, phase);
2271         for (dir = 1; dir < 0x10; dir <<= 1)
2272             if (barrier(state, x, y) & dir)
2273                 draw_barrier(fe, x, y, dir, phase);
2274     }
2275
2276     draw_update(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
2277 }
2278
2279 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
2280                  game_state *state, int dir, game_ui *ui, float t, float ft)
2281 {
2282     int x, y, tx, ty, frame, last_rotate_dir;
2283     unsigned char *active;
2284     float angle = 0.0;
2285
2286     /*
2287      * Clear the screen and draw the exterior barrier lines if this
2288      * is our first call.
2289      */
2290     if (!ds->started) {
2291         int phase;
2292
2293         ds->started = TRUE;
2294
2295         draw_rect(fe, 0, 0, 
2296                   WINDOW_OFFSET * 2 + TILE_SIZE * state->width + TILE_BORDER,
2297                   WINDOW_OFFSET * 2 + TILE_SIZE * state->height + TILE_BORDER,
2298                   COL_BACKGROUND);
2299         draw_update(fe, 0, 0, 
2300                     WINDOW_OFFSET*2 + TILE_SIZE*state->width + TILE_BORDER,
2301                     WINDOW_OFFSET*2 + TILE_SIZE*state->height + TILE_BORDER);
2302
2303         for (phase = 0; phase < 2; phase++) {
2304
2305             for (x = 0; x < ds->width; x++) {
2306                 if (barrier(state, x, 0) & UL)
2307                     draw_barrier_corner(fe, x, -1, LD, phase);
2308                 if (barrier(state, x, 0) & RU)
2309                     draw_barrier_corner(fe, x, -1, DR, phase);
2310                 if (barrier(state, x, 0) & U)
2311                     draw_barrier(fe, x, -1, D, phase);
2312                 if (barrier(state, x, ds->height-1) & DR)
2313                     draw_barrier_corner(fe, x, ds->height, RU, phase);
2314                 if (barrier(state, x, ds->height-1) & LD)
2315                     draw_barrier_corner(fe, x, ds->height, UL, phase);
2316                 if (barrier(state, x, ds->height-1) & D)
2317                     draw_barrier(fe, x, ds->height, U, phase);
2318             }
2319
2320             for (y = 0; y < ds->height; y++) {
2321                 if (barrier(state, 0, y) & UL)
2322                     draw_barrier_corner(fe, -1, y, RU, phase);
2323                 if (barrier(state, 0, y) & LD)
2324                     draw_barrier_corner(fe, -1, y, DR, phase);
2325                 if (barrier(state, 0, y) & L)
2326                     draw_barrier(fe, -1, y, R, phase);
2327                 if (barrier(state, ds->width-1, y) & RU)
2328                     draw_barrier_corner(fe, ds->width, y, UL, phase);
2329                 if (barrier(state, ds->width-1, y) & DR)
2330                     draw_barrier_corner(fe, ds->width, y, LD, phase);
2331                 if (barrier(state, ds->width-1, y) & R)
2332                     draw_barrier(fe, ds->width, y, L, phase);
2333             }
2334         }
2335     }
2336
2337     tx = ty = -1;
2338     last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2339                                 state->last_rotate_dir;
2340     if (oldstate && (t < ROTATE_TIME) && last_rotate_dir) {
2341         /*
2342          * We're animating a single tile rotation. Find the turning
2343          * tile.
2344          */
2345         tx = (dir==-1 ? oldstate->last_rotate_x : state->last_rotate_x);
2346         ty = (dir==-1 ? oldstate->last_rotate_y : state->last_rotate_y);
2347         angle = last_rotate_dir * dir * 90.0F * (t / ROTATE_TIME);
2348         state = oldstate;
2349     }
2350
2351     frame = -1;
2352     if (ft > 0) {
2353         /*
2354          * We're animating a completion flash. Find which frame
2355          * we're at.
2356          */
2357         frame = (int)(ft / FLASH_FRAME);
2358     }
2359
2360     /*
2361      * Draw any tile which differs from the way it was last drawn.
2362      */
2363     active = compute_active(state);
2364
2365     for (x = 0; x < ds->width; x++)
2366         for (y = 0; y < ds->height; y++) {
2367             unsigned char c = tile(state, x, y) | index(state, active, x, y);
2368
2369             /*
2370              * In a completion flash, we adjust the LOCKED bit
2371              * depending on our distance from the centre point and
2372              * the frame number.
2373              */
2374             if (frame >= 0) {
2375                 int xdist, ydist, dist;
2376                 xdist = (x < state->cx ? state->cx - x : x - state->cx);
2377                 ydist = (y < state->cy ? state->cy - y : y - state->cy);
2378                 dist = (xdist > ydist ? xdist : ydist);
2379
2380                 if (frame >= dist && frame < dist+4) {
2381                     int lock = (frame - dist) & 1;
2382                     lock = lock ? LOCKED : 0;
2383                     c = (c &~ LOCKED) | lock;
2384                 }
2385             }
2386
2387             if (index(state, ds->visible, x, y) != c ||
2388                 index(state, ds->visible, x, y) == 0xFF ||
2389                 (x == tx && y == ty) ||
2390                 (ui->cur_visible && x == ui->cur_x && y == ui->cur_y)) {
2391                 draw_tile(fe, state, x, y, c,
2392                           (x == tx && y == ty ? angle : 0.0F),
2393                           (ui->cur_visible && x == ui->cur_x && y == ui->cur_y));
2394                 if ((x == tx && y == ty) ||
2395                     (ui->cur_visible && x == ui->cur_x && y == ui->cur_y))
2396                     index(state, ds->visible, x, y) = 0xFF;
2397                 else
2398                     index(state, ds->visible, x, y) = c;
2399             }
2400         }
2401
2402     /*
2403      * Update the status bar.
2404      */
2405     {
2406         char statusbuf[256];
2407         int i, n, n2, a;
2408
2409         n = state->width * state->height;
2410         for (i = a = n2 = 0; i < n; i++) {
2411             if (active[i])
2412                 a++;
2413             if (state->tiles[i] & 0xF)
2414                 n2++;
2415         }
2416
2417         sprintf(statusbuf, "%sActive: %d/%d",
2418                 (state->used_solve ? "Auto-solved. " :
2419                  state->completed ? "COMPLETED! " : ""), a, n2);
2420
2421         status_bar(fe, statusbuf);
2422     }
2423
2424     sfree(active);
2425 }
2426
2427 static float game_anim_length(game_state *oldstate,
2428                               game_state *newstate, int dir)
2429 {
2430     int last_rotate_dir;
2431
2432     /*
2433      * Don't animate an auto-solve move.
2434      */
2435     if ((dir > 0 && newstate->just_used_solve) ||
2436        (dir < 0 && oldstate->just_used_solve))
2437        return 0.0F;
2438
2439     /*
2440      * Don't animate if last_rotate_dir is zero.
2441      */
2442     last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2443                                 newstate->last_rotate_dir;
2444     if (last_rotate_dir)
2445         return ROTATE_TIME;
2446
2447     return 0.0F;
2448 }
2449
2450 static float game_flash_length(game_state *oldstate,
2451                                game_state *newstate, int dir)
2452 {
2453     /*
2454      * If the game has just been completed, we display a completion
2455      * flash.
2456      */
2457     if (!oldstate->completed && newstate->completed &&
2458         !oldstate->used_solve && !newstate->used_solve) {
2459         int size;
2460         size = 0;
2461         if (size < newstate->cx+1)
2462             size = newstate->cx+1;
2463         if (size < newstate->cy+1)
2464             size = newstate->cy+1;
2465         if (size < newstate->width - newstate->cx)
2466             size = newstate->width - newstate->cx;
2467         if (size < newstate->height - newstate->cy)
2468             size = newstate->height - newstate->cy;
2469         return FLASH_FRAME * (size+4);
2470     }
2471
2472     return 0.0F;
2473 }
2474
2475 static int game_wants_statusbar(void)
2476 {
2477     return TRUE;
2478 }
2479
2480 #ifdef COMBINED
2481 #define thegame net
2482 #endif
2483
2484 const struct game thegame = {
2485     "Net", "games.net",
2486     default_params,
2487     game_fetch_preset,
2488     decode_params,
2489     encode_params,
2490     free_params,
2491     dup_params,
2492     TRUE, game_configure, custom_params,
2493     validate_params,
2494     new_game_desc,
2495     game_free_aux_info,
2496     validate_desc,
2497     new_game,
2498     dup_game,
2499     free_game,
2500     TRUE, solve_game,
2501     FALSE, game_text_format,
2502     new_ui,
2503     free_ui,
2504     make_move,
2505     game_size,
2506     game_colours,
2507     game_new_drawstate,
2508     game_free_drawstate,
2509     game_redraw,
2510     game_anim_length,
2511     game_flash_length,
2512     game_wants_statusbar,
2513 };