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