chiark / gitweb /
`BOOLEAN' is a term already used by Win32. Bah. Change terminology.
[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 <math.h>
10
11 #include "puzzles.h"
12 #include "tree234.h"
13
14 const char *const game_name = "Net";
15 const int game_can_configure = TRUE;
16
17 #define PI 3.141592653589793238462643383279502884197169399
18
19 #define MATMUL(xr,yr,m,x,y) do { \
20     float rx, ry, xx = (x), yy = (y), *mat = (m); \
21     rx = mat[0] * xx + mat[2] * yy; \
22     ry = mat[1] * xx + mat[3] * yy; \
23     (xr) = rx; (yr) = ry; \
24 } while (0)
25
26 /* Direction and other bitfields */
27 #define R 0x01
28 #define U 0x02
29 #define L 0x04
30 #define D 0x08
31 #define LOCKED 0x10
32 #define ACTIVE 0x20
33 /* Corner flags go in the barriers array */
34 #define RU 0x10
35 #define UL 0x20
36 #define LD 0x40
37 #define DR 0x80
38
39 /* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
40 #define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
41 #define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
42 #define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
43 #define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
44                     ((n)&3) == 1 ? A(x) : \
45                     ((n)&3) == 2 ? F(x) : C(x) )
46
47 /* X and Y displacements */
48 #define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
49 #define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
50
51 /* Bit count */
52 #define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
53                    (((x) & 0x02) >> 1) + ((x) & 0x01) )
54
55 #define TILE_SIZE 32
56 #define TILE_BORDER 1
57 #define WINDOW_OFFSET 16
58
59 #define ROTATE_TIME 0.1F
60 #define FLASH_FRAME 0.05F
61
62 enum {
63     COL_BACKGROUND,
64     COL_LOCKED,
65     COL_BORDER,
66     COL_WIRE,
67     COL_ENDPOINT,
68     COL_POWERED,
69     COL_BARRIER,
70     NCOLOURS
71 };
72
73 struct game_params {
74     int width;
75     int height;
76     int wrapping;
77     float barrier_probability;
78 };
79
80 struct game_state {
81     int width, height, cx, cy, wrapping, completed, last_rotate_dir;
82     unsigned char *tiles;
83     unsigned char *barriers;
84 };
85
86 #define OFFSET(x2,y2,x1,y1,dir,state) \
87     ( (x2) = ((x1) + (state)->width + X((dir))) % (state)->width, \
88       (y2) = ((y1) + (state)->height + Y((dir))) % (state)->height)
89
90 #define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
91 #define tile(state, x, y)     index(state, (state)->tiles, x, y)
92 #define barrier(state, x, y)  index(state, (state)->barriers, x, y)
93
94 struct xyd {
95     int x, y, direction;
96 };
97
98 static int xyd_cmp(void *av, void *bv) {
99     struct xyd *a = (struct xyd *)av;
100     struct xyd *b = (struct xyd *)bv;
101     if (a->x < b->x)
102         return -1;
103     if (a->x > b->x)
104         return +1;
105     if (a->y < b->y)
106         return -1;
107     if (a->y > b->y)
108         return +1;
109     if (a->direction < b->direction)
110         return -1;
111     if (a->direction > b->direction)
112         return +1;
113     return 0;
114 };
115
116 static struct xyd *new_xyd(int x, int y, int direction)
117 {
118     struct xyd *xyd = snew(struct xyd);
119     xyd->x = x;
120     xyd->y = y;
121     xyd->direction = direction;
122     return xyd;
123 }
124
125 /* ----------------------------------------------------------------------
126  * Manage game parameters.
127  */
128 game_params *default_params(void)
129 {
130     game_params *ret = snew(game_params);
131
132     ret->width = 5;
133     ret->height = 5;
134     ret->wrapping = FALSE;
135     ret->barrier_probability = 0.0;
136
137     return ret;
138 }
139
140 int game_fetch_preset(int i, char **name, game_params **params)
141 {
142     game_params *ret;
143     char str[80];
144     static const struct { int x, y, wrap; } values[] = {
145         {5, 5, FALSE},
146         {7, 7, FALSE},
147         {9, 9, FALSE},
148         {11, 11, FALSE},
149         {13, 11, FALSE},
150         {5, 5, TRUE},
151         {7, 7, TRUE},
152         {9, 9, TRUE},
153         {11, 11, TRUE},
154         {13, 11, TRUE},
155     };
156
157     if (i < 0 || i >= lenof(values))
158         return FALSE;
159
160     ret = snew(game_params);
161     ret->width = values[i].x;
162     ret->height = values[i].y;
163     ret->wrapping = values[i].wrap;
164     ret->barrier_probability = 0.0;
165
166     sprintf(str, "%dx%d%s", ret->width, ret->height,
167             ret->wrapping ? " wrapping" : "");
168
169     *name = dupstr(str);
170     *params = ret;
171     return TRUE;
172 }
173
174 void free_params(game_params *params)
175 {
176     sfree(params);
177 }
178
179 game_params *dup_params(game_params *params)
180 {
181     game_params *ret = snew(game_params);
182     *ret = *params;                    /* structure copy */
183     return ret;
184 }
185
186 config_item *game_configure(game_params *params)
187 {
188     config_item *ret;
189     char buf[80];
190
191     ret = snewn(5, config_item);
192
193     ret[0].name = "Width";
194     ret[0].type = C_STRING;
195     sprintf(buf, "%d", params->width);
196     ret[0].sval = dupstr(buf);
197     ret[0].ival = 0;
198
199     ret[1].name = "Height";
200     ret[1].type = C_STRING;
201     sprintf(buf, "%d", params->height);
202     ret[1].sval = dupstr(buf);
203     ret[1].ival = 0;
204
205     ret[2].name = "Walls wrap around";
206     ret[2].type = C_BOOLEAN;
207     ret[2].sval = NULL;
208     ret[2].ival = params->wrapping;
209
210     ret[3].name = "Barrier probability";
211     ret[3].type = C_STRING;
212     sprintf(buf, "%g", params->barrier_probability);
213     ret[3].sval = dupstr(buf);
214     ret[3].ival = 0;
215
216     ret[4].name = NULL;
217     ret[4].type = C_END;
218     ret[4].sval = NULL;
219     ret[4].ival = 0;
220
221     return ret;
222 }
223
224 game_params *custom_params(config_item *cfg)
225 {
226     game_params *ret = snew(game_params);
227
228     ret->width = atoi(cfg[0].sval);
229     ret->height = atoi(cfg[1].sval);
230     ret->wrapping = cfg[2].ival;
231     ret->barrier_probability = (float)atof(cfg[3].sval);
232
233     return ret;
234 }
235
236 char *validate_params(game_params *params)
237 {
238     if (params->width <= 0 && params->height <= 0)
239         return "Width and height must both be greater than zero";
240     if (params->width <= 0)
241         return "Width must be greater than zero";
242     if (params->height <= 0)
243         return "Height must be greater than zero";
244     if (params->width <= 1 && params->height <= 1)
245         return "At least one of width and height must be greater than one";
246     if (params->barrier_probability < 0)
247         return "Barrier probability may not be negative";
248     if (params->barrier_probability > 1)
249         return "Barrier probability may not be greater than 1";
250     return NULL;
251 }
252
253 /* ----------------------------------------------------------------------
254  * Randomly select a new game seed.
255  */
256
257 char *new_game_seed(game_params *params)
258 {
259     /*
260      * The full description of a Net game is far too large to
261      * encode directly in the seed, so by default we'll have to go
262      * for the simple approach of providing a random-number seed.
263      * 
264      * (This does not restrict me from _later on_ inventing a seed
265      * string syntax which can never be generated by this code -
266      * for example, strings beginning with a letter - allowing me
267      * to type in a precise game, and have new_game detect it and
268      * understand it and do something completely different.)
269      */
270     char buf[40];
271     sprintf(buf, "%d", rand());
272     return dupstr(buf);
273 }
274
275 /* ----------------------------------------------------------------------
276  * Construct an initial game state, given a seed and parameters.
277  */
278
279 game_state *new_game(game_params *params, char *seed)
280 {
281     random_state *rs;
282     game_state *state;
283     tree234 *possibilities, *barriers;
284     int w, h, x, y, nbarriers;
285
286     assert(params->width > 0 && params->height > 0);
287     assert(params->width > 1 || params->height > 1);
288
289     /*
290      * Create a blank game state.
291      */
292     state = snew(game_state);
293     w = state->width = params->width;
294     h = state->height = params->height;
295     state->cx = state->width / 2;
296     state->cy = state->height / 2;
297     state->wrapping = params->wrapping;
298     state->last_rotate_dir = +1;       /* *shrug* */
299     state->completed = FALSE;
300     state->tiles = snewn(state->width * state->height, unsigned char);
301     memset(state->tiles, 0, state->width * state->height);
302     state->barriers = snewn(state->width * state->height, unsigned char);
303     memset(state->barriers, 0, state->width * state->height);
304
305     /*
306      * Set up border barriers if this is a non-wrapping game.
307      */
308     if (!state->wrapping) {
309         for (x = 0; x < state->width; x++) {
310             barrier(state, x, 0) |= U;
311             barrier(state, x, state->height-1) |= D;
312         }
313         for (y = 0; y < state->height; y++) {
314             barrier(state, 0, y) |= L;
315             barrier(state, state->width-1, y) |= R;
316         }
317     }
318
319     /*
320      * Seed the internal random number generator.
321      */
322     rs = random_init(seed, strlen(seed));
323
324     /*
325      * Construct the unshuffled grid.
326      * 
327      * To do this, we simply start at the centre point, repeatedly
328      * choose a random possibility out of the available ways to
329      * extend a used square into an unused one, and do it. After
330      * extending the third line out of a square, we remove the
331      * fourth from the possibilities list to avoid any full-cross
332      * squares (which would make the game too easy because they
333      * only have one orientation).
334      * 
335      * The slightly worrying thing is the avoidance of full-cross
336      * squares. Can this cause our unsophisticated construction
337      * algorithm to paint itself into a corner, by getting into a
338      * situation where there are some unreached squares and the
339      * only way to reach any of them is to extend a T-piece into a
340      * full cross?
341      * 
342      * Answer: no it can't, and here's a proof.
343      * 
344      * Any contiguous group of such unreachable squares must be
345      * surrounded on _all_ sides by T-pieces pointing away from the
346      * group. (If not, then there is a square which can be extended
347      * into one of the `unreachable' ones, and so it wasn't
348      * unreachable after all.) In particular, this implies that
349      * each contiguous group of unreachable squares must be
350      * rectangular in shape (any deviation from that yields a
351      * non-T-piece next to an `unreachable' square).
352      * 
353      * So we have a rectangle of unreachable squares, with T-pieces
354      * forming a solid border around the rectangle. The corners of
355      * that border must be connected (since every tile connects all
356      * the lines arriving in it), and therefore the border must
357      * form a closed loop around the rectangle.
358      * 
359      * But this can't have happened in the first place, since we
360      * _know_ we've avoided creating closed loops! Hence, no such
361      * situation can ever arise, and the naive grid construction
362      * algorithm will guaranteeably result in a complete grid
363      * containing no unreached squares, no full crosses _and_ no
364      * closed loops. []
365      */
366     possibilities = newtree234(xyd_cmp);
367
368     if (state->cx+1 < state->width)
369         add234(possibilities, new_xyd(state->cx, state->cy, R));
370     if (state->cy-1 >= 0)
371         add234(possibilities, new_xyd(state->cx, state->cy, U));
372     if (state->cx-1 >= 0)
373         add234(possibilities, new_xyd(state->cx, state->cy, L));
374     if (state->cy+1 < state->height)
375         add234(possibilities, new_xyd(state->cx, state->cy, D));
376
377     while (count234(possibilities) > 0) {
378         int i;
379         struct xyd *xyd;
380         int x1, y1, d1, x2, y2, d2, d;
381
382         /*
383          * Extract a randomly chosen possibility from the list.
384          */
385         i = random_upto(rs, count234(possibilities));
386         xyd = delpos234(possibilities, i);
387         x1 = xyd->x;
388         y1 = xyd->y;
389         d1 = xyd->direction;
390         sfree(xyd);
391
392         OFFSET(x2, y2, x1, y1, d1, state);
393         d2 = F(d1);
394 #ifdef DEBUG
395         printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
396                x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
397 #endif
398
399         /*
400          * Make the connection. (We should be moving to an as yet
401          * unused tile.)
402          */
403         tile(state, x1, y1) |= d1;
404         assert(tile(state, x2, y2) == 0);
405         tile(state, x2, y2) |= d2;
406
407         /*
408          * If we have created a T-piece, remove its last
409          * possibility.
410          */
411         if (COUNT(tile(state, x1, y1)) == 3) {
412             struct xyd xyd1, *xydp;
413
414             xyd1.x = x1;
415             xyd1.y = y1;
416             xyd1.direction = 0x0F ^ tile(state, x1, y1);
417
418             xydp = find234(possibilities, &xyd1, NULL);
419
420             if (xydp) {
421 #ifdef DEBUG
422                 printf("T-piece; removing (%d,%d,%c)\n",
423                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
424 #endif
425                 del234(possibilities, xydp);
426                 sfree(xydp);
427             }
428         }
429
430         /*
431          * Remove all other possibilities that were pointing at the
432          * tile we've just moved into.
433          */
434         for (d = 1; d < 0x10; d <<= 1) {
435             int x3, y3, d3;
436             struct xyd xyd1, *xydp;
437
438             OFFSET(x3, y3, x2, y2, d, state);
439             d3 = F(d);
440
441             xyd1.x = x3;
442             xyd1.y = y3;
443             xyd1.direction = d3;
444
445             xydp = find234(possibilities, &xyd1, NULL);
446
447             if (xydp) {
448 #ifdef DEBUG
449                 printf("Loop avoidance; removing (%d,%d,%c)\n",
450                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
451 #endif
452                 del234(possibilities, xydp);
453                 sfree(xydp);
454             }
455         }
456
457         /*
458          * Add new possibilities to the list for moving _out_ of
459          * the tile we have just moved into.
460          */
461         for (d = 1; d < 0x10; d <<= 1) {
462             int x3, y3;
463
464             if (d == d2)
465                 continue;              /* we've got this one already */
466
467             if (!state->wrapping) {
468                 if (d == U && y2 == 0)
469                     continue;
470                 if (d == D && y2 == state->height-1)
471                     continue;
472                 if (d == L && x2 == 0)
473                     continue;
474                 if (d == R && x2 == state->width-1)
475                     continue;
476             }
477
478             OFFSET(x3, y3, x2, y2, d, state);
479
480             if (tile(state, x3, y3))
481                 continue;              /* this would create a loop */
482
483 #ifdef DEBUG
484             printf("New frontier; adding (%d,%d,%c)\n",
485                    x2, y2, "0RU3L567D9abcdef"[d]);
486 #endif
487             add234(possibilities, new_xyd(x2, y2, d));
488         }
489     }
490     /* Having done that, we should have no possibilities remaining. */
491     assert(count234(possibilities) == 0);
492     freetree234(possibilities);
493
494     /*
495      * Now compute a list of the possible barrier locations.
496      */
497     barriers = newtree234(xyd_cmp);
498     for (y = 0; y < state->height; y++) {
499         for (x = 0; x < state->width; x++) {
500
501             if (!(tile(state, x, y) & R) &&
502                 (state->wrapping || x < state->width-1))
503                 add234(barriers, new_xyd(x, y, R));
504             if (!(tile(state, x, y) & D) &&
505                 (state->wrapping || y < state->height-1))
506                 add234(barriers, new_xyd(x, y, D));
507         }
508     }
509
510     /*
511      * Now shuffle the grid.
512      */
513     for (y = 0; y < state->height; y++) {
514         for (x = 0; x < state->width; x++) {
515             int orig = tile(state, x, y);
516             int rot = random_upto(rs, 4);
517             tile(state, x, y) = ROT(orig, rot);
518         }
519     }
520
521     /*
522      * And now choose barrier locations. (We carefully do this
523      * _after_ shuffling, so that changing the barrier rate in the
524      * params while keeping the game seed the same will give the
525      * same shuffled grid and _only_ change the barrier locations.
526      * Also the way we choose barrier locations, by repeatedly
527      * choosing one possibility from the list until we have enough,
528      * is designed to ensure that raising the barrier rate while
529      * keeping the seed the same will provide a superset of the
530      * previous barrier set - i.e. if you ask for 10 barriers, and
531      * then decide that's still too hard and ask for 20, you'll get
532      * the original 10 plus 10 more, rather than getting 20 new
533      * ones and the chance of remembering your first 10.)
534      */
535     nbarriers = (int)(params->barrier_probability * count234(barriers));
536     assert(nbarriers >= 0 && nbarriers <= count234(barriers));
537
538     while (nbarriers > 0) {
539         int i;
540         struct xyd *xyd;
541         int x1, y1, d1, x2, y2, d2;
542
543         /*
544          * Extract a randomly chosen barrier from the list.
545          */
546         i = random_upto(rs, count234(barriers));
547         xyd = delpos234(barriers, i);
548
549         assert(xyd != NULL);
550
551         x1 = xyd->x;
552         y1 = xyd->y;
553         d1 = xyd->direction;
554         sfree(xyd);
555
556         OFFSET(x2, y2, x1, y1, d1, state);
557         d2 = F(d1);
558
559         barrier(state, x1, y1) |= d1;
560         barrier(state, x2, y2) |= d2;
561
562         nbarriers--;
563     }
564
565     /*
566      * Clean up the rest of the barrier list.
567      */
568     {
569         struct xyd *xyd;
570
571         while ( (xyd = delpos234(barriers, 0)) != NULL)
572             sfree(xyd);
573
574         freetree234(barriers);
575     }
576
577     /*
578      * Set up the barrier corner flags, for drawing barriers
579      * prettily when they meet.
580      */
581     for (y = 0; y < state->height; y++) {
582         for (x = 0; x < state->width; x++) {
583             int dir;
584
585             for (dir = 1; dir < 0x10; dir <<= 1) {
586                 int dir2 = A(dir);
587                 int x1, y1, x2, y2, x3, y3;
588                 int corner = FALSE;
589
590                 if (!(barrier(state, x, y) & dir))
591                     continue;
592
593                 if (barrier(state, x, y) & dir2)
594                     corner = TRUE;
595
596                 x1 = x + X(dir), y1 = y + Y(dir);
597                 if (x1 >= 0 && x1 < state->width &&
598                     y1 >= 0 && y1 < state->height &&
599                     (barrier(state, x1, y1) & dir2))
600                     corner = TRUE;
601
602                 x2 = x + X(dir2), y2 = y + Y(dir2);
603                 if (x2 >= 0 && x2 < state->width &&
604                     y2 >= 0 && y2 < state->height &&
605                     (barrier(state, x2, y2) & dir))
606                     corner = TRUE;
607
608                 if (corner) {
609                     barrier(state, x, y) |= (dir << 4);
610                     if (x1 >= 0 && x1 < state->width &&
611                         y1 >= 0 && y1 < state->height)
612                         barrier(state, x1, y1) |= (A(dir) << 4);
613                     if (x2 >= 0 && x2 < state->width &&
614                         y2 >= 0 && y2 < state->height)
615                         barrier(state, x2, y2) |= (C(dir) << 4);
616                     x3 = x + X(dir) + X(dir2), y3 = y + Y(dir) + Y(dir2);
617                     if (x3 >= 0 && x3 < state->width &&
618                         y3 >= 0 && y3 < state->height)
619                         barrier(state, x3, y3) |= (F(dir) << 4);
620                 }
621             }
622         }
623     }
624
625     random_free(rs);
626
627     return state;
628 }
629
630 game_state *dup_game(game_state *state)
631 {
632     game_state *ret;
633
634     ret = snew(game_state);
635     ret->width = state->width;
636     ret->height = state->height;
637     ret->cx = state->cx;
638     ret->cy = state->cy;
639     ret->wrapping = state->wrapping;
640     ret->completed = state->completed;
641     ret->last_rotate_dir = state->last_rotate_dir;
642     ret->tiles = snewn(state->width * state->height, unsigned char);
643     memcpy(ret->tiles, state->tiles, state->width * state->height);
644     ret->barriers = snewn(state->width * state->height, unsigned char);
645     memcpy(ret->barriers, state->barriers, state->width * state->height);
646
647     return ret;
648 }
649
650 void free_game(game_state *state)
651 {
652     sfree(state->tiles);
653     sfree(state->barriers);
654     sfree(state);
655 }
656
657 /* ----------------------------------------------------------------------
658  * Utility routine.
659  */
660
661 /*
662  * Compute which squares are reachable from the centre square, as a
663  * quick visual aid to determining how close the game is to
664  * completion. This is also a simple way to tell if the game _is_
665  * completed - just call this function and see whether every square
666  * is marked active.
667  */
668 static unsigned char *compute_active(game_state *state)
669 {
670     unsigned char *active;
671     tree234 *todo;
672     struct xyd *xyd;
673
674     active = snewn(state->width * state->height, unsigned char);
675     memset(active, 0, state->width * state->height);
676
677     /*
678      * We only store (x,y) pairs in todo, but it's easier to reuse
679      * xyd_cmp and just store direction 0 every time.
680      */
681     todo = newtree234(xyd_cmp);
682     index(state, active, state->cx, state->cy) = ACTIVE;
683     add234(todo, new_xyd(state->cx, state->cy, 0));
684
685     while ( (xyd = delpos234(todo, 0)) != NULL) {
686         int x1, y1, d1, x2, y2, d2;
687
688         x1 = xyd->x;
689         y1 = xyd->y;
690         sfree(xyd);
691
692         for (d1 = 1; d1 < 0x10; d1 <<= 1) {
693             OFFSET(x2, y2, x1, y1, d1, state);
694             d2 = F(d1);
695
696             /*
697              * If the next tile in this direction is connected to
698              * us, and there isn't a barrier in the way, and it
699              * isn't already marked active, then mark it active and
700              * add it to the to-examine list.
701              */
702             if ((tile(state, x1, y1) & d1) &&
703                 (tile(state, x2, y2) & d2) &&
704                 !(barrier(state, x1, y1) & d1) &&
705                 !index(state, active, x2, y2)) {
706                 index(state, active, x2, y2) = ACTIVE;
707                 add234(todo, new_xyd(x2, y2, 0));
708             }
709         }
710     }
711     /* Now we expect the todo list to have shrunk to zero size. */
712     assert(count234(todo) == 0);
713     freetree234(todo);
714
715     return active;
716 }
717
718 /* ----------------------------------------------------------------------
719  * Process a move.
720  */
721 game_state *make_move(game_state *state, int x, int y, int button)
722 {
723     game_state *ret;
724     int tx, ty, orig;
725
726     /*
727      * All moves in Net are made with the mouse.
728      */
729     if (button != LEFT_BUTTON &&
730         button != MIDDLE_BUTTON &&
731         button != RIGHT_BUTTON)
732         return NULL;
733
734     /*
735      * The button must have been clicked on a valid tile.
736      */
737     x -= WINDOW_OFFSET + TILE_BORDER;
738     y -= WINDOW_OFFSET + TILE_BORDER;
739     if (x < 0 || y < 0)
740         return NULL;
741     tx = x / TILE_SIZE;
742     ty = y / TILE_SIZE;
743     if (tx >= state->width || ty >= state->height)
744         return NULL;
745     if (tx % TILE_SIZE >= TILE_SIZE - TILE_BORDER ||
746         ty % TILE_SIZE >= TILE_SIZE - TILE_BORDER)
747         return NULL;
748
749     /*
750      * The middle button locks or unlocks a tile. (A locked tile
751      * cannot be turned, and is visually marked as being locked.
752      * This is a convenience for the player, so that once they are
753      * sure which way round a tile goes, they can lock it and thus
754      * avoid forgetting later on that they'd already done that one;
755      * and the locking also prevents them turning the tile by
756      * accident. If they change their mind, another middle click
757      * unlocks it.)
758      */
759     if (button == MIDDLE_BUTTON) {
760         ret = dup_game(state);
761         tile(ret, tx, ty) ^= LOCKED;
762         return ret;
763     }
764
765     /*
766      * The left and right buttons have no effect if clicked on a
767      * locked tile.
768      */
769     if (tile(state, tx, ty) & LOCKED)
770         return NULL;
771
772     /*
773      * Otherwise, turn the tile one way or the other. Left button
774      * turns anticlockwise; right button turns clockwise.
775      */
776     ret = dup_game(state);
777     orig = tile(ret, tx, ty);
778     if (button == LEFT_BUTTON) {
779         tile(ret, tx, ty) = A(orig);
780         ret->last_rotate_dir = +1;
781     } else {
782         tile(ret, tx, ty) = C(orig);
783         ret->last_rotate_dir = -1;
784     }
785
786     /*
787      * Check whether the game has been completed.
788      */
789     {
790         unsigned char *active = compute_active(ret);
791         int x1, y1;
792         int complete = TRUE;
793
794         for (x1 = 0; x1 < ret->width; x1++)
795             for (y1 = 0; y1 < ret->height; y1++)
796                 if (!index(ret, active, x1, y1)) {
797                     complete = FALSE;
798                     goto break_label;  /* break out of two loops at once */
799                 }
800         break_label:
801
802         sfree(active);
803
804         if (complete)
805             ret->completed = TRUE;
806     }
807
808     return ret;
809 }
810
811 /* ----------------------------------------------------------------------
812  * Routines for drawing the game position on the screen.
813  */
814
815 struct game_drawstate {
816     int started;
817     int width, height;
818     unsigned char *visible;
819 };
820
821 game_drawstate *game_new_drawstate(game_state *state)
822 {
823     game_drawstate *ds = snew(game_drawstate);
824
825     ds->started = FALSE;
826     ds->width = state->width;
827     ds->height = state->height;
828     ds->visible = snewn(state->width * state->height, unsigned char);
829     memset(ds->visible, 0xFF, state->width * state->height);
830
831     return ds;
832 }
833
834 void game_free_drawstate(game_drawstate *ds)
835 {
836     sfree(ds->visible);
837     sfree(ds);
838 }
839
840 void game_size(game_params *params, int *x, int *y)
841 {
842     *x = WINDOW_OFFSET * 2 + TILE_SIZE * params->width + TILE_BORDER;
843     *y = WINDOW_OFFSET * 2 + TILE_SIZE * params->height + TILE_BORDER;
844 }
845
846 float *game_colours(frontend *fe, game_state *state, int *ncolours)
847 {
848     float *ret;
849
850     ret = snewn(NCOLOURS * 3, float);
851     *ncolours = NCOLOURS;
852
853     /*
854      * Basic background colour is whatever the front end thinks is
855      * a sensible default.
856      */
857     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
858
859     /*
860      * Wires are black.
861      */
862     ret[COL_WIRE * 3 + 0] = 0.0F;
863     ret[COL_WIRE * 3 + 1] = 0.0F;
864     ret[COL_WIRE * 3 + 2] = 0.0F;
865
866     /*
867      * Powered wires and powered endpoints are cyan.
868      */
869     ret[COL_POWERED * 3 + 0] = 0.0F;
870     ret[COL_POWERED * 3 + 1] = 1.0F;
871     ret[COL_POWERED * 3 + 2] = 1.0F;
872
873     /*
874      * Barriers are red.
875      */
876     ret[COL_BARRIER * 3 + 0] = 1.0F;
877     ret[COL_BARRIER * 3 + 1] = 0.0F;
878     ret[COL_BARRIER * 3 + 2] = 0.0F;
879
880     /*
881      * Unpowered endpoints are blue.
882      */
883     ret[COL_ENDPOINT * 3 + 0] = 0.0F;
884     ret[COL_ENDPOINT * 3 + 1] = 0.0F;
885     ret[COL_ENDPOINT * 3 + 2] = 1.0F;
886
887     /*
888      * Tile borders are a darker grey than the background.
889      */
890     ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
891     ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
892     ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
893
894     /*
895      * Locked tiles are a grey in between those two.
896      */
897     ret[COL_LOCKED * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
898     ret[COL_LOCKED * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
899     ret[COL_LOCKED * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
900
901     return ret;
902 }
903
904 static void draw_thick_line(frontend *fe, int x1, int y1, int x2, int y2,
905                             int colour)
906 {
907     draw_line(fe, x1-1, y1, x2-1, y2, COL_WIRE);
908     draw_line(fe, x1+1, y1, x2+1, y2, COL_WIRE);
909     draw_line(fe, x1, y1-1, x2, y2-1, COL_WIRE);
910     draw_line(fe, x1, y1+1, x2, y2+1, COL_WIRE);
911     draw_line(fe, x1, y1, x2, y2, colour);
912 }
913
914 static void draw_rect_coords(frontend *fe, int x1, int y1, int x2, int y2,
915                              int colour)
916 {
917     int mx = (x1 < x2 ? x1 : x2);
918     int my = (y1 < y2 ? y1 : y2);
919     int dx = (x2 + x1 - 2*mx + 1);
920     int dy = (y2 + y1 - 2*my + 1);
921
922     draw_rect(fe, mx, my, dx, dy, colour);
923 }
924
925 static void draw_barrier_corner(frontend *fe, int x, int y, int dir, int phase)
926 {
927     int bx = WINDOW_OFFSET + TILE_SIZE * x;
928     int by = WINDOW_OFFSET + TILE_SIZE * y;
929     int x1, y1, dx, dy, dir2;
930
931     dir >>= 4;
932
933     dir2 = A(dir);
934     dx = X(dir) + X(dir2);
935     dy = Y(dir) + Y(dir2);
936     x1 = (dx > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
937     y1 = (dy > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
938
939     if (phase == 0) {
940         draw_rect_coords(fe, bx+x1, by+y1,
941                          bx+x1-TILE_BORDER*dx, by+y1-(TILE_BORDER-1)*dy,
942                          COL_WIRE);
943         draw_rect_coords(fe, bx+x1, by+y1,
944                          bx+x1-(TILE_BORDER-1)*dx, by+y1-TILE_BORDER*dy,
945                          COL_WIRE);
946     } else {
947         draw_rect_coords(fe, bx+x1, by+y1,
948                          bx+x1-(TILE_BORDER-1)*dx, by+y1-(TILE_BORDER-1)*dy,
949                          COL_BARRIER);
950     }
951 }
952
953 static void draw_barrier(frontend *fe, int x, int y, int dir, int phase)
954 {
955     int bx = WINDOW_OFFSET + TILE_SIZE * x;
956     int by = WINDOW_OFFSET + TILE_SIZE * y;
957     int x1, y1, w, h;
958
959     x1 = (X(dir) > 0 ? TILE_SIZE : X(dir) == 0 ? TILE_BORDER : 0);
960     y1 = (Y(dir) > 0 ? TILE_SIZE : Y(dir) == 0 ? TILE_BORDER : 0);
961     w = (X(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
962     h = (Y(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
963
964     if (phase == 0) {
965         draw_rect(fe, bx+x1-X(dir), by+y1-Y(dir), w, h, COL_WIRE);
966     } else {
967         draw_rect(fe, bx+x1, by+y1, w, h, COL_BARRIER);
968     }
969 }
970
971 static void draw_tile(frontend *fe, game_state *state, int x, int y, int tile,
972                       float angle)
973 {
974     int bx = WINDOW_OFFSET + TILE_SIZE * x;
975     int by = WINDOW_OFFSET + TILE_SIZE * y;
976     float matrix[4];
977     float cx, cy, ex, ey, tx, ty;
978     int dir, col, phase;
979
980     /*
981      * When we draw a single tile, we must draw everything up to
982      * and including the borders around the tile. This means that
983      * if the neighbouring tiles have connections to those borders,
984      * we must draw those connections on the borders themselves.
985      *
986      * This would be terribly fiddly if we ever had to draw a tile
987      * while its neighbour was in mid-rotate, because we'd have to
988      * arrange to _know_ that the neighbour was being rotated and
989      * hence had an anomalous effect on the redraw of this tile.
990      * Fortunately, the drawing algorithm avoids ever calling us in
991      * this circumstance: we're either drawing lots of straight
992      * tiles at game start or after a move is complete, or we're
993      * repeatedly drawing only the rotating tile. So no problem.
994      */
995
996     /*
997      * So. First blank the tile out completely: draw a big
998      * rectangle in border colour, and a smaller rectangle in
999      * background colour to fill it in.
1000      */
1001     draw_rect(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER,
1002               COL_BORDER);
1003     draw_rect(fe, bx+TILE_BORDER, by+TILE_BORDER,
1004               TILE_SIZE-TILE_BORDER, TILE_SIZE-TILE_BORDER,
1005               tile & LOCKED ? COL_LOCKED : COL_BACKGROUND);
1006
1007     /*
1008      * Set up the rotation matrix.
1009      */
1010     matrix[0] = (float)cos(angle * PI / 180.0);
1011     matrix[1] = (float)-sin(angle * PI / 180.0);
1012     matrix[2] = (float)sin(angle * PI / 180.0);
1013     matrix[3] = (float)cos(angle * PI / 180.0);
1014
1015     /*
1016      * Draw the wires.
1017      */
1018     cx = cy = TILE_BORDER + (TILE_SIZE-TILE_BORDER) / 2.0F - 0.5F;
1019     col = (tile & ACTIVE ? COL_POWERED : COL_WIRE);
1020     for (dir = 1; dir < 0x10; dir <<= 1) {
1021         if (tile & dir) {
1022             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
1023             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
1024             MATMUL(tx, ty, matrix, ex, ey);
1025             draw_thick_line(fe, bx+(int)cx, by+(int)cy,
1026                             bx+(int)(cx+tx), by+(int)(cy+ty),
1027                             COL_WIRE);
1028         }
1029     }
1030     for (dir = 1; dir < 0x10; dir <<= 1) {
1031         if (tile & dir) {
1032             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
1033             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
1034             MATMUL(tx, ty, matrix, ex, ey);
1035             draw_line(fe, bx+(int)cx, by+(int)cy,
1036                       bx+(int)(cx+tx), by+(int)(cy+ty), col);
1037         }
1038     }
1039
1040     /*
1041      * Draw the box in the middle. We do this in blue if the tile
1042      * is an unpowered endpoint, in cyan if the tile is a powered
1043      * endpoint, in black if the tile is the centrepiece, and
1044      * otherwise not at all.
1045      */
1046     col = -1;
1047     if (x == state->cx && y == state->cy)
1048         col = COL_WIRE;
1049     else if (COUNT(tile) == 1) {
1050         col = (tile & ACTIVE ? COL_POWERED : COL_ENDPOINT);
1051     }
1052     if (col >= 0) {
1053         int i, points[8];
1054
1055         points[0] = +1; points[1] = +1;
1056         points[2] = +1; points[3] = -1;
1057         points[4] = -1; points[5] = -1;
1058         points[6] = -1; points[7] = +1;
1059
1060         for (i = 0; i < 8; i += 2) {
1061             ex = (TILE_SIZE * 0.24F) * points[i];
1062             ey = (TILE_SIZE * 0.24F) * points[i+1];
1063             MATMUL(tx, ty, matrix, ex, ey);
1064             points[i] = bx+(int)(cx+tx);
1065             points[i+1] = by+(int)(cy+ty);
1066         }
1067
1068         draw_polygon(fe, points, 4, TRUE, col);
1069         draw_polygon(fe, points, 4, FALSE, COL_WIRE);
1070     }
1071
1072     /*
1073      * Draw the points on the border if other tiles are connected
1074      * to us.
1075      */
1076     for (dir = 1; dir < 0x10; dir <<= 1) {
1077         int dx, dy, px, py, lx, ly, vx, vy, ox, oy;
1078
1079         dx = X(dir);
1080         dy = Y(dir);
1081
1082         ox = x + dx;
1083         oy = y + dy;
1084
1085         if (ox < 0 || ox >= state->width || oy < 0 || oy >= state->height)
1086             continue;
1087
1088         if (!(tile(state, ox, oy) & F(dir)))
1089             continue;
1090
1091         px = bx + (int)(dx>0 ? TILE_SIZE + TILE_BORDER - 1 : dx<0 ? 0 : cx);
1092         py = by + (int)(dy>0 ? TILE_SIZE + TILE_BORDER - 1 : dy<0 ? 0 : cy);
1093         lx = dx * (TILE_BORDER-1);
1094         ly = dy * (TILE_BORDER-1);
1095         vx = (dy ? 1 : 0);
1096         vy = (dx ? 1 : 0);
1097
1098         if (angle == 0.0 && (tile & dir)) {
1099             /*
1100              * If we are fully connected to the other tile, we must
1101              * draw right across the tile border. (We can use our
1102              * own ACTIVE state to determine what colour to do this
1103              * in: if we are fully connected to the other tile then
1104              * the two ACTIVE states will be the same.)
1105              */
1106             draw_rect_coords(fe, px-vx, py-vy, px+lx+vx, py+ly+vy, COL_WIRE);
1107             draw_rect_coords(fe, px, py, px+lx, py+ly,
1108                              (tile & ACTIVE) ? COL_POWERED : COL_WIRE);
1109         } else {
1110             /*
1111              * The other tile extends into our border, but isn't
1112              * actually connected to us. Just draw a single black
1113              * dot.
1114              */
1115             draw_rect_coords(fe, px, py, px, py, COL_WIRE);
1116         }
1117     }
1118
1119     /*
1120      * Draw barrier corners, and then barriers.
1121      */
1122     for (phase = 0; phase < 2; phase++) {
1123         for (dir = 1; dir < 0x10; dir <<= 1)
1124             if (barrier(state, x, y) & (dir << 4))
1125                 draw_barrier_corner(fe, x, y, dir << 4, phase);
1126         for (dir = 1; dir < 0x10; dir <<= 1)
1127             if (barrier(state, x, y) & dir)
1128                 draw_barrier(fe, x, y, dir, phase);
1129     }
1130
1131     draw_update(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
1132 }
1133
1134 void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1135                  game_state *state, float t, float ft)
1136 {
1137     int x, y, tx, ty, frame;
1138     unsigned char *active;
1139     float angle = 0.0;
1140
1141     /*
1142      * Clear the screen and draw the exterior barrier lines if this
1143      * is our first call.
1144      */
1145     if (!ds->started) {
1146         int phase;
1147
1148         ds->started = TRUE;
1149
1150         draw_rect(fe, 0, 0, 
1151                   WINDOW_OFFSET * 2 + TILE_SIZE * state->width + TILE_BORDER,
1152                   WINDOW_OFFSET * 2 + TILE_SIZE * state->height + TILE_BORDER,
1153                   COL_BACKGROUND);
1154         draw_update(fe, 0, 0, 
1155                     WINDOW_OFFSET*2 + TILE_SIZE*state->width + TILE_BORDER,
1156                     WINDOW_OFFSET*2 + TILE_SIZE*state->height + TILE_BORDER);
1157
1158         for (phase = 0; phase < 2; phase++) {
1159
1160             for (x = 0; x < ds->width; x++) {
1161                 if (barrier(state, x, 0) & UL)
1162                     draw_barrier_corner(fe, x, -1, LD, phase);
1163                 if (barrier(state, x, 0) & RU)
1164                     draw_barrier_corner(fe, x, -1, DR, phase);
1165                 if (barrier(state, x, 0) & U)
1166                     draw_barrier(fe, x, -1, D, phase);
1167                 if (barrier(state, x, ds->height-1) & DR)
1168                     draw_barrier_corner(fe, x, ds->height, RU, phase);
1169                 if (barrier(state, x, ds->height-1) & LD)
1170                     draw_barrier_corner(fe, x, ds->height, UL, phase);
1171                 if (barrier(state, x, ds->height-1) & D)
1172                     draw_barrier(fe, x, ds->height, U, phase);
1173             }
1174
1175             for (y = 0; y < ds->height; y++) {
1176                 if (barrier(state, 0, y) & UL)
1177                     draw_barrier_corner(fe, -1, y, RU, phase);
1178                 if (barrier(state, 0, y) & LD)
1179                     draw_barrier_corner(fe, -1, y, DR, phase);
1180                 if (barrier(state, 0, y) & L)
1181                     draw_barrier(fe, -1, y, R, phase);
1182                 if (barrier(state, ds->width-1, y) & RU)
1183                     draw_barrier_corner(fe, ds->width, y, UL, phase);
1184                 if (barrier(state, ds->width-1, y) & DR)
1185                     draw_barrier_corner(fe, ds->width, y, LD, phase);
1186                 if (barrier(state, ds->width-1, y) & R)
1187                     draw_barrier(fe, ds->width, y, L, phase);
1188             }
1189         }
1190     }
1191
1192     tx = ty = -1;
1193     if (oldstate && (t < ROTATE_TIME)) {
1194         /*
1195          * We're animating a tile rotation. Find the turning tile,
1196          * if any.
1197          */
1198         for (x = 0; x < oldstate->width; x++)
1199             for (y = 0; y < oldstate->height; y++)
1200                 if ((tile(oldstate, x, y) ^ tile(state, x, y)) & 0xF) {
1201                     tx = x, ty = y;
1202                     goto break_label;  /* leave both loops at once */
1203                 }
1204         break_label:
1205
1206         if (tx >= 0) {
1207             if (tile(state, tx, ty) == ROT(tile(oldstate, tx, ty),
1208                                            state->last_rotate_dir))
1209                 angle = state->last_rotate_dir * 90.0F * (t / ROTATE_TIME);
1210             else
1211                 angle = state->last_rotate_dir * -90.0F * (t / ROTATE_TIME);
1212             state = oldstate;
1213         }
1214     }
1215     
1216     frame = -1;
1217     if (ft > 0) {
1218         /*
1219          * We're animating a completion flash. Find which frame
1220          * we're at.
1221          */
1222         frame = (int)(ft / FLASH_FRAME);
1223     }
1224
1225     /*
1226      * Draw any tile which differs from the way it was last drawn.
1227      */
1228     active = compute_active(state);
1229
1230     for (x = 0; x < ds->width; x++)
1231         for (y = 0; y < ds->height; y++) {
1232             unsigned char c = tile(state, x, y) | index(state, active, x, y);
1233
1234             /*
1235              * In a completion flash, we adjust the LOCKED bit
1236              * depending on our distance from the centre point and
1237              * the frame number.
1238              */
1239             if (frame >= 0) {
1240                 int xdist, ydist, dist;
1241                 xdist = (x < state->cx ? state->cx - x : x - state->cx);
1242                 ydist = (y < state->cy ? state->cy - y : y - state->cy);
1243                 dist = (xdist > ydist ? xdist : ydist);
1244
1245                 if (frame >= dist && frame < dist+4) {
1246                     int lock = (frame - dist) & 1;
1247                     lock = lock ? LOCKED : 0;
1248                     c = (c &~ LOCKED) | lock;
1249                 }
1250             }
1251
1252             if (index(state, ds->visible, x, y) != c ||
1253                 index(state, ds->visible, x, y) == 0xFF ||
1254                 (x == tx && y == ty)) {
1255                 draw_tile(fe, state, x, y, c,
1256                           (x == tx && y == ty ? angle : 0.0F));
1257                 if (x == tx && y == ty)
1258                     index(state, ds->visible, x, y) = 0xFF;
1259                 else
1260                     index(state, ds->visible, x, y) = c;
1261             }
1262         }
1263
1264     /*
1265      * Update the status bar.
1266      */
1267     {
1268         char statusbuf[256];
1269         int i, n, a;
1270
1271         n = state->width * state->height;
1272         for (i = a = 0; i < n; i++)
1273             if (active[i])
1274                 a++;
1275
1276         sprintf(statusbuf, "%sActive: %d/%d",
1277                 (state->completed ? "COMPLETED! " : ""), a, n);
1278
1279         status_bar(fe, statusbuf);
1280     }
1281
1282     sfree(active);
1283 }
1284
1285 float game_anim_length(game_state *oldstate, game_state *newstate)
1286 {
1287     int x, y;
1288
1289     /*
1290      * If there's a tile which has been rotated, allow time to
1291      * animate its rotation.
1292      */
1293     for (x = 0; x < oldstate->width; x++)
1294         for (y = 0; y < oldstate->height; y++)
1295             if ((tile(oldstate, x, y) ^ tile(newstate, x, y)) & 0xF) {
1296                 return ROTATE_TIME;
1297             }
1298
1299     return 0.0F;
1300 }
1301
1302 float game_flash_length(game_state *oldstate, game_state *newstate)
1303 {
1304     /*
1305      * If the game has just been completed, we display a completion
1306      * flash.
1307      */
1308     if (!oldstate->completed && newstate->completed) {
1309         int size;
1310         size = 0;
1311         if (size < newstate->cx+1)
1312             size = newstate->cx+1;
1313         if (size < newstate->cy+1)
1314             size = newstate->cy+1;
1315         if (size < newstate->width - newstate->cx)
1316             size = newstate->width - newstate->cx;
1317         if (size < newstate->height - newstate->cy)
1318             size = newstate->height - newstate->cy;
1319         return FLASH_FRAME * (size+4);
1320     }
1321
1322     return 0.0F;
1323 }
1324
1325 int game_wants_statusbar(void)
1326 {
1327     return TRUE;
1328 }