chiark / gitweb /
0448958925f80da18ebd2b65993708ecc5e7a794
[sgt-puzzles.git] / rect.c
1 /*
2  * rect.c: Puzzle from nikoli.co.jp. You have a square grid with
3  * numbers in some squares; you must divide the square grid up into
4  * variously sized rectangles, such that every rectangle contains
5  * exactly one numbered square and the area of each rectangle is
6  * equal to the number contained in it.
7  */
8
9 /*
10  * TODO:
11  * 
12  *  - Improve on singleton removal by making an aesthetic choice
13  *    about which of the options to take.
14  * 
15  *  - When doing the 3x3 trick in singleton removal, limit the size
16  *    of the generated rectangles in accordance with the max
17  *    rectangle size.
18  * 
19  *  - If we start by sorting the rectlist in descending order
20  *    of area, we might be able to bias our random number
21  *    selection to produce a few large rectangles more often
22  *    than oodles of small ones? Unsure, but might be worth a
23  *    try.
24  */
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <assert.h>
30 #include <ctype.h>
31 #include <math.h>
32
33 #include "puzzles.h"
34
35 enum {
36     COL_BACKGROUND,
37     COL_CORRECT,
38     COL_LINE,
39     COL_TEXT,
40     COL_GRID,
41     COL_DRAG,
42     NCOLOURS
43 };
44
45 struct game_params {
46     int w, h;
47     float expandfactor;
48     int unique;
49 };
50
51 #define INDEX(state, x, y)    (((y) * (state)->w) + (x))
52 #define index(state, a, x, y) ((a) [ INDEX(state,x,y) ])
53 #define grid(state,x,y)       index(state, (state)->grid, x, y)
54 #define vedge(state,x,y)      index(state, (state)->vedge, x, y)
55 #define hedge(state,x,y)      index(state, (state)->hedge, x, y)
56
57 #define CRANGE(state,x,y,dx,dy) ( (x) >= dx && (x) < (state)->w && \
58                                 (y) >= dy && (y) < (state)->h )
59 #define RANGE(state,x,y)  CRANGE(state,x,y,0,0)
60 #define HRANGE(state,x,y) CRANGE(state,x,y,0,1)
61 #define VRANGE(state,x,y) CRANGE(state,x,y,1,0)
62
63 #define TILE_SIZE 24
64 #define BORDER 18
65
66 #define CORNER_TOLERANCE 0.15F
67 #define CENTRE_TOLERANCE 0.15F
68
69 #define FLASH_TIME 0.13F
70
71 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
72 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
73
74 struct game_state {
75     int w, h;
76     int *grid;                         /* contains the numbers */
77     unsigned char *vedge;              /* (w+1) x h */
78     unsigned char *hedge;              /* w x (h+1) */
79     int completed, cheated;
80 };
81
82 static game_params *default_params(void)
83 {
84     game_params *ret = snew(game_params);
85
86     ret->w = ret->h = 7;
87     ret->expandfactor = 0.0F;
88     ret->unique = TRUE;
89
90     return ret;
91 }
92
93 static int game_fetch_preset(int i, char **name, game_params **params)
94 {
95     game_params *ret;
96     int w, h;
97     char buf[80];
98
99     switch (i) {
100       case 0: w = 7, h = 7; break;
101       case 1: w = 9, h = 9; break;
102       case 2: w = 11, h = 11; break;
103       case 3: w = 13, h = 13; break;
104       case 4: w = 15, h = 15; break;
105 #ifndef SLOW_SYSTEM
106       case 5: w = 17, h = 17; break;
107       case 6: w = 19, h = 19; break;
108 #endif
109       default: return FALSE;
110     }
111
112     sprintf(buf, "%dx%d", w, h);
113     *name = dupstr(buf);
114     *params = ret = snew(game_params);
115     ret->w = w;
116     ret->h = h;
117     ret->expandfactor = 0.0F;
118     ret->unique = TRUE;
119     return TRUE;
120 }
121
122 static void free_params(game_params *params)
123 {
124     sfree(params);
125 }
126
127 static game_params *dup_params(game_params *params)
128 {
129     game_params *ret = snew(game_params);
130     *ret = *params;                    /* structure copy */
131     return ret;
132 }
133
134 static void decode_params(game_params *ret, char const *string)
135 {
136     ret->w = ret->h = atoi(string);
137     while (*string && isdigit((unsigned char)*string)) string++;
138     if (*string == 'x') {
139         string++;
140         ret->h = atoi(string);
141         while (*string && isdigit((unsigned char)*string)) string++;
142     }
143     if (*string == 'e') {
144         string++;
145         ret->expandfactor = atof(string);
146         while (*string &&
147                (*string == '.' || isdigit((unsigned char)*string))) string++;
148     }
149     if (*string == 'a') {
150         string++;
151         ret->unique = FALSE;
152     }
153 }
154
155 static char *encode_params(game_params *params, int full)
156 {
157     char data[256];
158
159     sprintf(data, "%dx%d", params->w, params->h);
160     if (full && params->expandfactor)
161         sprintf(data + strlen(data), "e%g", params->expandfactor);
162     if (full && !params->unique)
163         strcat(data, "a");
164
165     return dupstr(data);
166 }
167
168 static config_item *game_configure(game_params *params)
169 {
170     config_item *ret;
171     char buf[80];
172
173     ret = snewn(5, config_item);
174
175     ret[0].name = "Width";
176     ret[0].type = C_STRING;
177     sprintf(buf, "%d", params->w);
178     ret[0].sval = dupstr(buf);
179     ret[0].ival = 0;
180
181     ret[1].name = "Height";
182     ret[1].type = C_STRING;
183     sprintf(buf, "%d", params->h);
184     ret[1].sval = dupstr(buf);
185     ret[1].ival = 0;
186
187     ret[2].name = "Expansion factor";
188     ret[2].type = C_STRING;
189     sprintf(buf, "%g", params->expandfactor);
190     ret[2].sval = dupstr(buf);
191     ret[2].ival = 0;
192
193     ret[3].name = "Ensure unique solution";
194     ret[3].type = C_BOOLEAN;
195     ret[3].sval = NULL;
196     ret[3].ival = params->unique;
197
198     ret[4].name = NULL;
199     ret[4].type = C_END;
200     ret[4].sval = NULL;
201     ret[4].ival = 0;
202
203     return ret;
204 }
205
206 static game_params *custom_params(config_item *cfg)
207 {
208     game_params *ret = snew(game_params);
209
210     ret->w = atoi(cfg[0].sval);
211     ret->h = atoi(cfg[1].sval);
212     ret->expandfactor = atof(cfg[2].sval);
213     ret->unique = cfg[3].ival;
214
215     return ret;
216 }
217
218 static char *validate_params(game_params *params)
219 {
220     if (params->w <= 0 || params->h <= 0)
221         return "Width and height must both be greater than zero";
222     if (params->w*params->h < 2)
223         return "Grid area must be greater than one";
224     if (params->expandfactor < 0.0F)
225         return "Expansion factor may not be negative";
226     return NULL;
227 }
228
229 struct point {
230     int x, y;
231 };
232
233 struct rect {
234     int x, y;
235     int w, h;
236 };
237
238 struct rectlist {
239     struct rect *rects;
240     int n;
241 };
242
243 struct numberdata {
244     int area;
245     int npoints;
246     struct point *points;
247 };
248
249 /* ----------------------------------------------------------------------
250  * Solver for Rectangles games.
251  * 
252  * This solver is souped up beyond the needs of actually _solving_
253  * a puzzle. It is also designed to cope with uncertainty about
254  * where the numbers have been placed. This is because I run it on
255  * my generated grids _before_ placing the numbers, and have it
256  * tell me where I need to place the numbers to ensure a unique
257  * solution.
258  */
259
260 static void remove_rect_placement(int w, int h,
261                                   struct rectlist *rectpositions,
262                                   int *overlaps,
263                                   int rectnum, int placement)
264 {
265     int x, y, xx, yy;
266
267 #ifdef SOLVER_DIAGNOSTICS
268     printf("ruling out rect %d placement at %d,%d w=%d h=%d\n", rectnum,
269            rectpositions[rectnum].rects[placement].x,
270            rectpositions[rectnum].rects[placement].y,
271            rectpositions[rectnum].rects[placement].w,
272            rectpositions[rectnum].rects[placement].h);
273 #endif
274
275     /*
276      * Decrement each entry in the overlaps array to reflect the
277      * removal of this rectangle placement.
278      */
279     for (yy = 0; yy < rectpositions[rectnum].rects[placement].h; yy++) {
280         y = yy + rectpositions[rectnum].rects[placement].y;
281         for (xx = 0; xx < rectpositions[rectnum].rects[placement].w; xx++) {
282             x = xx + rectpositions[rectnum].rects[placement].x;
283
284             assert(overlaps[(rectnum * h + y) * w + x] != 0);
285
286             if (overlaps[(rectnum * h + y) * w + x] > 0)
287                 overlaps[(rectnum * h + y) * w + x]--;
288         }
289     }
290
291     /*
292      * Remove the placement from the list of positions for that
293      * rectangle, by interchanging it with the one on the end.
294      */
295     if (placement < rectpositions[rectnum].n - 1) {
296         struct rect t;
297
298         t = rectpositions[rectnum].rects[rectpositions[rectnum].n - 1];
299         rectpositions[rectnum].rects[rectpositions[rectnum].n - 1] =
300             rectpositions[rectnum].rects[placement];
301         rectpositions[rectnum].rects[placement] = t;
302     }
303     rectpositions[rectnum].n--;
304 }
305
306 static void remove_number_placement(int w, int h, struct numberdata *number,
307                                     int index, int *rectbyplace)
308 {
309     /*
310      * Remove the entry from the rectbyplace array.
311      */
312     rectbyplace[number->points[index].y * w + number->points[index].x] = -1;
313
314     /*
315      * Remove the placement from the list of candidates for that
316      * number, by interchanging it with the one on the end.
317      */
318     if (index < number->npoints - 1) {
319         struct point t;
320
321         t = number->points[number->npoints - 1];
322         number->points[number->npoints - 1] = number->points[index];
323         number->points[index] = t;
324     }
325     number->npoints--;
326 }
327
328 static int rect_solver(int w, int h, int nrects, struct numberdata *numbers,
329                        game_state *result, random_state *rs)
330 {
331     struct rectlist *rectpositions;
332     int *overlaps, *rectbyplace, *workspace;
333     int i, ret;
334
335     /*
336      * Start by setting up a list of candidate positions for each
337      * rectangle.
338      */
339     rectpositions = snewn(nrects, struct rectlist);
340     for (i = 0; i < nrects; i++) {
341         int rw, rh, area = numbers[i].area;
342         int j, minx, miny, maxx, maxy;
343         struct rect *rlist;
344         int rlistn, rlistsize;
345
346         /*
347          * For each rectangle, begin by finding the bounding
348          * rectangle of its candidate number placements.
349          */
350         maxx = maxy = -1;
351         minx = w;
352         miny = h;
353         for (j = 0; j < numbers[i].npoints; j++) {
354             if (minx > numbers[i].points[j].x) minx = numbers[i].points[j].x;
355             if (miny > numbers[i].points[j].y) miny = numbers[i].points[j].y;
356             if (maxx < numbers[i].points[j].x) maxx = numbers[i].points[j].x;
357             if (maxy < numbers[i].points[j].y) maxy = numbers[i].points[j].y;
358         }
359
360         /*
361          * Now loop over all possible rectangle placements
362          * overlapping a point within that bounding rectangle;
363          * ensure each one actually contains a candidate number
364          * placement, and add it to the list.
365          */
366         rlist = NULL;
367         rlistn = rlistsize = 0;
368
369         for (rw = 1; rw <= area && rw <= w; rw++) {
370             int x, y;
371
372             if (area % rw)
373                 continue;
374             rh = area / rw;
375             if (rh > h)
376                 continue;
377
378             for (y = miny - rh + 1; y <= maxy; y++) {
379                 if (y < 0 || y+rh > h)
380                     continue;
381
382                 for (x = minx - rw + 1; x <= maxx; x++) {
383                     if (x < 0 || x+rw > w)
384                         continue;
385
386                     /*
387                      * See if we can find a candidate number
388                      * placement within this rectangle.
389                      */
390                     for (j = 0; j < numbers[i].npoints; j++)
391                         if (numbers[i].points[j].x >= x &&
392                             numbers[i].points[j].x < x+rw &&
393                             numbers[i].points[j].y >= y &&
394                             numbers[i].points[j].y < y+rh)
395                             break;
396
397                     if (j < numbers[i].npoints) {
398                         /*
399                          * Add this to the list of candidate
400                          * placements for this rectangle.
401                          */
402                         if (rlistn >= rlistsize) {
403                             rlistsize = rlistn + 32;
404                             rlist = sresize(rlist, rlistsize, struct rect);
405                         }
406                         rlist[rlistn].x = x;
407                         rlist[rlistn].y = y;
408                         rlist[rlistn].w = rw;
409                         rlist[rlistn].h = rh;
410 #ifdef SOLVER_DIAGNOSTICS
411                         printf("rect %d [area %d]: candidate position at"
412                                " %d,%d w=%d h=%d\n",
413                                i, area, x, y, rw, rh);
414 #endif
415                         rlistn++;
416                     }
417                 }
418             }
419         }
420
421         rectpositions[i].rects = rlist;
422         rectpositions[i].n = rlistn;
423     }
424
425     /*
426      * Next, construct a multidimensional array tracking how many
427      * candidate positions for each rectangle overlap each square.
428      * 
429      * Indexing of this array is by the formula
430      * 
431      *   overlaps[(rectindex * h + y) * w + x]
432      */
433     overlaps = snewn(nrects * w * h, int);
434     memset(overlaps, 0, nrects * w * h * sizeof(int));
435     for (i = 0; i < nrects; i++) {
436         int j;
437
438         for (j = 0; j < rectpositions[i].n; j++) {
439             int xx, yy;
440
441             for (yy = 0; yy < rectpositions[i].rects[j].h; yy++)
442                 for (xx = 0; xx < rectpositions[i].rects[j].w; xx++)
443                     overlaps[(i * h + yy+rectpositions[i].rects[j].y) * w +
444                              xx+rectpositions[i].rects[j].x]++;
445         }
446     }
447
448     /*
449      * Also we want an array covering the grid once, to make it
450      * easy to figure out which squares are candidate number
451      * placements for which rectangles. (The existence of this
452      * single array assumes that no square starts off as a
453      * candidate number placement for more than one rectangle. This
454      * assumption is justified, because this solver is _either_
455      * used to solve real problems - in which case there is a
456      * single placement for every number - _or_ used to decide on
457      * number placements for a new puzzle, in which case each
458      * number's placements are confined to the intended position of
459      * the rectangle containing that number.)
460      */
461     rectbyplace = snewn(w * h, int);
462     for (i = 0; i < w*h; i++)
463         rectbyplace[i] = -1;
464
465     for (i = 0; i < nrects; i++) {
466         int j;
467
468         for (j = 0; j < numbers[i].npoints; j++) {
469             int x = numbers[i].points[j].x;
470             int y = numbers[i].points[j].y;
471
472             assert(rectbyplace[y * w + x] == -1);
473             rectbyplace[y * w + x] = i;
474         }
475     }
476
477     workspace = snewn(nrects, int);
478
479     /*
480      * Now run the actual deduction loop.
481      */
482     while (1) {
483         int done_something = FALSE;
484
485 #ifdef SOLVER_DIAGNOSTICS
486         printf("starting deduction loop\n");
487
488         for (i = 0; i < nrects; i++) {
489             printf("rect %d overlaps:\n", i);
490             {
491                 int x, y;
492                 for (y = 0; y < h; y++) {
493                     for (x = 0; x < w; x++) {
494                         printf("%3d", overlaps[(i * h + y) * w + x]);
495                     }
496                     printf("\n");
497                 }
498             }
499         }
500         printf("rectbyplace:\n");
501         {
502             int x, y;
503             for (y = 0; y < h; y++) {
504                 for (x = 0; x < w; x++) {
505                     printf("%3d", rectbyplace[y * w + x]);
506                 }
507                 printf("\n");
508             }
509         }
510 #endif
511
512         /*
513          * Housekeeping. Look for rectangles whose number has only
514          * one candidate position left, and mark that square as
515          * known if it isn't already.
516          */
517         for (i = 0; i < nrects; i++) {
518             if (numbers[i].npoints == 1) {
519                 int x = numbers[i].points[0].x;
520                 int y = numbers[i].points[0].y;
521                 if (overlaps[(i * h + y) * w + x] >= -1) {
522                     int j;
523
524                     assert(overlaps[(i * h + y) * w + x] > 0);
525 #ifdef SOLVER_DIAGNOSTICS
526                     printf("marking %d,%d as known for rect %d"
527                            " (sole remaining number position)\n", x, y, i);
528 #endif
529
530                     for (j = 0; j < nrects; j++)
531                         overlaps[(j * h + y) * w + x] = -1;
532                     
533                     overlaps[(i * h + y) * w + x] = -2;
534                 }
535             }
536         }
537
538         /*
539          * Now look at the intersection of all possible placements
540          * for each rectangle, and mark all squares in that
541          * intersection as known for that rectangle if they aren't
542          * already.
543          */
544         for (i = 0; i < nrects; i++) {
545             int minx, miny, maxx, maxy, xx, yy, j;
546
547             minx = miny = 0;
548             maxx = w;
549             maxy = h;
550
551             for (j = 0; j < rectpositions[i].n; j++) {
552                 int x = rectpositions[i].rects[j].x;
553                 int y = rectpositions[i].rects[j].y;
554                 int w = rectpositions[i].rects[j].w;
555                 int h = rectpositions[i].rects[j].h;
556
557                 if (minx < x) minx = x;
558                 if (miny < y) miny = y;
559                 if (maxx > x+w) maxx = x+w;
560                 if (maxy > y+h) maxy = y+h;
561             }
562
563             for (yy = miny; yy < maxy; yy++)
564                 for (xx = minx; xx < maxx; xx++)
565                     if (overlaps[(i * h + yy) * w + xx] >= -1) {
566                         assert(overlaps[(i * h + yy) * w + xx] > 0);
567 #ifdef SOLVER_DIAGNOSTICS
568                         printf("marking %d,%d as known for rect %d"
569                                " (intersection of all placements)\n",
570                                xx, yy, i);
571 #endif
572
573                         for (j = 0; j < nrects; j++)
574                             overlaps[(j * h + yy) * w + xx] = -1;
575                     
576                         overlaps[(i * h + yy) * w + xx] = -2;
577                     }
578         }
579
580         /*
581          * Rectangle-focused deduction. Look at each rectangle in
582          * turn and try to rule out some of its candidate
583          * placements.
584          */
585         for (i = 0; i < nrects; i++) {
586             int j;
587
588             for (j = 0; j < rectpositions[i].n; j++) {
589                 int xx, yy, k;
590                 int del = FALSE;
591
592                 for (k = 0; k < nrects; k++)
593                     workspace[k] = 0;
594
595                 for (yy = 0; yy < rectpositions[i].rects[j].h; yy++) {
596                     int y = yy + rectpositions[i].rects[j].y;
597                     for (xx = 0; xx < rectpositions[i].rects[j].w; xx++) {
598                         int x = xx + rectpositions[i].rects[j].x;
599  
600                         if (overlaps[(i * h + y) * w + x] == -1) {
601                             /*
602                              * This placement overlaps a square
603                              * which is _known_ to be part of
604                              * another rectangle. Therefore we must
605                              * rule it out.
606                              */
607 #ifdef SOLVER_DIAGNOSTICS
608                             printf("rect %d placement at %d,%d w=%d h=%d "
609                                    "contains %d,%d which is known-other\n", i,
610                                    rectpositions[i].rects[j].x,
611                                    rectpositions[i].rects[j].y,
612                                    rectpositions[i].rects[j].w,
613                                    rectpositions[i].rects[j].h,
614                                    x, y);
615 #endif
616                             del = TRUE;
617                         }
618
619                         if (rectbyplace[y * w + x] != -1) {
620                             /*
621                              * This placement overlaps one of the
622                              * candidate number placements for some
623                              * rectangle. Count it.
624                              */
625                             workspace[rectbyplace[y * w + x]]++;
626                         }
627                     }
628                 }
629
630                 if (!del) {
631                     /*
632                      * If we haven't ruled this placement out
633                      * already, see if it overlaps _all_ of the
634                      * candidate number placements for any
635                      * rectangle. If so, we can rule it out.
636                      */
637                     for (k = 0; k < nrects; k++)
638                         if (k != i && workspace[k] == numbers[k].npoints) {
639 #ifdef SOLVER_DIAGNOSTICS
640                             printf("rect %d placement at %d,%d w=%d h=%d "
641                                    "contains all number points for rect %d\n",
642                                    i,
643                                    rectpositions[i].rects[j].x,
644                                    rectpositions[i].rects[j].y,
645                                    rectpositions[i].rects[j].w,
646                                    rectpositions[i].rects[j].h,
647                                    k);
648 #endif
649                             del = TRUE;
650                             break;
651                         }
652
653                     /*
654                      * Failing that, see if it overlaps at least
655                      * one of the candidate number placements for
656                      * itself! (This might not be the case if one
657                      * of those number placements has been removed
658                      * recently.).
659                      */
660                     if (!del && workspace[i] == 0) {
661 #ifdef SOLVER_DIAGNOSTICS
662                         printf("rect %d placement at %d,%d w=%d h=%d "
663                                "contains none of its own number points\n",
664                                i,
665                                rectpositions[i].rects[j].x,
666                                rectpositions[i].rects[j].y,
667                                rectpositions[i].rects[j].w,
668                                rectpositions[i].rects[j].h);
669 #endif
670                         del = TRUE;
671                     }
672                 }
673
674                 if (del) {
675                     remove_rect_placement(w, h, rectpositions, overlaps, i, j);
676
677                     j--;               /* don't skip over next placement */
678
679                     done_something = TRUE;
680                 }
681             }
682         }
683
684         /*
685          * Square-focused deduction. Look at each square not marked
686          * as known, and see if there are any which can only be
687          * part of a single rectangle.
688          */
689         {
690             int x, y, n, index;
691             for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
692                 /* Known squares are marked as <0 everywhere, so we only need
693                  * to check the overlaps entry for rect 0. */
694                 if (overlaps[y * w + x] < 0)
695                     continue;          /* known already */
696
697                 n = 0;
698                 index = -1;
699                 for (i = 0; i < nrects; i++)
700                     if (overlaps[(i * h + y) * w + x] > 0)
701                         n++, index = i;
702
703                 if (n == 1) {
704                     int j;
705
706                     /*
707                      * Now we can rule out all placements for
708                      * rectangle `index' which _don't_ contain
709                      * square x,y.
710                      */
711 #ifdef SOLVER_DIAGNOSTICS
712                     printf("square %d,%d can only be in rectangle %d\n",
713                            x, y, index);
714 #endif
715                     for (j = 0; j < rectpositions[index].n; j++) {
716                         struct rect *r = &rectpositions[index].rects[j];
717                         if (x >= r->x && x < r->x + r->w &&
718                             y >= r->y && y < r->y + r->h)
719                             continue;  /* this one is OK */
720                         remove_rect_placement(w, h, rectpositions, overlaps,
721                                               index, j);
722                         j--;           /* don't skip over next placement */
723                         done_something = TRUE;
724                     }
725                 }
726             }
727         }
728
729         /*
730          * If we've managed to deduce anything by normal means,
731          * loop round again and see if there's more to be done.
732          * Only if normal deduction has completely failed us should
733          * we now move on to narrowing down the possible number
734          * placements.
735          */
736         if (done_something)
737             continue;
738
739         /*
740          * Now we have done everything we can with the current set
741          * of number placements. So we need to winnow the number
742          * placements so as to narrow down the possibilities. We do
743          * this by searching for a candidate placement (of _any_
744          * rectangle) which overlaps a candidate placement of the
745          * number for some other rectangle.
746          */
747         if (rs) {
748             struct rpn {
749                 int rect;
750                 int placement;
751                 int number;
752             } *rpns = NULL;
753             int nrpns = 0, rpnsize = 0;
754             int j;
755
756             for (i = 0; i < nrects; i++) {
757                 for (j = 0; j < rectpositions[i].n; j++) {
758                     int xx, yy;
759
760                     for (yy = 0; yy < rectpositions[i].rects[j].h; yy++) {
761                         int y = yy + rectpositions[i].rects[j].y;
762                         for (xx = 0; xx < rectpositions[i].rects[j].w; xx++) {
763                             int x = xx + rectpositions[i].rects[j].x;
764
765                             if (rectbyplace[y * w + x] >= 0 &&
766                                 rectbyplace[y * w + x] != i) {
767                                 /*
768                                  * Add this to the list of
769                                  * winnowing possibilities.
770                                  */
771                                 if (nrpns >= rpnsize) {
772                                     rpnsize = rpnsize * 3 / 2 + 32;
773                                     rpns = sresize(rpns, rpnsize, struct rpn);
774                                 }
775                                 rpns[nrpns].rect = i;
776                                 rpns[nrpns].placement = j;
777                                 rpns[nrpns].number = rectbyplace[y * w + x];
778                                 nrpns++;
779                             }
780                         }
781                     }
782  
783                 }
784             }
785
786 #ifdef SOLVER_DIAGNOSTICS
787             printf("%d candidate rect placements we could eliminate\n", nrpns);
788 #endif
789             if (nrpns > 0) {
790                 /*
791                  * Now choose one of these unwanted rectangle
792                  * placements, and eliminate it.
793                  */
794                 int index = random_upto(rs, nrpns);
795                 int k, m;
796                 struct rpn rpn = rpns[index];
797                 struct rect r;
798                 sfree(rpns);
799
800                 i = rpn.rect;
801                 j = rpn.placement;
802                 k = rpn.number;
803                 r = rectpositions[i].rects[j];
804
805                 /*
806                  * We rule out placement j of rectangle i by means
807                  * of removing all of rectangle k's candidate
808                  * number placements which do _not_ overlap it.
809                  * This will ensure that it is eliminated during
810                  * the next pass of rectangle-focused deduction.
811                  */
812 #ifdef SOLVER_DIAGNOSTICS
813                 printf("ensuring number for rect %d is within"
814                        " rect %d's placement at %d,%d w=%d h=%d\n",
815                        k, i, r.x, r.y, r.w, r.h);
816 #endif
817
818                 for (m = 0; m < numbers[k].npoints; m++) {
819                     int x = numbers[k].points[m].x;
820                     int y = numbers[k].points[m].y;
821
822                     if (x < r.x || x >= r.x + r.w ||
823                         y < r.y || y >= r.y + r.h) {
824 #ifdef SOLVER_DIAGNOSTICS
825                         printf("eliminating number for rect %d at %d,%d\n",
826                                k, x, y);
827 #endif
828                         remove_number_placement(w, h, &numbers[k],
829                                                 m, rectbyplace);
830                         m--;           /* don't skip the next one */
831                         done_something = TRUE;
832                     }
833                 }
834             }
835         }
836
837         if (!done_something) {
838 #ifdef SOLVER_DIAGNOSTICS
839             printf("terminating deduction loop\n");
840 #endif
841             break;
842         }
843     }
844
845     ret = TRUE;
846     for (i = 0; i < nrects; i++) {
847 #ifdef SOLVER_DIAGNOSTICS
848         printf("rect %d has %d possible placements\n",
849                i, rectpositions[i].n);
850 #endif
851         assert(rectpositions[i].n > 0);
852         if (rectpositions[i].n > 1) {
853             ret = FALSE;
854         } else if (result) {
855             /*
856              * Place the rectangle in its only possible position.
857              */
858             int x, y;
859             struct rect *r = &rectpositions[i].rects[0];
860
861             for (y = 0; y < r->h; y++) {
862                 if (r->x > 0)
863                     vedge(result, r->x, r->y+y) = 1;
864                 if (r->x+r->w < result->w)
865                     vedge(result, r->x+r->w, r->y+y) = 1;
866             }
867             for (x = 0; x < r->w; x++) {
868                 if (r->y > 0)
869                     hedge(result, r->x+x, r->y) = 1;
870                 if (r->y+r->h < result->h)
871                     hedge(result, r->x+x, r->y+r->h) = 1;
872             }
873         }
874     }
875
876     /*
877      * Free up all allocated storage.
878      */
879     sfree(workspace);
880     sfree(rectbyplace);
881     sfree(overlaps);
882     for (i = 0; i < nrects; i++)
883         sfree(rectpositions[i].rects);
884     sfree(rectpositions);
885
886     return ret;
887 }
888
889 /* ----------------------------------------------------------------------
890  * Grid generation code.
891  */
892
893 static struct rectlist *get_rectlist(game_params *params, int *grid)
894 {
895     int rw, rh;
896     int x, y;
897     int maxarea;
898     struct rect *rects = NULL;
899     int nrects = 0, rectsize = 0;
900
901     /*
902      * Maximum rectangle area is 1/6 of total grid size, unless
903      * this means we can't place any rectangles at all in which
904      * case we set it to 2 at minimum.
905      */
906     maxarea = params->w * params->h / 6;
907     if (maxarea < 2)
908         maxarea = 2;
909
910     for (rw = 1; rw <= params->w; rw++)
911         for (rh = 1; rh <= params->h; rh++) {
912             if (rw * rh > maxarea)
913                 continue;
914             if (rw * rh == 1)
915                 continue;
916             for (x = 0; x <= params->w - rw; x++)
917                 for (y = 0; y <= params->h - rh; y++) {
918                     if (nrects >= rectsize) {
919                         rectsize = nrects + 256;
920                         rects = sresize(rects, rectsize, struct rect);
921                     }
922
923                     rects[nrects].x = x;
924                     rects[nrects].y = y;
925                     rects[nrects].w = rw;
926                     rects[nrects].h = rh;
927                     nrects++;
928                 }
929         }
930
931     if (nrects > 0) {
932         struct rectlist *ret;
933         ret = snew(struct rectlist);
934         ret->rects = rects;
935         ret->n = nrects;
936         return ret;
937     } else {
938         assert(rects == NULL);         /* hence no need to free */
939         return NULL;
940     }
941 }
942
943 static void free_rectlist(struct rectlist *list)
944 {
945     sfree(list->rects);
946     sfree(list);
947 }
948
949 static void place_rect(game_params *params, int *grid, struct rect r)
950 {
951     int idx = INDEX(params, r.x, r.y);
952     int x, y;
953
954     for (x = r.x; x < r.x+r.w; x++)
955         for (y = r.y; y < r.y+r.h; y++) {
956             index(params, grid, x, y) = idx;
957         }
958 #ifdef GENERATION_DIAGNOSTICS
959     printf("    placing rectangle at (%d,%d) size %d x %d\n",
960            r.x, r.y, r.w, r.h);
961 #endif
962 }
963
964 static struct rect find_rect(game_params *params, int *grid, int x, int y)
965 {
966     int idx, w, h;
967     struct rect r;
968
969     /*
970      * Find the top left of the rectangle.
971      */
972     idx = index(params, grid, x, y);
973
974     if (idx < 0) {
975         r.x = x;
976         r.y = y;
977         r.w = r.h = 1;
978         return r;                      /* 1x1 singleton here */
979     }
980
981     y = idx / params->w;
982     x = idx % params->w;
983
984     /*
985      * Find the width and height of the rectangle.
986      */
987     for (w = 1;
988          (x+w < params->w && index(params,grid,x+w,y)==idx);
989          w++);
990     for (h = 1;
991          (y+h < params->h && index(params,grid,x,y+h)==idx);
992          h++);
993
994     r.x = x;
995     r.y = y;
996     r.w = w;
997     r.h = h;
998
999     return r;
1000 }
1001
1002 #ifdef GENERATION_DIAGNOSTICS
1003 static void display_grid(game_params *params, int *grid, int *numbers, int all)
1004 {
1005     unsigned char *egrid = snewn((params->w*2+3) * (params->h*2+3),
1006                                  unsigned char);
1007     int x, y;
1008     int r = (params->w*2+3);
1009
1010     memset(egrid, 0, (params->w*2+3) * (params->h*2+3));
1011
1012     for (x = 0; x < params->w; x++)
1013         for (y = 0; y < params->h; y++) {
1014             int i = index(params, grid, x, y);
1015             if (x == 0 || index(params, grid, x-1, y) != i)
1016                 egrid[(2*y+2) * r + (2*x+1)] = 1;
1017             if (x == params->w-1 || index(params, grid, x+1, y) != i)
1018                 egrid[(2*y+2) * r + (2*x+3)] = 1;
1019             if (y == 0 || index(params, grid, x, y-1) != i)
1020                 egrid[(2*y+1) * r + (2*x+2)] = 1;
1021             if (y == params->h-1 || index(params, grid, x, y+1) != i)
1022                 egrid[(2*y+3) * r + (2*x+2)] = 1;
1023         }
1024
1025     for (y = 1; y < 2*params->h+2; y++) {
1026         for (x = 1; x < 2*params->w+2; x++) {
1027             if (!((y|x)&1)) {
1028                 int k = numbers ? index(params, numbers, x/2-1, y/2-1) : 0;
1029                 if (k || (all && numbers)) printf("%2d", k); else printf("  ");
1030             } else if (!((y&x)&1)) {
1031                 int v = egrid[y*r+x];
1032                 if ((y&1) && v) v = '-';
1033                 if ((x&1) && v) v = '|';
1034                 if (!v) v = ' ';
1035                 putchar(v);
1036                 if (!(x&1)) putchar(v);
1037             } else {
1038                 int c, d = 0;
1039                 if (egrid[y*r+(x+1)]) d |= 1;
1040                 if (egrid[(y-1)*r+x]) d |= 2;
1041                 if (egrid[y*r+(x-1)]) d |= 4;
1042                 if (egrid[(y+1)*r+x]) d |= 8;
1043                 c = " ??+?-++?+|+++++"[d];
1044                 putchar(c);
1045                 if (!(x&1)) putchar(c);
1046             }
1047         }
1048         putchar('\n');
1049     }
1050
1051     sfree(egrid);
1052 }
1053 #endif
1054
1055 struct game_aux_info {
1056     int w, h;
1057     unsigned char *vedge;              /* (w+1) x h */
1058     unsigned char *hedge;              /* w x (h+1) */
1059 };
1060
1061 static char *new_game_desc(game_params *params, random_state *rs,
1062                            game_aux_info **aux, int interactive)
1063 {
1064     int *grid, *numbers = NULL;
1065     struct rectlist *list;
1066     int x, y, y2, y2last, yx, run, i;
1067     char *desc, *p;
1068     game_params params2real, *params2 = &params2real;
1069
1070     while (1) {
1071         /*
1072          * Set up the smaller width and height which we will use to
1073          * generate the base grid.
1074          */
1075         params2->w = params->w / (1.0F + params->expandfactor);
1076         if (params2->w < 2 && params->w >= 2) params2->w = 2;
1077         params2->h = params->h / (1.0F + params->expandfactor);
1078         if (params2->h < 2 && params->h >= 2) params2->h = 2;
1079
1080         grid = snewn(params2->w * params2->h, int);
1081
1082         for (y = 0; y < params2->h; y++)
1083             for (x = 0; x < params2->w; x++) {
1084                 index(params2, grid, x, y) = -1;
1085             }
1086
1087         list = get_rectlist(params2, grid);
1088         assert(list != NULL);
1089
1090         /*
1091          * Place rectangles until we can't any more.
1092          */
1093         while (list->n > 0) {
1094             int i, m;
1095             struct rect r;
1096
1097             /*
1098              * Pick a random rectangle.
1099              */
1100             i = random_upto(rs, list->n);
1101             r = list->rects[i];
1102
1103             /*
1104              * Place it.
1105              */
1106             place_rect(params2, grid, r);
1107
1108             /*
1109              * Winnow the list by removing any rectangles which
1110              * overlap this one.
1111              */
1112             m = 0;
1113             for (i = 0; i < list->n; i++) {
1114                 struct rect s = list->rects[i];
1115                 if (s.x+s.w <= r.x || r.x+r.w <= s.x ||
1116                     s.y+s.h <= r.y || r.y+r.h <= s.y)
1117                     list->rects[m++] = s;
1118             }
1119             list->n = m;
1120         }
1121
1122         free_rectlist(list);
1123
1124         /*
1125          * Deal with singleton spaces remaining in the grid, one by
1126          * one.
1127          *
1128          * We do this by making a local change to the layout. There are
1129          * several possibilities:
1130          *
1131          *     +-----+-----+    Here, we can remove the singleton by
1132          *     |     |     |    extending the 1x2 rectangle below it
1133          *     +--+--+-----+    into a 1x3.
1134          *     |  |  |     |
1135          *     |  +--+     |
1136          *     |  |  |     |
1137          *     |  |  |     |
1138          *     |  |  |     |
1139          *     +--+--+-----+
1140          *
1141          *     +--+--+--+       Here, that trick doesn't work: there's no
1142          *     |     |  |       1 x n rectangle with the singleton at one
1143          *     |     |  |       end. Instead, we extend a 1 x n rectangle
1144          *     |     |  |       _out_ from the singleton, shaving a layer
1145          *     +--+--+  |       off the end of another rectangle. So if we
1146          *     |  |  |  |       extended up, we'd make our singleton part
1147          *     |  +--+--+       of a 1x3 and generate a 1x2 where the 2x2
1148          *     |  |     |       used to be; or we could extend right into
1149          *     +--+-----+       a 2x1, turning the 1x3 into a 1x2.
1150          *
1151          *     +-----+--+       Here, we can't even do _that_, since any
1152          *     |     |  |       direction we choose to extend the singleton
1153          *     +--+--+  |       will produce a new singleton as a result of
1154          *     |  |  |  |       truncating one of the size-2 rectangles.
1155          *     |  +--+--+       Fortunately, this case can _only_ occur when
1156          *     |  |     |       a singleton is surrounded by four size-2s
1157          *     +--+-----+       in this fashion; so instead we can simply
1158          *                      replace the whole section with a single 3x3.
1159          */
1160         for (x = 0; x < params2->w; x++) {
1161             for (y = 0; y < params2->h; y++) {
1162                 if (index(params2, grid, x, y) < 0) {
1163                     int dirs[4], ndirs;
1164
1165 #ifdef GENERATION_DIAGNOSTICS
1166                     display_grid(params2, grid, NULL, FALSE);
1167                     printf("singleton at %d,%d\n", x, y);
1168 #endif
1169
1170                     /*
1171                      * Check in which directions we can feasibly extend
1172                      * the singleton. We can extend in a particular
1173                      * direction iff either:
1174                      *
1175                      *  - the rectangle on that side of the singleton
1176                      *    is not 2x1, and we are at one end of the edge
1177                      *    of it we are touching
1178                      *
1179                      *  - it is 2x1 but we are on its short side.
1180                      *
1181                      * FIXME: we could plausibly choose between these
1182                      * based on the sizes of the rectangles they would
1183                      * create?
1184                      */
1185                     ndirs = 0;
1186                     if (x < params2->w-1) {
1187                         struct rect r = find_rect(params2, grid, x+1, y);
1188                         if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
1189                             dirs[ndirs++] = 1;   /* right */
1190                     }
1191                     if (y > 0) {
1192                         struct rect r = find_rect(params2, grid, x, y-1);
1193                         if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
1194                             dirs[ndirs++] = 2;   /* up */
1195                     }
1196                     if (x > 0) {
1197                         struct rect r = find_rect(params2, grid, x-1, y);
1198                         if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
1199                             dirs[ndirs++] = 4;   /* left */
1200                     }
1201                     if (y < params2->h-1) {
1202                         struct rect r = find_rect(params2, grid, x, y+1);
1203                         if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
1204                             dirs[ndirs++] = 8;   /* down */
1205                     }
1206
1207                     if (ndirs > 0) {
1208                         int which, dir;
1209                         struct rect r1, r2;
1210
1211                         which = random_upto(rs, ndirs);
1212                         dir = dirs[which];
1213
1214                         switch (dir) {
1215                           case 1:          /* right */
1216                             assert(x < params2->w+1);
1217 #ifdef GENERATION_DIAGNOSTICS
1218                             printf("extending right\n");
1219 #endif
1220                             r1 = find_rect(params2, grid, x+1, y);
1221                             r2.x = x;
1222                             r2.y = y;
1223                             r2.w = 1 + r1.w;
1224                             r2.h = 1;
1225                             if (r1.y == y)
1226                                 r1.y++;
1227                             r1.h--;
1228                             break;
1229                           case 2:          /* up */
1230                             assert(y > 0);
1231 #ifdef GENERATION_DIAGNOSTICS
1232                             printf("extending up\n");
1233 #endif
1234                             r1 = find_rect(params2, grid, x, y-1);
1235                             r2.x = x;
1236                             r2.y = r1.y;
1237                             r2.w = 1;
1238                             r2.h = 1 + r1.h;
1239                             if (r1.x == x)
1240                                 r1.x++;
1241                             r1.w--;
1242                             break;
1243                           case 4:          /* left */
1244                             assert(x > 0);
1245 #ifdef GENERATION_DIAGNOSTICS
1246                             printf("extending left\n");
1247 #endif
1248                             r1 = find_rect(params2, grid, x-1, y);
1249                             r2.x = r1.x;
1250                             r2.y = y;
1251                             r2.w = 1 + r1.w;
1252                             r2.h = 1;
1253                             if (r1.y == y)
1254                                 r1.y++;
1255                             r1.h--;
1256                             break;
1257                           case 8:          /* down */
1258                             assert(y < params2->h+1);
1259 #ifdef GENERATION_DIAGNOSTICS
1260                             printf("extending down\n");
1261 #endif
1262                             r1 = find_rect(params2, grid, x, y+1);
1263                             r2.x = x;
1264                             r2.y = y;
1265                             r2.w = 1;
1266                             r2.h = 1 + r1.h;
1267                             if (r1.x == x)
1268                                 r1.x++;
1269                             r1.w--;
1270                             break;
1271                         }
1272                         if (r1.h > 0 && r1.w > 0)
1273                             place_rect(params2, grid, r1);
1274                         place_rect(params2, grid, r2);
1275                     } else {
1276 #ifndef NDEBUG
1277                         /*
1278                          * Sanity-check that there really is a 3x3
1279                          * rectangle surrounding this singleton and it
1280                          * contains absolutely everything we could
1281                          * possibly need.
1282                          */
1283                         {
1284                             int xx, yy;
1285                             assert(x > 0 && x < params2->w-1);
1286                             assert(y > 0 && y < params2->h-1);
1287
1288                             for (xx = x-1; xx <= x+1; xx++)
1289                                 for (yy = y-1; yy <= y+1; yy++) {
1290                                     struct rect r = find_rect(params2,grid,xx,yy);
1291                                     assert(r.x >= x-1);
1292                                     assert(r.y >= y-1);
1293                                     assert(r.x+r.w-1 <= x+1);
1294                                     assert(r.y+r.h-1 <= y+1);
1295                                 }
1296                         }
1297 #endif
1298
1299 #ifdef GENERATION_DIAGNOSTICS
1300                         printf("need the 3x3 trick\n");
1301 #endif
1302
1303                         /*
1304                          * FIXME: If the maximum rectangle area for
1305                          * this grid is less than 9, we ought to
1306                          * subdivide the 3x3 in some fashion. There are
1307                          * five other possibilities:
1308                          *
1309                          *  - a 6 and a 3
1310                          *  - a 4, a 3 and a 2
1311                          *  - three 3s
1312                          *  - a 3 and three 2s (two different arrangements).
1313                          */
1314
1315                         {
1316                             struct rect r;
1317                             r.x = x-1;
1318                             r.y = y-1;
1319                             r.w = r.h = 3;
1320                             place_rect(params2, grid, r);
1321                         }
1322                     }
1323                 }
1324             }
1325         }
1326
1327         /*
1328          * We have now constructed a grid of the size specified in
1329          * params2. Now we extend it into a grid of the size specified
1330          * in params. We do this in two passes: we extend it vertically
1331          * until it's the right height, then we transpose it, then
1332          * extend it vertically again (getting it effectively the right
1333          * width), then finally transpose again.
1334          */
1335         for (i = 0; i < 2; i++) {
1336             int *grid2, *expand, *where;
1337             game_params params3real, *params3 = &params3real;
1338
1339 #ifdef GENERATION_DIAGNOSTICS
1340             printf("before expansion:\n");
1341             display_grid(params2, grid, NULL, TRUE);
1342 #endif
1343
1344             /*
1345              * Set up the new grid.
1346              */
1347             grid2 = snewn(params2->w * params->h, int);
1348             expand = snewn(params2->h-1, int);
1349             where = snewn(params2->w, int);
1350             params3->w = params2->w;
1351             params3->h = params->h;
1352
1353             /*
1354              * Decide which horizontal edges are going to get expanded,
1355              * and by how much.
1356              */
1357             for (y = 0; y < params2->h-1; y++)
1358                 expand[y] = 0;
1359             for (y = params2->h; y < params->h; y++) {
1360                 x = random_upto(rs, params2->h-1);
1361                 expand[x]++;
1362             }
1363
1364 #ifdef GENERATION_DIAGNOSTICS
1365             printf("expand[] = {");
1366             for (y = 0; y < params2->h-1; y++)
1367                 printf(" %d", expand[y]);
1368             printf(" }\n");
1369 #endif
1370
1371             /*
1372              * Perform the expansion. The way this works is that we
1373              * alternately:
1374              *
1375              *  - copy a row from grid into grid2
1376              *
1377              *  - invent some number of additional rows in grid2 where
1378              *    there was previously only a horizontal line between
1379              *    rows in grid, and make random decisions about where
1380              *    among these to place each rectangle edge that ran
1381              *    along this line.
1382              */
1383             for (y = y2 = y2last = 0; y < params2->h; y++) {
1384                 /*
1385                  * Copy a single line from row y of grid into row y2 of
1386                  * grid2.
1387                  */
1388                 for (x = 0; x < params2->w; x++) {
1389                     int val = index(params2, grid, x, y);
1390                     if (val / params2->w == y &&   /* rect starts on this line */
1391                         (y2 == 0 ||            /* we're at the very top, or... */
1392                          index(params3, grid2, x, y2-1) / params3->w < y2last
1393                          /* this rect isn't already started */))
1394                         index(params3, grid2, x, y2) =
1395                         INDEX(params3, val % params2->w, y2);
1396                     else
1397                         index(params3, grid2, x, y2) =
1398                         index(params3, grid2, x, y2-1);
1399                 }
1400
1401                 /*
1402                  * If that was the last line, terminate the loop early.
1403                  */
1404                 if (++y2 == params3->h)
1405                     break;
1406
1407                 y2last = y2;
1408
1409                 /*
1410                  * Invent some number of additional lines. First walk
1411                  * along this line working out where to put all the
1412                  * edges that coincide with it.
1413                  */
1414                 yx = -1;
1415                 for (x = 0; x < params2->w; x++) {
1416                     if (index(params2, grid, x, y) !=
1417                         index(params2, grid, x, y+1)) {
1418                         /*
1419                          * This is a horizontal edge, so it needs
1420                          * placing.
1421                          */
1422                         if (x == 0 ||
1423                             (index(params2, grid, x-1, y) !=
1424                              index(params2, grid, x, y) &&
1425                              index(params2, grid, x-1, y+1) !=
1426                              index(params2, grid, x, y+1))) {
1427                             /*
1428                              * Here we have the chance to make a new
1429                              * decision.
1430                              */
1431                             yx = random_upto(rs, expand[y]+1);
1432                         } else {
1433                             /*
1434                              * Here we just reuse the previous value of
1435                              * yx.
1436                              */
1437                         }
1438                     } else
1439                         yx = -1;
1440                     where[x] = yx;
1441                 }
1442
1443                 for (yx = 0; yx < expand[y]; yx++) {
1444                     /*
1445                      * Invent a single row. For each square in the row,
1446                      * we copy the grid entry from the square above it,
1447                      * unless we're starting the new rectangle here.
1448                      */
1449                     for (x = 0; x < params2->w; x++) {
1450                         if (yx == where[x]) {
1451                             int val = index(params2, grid, x, y+1);
1452                             val %= params2->w;
1453                             val = INDEX(params3, val, y2);
1454                             index(params3, grid2, x, y2) = val;
1455                         } else
1456                             index(params3, grid2, x, y2) =
1457                             index(params3, grid2, x, y2-1);
1458                     }
1459
1460                     y2++;
1461                 }
1462             }
1463
1464             sfree(expand);
1465             sfree(where);
1466
1467 #ifdef GENERATION_DIAGNOSTICS
1468             printf("after expansion:\n");
1469             display_grid(params3, grid2, NULL, TRUE);
1470 #endif
1471             /*
1472              * Transpose.
1473              */
1474             params2->w = params3->h;
1475             params2->h = params3->w;
1476             sfree(grid);
1477             grid = snewn(params2->w * params2->h, int);
1478             for (x = 0; x < params2->w; x++)
1479                 for (y = 0; y < params2->h; y++) {
1480                     int idx1 = INDEX(params2, x, y);
1481                     int idx2 = INDEX(params3, y, x);
1482                     int tmp;
1483
1484                     tmp = grid2[idx2];
1485                     tmp = (tmp % params3->w) * params2->w + (tmp / params3->w);
1486                     grid[idx1] = tmp;
1487                 }
1488
1489             sfree(grid2);
1490
1491             {
1492                 int tmp;
1493                 tmp = params->w;
1494                 params->w = params->h;
1495                 params->h = tmp;
1496             }
1497
1498 #ifdef GENERATION_DIAGNOSTICS
1499             printf("after transposition:\n");
1500             display_grid(params2, grid, NULL, TRUE);
1501 #endif
1502         }
1503
1504         /*
1505          * Run the solver to narrow down the possible number
1506          * placements.
1507          */
1508         {
1509             struct numberdata *nd;
1510             int nnumbers, i, ret;
1511
1512             /* Count the rectangles. */
1513             nnumbers = 0;
1514             for (y = 0; y < params->h; y++) {
1515                 for (x = 0; x < params->w; x++) {
1516                     int idx = INDEX(params, x, y);
1517                     if (index(params, grid, x, y) == idx)
1518                         nnumbers++;
1519                 }
1520             }
1521
1522             nd = snewn(nnumbers, struct numberdata);
1523
1524             /* Now set up each number's candidate position list. */
1525             i = 0;
1526             for (y = 0; y < params->h; y++) {
1527                 for (x = 0; x < params->w; x++) {
1528                     int idx = INDEX(params, x, y);
1529                     if (index(params, grid, x, y) == idx) {
1530                         struct rect r = find_rect(params, grid, x, y);
1531                         int j, k, m;
1532
1533                         nd[i].area = r.w * r.h;
1534                         nd[i].npoints = nd[i].area;
1535                         nd[i].points = snewn(nd[i].npoints, struct point);
1536                         m = 0;
1537                         for (j = 0; j < r.h; j++)
1538                             for (k = 0; k < r.w; k++) {
1539                                 nd[i].points[m].x = k + r.x;
1540                                 nd[i].points[m].y = j + r.y;
1541                                 m++;
1542                             }
1543                         assert(m == nd[i].npoints);
1544
1545                         i++;
1546                     }
1547                 }
1548             }
1549
1550             if (params->unique)
1551                 ret = rect_solver(params->w, params->h, nnumbers, nd,
1552                                   NULL, rs);
1553             else
1554                 ret = TRUE;            /* allow any number placement at all */
1555
1556             if (ret) {
1557                 /*
1558                  * Now place the numbers according to the solver's
1559                  * recommendations.
1560                  */
1561                 numbers = snewn(params->w * params->h, int);
1562
1563                 for (y = 0; y < params->h; y++)
1564                     for (x = 0; x < params->w; x++) {
1565                         index(params, numbers, x, y) = 0;
1566                     }
1567
1568                 for (i = 0; i < nnumbers; i++) {
1569                     int idx = random_upto(rs, nd[i].npoints);
1570                     int x = nd[i].points[idx].x;
1571                     int y = nd[i].points[idx].y;
1572                     index(params,numbers,x,y) = nd[i].area;
1573                 }
1574             }
1575
1576             /*
1577              * Clean up.
1578              */
1579             for (i = 0; i < nnumbers; i++)
1580                 sfree(nd[i].points);
1581             sfree(nd);
1582
1583             /*
1584              * If we've succeeded, then terminate the loop.
1585              */
1586             if (ret)
1587                 break;
1588         }
1589
1590         /*
1591          * Give up and go round again.
1592          */
1593         sfree(grid);
1594     }
1595
1596     /*
1597      * Store the rectangle data in the game_aux_info.
1598      */
1599     {
1600         game_aux_info *ai = snew(game_aux_info);
1601
1602         ai->w = params->w;
1603         ai->h = params->h;
1604         ai->vedge = snewn(ai->w * ai->h, unsigned char);
1605         ai->hedge = snewn(ai->w * ai->h, unsigned char);
1606
1607         for (y = 0; y < params->h; y++)
1608             for (x = 1; x < params->w; x++) {
1609                 vedge(ai, x, y) =
1610                     index(params, grid, x, y) != index(params, grid, x-1, y);
1611             }
1612         for (y = 1; y < params->h; y++)
1613             for (x = 0; x < params->w; x++) {
1614                 hedge(ai, x, y) =
1615                     index(params, grid, x, y) != index(params, grid, x, y-1);
1616             }
1617
1618         *aux = ai;
1619     }
1620
1621 #ifdef GENERATION_DIAGNOSTICS
1622     display_grid(params, grid, numbers, FALSE);
1623 #endif
1624
1625     desc = snewn(11 * params->w * params->h, char);
1626     p = desc;
1627     run = 0;
1628     for (i = 0; i <= params->w * params->h; i++) {
1629         int n = (i < params->w * params->h ? numbers[i] : -1);
1630
1631         if (!n)
1632             run++;
1633         else {
1634             if (run) {
1635                 while (run > 0) {
1636                     int c = 'a' - 1 + run;
1637                     if (run > 26)
1638                         c = 'z';
1639                     *p++ = c;
1640                     run -= c - ('a' - 1);
1641                 }
1642             } else {
1643                 /*
1644                  * If there's a number in the very top left or
1645                  * bottom right, there's no point putting an
1646                  * unnecessary _ before or after it.
1647                  */
1648                 if (p > desc && n > 0)
1649                     *p++ = '_';
1650             }
1651             if (n > 0)
1652                 p += sprintf(p, "%d", n);
1653             run = 0;
1654         }
1655     }
1656     *p = '\0';
1657
1658     sfree(grid);
1659     sfree(numbers);
1660
1661     return desc;
1662 }
1663
1664 static void game_free_aux_info(game_aux_info *ai)
1665 {
1666     sfree(ai->vedge);
1667     sfree(ai->hedge);
1668     sfree(ai);
1669 }
1670
1671 static char *validate_desc(game_params *params, char *desc)
1672 {
1673     int area = params->w * params->h;
1674     int squares = 0;
1675
1676     while (*desc) {
1677         int n = *desc++;
1678         if (n >= 'a' && n <= 'z') {
1679             squares += n - 'a' + 1;
1680         } else if (n == '_') {
1681             /* do nothing */;
1682         } else if (n > '0' && n <= '9') {
1683             squares++;
1684             while (*desc >= '0' && *desc <= '9')
1685                 desc++;
1686         } else
1687             return "Invalid character in game description";
1688     }
1689
1690     if (squares < area)
1691         return "Not enough data to fill grid";
1692
1693     if (squares > area)
1694         return "Too much data to fit in grid";
1695
1696     return NULL;
1697 }
1698
1699 static game_state *new_game(midend_data *me, game_params *params, char *desc)
1700 {
1701     game_state *state = snew(game_state);
1702     int x, y, i, area;
1703
1704     state->w = params->w;
1705     state->h = params->h;
1706
1707     area = state->w * state->h;
1708
1709     state->grid = snewn(area, int);
1710     state->vedge = snewn(area, unsigned char);
1711     state->hedge = snewn(area, unsigned char);
1712     state->completed = state->cheated = FALSE;
1713
1714     i = 0;
1715     while (*desc) {
1716         int n = *desc++;
1717         if (n >= 'a' && n <= 'z') {
1718             int run = n - 'a' + 1;
1719             assert(i + run <= area);
1720             while (run-- > 0)
1721                 state->grid[i++] = 0;
1722         } else if (n == '_') {
1723             /* do nothing */;
1724         } else if (n > '0' && n <= '9') {
1725             assert(i < area);
1726             state->grid[i++] = atoi(desc-1);
1727             while (*desc >= '0' && *desc <= '9')
1728                 desc++;
1729         } else {
1730             assert(!"We can't get here");
1731         }
1732     }
1733     assert(i == area);
1734
1735     for (y = 0; y < state->h; y++)
1736         for (x = 0; x < state->w; x++)
1737             vedge(state,x,y) = hedge(state,x,y) = 0;
1738
1739     return state;
1740 }
1741
1742 static game_state *dup_game(game_state *state)
1743 {
1744     game_state *ret = snew(game_state);
1745
1746     ret->w = state->w;
1747     ret->h = state->h;
1748
1749     ret->vedge = snewn(state->w * state->h, unsigned char);
1750     ret->hedge = snewn(state->w * state->h, unsigned char);
1751     ret->grid = snewn(state->w * state->h, int);
1752
1753     ret->completed = state->completed;
1754     ret->cheated = state->cheated;
1755
1756     memcpy(ret->grid, state->grid, state->w * state->h * sizeof(int));
1757     memcpy(ret->vedge, state->vedge, state->w*state->h*sizeof(unsigned char));
1758     memcpy(ret->hedge, state->hedge, state->w*state->h*sizeof(unsigned char));
1759
1760     return ret;
1761 }
1762
1763 static void free_game(game_state *state)
1764 {
1765     sfree(state->grid);
1766     sfree(state->vedge);
1767     sfree(state->hedge);
1768     sfree(state);
1769 }
1770
1771 static game_state *solve_game(game_state *state, game_aux_info *ai,
1772                               char **error)
1773 {
1774     game_state *ret;
1775
1776     if (!ai) {
1777         int i, j, n;
1778         struct numberdata *nd;
1779
1780         /*
1781          * Attempt the in-built solver.
1782          */
1783
1784         /* Set up each number's (very short) candidate position list. */
1785         for (i = n = 0; i < state->h * state->w; i++)
1786             if (state->grid[i])
1787                 n++;
1788
1789         nd = snewn(n, struct numberdata);
1790
1791         for (i = j = 0; i < state->h * state->w; i++)
1792             if (state->grid[i]) {
1793                 nd[j].area = state->grid[i];
1794                 nd[j].npoints = 1;
1795                 nd[j].points = snewn(1, struct point);
1796                 nd[j].points[0].x = i % state->w;
1797                 nd[j].points[0].y = i / state->w;
1798                 j++;
1799             }
1800
1801         assert(j == n);
1802
1803         ret = dup_game(state);
1804         ret->cheated = TRUE;
1805
1806         rect_solver(state->w, state->h, n, nd, ret, NULL);
1807
1808         /*
1809          * Clean up.
1810          */
1811         for (i = 0; i < n; i++)
1812             sfree(nd[i].points);
1813         sfree(nd);
1814
1815         return ret;
1816     }
1817
1818     assert(state->w == ai->w);
1819     assert(state->h == ai->h);
1820
1821     ret = dup_game(state);
1822     memcpy(ret->vedge, ai->vedge, ai->w * ai->h * sizeof(unsigned char));
1823     memcpy(ret->hedge, ai->hedge, ai->w * ai->h * sizeof(unsigned char));
1824     ret->cheated = TRUE;
1825
1826     return ret;
1827 }
1828
1829 static char *game_text_format(game_state *state)
1830 {
1831     char *ret, *p, buf[80];
1832     int i, x, y, col, maxlen;
1833
1834     /*
1835      * First determine the number of spaces required to display a
1836      * number. We'll use at least two, because one looks a bit
1837      * silly.
1838      */
1839     col = 2;
1840     for (i = 0; i < state->w * state->h; i++) {
1841         x = sprintf(buf, "%d", state->grid[i]);
1842         if (col < x) col = x;
1843     }
1844
1845     /*
1846      * Now we know the exact total size of the grid we're going to
1847      * produce: it's got 2*h+1 rows, each containing w lots of col,
1848      * w+1 boundary characters and a trailing newline.
1849      */
1850     maxlen = (2*state->h+1) * (state->w * (col+1) + 2);
1851
1852     ret = snewn(maxlen+1, char);
1853     p = ret;
1854
1855     for (y = 0; y <= 2*state->h; y++) {
1856         for (x = 0; x <= 2*state->w; x++) {
1857             if (x & y & 1) {
1858                 /*
1859                  * Display a number.
1860                  */
1861                 int v = grid(state, x/2, y/2);
1862                 if (v)
1863                     sprintf(buf, "%*d", col, v);
1864                 else
1865                     sprintf(buf, "%*s", col, "");
1866                 memcpy(p, buf, col);
1867                 p += col;
1868             } else if (x & 1) {
1869                 /*
1870                  * Display a horizontal edge or nothing.
1871                  */
1872                 int h = (y==0 || y==2*state->h ? 1 :
1873                          HRANGE(state, x/2, y/2) && hedge(state, x/2, y/2));
1874                 int i;
1875                 if (h)
1876                     h = '-';
1877                 else
1878                     h = ' ';
1879                 for (i = 0; i < col; i++)
1880                     *p++ = h;
1881             } else if (y & 1) {
1882                 /*
1883                  * Display a vertical edge or nothing.
1884                  */
1885                 int v = (x==0 || x==2*state->w ? 1 :
1886                          VRANGE(state, x/2, y/2) && vedge(state, x/2, y/2));
1887                 if (v)
1888                     *p++ = '|';
1889                 else
1890                     *p++ = ' ';
1891             } else {
1892                 /*
1893                  * Display a corner, or a vertical edge, or a
1894                  * horizontal edge, or nothing.
1895                  */
1896                 int hl = (y==0 || y==2*state->h ? 1 :
1897                           HRANGE(state, (x-1)/2, y/2) && hedge(state, (x-1)/2, y/2));
1898                 int hr = (y==0 || y==2*state->h ? 1 :
1899                           HRANGE(state, (x+1)/2, y/2) && hedge(state, (x+1)/2, y/2));
1900                 int vu = (x==0 || x==2*state->w ? 1 :
1901                           VRANGE(state, x/2, (y-1)/2) && vedge(state, x/2, (y-1)/2));
1902                 int vd = (x==0 || x==2*state->w ? 1 :
1903                           VRANGE(state, x/2, (y+1)/2) && vedge(state, x/2, (y+1)/2));
1904                 if (!hl && !hr && !vu && !vd)
1905                     *p++ = ' ';
1906                 else if (hl && hr && !vu && !vd)
1907                     *p++ = '-';
1908                 else if (!hl && !hr && vu && vd)
1909                     *p++ = '|';
1910                 else
1911                     *p++ = '+';
1912             }
1913         }
1914         *p++ = '\n';
1915     }
1916
1917     assert(p - ret == maxlen);
1918     *p = '\0';
1919     return ret;
1920 }
1921
1922 static unsigned char *get_correct(game_state *state)
1923 {
1924     unsigned char *ret;
1925     int x, y;
1926
1927     ret = snewn(state->w * state->h, unsigned char);
1928     memset(ret, 0xFF, state->w * state->h);
1929
1930     for (x = 0; x < state->w; x++)
1931         for (y = 0; y < state->h; y++)
1932             if (index(state,ret,x,y) == 0xFF) {
1933                 int rw, rh;
1934                 int xx, yy;
1935                 int num, area, valid;
1936
1937                 /*
1938                  * Find a rectangle starting at this point.
1939                  */
1940                 rw = 1;
1941                 while (x+rw < state->w && !vedge(state,x+rw,y))
1942                     rw++;
1943                 rh = 1;
1944                 while (y+rh < state->h && !hedge(state,x,y+rh))
1945                     rh++;
1946
1947                 /*
1948                  * We know what the dimensions of the rectangle
1949                  * should be if it's there at all. Find out if we
1950                  * really have a valid rectangle.
1951                  */
1952                 valid = TRUE;
1953                 /* Check the horizontal edges. */
1954                 for (xx = x; xx < x+rw; xx++) {
1955                     for (yy = y; yy <= y+rh; yy++) {
1956                         int e = !HRANGE(state,xx,yy) || hedge(state,xx,yy);
1957                         int ec = (yy == y || yy == y+rh);
1958                         if (e != ec)
1959                             valid = FALSE;
1960                     }
1961                 }
1962                 /* Check the vertical edges. */
1963                 for (yy = y; yy < y+rh; yy++) {
1964                     for (xx = x; xx <= x+rw; xx++) {
1965                         int e = !VRANGE(state,xx,yy) || vedge(state,xx,yy);
1966                         int ec = (xx == x || xx == x+rw);
1967                         if (e != ec)
1968                             valid = FALSE;
1969                     }
1970                 }
1971
1972                 /*
1973                  * If this is not a valid rectangle with no other
1974                  * edges inside it, we just mark this square as not
1975                  * complete and proceed to the next square.
1976                  */
1977                 if (!valid) {
1978                     index(state, ret, x, y) = 0;
1979                     continue;
1980                 }
1981
1982                 /*
1983                  * We have a rectangle. Now see what its area is,
1984                  * and how many numbers are in it.
1985                  */
1986                 num = 0;
1987                 area = 0;
1988                 for (xx = x; xx < x+rw; xx++) {
1989                     for (yy = y; yy < y+rh; yy++) {
1990                         area++;
1991                         if (grid(state,xx,yy)) {
1992                             if (num > 0)
1993                                 valid = FALSE;   /* two numbers */
1994                             num = grid(state,xx,yy);
1995                         }
1996                     }
1997                 }
1998                 if (num != area)
1999                     valid = FALSE;
2000
2001                 /*
2002                  * Now fill in the whole rectangle based on the
2003                  * value of `valid'.
2004                  */
2005                 for (xx = x; xx < x+rw; xx++) {
2006                     for (yy = y; yy < y+rh; yy++) {
2007                         index(state, ret, xx, yy) = valid;
2008                     }
2009                 }
2010             }
2011
2012     return ret;
2013 }
2014
2015 struct game_ui {
2016     /*
2017      * These coordinates are 2 times the obvious grid coordinates.
2018      * Hence, the top left of the grid is (0,0), the grid point to
2019      * the right of that is (2,0), the one _below that_ is (2,2)
2020      * and so on. This is so that we can specify a drag start point
2021      * on an edge (one odd coordinate) or in the middle of a square
2022      * (two odd coordinates) rather than always at a corner.
2023      * 
2024      * -1,-1 means no drag is in progress.
2025      */
2026     int drag_start_x;
2027     int drag_start_y;
2028     int drag_end_x;
2029     int drag_end_y;
2030     /*
2031      * This flag is set as soon as a dragging action moves the
2032      * mouse pointer away from its starting point, so that even if
2033      * the pointer _returns_ to its starting point the action is
2034      * treated as a small drag rather than a click.
2035      */
2036     int dragged;
2037 };
2038
2039 static game_ui *new_ui(game_state *state)
2040 {
2041     game_ui *ui = snew(game_ui);
2042     ui->drag_start_x = -1;
2043     ui->drag_start_y = -1;
2044     ui->drag_end_x = -1;
2045     ui->drag_end_y = -1;
2046     ui->dragged = FALSE;
2047     return ui;
2048 }
2049
2050 static void free_ui(game_ui *ui)
2051 {
2052     sfree(ui);
2053 }
2054
2055 static void coord_round(float x, float y, int *xr, int *yr)
2056 {
2057     float xs, ys, xv, yv, dx, dy, dist;
2058
2059     /*
2060      * Find the nearest square-centre.
2061      */
2062     xs = (float)floor(x) + 0.5F;
2063     ys = (float)floor(y) + 0.5F;
2064
2065     /*
2066      * And find the nearest grid vertex.
2067      */
2068     xv = (float)floor(x + 0.5F);
2069     yv = (float)floor(y + 0.5F);
2070
2071     /*
2072      * We allocate clicks in parts of the grid square to either
2073      * corners, edges or square centres, as follows:
2074      * 
2075      *   +--+--------+--+
2076      *   |  |        |  |
2077      *   +--+        +--+
2078      *   |   `.    ,'   |
2079      *   |     +--+     |
2080      *   |     |  |     |
2081      *   |     +--+     |
2082      *   |   ,'    `.   |
2083      *   +--+        +--+
2084      *   |  |        |  |
2085      *   +--+--------+--+
2086      * 
2087      * (Not to scale!)
2088      * 
2089      * In other words: we measure the square distance (i.e.
2090      * max(dx,dy)) from the click to the nearest corner, and if
2091      * it's within CORNER_TOLERANCE then we return a corner click.
2092      * We measure the square distance from the click to the nearest
2093      * centre, and if that's within CENTRE_TOLERANCE we return a
2094      * centre click. Failing that, we find which of the two edge
2095      * centres is nearer to the click and return that edge.
2096      */
2097
2098     /*
2099      * Check for corner click.
2100      */
2101     dx = (float)fabs(x - xv);
2102     dy = (float)fabs(y - yv);
2103     dist = (dx > dy ? dx : dy);
2104     if (dist < CORNER_TOLERANCE) {
2105         *xr = 2 * (int)xv;
2106         *yr = 2 * (int)yv;
2107     } else {
2108         /*
2109          * Check for centre click.
2110          */
2111         dx = (float)fabs(x - xs);
2112         dy = (float)fabs(y - ys);
2113         dist = (dx > dy ? dx : dy);
2114         if (dist < CENTRE_TOLERANCE) {
2115             *xr = 1 + 2 * (int)xs;
2116             *yr = 1 + 2 * (int)ys;
2117         } else {
2118             /*
2119              * Failing both of those, see which edge we're closer to.
2120              * Conveniently, this is simply done by testing the relative
2121              * magnitude of dx and dy (which are currently distances from
2122              * the square centre).
2123              */
2124             if (dx > dy) {
2125                 /* Vertical edge: x-coord of corner,
2126                  * y-coord of square centre. */
2127                 *xr = 2 * (int)xv;
2128                 *yr = 1 + 2 * (int)ys;
2129             } else {
2130                 /* Horizontal edge: x-coord of square centre,
2131                  * y-coord of corner. */
2132                 *xr = 1 + 2 * (int)xs;
2133                 *yr = 2 * (int)yv;
2134             }
2135         }
2136     }
2137 }
2138
2139 static void ui_draw_rect(game_state *state, game_ui *ui,
2140                          unsigned char *hedge, unsigned char *vedge, int c)
2141 {
2142     int x1, x2, y1, y2, x, y, t;
2143
2144     x1 = ui->drag_start_x;
2145     x2 = ui->drag_end_x;
2146     if (x2 < x1) { t = x1; x1 = x2; x2 = t; }
2147
2148     y1 = ui->drag_start_y;
2149     y2 = ui->drag_end_y;
2150     if (y2 < y1) { t = y1; y1 = y2; y2 = t; }
2151
2152     x1 = x1 / 2;               /* rounds down */
2153     x2 = (x2+1) / 2;           /* rounds up */
2154     y1 = y1 / 2;               /* rounds down */
2155     y2 = (y2+1) / 2;           /* rounds up */
2156
2157     /*
2158      * Draw horizontal edges of rectangles.
2159      */
2160     for (x = x1; x < x2; x++)
2161         for (y = y1; y <= y2; y++)
2162             if (HRANGE(state,x,y)) {
2163                 int val = index(state,hedge,x,y);
2164                 if (y == y1 || y == y2)
2165                     val = c;
2166                 else if (c == 1)
2167                     val = 0;
2168                 index(state,hedge,x,y) = val;
2169             }
2170
2171     /*
2172      * Draw vertical edges of rectangles.
2173      */
2174     for (y = y1; y < y2; y++)
2175         for (x = x1; x <= x2; x++)
2176             if (VRANGE(state,x,y)) {
2177                 int val = index(state,vedge,x,y);
2178                 if (x == x1 || x == x2)
2179                     val = c;
2180                 else if (c == 1)
2181                     val = 0;
2182                 index(state,vedge,x,y) = val;
2183             }
2184 }
2185
2186 static game_state *make_move(game_state *from, game_ui *ui, game_drawstate *ds,
2187                              int x, int y, int button) {
2188     int xc, yc;
2189     int startdrag = FALSE, enddrag = FALSE, active = FALSE;
2190     game_state *ret;
2191
2192     button &= ~MOD_MASK;
2193
2194     if (button == LEFT_BUTTON) {
2195         startdrag = TRUE;
2196     } else if (button == LEFT_RELEASE) {
2197         enddrag = TRUE;
2198     } else if (button != LEFT_DRAG) {
2199         return NULL;
2200     }
2201
2202     coord_round(FROMCOORD((float)x), FROMCOORD((float)y), &xc, &yc);
2203
2204     if (startdrag) {
2205         ui->drag_start_x = xc;
2206         ui->drag_start_y = yc;
2207         ui->drag_end_x = xc;
2208         ui->drag_end_y = yc;
2209         ui->dragged = FALSE;
2210         active = TRUE;
2211     }
2212
2213     if (xc != ui->drag_end_x || yc != ui->drag_end_y) {
2214         ui->drag_end_x = xc;
2215         ui->drag_end_y = yc;
2216         ui->dragged = TRUE;
2217         active = TRUE;
2218     }
2219
2220     ret = NULL;
2221
2222     if (enddrag) {
2223         if (xc >= 0 && xc <= 2*from->w &&
2224             yc >= 0 && yc <= 2*from->h) {
2225             ret = dup_game(from);
2226
2227             if (ui->dragged) {
2228                 ui_draw_rect(ret, ui, ret->hedge, ret->vedge, 1);
2229             } else {
2230                 if ((xc & 1) && !(yc & 1) && HRANGE(from,xc/2,yc/2)) {
2231                     hedge(ret,xc/2,yc/2) = !hedge(ret,xc/2,yc/2);
2232                 }
2233                 if ((yc & 1) && !(xc & 1) && VRANGE(from,xc/2,yc/2)) {
2234                     vedge(ret,xc/2,yc/2) = !vedge(ret,xc/2,yc/2);
2235                 }
2236             }
2237
2238             if (!memcmp(ret->hedge, from->hedge, from->w*from->h) &&
2239                 !memcmp(ret->vedge, from->vedge, from->w*from->h)) {
2240                 free_game(ret);
2241                 ret = NULL;
2242             }
2243
2244             /*
2245              * We've made a real change to the grid. Check to see
2246              * if the game has been completed.
2247              */
2248             if (ret && !ret->completed) {
2249                 int x, y, ok;
2250                 unsigned char *correct = get_correct(ret);
2251
2252                 ok = TRUE;
2253                 for (x = 0; x < ret->w; x++)
2254                     for (y = 0; y < ret->h; y++)
2255                         if (!index(ret, correct, x, y))
2256                             ok = FALSE;
2257
2258                 sfree(correct);
2259
2260                 if (ok)
2261                     ret->completed = TRUE;
2262             }
2263         }
2264
2265         ui->drag_start_x = -1;
2266         ui->drag_start_y = -1;
2267         ui->drag_end_x = -1;
2268         ui->drag_end_y = -1;
2269         ui->dragged = FALSE;
2270         active = TRUE;
2271     }
2272
2273     if (ret)
2274         return ret;                    /* a move has been made */
2275     else if (active)
2276         return from;                   /* UI activity has occurred */
2277     else
2278         return NULL;
2279 }
2280
2281 /* ----------------------------------------------------------------------
2282  * Drawing routines.
2283  */
2284
2285 #define CORRECT (1L<<16)
2286
2287 #define COLOUR(k) ( (k)==1 ? COL_LINE : COL_DRAG )
2288 #define MAX4(x,y,z,w) ( max(max(x,y),max(z,w)) )
2289
2290 struct game_drawstate {
2291     int started;
2292     int w, h;
2293     unsigned long *visible;
2294 };
2295
2296 static void game_size(game_params *params, int *x, int *y)
2297 {
2298     *x = params->w * TILE_SIZE + 2*BORDER + 1;
2299     *y = params->h * TILE_SIZE + 2*BORDER + 1;
2300 }
2301
2302 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2303 {
2304     float *ret = snewn(3 * NCOLOURS, float);
2305
2306     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2307
2308     ret[COL_GRID * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2309     ret[COL_GRID * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2310     ret[COL_GRID * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2311
2312     ret[COL_DRAG * 3 + 0] = 1.0F;
2313     ret[COL_DRAG * 3 + 1] = 0.0F;
2314     ret[COL_DRAG * 3 + 2] = 0.0F;
2315
2316     ret[COL_CORRECT * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2317     ret[COL_CORRECT * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2318     ret[COL_CORRECT * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2319
2320     ret[COL_LINE * 3 + 0] = 0.0F;
2321     ret[COL_LINE * 3 + 1] = 0.0F;
2322     ret[COL_LINE * 3 + 2] = 0.0F;
2323
2324     ret[COL_TEXT * 3 + 0] = 0.0F;
2325     ret[COL_TEXT * 3 + 1] = 0.0F;
2326     ret[COL_TEXT * 3 + 2] = 0.0F;
2327
2328     *ncolours = NCOLOURS;
2329     return ret;
2330 }
2331
2332 static game_drawstate *game_new_drawstate(game_state *state)
2333 {
2334     struct game_drawstate *ds = snew(struct game_drawstate);
2335     int i;
2336
2337     ds->started = FALSE;
2338     ds->w = state->w;
2339     ds->h = state->h;
2340     ds->visible = snewn(ds->w * ds->h, unsigned long);
2341     for (i = 0; i < ds->w * ds->h; i++)
2342         ds->visible[i] = 0xFFFF;
2343
2344     return ds;
2345 }
2346
2347 static void game_free_drawstate(game_drawstate *ds)
2348 {
2349     sfree(ds->visible);
2350     sfree(ds);
2351 }
2352
2353 static void draw_tile(frontend *fe, game_state *state, int x, int y,
2354                unsigned char *hedge, unsigned char *vedge,
2355                unsigned char *corners, int correct)
2356 {
2357     int cx = COORD(x), cy = COORD(y);
2358     char str[80];
2359
2360     draw_rect(fe, cx, cy, TILE_SIZE+1, TILE_SIZE+1, COL_GRID);
2361     draw_rect(fe, cx+1, cy+1, TILE_SIZE-1, TILE_SIZE-1,
2362               correct ? COL_CORRECT : COL_BACKGROUND);
2363
2364     if (grid(state,x,y)) {
2365         sprintf(str, "%d", grid(state,x,y));
2366         draw_text(fe, cx+TILE_SIZE/2, cy+TILE_SIZE/2, FONT_VARIABLE,
2367                   TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, COL_TEXT, str);
2368     }
2369
2370     /*
2371      * Draw edges.
2372      */
2373     if (!HRANGE(state,x,y) || index(state,hedge,x,y))
2374         draw_rect(fe, cx, cy, TILE_SIZE+1, 2,
2375                   HRANGE(state,x,y) ? COLOUR(index(state,hedge,x,y)) :
2376                   COL_LINE);
2377     if (!HRANGE(state,x,y+1) || index(state,hedge,x,y+1))
2378         draw_rect(fe, cx, cy+TILE_SIZE-1, TILE_SIZE+1, 2,
2379                   HRANGE(state,x,y+1) ? COLOUR(index(state,hedge,x,y+1)) :
2380                   COL_LINE);
2381     if (!VRANGE(state,x,y) || index(state,vedge,x,y))
2382         draw_rect(fe, cx, cy, 2, TILE_SIZE+1,
2383                   VRANGE(state,x,y) ? COLOUR(index(state,vedge,x,y)) :
2384                   COL_LINE);
2385     if (!VRANGE(state,x+1,y) || index(state,vedge,x+1,y))
2386         draw_rect(fe, cx+TILE_SIZE-1, cy, 2, TILE_SIZE+1,
2387                   VRANGE(state,x+1,y) ? COLOUR(index(state,vedge,x+1,y)) :
2388                   COL_LINE);
2389
2390     /*
2391      * Draw corners.
2392      */
2393     if (index(state,corners,x,y))
2394         draw_rect(fe, cx, cy, 2, 2,
2395                   COLOUR(index(state,corners,x,y)));
2396     if (x+1 < state->w && index(state,corners,x+1,y))
2397         draw_rect(fe, cx+TILE_SIZE-1, cy, 2, 2,
2398                   COLOUR(index(state,corners,x+1,y)));
2399     if (y+1 < state->h && index(state,corners,x,y+1))
2400         draw_rect(fe, cx, cy+TILE_SIZE-1, 2, 2,
2401                   COLOUR(index(state,corners,x,y+1)));
2402     if (x+1 < state->w && y+1 < state->h && index(state,corners,x+1,y+1))
2403         draw_rect(fe, cx+TILE_SIZE-1, cy+TILE_SIZE-1, 2, 2,
2404                   COLOUR(index(state,corners,x+1,y+1)));
2405
2406     draw_update(fe, cx, cy, TILE_SIZE+1, TILE_SIZE+1);
2407 }
2408
2409 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
2410                  game_state *state, int dir, game_ui *ui,
2411                  float animtime, float flashtime)
2412 {
2413     int x, y;
2414     unsigned char *correct;
2415     unsigned char *hedge, *vedge, *corners;
2416
2417     correct = get_correct(state);
2418
2419     if (ui->dragged) {
2420         hedge = snewn(state->w*state->h, unsigned char);
2421         vedge = snewn(state->w*state->h, unsigned char);
2422         memcpy(hedge, state->hedge, state->w*state->h);
2423         memcpy(vedge, state->vedge, state->w*state->h);
2424         ui_draw_rect(state, ui, hedge, vedge, 2);
2425     } else {
2426         hedge = state->hedge;
2427         vedge = state->vedge;
2428     }
2429
2430     corners = snewn(state->w * state->h, unsigned char);
2431     memset(corners, 0, state->w * state->h);
2432     for (x = 0; x < state->w; x++)
2433         for (y = 0; y < state->h; y++) {
2434             if (x > 0) {
2435                 int e = index(state, vedge, x, y);
2436                 if (index(state,corners,x,y) < e)
2437                     index(state,corners,x,y) = e;
2438                 if (y+1 < state->h &&
2439                     index(state,corners,x,y+1) < e)
2440                     index(state,corners,x,y+1) = e;
2441             }
2442             if (y > 0) {
2443                 int e = index(state, hedge, x, y);
2444                 if (index(state,corners,x,y) < e)
2445                     index(state,corners,x,y) = e;
2446                 if (x+1 < state->w &&
2447                     index(state,corners,x+1,y) < e)
2448                     index(state,corners,x+1,y) = e;
2449             }
2450         }
2451
2452     if (!ds->started) {
2453         draw_rect(fe, 0, 0,
2454                   state->w * TILE_SIZE + 2*BORDER + 1,
2455                   state->h * TILE_SIZE + 2*BORDER + 1, COL_BACKGROUND);
2456         draw_rect(fe, COORD(0)-1, COORD(0)-1,
2457                   ds->w*TILE_SIZE+3, ds->h*TILE_SIZE+3, COL_LINE);
2458         ds->started = TRUE;
2459         draw_update(fe, 0, 0,
2460                     state->w * TILE_SIZE + 2*BORDER + 1,
2461                     state->h * TILE_SIZE + 2*BORDER + 1);
2462     }
2463
2464     for (x = 0; x < state->w; x++)
2465         for (y = 0; y < state->h; y++) {
2466             unsigned long c = 0;
2467
2468             if (HRANGE(state,x,y))
2469                 c |= index(state,hedge,x,y);
2470             if (HRANGE(state,x,y+1))
2471                 c |= index(state,hedge,x,y+1) << 2;
2472             if (VRANGE(state,x,y))
2473                 c |= index(state,vedge,x,y) << 4;
2474             if (VRANGE(state,x+1,y))
2475                 c |= index(state,vedge,x+1,y) << 6;
2476             c |= index(state,corners,x,y) << 8;
2477             if (x+1 < state->w)
2478                 c |= index(state,corners,x+1,y) << 10;
2479             if (y+1 < state->h)
2480                 c |= index(state,corners,x,y+1) << 12;
2481             if (x+1 < state->w && y+1 < state->h)
2482                 /* cast to prevent 2<<14 sign-extending on promotion to long */
2483                 c |= (unsigned long)index(state,corners,x+1,y+1) << 14;
2484             if (index(state, correct, x, y) && !flashtime)
2485                 c |= CORRECT;
2486
2487             if (index(ds,ds->visible,x,y) != c) {
2488                 draw_tile(fe, state, x, y, hedge, vedge, corners,
2489                           (c & CORRECT) ? 1 : 0);
2490                 index(ds,ds->visible,x,y) = c;
2491             }
2492         }
2493
2494     if (hedge != state->hedge) {
2495         sfree(hedge);
2496         sfree(vedge);
2497    }
2498
2499     sfree(corners);
2500     sfree(correct);
2501 }
2502
2503 static float game_anim_length(game_state *oldstate,
2504                               game_state *newstate, int dir, game_ui *ui)
2505 {
2506     return 0.0F;
2507 }
2508
2509 static float game_flash_length(game_state *oldstate,
2510                                game_state *newstate, int dir, game_ui *ui)
2511 {
2512     if (!oldstate->completed && newstate->completed &&
2513         !oldstate->cheated && !newstate->cheated)
2514         return FLASH_TIME;
2515     return 0.0F;
2516 }
2517
2518 static int game_wants_statusbar(void)
2519 {
2520     return FALSE;
2521 }
2522
2523 static int game_timing_state(game_state *state)
2524 {
2525     return TRUE;
2526 }
2527
2528 #ifdef COMBINED
2529 #define thegame rect
2530 #endif
2531
2532 const struct game thegame = {
2533     "Rectangles", "games.rectangles",
2534     default_params,
2535     game_fetch_preset,
2536     decode_params,
2537     encode_params,
2538     free_params,
2539     dup_params,
2540     TRUE, game_configure, custom_params,
2541     validate_params,
2542     new_game_desc,
2543     game_free_aux_info,
2544     validate_desc,
2545     new_game,
2546     dup_game,
2547     free_game,
2548     TRUE, solve_game,
2549     TRUE, game_text_format,
2550     new_ui,
2551     free_ui,
2552     make_move,
2553     game_size,
2554     game_colours,
2555     game_new_drawstate,
2556     game_free_drawstate,
2557     game_redraw,
2558     game_anim_length,
2559     game_flash_length,
2560     game_wants_statusbar,
2561     FALSE, game_timing_state,
2562     0,                                 /* mouse_priorities */
2563 };