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