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