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