chiark / gitweb /
Fix zillions of MSVC compiler warnings. Sigh.
[sgt-puzzles.git] / cube.c
1 /*
2  * cube.c: Cube 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
13 #define MAXVERTICES 20
14 #define MAXFACES 20
15 #define MAXORDER 4
16 struct solid {
17     int nvertices;
18     float vertices[MAXVERTICES * 3];   /* 3*npoints coordinates */
19     int order;
20     int nfaces;
21     int faces[MAXFACES * MAXORDER];    /* order*nfaces point indices */
22     float normals[MAXFACES * 3];       /* 3*npoints vector components */
23     float shear;                       /* isometric shear for nice drawing */
24     float border;                      /* border required around arena */
25 };
26
27 static const struct solid tetrahedron = {
28     4,
29     {
30         0.0F, -0.57735026919F, -0.20412414523F,
31         -0.5F, 0.28867513459F, -0.20412414523F,
32         0.0F, -0.0F, 0.6123724357F,
33         0.5F, 0.28867513459F, -0.20412414523F,
34     },
35     3, 4,
36     {
37         0,2,1, 3,1,2, 2,0,3, 1,3,0
38     },
39     {
40         -0.816496580928F, -0.471404520791F, 0.333333333334F,
41         0.0F, 0.942809041583F, 0.333333333333F,
42         0.816496580928F, -0.471404520791F, 0.333333333334F,
43         0.0F, 0.0F, -1.0F,
44     },
45     0.0F, 0.3F
46 };
47
48 static const struct solid cube = {
49     8,
50     {
51         -0.5F,-0.5F,-0.5F, -0.5F,-0.5F,+0.5F,
52         -0.5F,+0.5F,-0.5F, -0.5F,+0.5F,+0.5F,
53         +0.5F,-0.5F,-0.5F, +0.5F,-0.5F,+0.5F,
54         +0.5F,+0.5F,-0.5F, +0.5F,+0.5F,+0.5F,
55     },
56     4, 6,
57     {
58         0,1,3,2, 1,5,7,3, 5,4,6,7, 4,0,2,6, 0,4,5,1, 3,7,6,2
59     },
60     {
61         -1.0F,0.0F,0.0F, 0.0F,0.0F,+1.0F,
62         +1.0F,0.0F,0.0F, 0.0F,0.0F,-1.0F,
63         0.0F,-1.0F,0.0F, 0.0F,+1.0F,0.0F
64     },
65     0.3F, 0.5F
66 };
67
68 static const struct solid octahedron = {
69     6,
70     {
71         -0.5F, -0.28867513459472505F, 0.4082482904638664F,
72         0.5F, 0.28867513459472505F, -0.4082482904638664F,
73         -0.5F, 0.28867513459472505F, -0.4082482904638664F,
74         0.5F, -0.28867513459472505F, 0.4082482904638664F,
75         0.0F, -0.57735026918945009F, -0.4082482904638664F,
76         0.0F, 0.57735026918945009F, 0.4082482904638664F,
77     },
78     3, 8,
79     {
80         4,0,2, 0,5,2, 0,4,3, 5,0,3, 1,4,2, 5,1,2, 4,1,3, 1,5,3
81     },
82     {
83         -0.816496580928F, -0.471404520791F, -0.333333333334F,
84         -0.816496580928F, 0.471404520791F, 0.333333333334F,
85         0.0F, -0.942809041583F, 0.333333333333F,
86         0.0F, 0.0F, 1.0F,
87         0.0F, 0.0F, -1.0F,
88         0.0F, 0.942809041583F, -0.333333333333F,
89         0.816496580928F, -0.471404520791F, -0.333333333334F,
90         0.816496580928F, 0.471404520791F, 0.333333333334F,
91     },
92     0.0F, 0.5F
93 };
94
95 static const struct solid icosahedron = {
96     12,
97     {
98         0.0F, 0.57735026919F, 0.75576131408F,
99         0.0F, -0.93417235896F, 0.17841104489F,
100         0.0F, 0.93417235896F, -0.17841104489F,
101         0.0F, -0.57735026919F, -0.75576131408F,
102         -0.5F, -0.28867513459F, 0.75576131408F,
103         -0.5F, 0.28867513459F, -0.75576131408F,
104         0.5F, -0.28867513459F, 0.75576131408F,
105         0.5F, 0.28867513459F, -0.75576131408F,
106         -0.80901699437F, 0.46708617948F, 0.17841104489F,
107         0.80901699437F, 0.46708617948F, 0.17841104489F,
108         -0.80901699437F, -0.46708617948F, -0.17841104489F,
109         0.80901699437F, -0.46708617948F, -0.17841104489F,
110     },
111     3, 20,
112     {
113         8,0,2,  0,9,2,  1,10,3, 11,1,3,  0,4,6,
114         4,1,6,  5,2,7,  3,5,7,  4,8,10,  8,5,10,
115         9,6,11, 7,9,11,  0,8,4,  9,0,6,  10,1,4,
116         1,11,6, 8,2,5,  2,9,7,  3,10,5, 11,3,7,
117     },
118     {
119         -0.356822089773F, 0.87267799625F, 0.333333333333F,
120         0.356822089773F, 0.87267799625F, 0.333333333333F,
121         -0.356822089773F, -0.87267799625F, -0.333333333333F,
122         0.356822089773F, -0.87267799625F, -0.333333333333F,
123         -0.0F, 0.0F, 1.0F,
124         0.0F, -0.666666666667F, 0.745355992501F,
125         0.0F, 0.666666666667F, -0.745355992501F,
126         0.0F, 0.0F, -1.0F,
127         -0.934172358963F, -0.12732200375F, 0.333333333333F,
128         -0.934172358963F, 0.12732200375F, -0.333333333333F,
129         0.934172358963F, -0.12732200375F, 0.333333333333F,
130         0.934172358963F, 0.12732200375F, -0.333333333333F,
131         -0.57735026919F, 0.333333333334F, 0.745355992501F,
132         0.57735026919F, 0.333333333334F, 0.745355992501F,
133         -0.57735026919F, -0.745355992501F, 0.333333333334F,
134         0.57735026919F, -0.745355992501F, 0.333333333334F,
135         -0.57735026919F, 0.745355992501F, -0.333333333334F,
136         0.57735026919F, 0.745355992501F, -0.333333333334F,
137         -0.57735026919F, -0.333333333334F, -0.745355992501F,
138         0.57735026919F, -0.333333333334F, -0.745355992501F,
139     },
140     0.0F, 0.8F
141 };
142
143 enum {
144     TETRAHEDRON, CUBE, OCTAHEDRON, ICOSAHEDRON
145 };
146 static const struct solid *solids[] = {
147     &tetrahedron, &cube, &octahedron, &icosahedron
148 };
149
150 enum {
151     COL_BACKGROUND,
152     COL_BORDER,
153     COL_BLUE,
154     NCOLOURS
155 };
156
157 enum { LEFT, RIGHT, UP, DOWN, UP_LEFT, UP_RIGHT, DOWN_LEFT, DOWN_RIGHT };
158
159 #define GRID_SCALE 48.0F
160 #define ROLLTIME 0.1F
161
162 #define SQ(x) ( (x) * (x) )
163
164 #define MATMUL(ra,m,a) do { \
165     float rx, ry, rz, xx = (a)[0], yy = (a)[1], zz = (a)[2], *mat = (m); \
166     rx = mat[0] * xx + mat[3] * yy + mat[6] * zz; \
167     ry = mat[1] * xx + mat[4] * yy + mat[7] * zz; \
168     rz = mat[2] * xx + mat[5] * yy + mat[8] * zz; \
169     (ra)[0] = rx; (ra)[1] = ry; (ra)[2] = rz; \
170 } while (0)
171
172 #define APPROXEQ(x,y) ( SQ(x-y) < 0.1 )
173
174 struct grid_square {
175     float x, y;
176     int npoints;
177     float points[8];                   /* maximum */
178     int directions[8];                 /* bit masks showing point pairs */
179     int flip;
180     int blue;
181     int tetra_class;
182 };
183
184 struct game_params {
185     int solid;
186     /*
187      * Grid dimensions. For a square grid these are width and
188      * height respectively; otherwise the grid is a hexagon, with
189      * the top side and the two lower diagonals having length d1
190      * and the remaining three sides having length d2 (so that
191      * d1==d2 gives a regular hexagon, and d2==0 gives a triangle).
192      */
193     int d1, d2;
194 };
195
196 struct game_state {
197     struct game_params params;
198     const struct solid *solid;
199     int *facecolours;
200     struct grid_square *squares;
201     int nsquares;
202     int current;                       /* index of current grid square */
203     int sgkey[2];                      /* key-point indices into grid sq */
204     int dgkey[2];                      /* key-point indices into grid sq */
205     int spkey[2];                      /* key-point indices into polyhedron */
206     int dpkey[2];                      /* key-point indices into polyhedron */
207     int previous;
208     float angle;
209     int completed;
210     int movecount;
211 };
212
213 game_params *default_params(void)
214 {
215     game_params *ret = snew(game_params);
216
217     ret->solid = CUBE;
218     ret->d1 = 4;
219     ret->d2 = 4;
220
221     return ret;
222 }
223
224 int game_fetch_preset(int i, char **name, game_params **params)
225 {
226     game_params *ret = snew(game_params);
227     char *str;
228
229     switch (i) {
230       case 0:
231         str = "Cube";
232         ret->solid = CUBE;
233         ret->d1 = 4;
234         ret->d2 = 4;
235         break;
236       case 1:
237         str = "Tetrahedron";
238         ret->solid = TETRAHEDRON;
239         ret->d1 = 2;
240         ret->d2 = 1;
241         break;
242       case 2:
243         str = "Octahedron";
244         ret->solid = OCTAHEDRON;
245         ret->d1 = 2;
246         ret->d2 = 2;
247         break;
248       case 3:
249         str = "Icosahedron";
250         ret->solid = ICOSAHEDRON;
251         ret->d1 = 3;
252         ret->d2 = 3;
253         break;
254       default:
255         sfree(ret);
256         return FALSE;
257     }
258
259     *name = dupstr(str);
260     *params = ret;
261     return TRUE;
262 }
263
264 void free_params(game_params *params)
265 {
266     sfree(params);
267 }
268
269 game_params *dup_params(game_params *params)
270 {
271     game_params *ret = snew(game_params);
272     *ret = *params;                    /* structure copy */
273     return ret;
274 }
275
276 static void enum_grid_squares(game_params *params,
277                               void (*callback)(void *, struct grid_square *),
278                               void *ctx)
279 {
280     const struct solid *solid = solids[params->solid];
281
282     if (solid->order == 4) {
283         int x, y;
284
285         for (x = 0; x < params->d1; x++)
286             for (y = 0; y < params->d2; y++) {
287                 struct grid_square sq;
288
289                 sq.x = (float)x;
290                 sq.y = (float)y;
291                 sq.points[0] = x - 0.5F;
292                 sq.points[1] = y - 0.5F;
293                 sq.points[2] = x - 0.5F;
294                 sq.points[3] = y + 0.5F;
295                 sq.points[4] = x + 0.5F;
296                 sq.points[5] = y + 0.5F;
297                 sq.points[6] = x + 0.5F;
298                 sq.points[7] = y - 0.5F;
299                 sq.npoints = 4;
300
301                 sq.directions[LEFT]  = 0x03;   /* 0,1 */
302                 sq.directions[RIGHT] = 0x0C;   /* 2,3 */
303                 sq.directions[UP]    = 0x09;   /* 0,3 */
304                 sq.directions[DOWN]  = 0x06;   /* 1,2 */
305                 sq.directions[UP_LEFT] = 0;   /* no diagonals in a square */
306                 sq.directions[UP_RIGHT] = 0;   /* no diagonals in a square */
307                 sq.directions[DOWN_LEFT] = 0;   /* no diagonals in a square */
308                 sq.directions[DOWN_RIGHT] = 0;   /* no diagonals in a square */
309
310                 sq.flip = FALSE;
311
312                 /*
313                  * This is supremely irrelevant, but just to avoid
314                  * having any uninitialised structure members...
315                  */
316                 sq.tetra_class = 0;
317
318                 callback(ctx, &sq);
319             }
320     } else {
321         int row, rowlen, other, i, firstix = -1;
322         float theight = (float)(sqrt(3) / 2.0);
323
324         for (row = 0; row < params->d1 + params->d2; row++) {
325             if (row < params->d1) {
326                 other = +1;
327                 rowlen = row + params->d2;
328             } else {
329                 other = -1;
330                 rowlen = 2*params->d1 + params->d2 - row;
331             }
332
333             /*
334              * There are `rowlen' down-pointing triangles.
335              */
336             for (i = 0; i < rowlen; i++) {
337                 struct grid_square sq;
338                 int ix;
339                 float x, y;
340
341                 ix = (2 * i - (rowlen-1));
342                 x = ix * 0.5F;
343                 y = theight * row;
344                 sq.x = x;
345                 sq.y = y + theight / 3;
346                 sq.points[0] = x - 0.5F;
347                 sq.points[1] = y;
348                 sq.points[2] = x;
349                 sq.points[3] = y + theight;
350                 sq.points[4] = x + 0.5F;
351                 sq.points[5] = y;
352                 sq.npoints = 3;
353
354                 sq.directions[LEFT]  = 0x03;   /* 0,1 */
355                 sq.directions[RIGHT] = 0x06;   /* 1,2 */
356                 sq.directions[UP]    = 0x05;   /* 0,2 */
357                 sq.directions[DOWN]  = 0;      /* invalid move */
358
359                 /*
360                  * Down-pointing triangle: both the up diagonals go
361                  * up, and the down ones go left and right.
362                  */
363                 sq.directions[UP_LEFT] = sq.directions[UP_RIGHT] =
364                     sq.directions[UP];
365                 sq.directions[DOWN_LEFT] = sq.directions[LEFT];
366                 sq.directions[DOWN_RIGHT] = sq.directions[RIGHT];
367
368                 sq.flip = TRUE;
369
370                 if (firstix < 0)
371                     firstix = ix & 3;
372                 ix -= firstix;
373                 sq.tetra_class = ((row+(ix&1)) & 2) ^ (ix & 3);
374
375                 callback(ctx, &sq);
376             }
377
378             /*
379              * There are `rowlen+other' up-pointing triangles.
380              */
381             for (i = 0; i < rowlen+other; i++) {
382                 struct grid_square sq;
383                 int ix;
384                 float x, y;
385
386                 ix = (2 * i - (rowlen+other-1));
387                 x = ix * 0.5F;
388                 y = theight * row;
389                 sq.x = x;
390                 sq.y = y + 2*theight / 3;
391                 sq.points[0] = x + 0.5F;
392                 sq.points[1] = y + theight;
393                 sq.points[2] = x;
394                 sq.points[3] = y;
395                 sq.points[4] = x - 0.5F;
396                 sq.points[5] = y + theight;
397                 sq.npoints = 3;
398
399                 sq.directions[LEFT]  = 0x06;   /* 1,2 */
400                 sq.directions[RIGHT] = 0x03;   /* 0,1 */
401                 sq.directions[DOWN]  = 0x05;   /* 0,2 */
402                 sq.directions[UP]    = 0;      /* invalid move */
403
404                 /*
405                  * Up-pointing triangle: both the down diagonals go
406                  * down, and the up ones go left and right.
407                  */
408                 sq.directions[DOWN_LEFT] = sq.directions[DOWN_RIGHT] =
409                     sq.directions[DOWN];
410                 sq.directions[UP_LEFT] = sq.directions[LEFT];
411                 sq.directions[UP_RIGHT] = sq.directions[RIGHT];
412
413                 sq.flip = FALSE;
414
415                 if (firstix < 0)
416                     firstix = ix;
417                 ix -= firstix;
418                 sq.tetra_class = ((row+(ix&1)) & 2) ^ (ix & 3);
419
420                 callback(ctx, &sq);
421             }
422         }
423     }
424 }
425
426 static int grid_area(int d1, int d2, int order)
427 {
428     /*
429      * An NxM grid of squares has NM squares in it.
430      * 
431      * A grid of triangles with dimensions A and B has a total of
432      * A^2 + B^2 + 4AB triangles in it. (You can divide it up into
433      * a side-A triangle containing A^2 subtriangles, a side-B
434      * triangle containing B^2, and two congruent parallelograms,
435      * each with side lengths A and B, each therefore containing AB
436      * two-triangle rhombuses.)
437      */
438     if (order == 4)
439         return d1 * d2;
440     else
441         return d1*d1 + d2*d2 + 4*d1*d2;
442 }
443
444 struct grid_data {
445     int *gridptrs[4];
446     int nsquares[4];
447     int nclasses;
448     int squareindex;
449 };
450
451 static void classify_grid_square_callback(void *ctx, struct grid_square *sq)
452 {
453     struct grid_data *data = (struct grid_data *)ctx;
454     int thisclass;
455
456     if (data->nclasses == 4)
457         thisclass = sq->tetra_class;
458     else if (data->nclasses == 2)
459         thisclass = sq->flip;
460     else
461         thisclass = 0;
462
463     data->gridptrs[thisclass][data->nsquares[thisclass]++] =
464         data->squareindex++;
465 }
466
467 char *new_game_seed(game_params *params)
468 {
469     struct grid_data data;
470     int i, j, k, m, area, facesperclass;
471     int *flags;
472     char *seed, *p;
473
474     /*
475      * Enumerate the grid squares, dividing them into equivalence
476      * classes as appropriate. (For the tetrahedron, there is one
477      * equivalence class for each face; for the octahedron there
478      * are two classes; for the other two solids there's only one.)
479      */
480
481     area = grid_area(params->d1, params->d2, solids[params->solid]->order);
482     if (params->solid == TETRAHEDRON)
483         data.nclasses = 4;
484     else if (params->solid == OCTAHEDRON)
485         data.nclasses = 2;
486     else
487         data.nclasses = 1;
488     data.gridptrs[0] = snewn(data.nclasses * area, int);
489     for (i = 0; i < data.nclasses; i++) {
490         data.gridptrs[i] = data.gridptrs[0] + i * area;
491         data.nsquares[i] = 0;
492     }
493     data.squareindex = 0;
494     enum_grid_squares(params, classify_grid_square_callback, &data);
495
496     facesperclass = solids[params->solid]->nfaces / data.nclasses;
497
498     for (i = 0; i < data.nclasses; i++)
499         assert(data.nsquares[i] >= facesperclass);
500     assert(data.squareindex == area);
501
502     /*
503      * So now we know how many faces to allocate in each class. Get
504      * on with it.
505      */
506     flags = snewn(area, int);
507     for (i = 0; i < area; i++)
508         flags[i] = FALSE;
509
510     for (i = 0; i < data.nclasses; i++) {
511         for (j = 0; j < facesperclass; j++) {
512             unsigned long divisor = RAND_MAX / data.nsquares[i];
513             unsigned long max = divisor * data.nsquares[i];
514             unsigned long n;
515
516             do {
517                 n = rand();
518             } while (n >= max);
519
520             n /= divisor;
521
522             assert(!flags[data.gridptrs[i][n]]);
523             flags[data.gridptrs[i][n]] = TRUE;
524
525             /*
526              * Move everything else up the array. I ought to use a
527              * better data structure for this, but for such small
528              * numbers it hardly seems worth the effort.
529              */
530             while ((int)n < data.nsquares[i]-1) {
531                 data.gridptrs[i][n] = data.gridptrs[i][n+1];
532                 n++;
533             }
534             data.nsquares[i]--;
535         }
536     }
537
538     /*
539      * Now we know precisely which squares are blue. Encode this
540      * information in hex. While we're looping over this, collect
541      * the non-blue squares into a list in the now-unused gridptrs
542      * array.
543      */
544     seed = snewn(area / 4 + 40, char);
545     p = seed;
546     j = 0;
547     k = 8;
548     m = 0;
549     for (i = 0; i < area; i++) {
550         if (flags[i]) {
551             j |= k;
552         } else {
553             data.gridptrs[0][m++] = i;
554         }
555         k >>= 1;
556         if (!k) {
557             *p++ = "0123456789ABCDEF"[j];
558             k = 8;
559             j = 0;
560         }
561     }
562     if (k != 8)
563         *p++ = "0123456789ABCDEF"[j];
564
565     /*
566      * Choose a non-blue square for the polyhedron.
567      */
568     {
569         unsigned long divisor = RAND_MAX / m;
570         unsigned long max = divisor * m;
571         unsigned long n;
572
573         do {
574             n = rand();
575         } while (n >= max);
576
577         n /= divisor;
578
579         sprintf(p, ":%d", data.gridptrs[0][n]);
580     }
581
582     sfree(data.gridptrs[0]);
583     sfree(flags);
584
585     return seed;
586 }
587
588 static void add_grid_square_callback(void *ctx, struct grid_square *sq)
589 {
590     game_state *state = (game_state *)ctx;
591
592     state->squares[state->nsquares] = *sq;   /* structure copy */
593     state->squares[state->nsquares].blue = FALSE;
594     state->nsquares++;
595 }
596
597 static int lowest_face(const struct solid *solid)
598 {
599     int i, j, best;
600     float zmin;
601
602     best = 0;
603     zmin = 0.0;
604     for (i = 0; i < solid->nfaces; i++) {
605         float z = 0;
606
607         for (j = 0; j < solid->order; j++) {
608             int f = solid->faces[i*solid->order + j];
609             z += solid->vertices[f*3+2];
610         }
611
612         if (i == 0 || zmin > z) {
613             zmin = z;
614             best = i;
615         }
616     }
617
618     return best;
619 }
620
621 static int align_poly(const struct solid *solid, struct grid_square *sq,
622                       int *pkey)
623 {
624     float zmin;
625     int i, j;
626     int flip = (sq->flip ? -1 : +1);
627
628     /*
629      * First, find the lowest z-coordinate present in the solid.
630      */
631     zmin = 0.0;
632     for (i = 0; i < solid->nvertices; i++)
633         if (zmin > solid->vertices[i*3+2])
634             zmin = solid->vertices[i*3+2];
635
636     /*
637      * Now go round the grid square. For each point in the grid
638      * square, we're looking for a point of the polyhedron with the
639      * same x- and y-coordinates (relative to the square's centre),
640      * and z-coordinate equal to zmin (near enough).
641      */
642     for (j = 0; j < sq->npoints; j++) {
643         int matches, index;
644
645         matches = 0;
646         index = -1;
647
648         for (i = 0; i < solid->nvertices; i++) {
649             float dist = 0;
650
651             dist += SQ(solid->vertices[i*3+0] * flip - sq->points[j*2+0] + sq->x);
652             dist += SQ(solid->vertices[i*3+1] * flip - sq->points[j*2+1] + sq->y);
653             dist += SQ(solid->vertices[i*3+2] - zmin);
654
655             if (dist < 0.1) {
656                 matches++;
657                 index = i;
658             }
659         }
660
661         if (matches != 1 || index < 0)
662             return FALSE;
663         pkey[j] = index;
664     }
665
666     return TRUE;
667 }
668
669 static void flip_poly(struct solid *solid, int flip)
670 {
671     int i;
672
673     if (flip) {
674         for (i = 0; i < solid->nvertices; i++) {
675             solid->vertices[i*3+0] *= -1;
676             solid->vertices[i*3+1] *= -1;
677         }
678         for (i = 0; i < solid->nfaces; i++) {
679             solid->normals[i*3+0] *= -1;
680             solid->normals[i*3+1] *= -1;
681         }
682     }
683 }
684
685 static struct solid *transform_poly(const struct solid *solid, int flip,
686                                     int key0, int key1, float angle)
687 {
688     struct solid *ret = snew(struct solid);
689     float vx, vy, ax, ay;
690     float vmatrix[9], amatrix[9], vmatrix2[9];
691     int i;
692
693     *ret = *solid;                     /* structure copy */
694
695     flip_poly(ret, flip);
696
697     /*
698      * Now rotate the polyhedron through the given angle. We must
699      * rotate about the Z-axis to bring the two vertices key0 and
700      * key1 into horizontal alignment, then rotate about the
701      * X-axis, then rotate back again.
702      */
703     vx = ret->vertices[key1*3+0] - ret->vertices[key0*3+0];
704     vy = ret->vertices[key1*3+1] - ret->vertices[key0*3+1];
705     assert(APPROXEQ(vx*vx + vy*vy, 1.0));
706
707     vmatrix[0] =  vx; vmatrix[3] = vy; vmatrix[6] = 0;
708     vmatrix[1] = -vy; vmatrix[4] = vx; vmatrix[7] = 0;
709     vmatrix[2] =   0; vmatrix[5] =  0; vmatrix[8] = 1;
710
711     ax = (float)cos(angle);
712     ay = (float)sin(angle);
713
714     amatrix[0] = 1; amatrix[3] =   0; amatrix[6] =  0;
715     amatrix[1] = 0; amatrix[4] =  ax; amatrix[7] = ay;
716     amatrix[2] = 0; amatrix[5] = -ay; amatrix[8] = ax;
717
718     memcpy(vmatrix2, vmatrix, sizeof(vmatrix));
719     vmatrix2[1] = vy;
720     vmatrix2[3] = -vy;
721
722     for (i = 0; i < ret->nvertices; i++) {
723         MATMUL(ret->vertices + 3*i, vmatrix, ret->vertices + 3*i);
724         MATMUL(ret->vertices + 3*i, amatrix, ret->vertices + 3*i);
725         MATMUL(ret->vertices + 3*i, vmatrix2, ret->vertices + 3*i);
726     }
727     for (i = 0; i < ret->nfaces; i++) {
728         MATMUL(ret->normals + 3*i, vmatrix, ret->normals + 3*i);
729         MATMUL(ret->normals + 3*i, amatrix, ret->normals + 3*i);
730         MATMUL(ret->normals + 3*i, vmatrix2, ret->normals + 3*i);
731     }
732
733     return ret;
734 }
735
736 game_state *new_game(game_params *params, char *seed)
737 {
738     game_state *state = snew(game_state);
739     int area;
740
741     state->params = *params;           /* structure copy */
742     state->solid = solids[params->solid];
743
744     area = grid_area(params->d1, params->d2, state->solid->order);
745     state->squares = snewn(area, struct grid_square);
746     state->nsquares = 0;
747     enum_grid_squares(params, add_grid_square_callback, state);
748     assert(state->nsquares == area);
749
750     state->facecolours = snewn(state->solid->nfaces, int);
751     memset(state->facecolours, 0, state->solid->nfaces * sizeof(int));
752
753     /*
754      * Set up the blue squares and polyhedron position according to
755      * the game seed.
756      */
757     {
758         char *p = seed;
759         int i, j, v;
760
761         j = 8;
762         v = 0;
763         for (i = 0; i < state->nsquares; i++) {
764             if (j == 8) {
765                 v = *p++;
766                 if (v >= '0' && v <= '9')
767                     v -= '0';
768                 else if (v >= 'A' && v <= 'F')
769                     v -= 'A' - 10;
770                 else if (v >= 'a' && v <= 'f')
771                     v -= 'a' - 10;
772                 else
773                     break;
774             }
775             if (v & j)
776                 state->squares[i].blue = TRUE;
777             j >>= 1;
778             if (j == 0)
779                 j = 8;
780         }
781
782         if (*p == ':')
783             p++;
784
785         state->current = atoi(p);
786         if (state->current < 0 || state->current >= state->nsquares)
787             state->current = 0;        /* got to do _something_ */
788     }
789
790     /*
791      * Align the polyhedron with its grid square and determine
792      * initial key points.
793      */
794     {
795         int pkey[4];
796         int ret;
797
798         ret = align_poly(state->solid, &state->squares[state->current], pkey);
799         assert(ret);
800
801         state->dpkey[0] = state->spkey[0] = pkey[0];
802         state->dpkey[1] = state->spkey[0] = pkey[1];
803         state->dgkey[0] = state->sgkey[0] = 0;
804         state->dgkey[1] = state->sgkey[0] = 1;
805     }
806
807     state->previous = state->current;
808     state->angle = 0.0;
809     state->completed = FALSE;
810     state->movecount = 0;
811
812     return state;
813 }
814
815 game_state *dup_game(game_state *state)
816 {
817     game_state *ret = snew(game_state);
818
819     ret->params = state->params;           /* structure copy */
820     ret->solid = state->solid;
821     ret->facecolours = snewn(ret->solid->nfaces, int);
822     memcpy(ret->facecolours, state->facecolours,
823            ret->solid->nfaces * sizeof(int));
824     ret->nsquares = state->nsquares;
825     ret->squares = snewn(ret->nsquares, struct grid_square);
826     memcpy(ret->squares, state->squares,
827            ret->nsquares * sizeof(struct grid_square));
828     ret->dpkey[0] = state->dpkey[0];
829     ret->dpkey[1] = state->dpkey[1];
830     ret->dgkey[0] = state->dgkey[0];
831     ret->dgkey[1] = state->dgkey[1];
832     ret->spkey[0] = state->spkey[0];
833     ret->spkey[1] = state->spkey[1];
834     ret->sgkey[0] = state->sgkey[0];
835     ret->sgkey[1] = state->sgkey[1];
836     ret->previous = state->previous;
837     ret->angle = state->angle;
838     ret->completed = state->completed;
839     ret->movecount = state->movecount;
840
841     return ret;
842 }
843
844 void free_game(game_state *state)
845 {
846     sfree(state);
847 }
848
849 game_state *make_move(game_state *from, int x, int y, int button)
850 {
851     int direction;
852     int pkey[2], skey[2], dkey[2];
853     float points[4];
854     game_state *ret;
855     float angle;
856     int i, j, dest, mask;
857     struct solid *poly;
858
859     /*
860      * All moves are made with the cursor keys.
861      */
862     if (button == CURSOR_UP)
863         direction = UP;
864     else if (button == CURSOR_DOWN)
865         direction = DOWN;
866     else if (button == CURSOR_LEFT)
867         direction = LEFT;
868     else if (button == CURSOR_RIGHT)
869         direction = RIGHT;
870     else if (button == CURSOR_UP_LEFT)
871         direction = UP_LEFT;
872     else if (button == CURSOR_DOWN_LEFT)
873         direction = DOWN_LEFT;
874     else if (button == CURSOR_UP_RIGHT)
875         direction = UP_RIGHT;
876     else if (button == CURSOR_DOWN_RIGHT)
877         direction = DOWN_RIGHT;
878     else
879         return NULL;
880
881     /*
882      * Find the two points in the current grid square which
883      * correspond to this move.
884      */
885     mask = from->squares[from->current].directions[direction];
886     if (mask == 0)
887         return NULL;
888     for (i = j = 0; i < from->squares[from->current].npoints; i++)
889         if (mask & (1 << i)) {
890             points[j*2] = from->squares[from->current].points[i*2];
891             points[j*2+1] = from->squares[from->current].points[i*2+1];
892             skey[j] = i;
893             j++;
894         }
895     assert(j == 2);
896
897     /*
898      * Now find the other grid square which shares those points.
899      * This is our move destination.
900      */
901     dest = -1;
902     for (i = 0; i < from->nsquares; i++)
903         if (i != from->current) {
904             int match = 0;
905             float dist;
906
907             for (j = 0; j < from->squares[i].npoints; j++) {
908                 dist = (SQ(from->squares[i].points[j*2] - points[0]) +
909                         SQ(from->squares[i].points[j*2+1] - points[1]));
910                 if (dist < 0.1)
911                     dkey[match++] = j;
912                 dist = (SQ(from->squares[i].points[j*2] - points[2]) +
913                         SQ(from->squares[i].points[j*2+1] - points[3]));
914                 if (dist < 0.1)
915                     dkey[match++] = j;
916             }
917
918             if (match == 2) {
919                 dest = i;
920                 break;
921             }
922         }
923
924     if (dest < 0)
925         return NULL;
926
927     ret = dup_game(from);
928     ret->current = i;
929
930     /*
931      * So we know what grid square we're aiming for, and we also
932      * know the two key points (as indices in both the source and
933      * destination grid squares) which are invariant between source
934      * and destination.
935      * 
936      * Next we must roll the polyhedron on to that square. So we
937      * find the indices of the key points within the polyhedron's
938      * vertex array, then use those in a call to transform_poly,
939      * and align the result on the new grid square.
940      */
941     {
942         int all_pkey[4];
943         align_poly(from->solid, &from->squares[from->current], all_pkey);
944         pkey[0] = all_pkey[skey[0]];
945         pkey[1] = all_pkey[skey[1]];
946         /*
947          * Now pkey[0] corresponds to skey[0] and dkey[0], and
948          * likewise [1].
949          */
950     }
951
952     /*
953      * Now find the angle through which to rotate the polyhedron.
954      * Do this by finding the two faces that share the two vertices
955      * we've found, and taking the dot product of their normals.
956      */
957     {
958         int f[2], nf = 0;
959         float dp;
960
961         for (i = 0; i < from->solid->nfaces; i++) {
962             int match = 0;
963             for (j = 0; j < from->solid->order; j++)
964                 if (from->solid->faces[i*from->solid->order + j] == pkey[0] ||
965                     from->solid->faces[i*from->solid->order + j] == pkey[1])
966                     match++;
967             if (match == 2) {
968                 assert(nf < 2);
969                 f[nf++] = i;
970             }
971         }
972
973         assert(nf == 2);
974
975         dp = 0;
976         for (i = 0; i < 3; i++)
977             dp += (from->solid->normals[f[0]*3+i] *
978                    from->solid->normals[f[1]*3+i]);
979         angle = (float)acos(dp);
980     }
981
982     /*
983      * Now transform the polyhedron. We aren't entirely sure
984      * whether we need to rotate through angle or -angle, and the
985      * simplest way round this is to try both and see which one
986      * aligns successfully!
987      * 
988      * Unfortunately, _both_ will align successfully if this is a
989      * cube, which won't tell us anything much. So for that
990      * particular case, I resort to gross hackery: I simply negate
991      * the angle before trying the alignment, depending on the
992      * direction. Which directions work which way is determined by
993      * pure trial and error. I said it was gross :-/
994      */
995     {
996         int all_pkey[4];
997         int success;
998
999         if (from->solid->order == 4 && direction == UP)
1000             angle = -angle;            /* HACK */
1001
1002         poly = transform_poly(from->solid,
1003                               from->squares[from->current].flip,
1004                               pkey[0], pkey[1], angle);
1005         flip_poly(poly, from->squares[ret->current].flip);
1006         success = align_poly(poly, &from->squares[ret->current], all_pkey);
1007
1008         if (!success) {
1009             angle = -angle;
1010             poly = transform_poly(from->solid,
1011                                   from->squares[from->current].flip,
1012                                   pkey[0], pkey[1], angle);
1013             flip_poly(poly, from->squares[ret->current].flip);
1014             success = align_poly(poly, &from->squares[ret->current], all_pkey);
1015         }
1016
1017         assert(success);
1018     }
1019
1020     /*
1021      * Now we have our rotated polyhedron, which we expect to be
1022      * exactly congruent to the one we started with - but with the
1023      * faces permuted. So we map that congruence and thereby figure
1024      * out how to permute the faces as a result of the polyhedron
1025      * having rolled.
1026      */
1027     {
1028         int *newcolours = snewn(from->solid->nfaces, int);
1029
1030         for (i = 0; i < from->solid->nfaces; i++)
1031             newcolours[i] = -1;
1032
1033         for (i = 0; i < from->solid->nfaces; i++) {
1034             int nmatch = 0;
1035
1036             /*
1037              * Now go through the transformed polyhedron's faces
1038              * and figure out which one's normal is approximately
1039              * equal to this one.
1040              */
1041             for (j = 0; j < poly->nfaces; j++) {
1042                 float dist;
1043                 int k;
1044
1045                 dist = 0;
1046
1047                 for (k = 0; k < 3; k++)
1048                     dist += SQ(poly->normals[j*3+k] -
1049                                from->solid->normals[i*3+k]);
1050
1051                 if (APPROXEQ(dist, 0)) {
1052                     nmatch++;
1053                     newcolours[i] = ret->facecolours[j];
1054                 }
1055             }
1056
1057             assert(nmatch == 1);
1058         }
1059
1060         for (i = 0; i < from->solid->nfaces; i++)
1061             assert(newcolours[i] != -1);
1062
1063         sfree(ret->facecolours);
1064         ret->facecolours = newcolours;
1065     }
1066
1067     /*
1068      * And finally, swap the colour between the bottom face of the
1069      * polyhedron and the face we've just landed on.
1070      * 
1071      * We don't do this if the game is already complete, since we
1072      * allow the user to roll the fully blue polyhedron around the
1073      * grid as a feeble reward.
1074      */
1075     if (!ret->completed) {
1076         i = lowest_face(from->solid);
1077         j = ret->facecolours[i];
1078         ret->facecolours[i] = ret->squares[ret->current].blue;
1079         ret->squares[ret->current].blue = j;
1080
1081         /*
1082          * Detect game completion.
1083          */
1084         j = 0;
1085         for (i = 0; i < ret->solid->nfaces; i++)
1086             if (ret->facecolours[i])
1087                 j++;
1088         if (j == ret->solid->nfaces)
1089             ret->completed = TRUE;
1090     }
1091
1092     sfree(poly);
1093
1094     /*
1095      * Align the normal polyhedron with its grid square, to get key
1096      * points for non-animated display.
1097      */
1098     {
1099         int pkey[4];
1100         int success;
1101
1102         success = align_poly(ret->solid, &ret->squares[ret->current], pkey);
1103         assert(success);
1104
1105         ret->dpkey[0] = pkey[0];
1106         ret->dpkey[1] = pkey[1];
1107         ret->dgkey[0] = 0;
1108         ret->dgkey[1] = 1;
1109     }
1110
1111
1112     ret->spkey[0] = pkey[0];
1113     ret->spkey[1] = pkey[1];
1114     ret->sgkey[0] = skey[0];
1115     ret->sgkey[1] = skey[1];
1116     ret->previous = from->current;
1117     ret->angle = angle;
1118     ret->movecount++;
1119
1120     return ret;
1121 }
1122
1123 /* ----------------------------------------------------------------------
1124  * Drawing routines.
1125  */
1126
1127 struct bbox {
1128     float l, r, u, d;
1129 };
1130
1131 struct game_drawstate {
1132     int ox, oy;                        /* pixel position of float origin */
1133 };
1134
1135 static void find_bbox_callback(void *ctx, struct grid_square *sq)
1136 {
1137     struct bbox *bb = (struct bbox *)ctx;
1138     int i;
1139
1140     for (i = 0; i < sq->npoints; i++) {
1141         if (bb->l > sq->points[i*2]) bb->l = sq->points[i*2];
1142         if (bb->r < sq->points[i*2]) bb->r = sq->points[i*2];
1143         if (bb->u > sq->points[i*2+1]) bb->u = sq->points[i*2+1];
1144         if (bb->d < sq->points[i*2+1]) bb->d = sq->points[i*2+1];
1145     }
1146 }
1147
1148 static struct bbox find_bbox(game_params *params)
1149 {
1150     struct bbox bb;
1151
1152     /*
1153      * These should be hugely more than the real bounding box will
1154      * be.
1155      */
1156     bb.l = 2.0F * (params->d1 + params->d2);
1157     bb.r = -2.0F * (params->d1 + params->d2);
1158     bb.u = 2.0F * (params->d1 + params->d2);
1159     bb.d = -2.0F * (params->d1 + params->d2);
1160     enum_grid_squares(params, find_bbox_callback, &bb);
1161
1162     return bb;
1163 }
1164
1165 void game_size(game_params *params, int *x, int *y)
1166 {
1167     struct bbox bb = find_bbox(params);
1168     *x = (int)((bb.r - bb.l + 2*solids[params->solid]->border) * GRID_SCALE);
1169     *y = (int)((bb.d - bb.u + 2*solids[params->solid]->border) * GRID_SCALE);
1170 }
1171
1172 float *game_colours(frontend *fe, game_state *state, int *ncolours)
1173 {
1174     float *ret = snewn(3 * NCOLOURS, float);
1175
1176     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1177
1178     ret[COL_BORDER * 3 + 0] = 0.0;
1179     ret[COL_BORDER * 3 + 1] = 0.0;
1180     ret[COL_BORDER * 3 + 2] = 0.0;
1181
1182     ret[COL_BLUE * 3 + 0] = 0.0;
1183     ret[COL_BLUE * 3 + 1] = 0.0;
1184     ret[COL_BLUE * 3 + 2] = 1.0;
1185
1186     *ncolours = NCOLOURS;
1187     return ret;
1188 }
1189
1190 game_drawstate *game_new_drawstate(game_state *state)
1191 {
1192     struct game_drawstate *ds = snew(struct game_drawstate);
1193     struct bbox bb = find_bbox(&state->params);
1194
1195     ds->ox = (int)(-(bb.l - state->solid->border) * GRID_SCALE);
1196     ds->oy = (int)(-(bb.u - state->solid->border) * GRID_SCALE);
1197
1198     return ds;
1199 }
1200
1201 void game_free_drawstate(game_drawstate *ds)
1202 {
1203     sfree(ds);
1204 }
1205
1206 void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1207                  game_state *state, float animtime)
1208 {
1209     int i, j;
1210     struct bbox bb = find_bbox(&state->params);
1211     struct solid *poly;
1212     int *pkey, *gkey;
1213     float t[3];
1214     float angle;
1215     game_state *newstate;
1216     int square;
1217
1218     draw_rect(fe, 0, 0, (int)((bb.r-bb.l+2.0F) * GRID_SCALE),
1219               (int)((bb.d-bb.u+2.0F) * GRID_SCALE), COL_BACKGROUND);
1220
1221     if (oldstate && oldstate->movecount > state->movecount) {
1222         game_state *t;
1223
1224         /*
1225          * This is an Undo. So reverse the order of the states, and
1226          * run the roll timer backwards.
1227          */
1228         t = oldstate;
1229         oldstate = state;
1230         state = t;
1231
1232         animtime = ROLLTIME - animtime;
1233     }
1234
1235     if (!oldstate) {
1236         oldstate = state;
1237         angle = 0.0;
1238         square = state->current;
1239         pkey = state->dpkey;
1240         gkey = state->dgkey;
1241     } else {
1242         angle = state->angle * animtime / ROLLTIME;
1243         square = state->previous;
1244         pkey = state->spkey;
1245         gkey = state->sgkey;
1246     }
1247     newstate = state;
1248     state = oldstate;
1249
1250     for (i = 0; i < state->nsquares; i++) {
1251         int coords[8];
1252
1253         for (j = 0; j < state->squares[i].npoints; j++) {
1254             coords[2*j] = ((int)(state->squares[i].points[2*j] * GRID_SCALE)
1255                            + ds->ox);
1256             coords[2*j+1] = ((int)(state->squares[i].points[2*j+1]*GRID_SCALE)
1257                              + ds->oy);
1258         }
1259
1260         draw_polygon(fe, coords, state->squares[i].npoints, TRUE,
1261                      state->squares[i].blue ? COL_BLUE : COL_BACKGROUND);
1262         draw_polygon(fe, coords, state->squares[i].npoints, FALSE, COL_BORDER);
1263     }
1264
1265     /*
1266      * Now compute and draw the polyhedron.
1267      */
1268     poly = transform_poly(state->solid, state->squares[square].flip,
1269                           pkey[0], pkey[1], angle);
1270
1271     /*
1272      * Compute the translation required to align the two key points
1273      * on the polyhedron with the same key points on the current
1274      * face.
1275      */
1276     for (i = 0; i < 3; i++) {
1277         float tc = 0.0;
1278
1279         for (j = 0; j < 2; j++) {
1280             float grid_coord;
1281
1282             if (i < 2) {
1283                 grid_coord =
1284                     state->squares[square].points[gkey[j]*2+i];
1285             } else {
1286                 grid_coord = 0.0;
1287             }
1288
1289             tc += (grid_coord - poly->vertices[pkey[j]*3+i]);
1290         }
1291
1292         t[i] = tc / 2;
1293     }
1294     for (i = 0; i < poly->nvertices; i++)
1295         for (j = 0; j < 3; j++)
1296             poly->vertices[i*3+j] += t[j];
1297
1298     /*
1299      * Now actually draw each face.
1300      */
1301     for (i = 0; i < poly->nfaces; i++) {
1302         float points[8];
1303         int coords[8];
1304
1305         for (j = 0; j < poly->order; j++) {
1306             int f = poly->faces[i*poly->order + j];
1307             points[j*2] = (poly->vertices[f*3+0] -
1308                            poly->vertices[f*3+2] * poly->shear);
1309             points[j*2+1] = (poly->vertices[f*3+1] -
1310                              poly->vertices[f*3+2] * poly->shear);
1311         }
1312
1313         for (j = 0; j < poly->order; j++) {
1314             coords[j*2] = (int)(points[j*2] * GRID_SCALE) + ds->ox;
1315             coords[j*2+1] = (int)(points[j*2+1] * GRID_SCALE) + ds->oy;
1316         }
1317
1318         /*
1319          * Find out whether these points are in a clockwise or
1320          * anticlockwise arrangement. If the latter, discard the
1321          * face because it's facing away from the viewer.
1322          *
1323          * This would involve fiddly winding-number stuff for a
1324          * general polygon, but for the simple parallelograms we'll
1325          * be seeing here, all we have to do is check whether the
1326          * corners turn right or left. So we'll take the vector
1327          * from point 0 to point 1, turn it right 90 degrees,
1328          * and check the sign of the dot product with that and the
1329          * next vector (point 1 to point 2).
1330          */
1331         {
1332             float v1x = points[2]-points[0];
1333             float v1y = points[3]-points[1];
1334             float v2x = points[4]-points[2];
1335             float v2y = points[5]-points[3];
1336             float dp = v1x * v2y - v1y * v2x;
1337
1338             if (dp <= 0)
1339                 continue;
1340         }
1341
1342         draw_polygon(fe, coords, poly->order, TRUE,
1343                      state->facecolours[i] ? COL_BLUE : COL_BACKGROUND);
1344         draw_polygon(fe, coords, poly->order, FALSE, COL_BORDER);
1345     }
1346     sfree(poly);
1347
1348     draw_update(fe, 0, 0, (int)((bb.r-bb.l+2.0F) * GRID_SCALE),
1349                 (int)((bb.d-bb.u+2.0F) * GRID_SCALE));
1350 }
1351
1352 float game_anim_length(game_state *oldstate, game_state *newstate)
1353 {
1354     return ROLLTIME;
1355 }