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