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