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