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