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