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