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