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