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