]> git.pond.sub.org Git - empserver/blob - src/util/fairland.c
56aac1bda78bb2cb9e5b1cca8aa9e6a74bb4cc2d
[empserver] / src / util / fairland.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2020, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  fairland.c: Create a nice, new world
28  *
29  *  Known contributors to this file:
30  *     Ken Stevens, 1995
31  *     Steve McClure, 1998
32  *     Markus Armbruster, 2004-2020
33  */
34
35 /*
36  * How fairland works
37  *
38  * 1. Place capitals
39  *
40  * Place the capitals on the torus in such a way so as to maximize
41  * their distances from one another.  This uses the perturbation
42  * technique of calculus of variations.
43  *
44  * 2. Grow start islands ("continents")
45  *
46  * For all continents, add the first sector at the capital's location,
47  * and the second right to it.  These are the capital sectors.  Then
48  * add one sector to each continent in turn, until they have the
49  * specified size.
50  *
51  * Growth uses weighted random sampling to pick one sector from the
52  * set of adjacent sea sectors that aren't too close to another
53  * continent.  Growth operates in spiking mode with a chance given by
54  * the spike percentage.  When "spiking", a sector's weight increases
55  * with number of adjacent sea sectors.  This directs the growth away
56  * from land, resulting in spikes.  When not spiking, the weight
57  * increases with the number of adjacent land sectors.  This makes the
58  * island more rounded.
59  *
60  * If growing fails due to lack of room, start over.  If it fails too
61  * many times, give up and terminate unsuccessfully.
62  *
63  * 3. Place and grow additional islands
64  *
65  * Each continent has a "sphere of influence": the set of sectors
66  * closer to it than to any other continent.  Each island is entirely
67  * in one such sphere, and each sphere contains the same number of
68  * islands with the same sizes.
69  *
70  * First, split the specified number of island sectors per continent
71  * randomly into the island sizes.  Sort by size so that larger
72  * islands are grown before smaller ones, to give the large ones the
73  * best chance to grow to their planned size.
74  *
75  * Then place one island's first sector into each sphere, using
76  * weighted random sampling with weights favoring sectors away from
77  * land and other spheres.  Add one sector to each island in turn,
78  * until they have the intended size.  Repeat until the specified
79  * number of islands has been grown.
80  *
81  * If placement fails due to lack of room, start over, just like for
82  * continents.
83  *
84  * Growing works as for continents, except the minimum distance for
85  * additional islands applies, and growing simply stops when any of
86  * the islands being grown lacks the room to grow further.  The number
87  * of sectors not grown carries over to the next island size.
88  *
89  * 4. Compute elevation
90  *
91  * First, use a simple random hill algorithm to assign raw elevations:
92  * initialize elevation to zero, then randomly raise circular hills on
93  * land / lower circular depressions at sea.  Their size and height
94  * depends on the distance to the coast.
95  *
96  * Then, elevate islands one after the other.
97  *
98  * Set the capitals' elevation to a fixed value.  Process the
99  * remaining sectors in order of increasing raw elevation, first
100  * non-mountains, then mountains.  Non-mountain elevation starts at 1,
101  * and increases linearly to just below "high" elevation.  Mountain
102  * elevation starts at "high" elevation, and increases linearly.
103  *
104  * This gives islands of the same size the same set of elevations.
105  * Larger islands get more and taller mountains.
106  *
107  * Finally, elevate sea: normalize the raw elevations to [-127:-1].
108  *
109  * 5. Set resources
110  *
111  * Sector resources are simple functions of elevation.  You can alter
112  * iron_conf[], gold_conf[], fert_conf[], oil_conf[], and uran_conf[]
113  * to customize them.
114  */
115
116 #include <config.h>
117
118 #include <assert.h>
119 #include <errno.h>
120 #include <limits.h>
121 #include <stdarg.h>
122 #include <stdio.h>
123 #include <unistd.h>
124 #include "chance.h"
125 #include "optlist.h"
126 #include "path.h"
127 #include "prototypes.h"
128 #include "sect.h"
129 #include "version.h"
130 #include "xy.h"
131
132 /* do not change these defines */
133 #define LANDMIN         1       /* plate altitude for normal land */
134 #define PLATMIN         36      /* plate altitude for plateau */
135 #define HIGHMIN         98      /* plate altitude for mountains */
136
137 /*
138  * Resource configuration
139
140  * Resources are determined by elevation.  The map from elevation to
141  * resource is defined as a linear interpolation of resource data
142  * points (elev, res) defined in the tables below.  Elevations range
143  * from -127 to 127, and resource values from 0 to 100.
144  */
145
146 struct resource_point {
147     int elev, res;
148 };
149
150 struct resource_point iron_conf[] = {
151     { -127, 0 },
152     { 21, 0 },
153     { 85, 100 },
154     { HIGHMIN - 1, 100 },
155     { HIGHMIN , 0 },
156     { 127, 0 } };
157
158 struct resource_point gold_conf[] = {
159     { -127, 0 },
160     { 35, 0 },
161     { HIGHMIN - 1, 80 },
162     { HIGHMIN, 80 },
163     { 127, 85 } };
164
165 struct resource_point fert_conf[] = {
166     { -127, 100 },
167     { -59, 100 },
168     { LANDMIN - 1, 41 },
169     { LANDMIN, 100 },
170     { 10, 100 },
171     { 56, 0 },
172     { 127, 0 } };
173
174 struct resource_point oil_conf[] = {
175     { -127, 100 },
176     { -49, 100 },
177     { LANDMIN - 1, 2 },
178     { LANDMIN, 100 },
179     { 6, 100 },
180     { 34, 0 },
181     { 127, 0 } };
182
183 struct resource_point uran_conf[] = {
184     { -127, 0 },
185     { 55, 0 },
186     { 90, 100 },
187     { 97, 100 },
188     { 98, 0 },
189     { 127, 0 } };
190
191 static void qprint(const char * const fmt, ...)
192     ATTRIBUTE((format (printf, 1, 2)));
193
194 /*
195  * Program arguments and options
196  */
197 static char *program_name;
198 static int nc, sc;              /* number and size of continents */
199 static int ni, is;              /* number and size of islands */
200 #define DEFAULT_SPIKE 10
201 static int sp = DEFAULT_SPIKE;  /* spike percentage */
202 #define DEFAULT_MOUNTAIN 0
203 static int pm = DEFAULT_MOUNTAIN; /* mountain percentage */
204 #define DEFAULT_CONTDIST 2
205 static int di = DEFAULT_CONTDIST; /* min. distance between continents */
206 #define DEFAULT_ISLDIST 1
207 static int id = DEFAULT_ISLDIST;  /* ... continents and islands */
208 /* don't let the islands crash into each other.
209    1 = don't merge, 0 = merge. */
210 static int DISTINCT_ISLANDS = 1;
211 static int quiet;
212 #define DEFAULT_OUTFILE_NAME "newcap_script"
213 static const char *outfile = DEFAULT_OUTFILE_NAME;
214
215 #define STABLE_CYCLE 4          /* stability required for perterbed capitals */
216 #define DRIFT_BEFORE_CHECK ((WORLD_X + WORLD_Y)/2)
217 #define DRIFT_MAX ((WORLD_X + WORLD_Y)*2)
218
219 /* handy macros:
220 */
221
222 #define new_x(newx) (((newx) + WORLD_X) % WORLD_X)
223 #define new_y(newy) (((newy) + WORLD_Y) % WORLD_Y)
224
225 /*
226  * Island sizes
227  * isecs[i] is the size of the i-th island.
228  */
229 static int *isecs;
230
231 static int *capx, *capy;        /* location of the nc capitals */
232
233 /*
234  * Island at x, y
235  * own[XYOFFSET(x, y)] is x,y's island number, -1 if water.
236  */
237 static short *own;
238
239 /*
240  * Adjacent land sectors
241  * adj_land[XYOFFSET(x, y)] bit d is set exactly when the sector next
242  * to x, y in direction d is land.
243  */
244 static unsigned char *adj_land;
245
246 /*
247  * Elevation at x,y
248  * elev[XYOFFSET(x, y)] is x,y's elevation.
249  */
250 static short *elev;
251
252 /*
253  * Exclusive zones
254  * Each island is surrounded by an exclusive zone where only it may
255  * grow.  The width of the zone depends on minimum distances.
256  * While growing continents, it is @di sectors wide.
257  * While growing additional islands, it is @id sectors wide.
258  * DISTINCT_ISLANDS nullifies the exclusive zone then.
259  * xzone[XYOFFSET(x, y)] is -1 when the sector is in no exclusive
260  * zone, a (non-negative) island number when it is in that island's
261  * exclusive zone and no other, and -2 when it is in multiple
262  * exclusive zones.
263  */
264 static short *xzone;
265
266 /*
267  * Set of sectors seen already
268  * Increment @cur_seen to empty the set of sectors seen, set
269  * seen[XYOFFSET(x, y)] to @cur_seen to add x,y to the set.
270  */
271 static unsigned *seen;
272 static unsigned cur_seen;
273
274 /*
275  * Closest continent and "distance"
276  * closest[XYOFFSET(x, y)] is the closest continent's number.
277  * distance[] is complicated; see init_spheres_of_influence() and
278  * init_distance_to_coast().
279  */
280 static natid *closest;
281 static unsigned short *distance;
282
283 /*
284  * Queue for breadth-first search
285  */
286 static int *bfs_queue;
287 static int bfs_queue_head, bfs_queue_tail;
288
289 static int **sectx, **secty;    /* the sectors for each continent */
290
291 #define NUMTRIES 10             /* keep trying to grow this many times */
292
293 static const char *numletter =
294     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
295
296 static void help(char *);
297 static void usage(void);
298 static void parse_args(int argc, char *argv[]);
299 static void allocate_memory(void);
300 static void init(void);
301 static int drift(void);
302 static int grow_continents(void);
303 static void create_elevations(void);
304 static void write_sects(void);
305 static void output(void);
306 static int write_newcap_script(void);
307 static int stable(int);
308 static void elevate_prep(void);
309 static void elevate_land(void);
310 static void elevate_sea(void);
311
312 static void print_vars(void);
313 static void fl_move(int);
314 static int grow_islands(void);
315
316 /* Debugging aids: */
317 void print_own_map(void);
318 void print_xzone_map(void);
319 void print_closest_map(void);
320 void print_distance_map(void);
321 void print_elev_map(void);
322
323 /****************************************************************************
324   MAIN
325 ****************************************************************************/
326
327 int
328 main(int argc, char *argv[])
329 {
330     int opt;
331     char *config_file = NULL;
332     int try, done;
333     unsigned rnd_seed = 0;
334     int seed_set = 0;
335
336     program_name = argv[0];
337
338     while ((opt = getopt(argc, argv, "e:hiqR:s:v")) != EOF) {
339         switch (opt) {
340         case 'e':
341             config_file = optarg;
342             break;
343         case 'i':
344             DISTINCT_ISLANDS = 0;
345             break;
346         case 'q':
347             quiet = 1;
348             break;
349         case 'R':
350             rnd_seed = strtoul(optarg, NULL, 10);
351             seed_set = 1;
352             break;
353         case 's':
354             outfile = optarg;
355             break;
356         case 'h':
357             usage();
358             exit(0);
359         case 'v':
360             printf("%s\n\n%s", version, legal);
361             exit(0);
362         default:
363             help(NULL);
364             exit(1);
365         }
366     }
367
368     if (!seed_set)
369         rnd_seed = pick_seed();
370     seed_prng(rnd_seed);
371     empfile_init();
372     if (emp_config(config_file) < 0)
373         exit(1);
374     empfile_fixup();
375
376     parse_args(argc - optind, argv + optind);
377
378     allocate_memory();
379     print_vars();
380
381     qprint("\n        #*# ...fairland rips open a rift in the datumplane... #*#\n\n");
382     qprint("seed is %u\n", rnd_seed);
383     try = 0;
384     do {
385         init();
386         if (try)
387             qprint("\ntry #%d (out of %d)...\n", try + 1, NUMTRIES);
388         qprint("placing capitals...\n");
389         if (!drift())
390             qprint("unstable drift\n");
391         qprint("growing continents...\n");
392         done = grow_continents();
393         if (!done)
394             continue;
395         qprint("growing islands:");
396         done = grow_islands();
397     } while (!done && ++try < NUMTRIES);
398     if (!done) {
399         fprintf(stderr, "%s: world not large enough for this much land\n",
400                 program_name);
401         exit(1);
402     }
403     qprint("elevating land...\n");
404     create_elevations();
405
406     qprint("writing to sectors file...\n");
407     if (!write_newcap_script())
408         exit(1);
409     if (chdir(gamedir)) {
410         fprintf(stderr, "%s: can't chdir to %s (%s)\n",
411                 program_name, gamedir, strerror(errno));
412         exit(1);
413     }
414     if (!ef_open(EF_SECTOR, EFF_MEM | EFF_NOTIME))
415         exit(1);
416     write_sects();
417     if (!ef_close(EF_SECTOR))
418         exit(1);
419
420     output();
421     qprint("\n\nA script for adding all the countries can be found in \"%s\".\n",
422            outfile);
423     exit(0);
424 }
425
426 static void
427 print_vars(void)
428 {
429     if (quiet)
430         return;
431     puts("Creating a planet with:\n");
432     printf("%d continents\n", nc);
433     printf("continent size: %d\n", sc);
434     printf("number of islands: %d\n", ni);
435     printf("average size of islands: %d\n", is);
436     printf("spike: %d%%\n", sp);
437     printf("%d%% of land is mountain (each continent will have %d mountains)\n",
438            pm, (pm * sc) / 100);
439     printf("minimum distance between continents: %d\n", di);
440     printf("minimum distance from islands to continents: %d\n", id);
441     printf("World dimensions: %dx%d\n", WORLD_X, WORLD_Y);
442 }
443
444 static void
445 help(char *complaint)
446 {
447     if (complaint)
448         fprintf(stderr, "%s: %s\n", program_name, complaint);
449     fprintf(stderr, "Try -h for help.\n");
450 }
451
452 static void
453 usage(void)
454 {
455     printf("Usage: %s [OPTION]... NC SC [NI] [IS] [SP] [PM] [DI] [ID]\n"
456            "  -e CONFIG-FILE  configuration file\n"
457            "                  (default %s)\n"
458            "  -i              islands may merge\n"
459            "  -q              quiet\n"
460            "  -R SEED         seed for random number generator\n"
461            "  -s SCRIPT       name of script to create (default %s)\n"
462            "  -h              display this help and exit\n"
463            "  -v              display version information and exit\n"
464            "  NC              number of continents\n"
465            "  SC              continent size\n"
466            "  NI              number of islands (default NC)\n"
467            "  IS              average island size (default SC/2)\n"
468            "  SP              spike percentage: 0 = round, 100 = snake (default %d)\n"
469            "  PM              percentage of land that is mountain (default %d)\n"
470            "  DI              minimum distance between continents (default %d)\n"
471            "  ID              minimum distance from islands to continents (default %d)\n",
472            program_name, dflt_econfig, DEFAULT_OUTFILE_NAME,
473            DEFAULT_SPIKE, DEFAULT_MOUNTAIN, DEFAULT_CONTDIST, DEFAULT_ISLDIST);
474 }
475
476 static void
477 parse_args(int argc, char *argv[])
478 {
479     int dist_max = mapdist(0, 0, WORLD_X / 2, WORLD_Y / 2);
480
481     if (argc < 2) {
482         help("missing arguments");
483         exit(1);
484     }
485     if (argc > 8) {
486         help("too many arguments");
487         exit(1);
488     }
489     nc = atoi(argv[0]);
490     if (nc < 1) {
491         fprintf(stderr, "%s: number of continents must be > 0\n",
492                 program_name);
493         exit(1);
494     }
495
496     sc = atoi(argv[1]);
497     if (sc < 2) {
498         fprintf(stderr, "%s: size of continents must be > 1\n",
499                 program_name);
500         exit(1);
501     }
502
503     ni = nc;
504     is = sc / 2;
505
506     if (argc > 2)
507         ni = atoi(argv[2]);
508     if (ni < 0) {
509         fprintf(stderr, "%s: number of islands must be >= 0\n",
510                 program_name);
511         exit(1);
512     }
513     if (ni % nc) {
514         fprintf(stderr, "%s: number of islands must be a multiple of"
515                 " the number of continents\n",
516                 program_name);
517         exit(1);
518     }
519
520     if (argc > 3)
521         is = atoi(argv[3]);
522     if (is < 1) {
523         fprintf(stderr, "%s: size of islands must be > 0\n",
524                 program_name);
525         exit(1);
526     }
527
528     if (argc > 4)
529         sp = atoi(argv[4]);
530     if (sp < 0 || sp > 100) {
531         fprintf(stderr,
532                 "%s: spike percentage must be between 0 and 100\n",
533                 program_name);
534         exit(1);
535     }
536
537     if (argc > 5)
538         pm = atoi(argv[5]);
539     if (pm < 0 || pm > 100) {
540         fprintf(stderr,
541                 "%s: mountain percentage must be between 0 and 100\n",
542                 program_name);
543         exit(1);
544     }
545
546     if (argc > 6)
547         di = atoi(argv[6]);
548     if (di < 0) {
549         fprintf(stderr, "%s: distance between continents must be >= 0\n",
550                 program_name);
551         exit(1);
552     }
553     if (di > dist_max) {
554         fprintf(stderr, "%s: distance between continents too large\n",
555                 program_name);
556         exit(1);
557     }
558
559     if (argc > 7)
560         id = atoi(argv[7]);
561     if (id < 0) {
562         fprintf(stderr,
563                 "%s: distance from islands to continents must be >= 0\n",
564                 program_name);
565         exit(1);
566     }
567     if (id > dist_max) {
568         fprintf(stderr,
569                 "%s: distance from islands to continents too large\n",
570                 program_name);
571         exit(1);
572     }
573 }
574
575 /****************************************************************************
576   VARIABLE INITIALIZATION
577 ****************************************************************************/
578
579 static void
580 allocate_memory(void)
581 {
582     int i;
583
584     capx = calloc(nc, sizeof(int));
585     capy = calloc(nc, sizeof(int));
586     own = malloc(WORLD_SZ() * sizeof(*own));
587     adj_land = malloc(WORLD_SZ() * sizeof(*adj_land));
588     elev = calloc(WORLD_SZ(), sizeof(*elev));
589     xzone = malloc(WORLD_SZ() * sizeof(*xzone));
590     seen = calloc(WORLD_SZ(), sizeof(*seen));
591     closest = malloc(WORLD_SZ() * sizeof(*closest));
592     distance = malloc(WORLD_SZ() * sizeof(*distance));
593     bfs_queue = malloc(WORLD_SZ() * sizeof(*bfs_queue));
594     sectx = calloc(nc + ni, sizeof(int *));
595     secty = calloc(nc + ni, sizeof(int *));
596     isecs = calloc(nc + ni, sizeof(int));
597     for (i = 0; i < nc; ++i) {
598         sectx[i] = calloc(sc, sizeof(int));
599         secty[i] = calloc(sc, sizeof(int));
600     }
601     for (i = nc; i < nc + ni; ++i) {
602         sectx[i] = calloc(is * 2, sizeof(int));
603         secty[i] = calloc(is * 2, sizeof(int));
604     }
605
606 }
607
608 static void
609 init(void)
610 {
611     int i;
612
613     for (i = 0; i < WORLD_SZ(); i++)
614         own[i] = -1;
615     memset(adj_land, 0, WORLD_SZ() * sizeof(*adj_land));
616 }
617
618 /****************************************************************************
619   DRIFT THE CAPITALS UNTIL THEY ARE AS FAR AWAY FROM EACH OTHER AS POSSIBLE
620 ****************************************************************************/
621
622 /*
623  * How isolated is capital @j at @newx,@newy?
624  * Return the distance to the closest other capital.
625  */
626 static int
627 iso(int j, int newx, int newy)
628 {
629     int d = INT_MAX;
630     int i, md;
631
632     for (i = 0; i < nc; ++i) {
633         if (i == j)
634             continue;
635         md = mapdist(capx[i], capy[i], newx, newy);
636         if (md < d)
637             d = md;
638     }
639
640     return d;
641 }
642
643 /*
644  * Drift the capitals
645  * Return 1 for a stable drift, 0 for an unstable one.
646  */
647 static int
648 drift(void)
649 {
650     int turns, i;
651
652     for (i = 0; i < nc; i++) {
653         capy[i] = (2 * i) / WORLD_X;
654         capx[i] = (2 * i) % WORLD_X + capy[i] % 2;
655         if (capy[i] >= WORLD_Y) {
656             fprintf(stderr,
657                     "%s: world not big enough for all the continents\n",
658                     program_name);
659             exit(1);
660         }
661     }
662
663     for (turns = 0; turns < DRIFT_MAX; ++turns) {
664         if (stable(turns))
665             return 1;
666         for (i = 0; i < nc; ++i)
667             fl_move(i);
668     }
669     return 0;
670 }
671
672 /*
673  * Has the drift stabilized?
674  * @turns is the number of turns so far.
675  */
676 static int
677 stable(int turns)
678 {
679     static int mc[STABLE_CYCLE];
680     int i, isod, d = 0, stab = 1;
681
682     if (!turns) {
683         for (i = 0; i < STABLE_CYCLE; i++)
684             mc[i] = i;
685     }
686
687     if (turns <= DRIFT_BEFORE_CHECK)
688         return 0;
689
690     for (i = 0; i < nc; ++i) {
691         isod = iso(i, capx[i], capy[i]);
692         if (isod > d)
693             d = isod;
694     }
695
696     for (i = 0; i < STABLE_CYCLE; ++i)
697         if (d != mc[i])
698             stab = 0;
699
700     mc[turns % STABLE_CYCLE] = d;
701     return stab;
702 }
703
704 /* This routine does the actual drifting
705 */
706
707 static void
708 fl_move(int j)
709 {
710     int dir, i, newx, newy;
711
712     dir = DIR_L + roll0(6);
713     for (i = 0; i < 6; i++) {
714         if (dir > DIR_LAST)
715             dir -= 6;
716         newx = new_x(capx[j] + diroff[dir][0]);
717         newy = new_y(capy[j] + diroff[dir][1]);
718         dir++;
719         if (iso(j, newx, newy) >= iso(j, capx[j], capy[j])) {
720             capx[j] = newx;
721             capy[j] = newy;
722             return;
723         }
724     }
725 }
726
727 /****************************************************************************
728   GROW THE CONTINENTS
729 ****************************************************************************/
730
731 static int
732 is_coastal(int x, int y)
733 {
734     return adj_land[XYOFFSET(x, y)]
735         != (1u << (DIR_LAST + 1)) - (1u << DIR_FIRST);
736 }
737
738 struct hexagon_iter {
739     int dir, i, n;
740 };
741
742 /*
743  * Start iterating around @x0,@y0 at distance @d.
744  * Set *x,*y to coordinates of the first sector.
745  */
746 static inline void
747 hexagon_first(struct hexagon_iter *iter, int x0, int y0, int n,
748               int *x, int *y)
749 {
750     *x = new_x(x0 - 2 * n);
751     *y = y0;
752     iter->dir = DIR_FIRST;
753     iter->i = 0;
754     iter->n = n;
755 }
756
757 /*
758  * Continue iteration started with hexagon_first().
759  * Set *x,*y to coordinates of the next sector.
760  * Return whether we're back at the first sector, i.e. iteration is
761  * complete.
762  */
763 static inline int
764 hexagon_next(struct hexagon_iter *iter, int *x, int *y)
765 {
766     *x = new_x(*x + diroff[iter->dir][0]);
767     *y = new_y(*y + diroff[iter->dir][1]);
768     iter->i++;
769     if (iter->i == iter->n) {
770         iter->i = 0;
771         iter->dir++;
772     }
773     return iter->dir <= DIR_LAST;
774 }
775
776 /*
777  * Is @x,@y in no exclusive zone other than perhaps @c's?
778  */
779 static int
780 xzone_ok(int c, int x, int y)
781 {
782     int off = XYOFFSET(x, y);
783
784     return xzone[off] == c || xzone[off] == -1;
785 }
786
787 /*
788  * Add sectors within distance @dist of @x,@y to @c's exclusive zone.
789  */
790 static void
791 xzone_around_sector(int c, int x, int y, int dist)
792 {
793     int d, x1, y1, off;
794     struct hexagon_iter hexit;
795
796     assert(xzone_ok(c, x, y));
797
798     xzone[XYOFFSET(x, y)] = c;
799     for (d = 1; d <= dist; d++) {
800         hexagon_first(&hexit, x, y, d, &x1, &y1);
801         do {
802             off = XYOFFSET(x1, y1);
803             if (xzone[off] == -1)
804                 xzone[off] = c;
805             else if (xzone[off] != c)
806                 xzone[off] = -2;
807         } while (hexagon_next(&hexit, &x1, &y1));
808     }
809 }
810
811 /*
812  * Add sectors within distance @dist to island @c's exclusive zone.
813  */
814 static void
815 xzone_around_island(int c, int dist)
816 {
817     int i;
818
819     for (i = 0; i < isecs[c]; i++)
820         xzone_around_sector(c, sectx[c][i], secty[c][i], dist);
821 }
822
823 /*
824  * Initialize exclusive zones around @n islands.
825  */
826 static void
827 xzone_init(int n)
828 {
829     int i, c;
830
831     for (i = 0; i < WORLD_SZ(); i++)
832         xzone[i] = -1;
833
834     for (c = 0; c < n; c++)
835         xzone_around_island(c, id);
836 }
837
838 /*
839  * Initialize breadth-first search.
840  */
841 static void
842 bfs_init(void)
843 {
844     int i;
845
846     for (i = 0; i < WORLD_SZ(); i++) {
847         closest[i] = -1;
848         distance[i] = USHRT_MAX;
849     }
850
851     bfs_queue_head = bfs_queue_tail = 0;
852 }
853
854 /*
855  * Add sector @x,@y to the BFS queue.
856  * It's closest to @c, with distance @dist.
857  */
858 static void
859 bfs_enqueue(int c, int x, int y, int dist)
860 {
861     int off = XYOFFSET(x, y);
862
863     assert(dist < distance[off]);
864     closest[off] = c;
865     distance[off] = dist;
866     bfs_queue[bfs_queue_tail] = off;
867     bfs_queue_tail++;
868     if (bfs_queue_tail >= WORLD_SZ())
869         bfs_queue_tail = 0;
870     assert(bfs_queue_tail != bfs_queue_head);
871 }
872
873 /*
874  * Search breadth-first until the queue is empty.
875  */
876 static void
877 bfs_run_queue(void)
878 {
879     int off, dist, i, noff, nx, ny;
880     coord x, y;
881
882     while (bfs_queue_head != bfs_queue_tail) {
883         off = bfs_queue[bfs_queue_head];
884         bfs_queue_head++;
885         if (bfs_queue_head >= WORLD_SZ())
886             bfs_queue_head = 0;
887         dist = distance[off] + 1;
888         sctoff2xy(&x, &y, off);
889         for (i = DIR_FIRST; i <= DIR_LAST; i++) {
890             nx = new_x(x + diroff[i][0]);
891             ny = new_y(y + diroff[i][1]);
892             noff = XYOFFSET(nx, ny);
893             if (dist < distance[noff]) {
894                 bfs_enqueue(closest[off], nx, ny, dist);
895             } else if (distance[noff] == dist) {
896                 if (closest[off] != closest[noff])
897                     closest[noff] = (natid)-1;
898             } else
899                 assert(distance[noff] < dist);
900         }
901     }
902 }
903
904 /*
905  * Add island @c's coastal sectors to the BFS queue, with distance 0.
906  */
907 static void
908 bfs_enqueue_island(int c)
909 {
910     int i;
911
912     for (i = 0; i < isecs[c]; i++) {
913         if (is_coastal(sectx[c][i], secty[c][i]))
914             bfs_enqueue(c, sectx[c][i], secty[c][i], 0);
915     }
916 }
917
918 /*
919  * Enqueue spheres of influence borders for breadth-first search.
920  */
921 static void
922 bfs_enqueue_border(void)
923 {
924     int x, y, off, dir, nx, ny, noff;
925
926     for (y = 0; y < WORLD_Y; y++) {
927         for (x = y % 2; x < WORLD_X; x += 2) {
928             off = XYOFFSET(x, y);
929             if (distance[off] <= id + 1)
930                 continue;
931             if (closest[off] == (natid)-1)
932                 continue;
933             for (dir = DIR_FIRST; dir <= DIR_LAST; dir++) {
934                 nx = new_x(x + diroff[dir][0]);
935                 ny = new_y(y + diroff[dir][1]);
936                 noff = XYOFFSET(nx, ny);
937                 if (closest[noff] != closest[off]) {
938                     bfs_enqueue(closest[off], x, y, id + 1);
939                     break;
940                 }
941             }
942         }
943     }
944 }
945
946 /*
947  * Compute spheres of influence
948  * A continent's sphere of influence is the set of sectors closer to
949  * it than to any other continent.
950  * Set closest[XYOFFSET(x, y)] to the closest continent's number,
951  * -1 if no single continent is closest.
952  * Set distance[XYOFFSET(x, y)] to the minimum of the distance to the
953  * closest coastal land sector and the distance to just outside the
954  * sphere of influence plus @id.  For sea sectors within a continent's
955  * sphere of influence, distance[off] - id is the distance to the
956  * border of the area where additional islands can be placed.
957  */
958 static void
959 init_spheres_of_influence(void)
960 {
961     int c;
962
963     bfs_init();
964     for (c = 0; c < nc; c++)
965         bfs_enqueue_island(c);
966     bfs_run_queue();
967     bfs_enqueue_border();
968     bfs_run_queue();
969 }
970
971 /*
972  * Precompute distance to coast
973  * Set distance[XYOFFSET(x, y)] to the distance to the closest coastal
974  * land sector.
975  * Set closest[XYOFFSET(x, y)] to the closest continent's number,
976  * -1 if no single continent is closest.
977  */
978 static void
979 init_distance_to_coast(void)
980 {
981     int c;
982
983     bfs_init();
984     for (c = 0; c < nc + ni; c++)
985         bfs_enqueue_island(c);
986     bfs_run_queue();
987 }
988
989 /*
990  * Is @x,@y in the same sphere of influence as island @c?
991  * Always true when @c is a continent.
992  */
993 static int
994 is_in_sphere(int c, int x, int y)
995 {
996     return c < nc || closest[XYOFFSET(x, y)] == c % nc;
997 }
998
999 /*
1000  * Can island @c grow at @x,@y?
1001  */
1002 static int
1003 can_grow_at(int c, int x, int y)
1004 {
1005     return own[XYOFFSET(x, y)] == -1 && xzone_ok(c, x, y)
1006         && is_in_sphere(c, x, y);
1007 }
1008
1009 static void
1010 adj_land_update(int x, int y)
1011 {
1012     int is_land = own[XYOFFSET(x, y)] != -1;
1013     int dir, nx, ny, noff;
1014
1015     for (dir = DIR_FIRST; dir <= DIR_LAST; dir++) {
1016         nx = new_x(x + diroff[dir][0]);
1017         ny = new_y(y + diroff[dir][1]);
1018         noff = XYOFFSET(nx, ny);
1019         if (is_land)
1020             adj_land[noff] |= 1u << DIR_BACK(dir);
1021         else
1022             adj_land[noff] &= ~(1u << DIR_BACK(dir));
1023     }
1024 }
1025
1026 static void
1027 add_sector(int c, int x, int y)
1028 {
1029     int off = XYOFFSET(x, y);
1030
1031     assert(own[off] == -1);
1032     xzone_around_sector(c, x, y, c < nc ? di : DISTINCT_ISLANDS ? id : 0);
1033     sectx[c][isecs[c]] = x;
1034     secty[c][isecs[c]] = y;
1035     isecs[c]++;
1036     own[off] = c;
1037     adj_land_update(x, y);
1038 }
1039
1040 static int grow_weight(int c, int x, int y, int spike)
1041 {
1042     int n, b;
1043
1044     /*
1045      * #Land neighbors is #bits set in adj_land[].
1046      * Count them Brian Kernighan's way.
1047      */
1048     n = 0;
1049     for (b = adj_land[XYOFFSET(x, y)]; b; b &= b - 1)
1050         n++;
1051     assert(n > 0 && n < 7);
1052
1053     if (spike)
1054         return (6 - n) * (6 - n);
1055
1056     return n * n * n;
1057 }
1058
1059 static int
1060 grow_one_sector(int c)
1061 {
1062     int spike = roll0(100) < sp;
1063     int wsum, newx, newy, i, x, y, off, dir, nx, ny, noff, w;
1064
1065     assert(cur_seen < UINT_MAX);
1066     cur_seen++;
1067     wsum = 0;
1068     newx = newy = -1;
1069
1070     for (i = 0; i < isecs[c]; i++) {
1071         x = sectx[c][i];
1072         y = secty[c][i];
1073         off = XYOFFSET(x, y);
1074
1075         for (dir = DIR_FIRST; dir <= DIR_LAST; dir++) {
1076             if (adj_land[off] & (1u << dir))
1077                 continue;
1078             nx = new_x(x + diroff[dir][0]);
1079             ny = new_y(y + diroff[dir][1]);
1080             noff = XYOFFSET(nx, ny);
1081             if (seen[noff] == cur_seen)
1082                 continue;
1083             assert(seen[noff] < cur_seen);
1084             seen[noff] = cur_seen;
1085             if (!can_grow_at(c, nx, ny))
1086                 continue;
1087             w = grow_weight(c, nx, ny, spike);
1088             assert(wsum < INT_MAX - w);
1089             wsum += w;
1090             if (roll0(wsum) < w) {
1091                 newx = nx;
1092                 newy = ny;
1093             }
1094         }
1095     }
1096
1097     if (!wsum)
1098         return 0;
1099
1100     add_sector(c, newx, newy);
1101     return 1;
1102 }
1103
1104 /*
1105  * Grow the continents.
1106  * Return 1 on success, 0 on error.
1107  */
1108 static int
1109 grow_continents(void)
1110 {
1111     int done = 1;
1112     int c, secs;
1113
1114     xzone_init(0);
1115
1116     for (c = 0; c < nc; ++c) {
1117         isecs[c] = 0;
1118         if (!can_grow_at(c, capx[c], capy[c])
1119             || !can_grow_at(c, new_x(capx[c] + 2), capy[c])) {
1120             done = 0;
1121             continue;
1122         }
1123         add_sector(c, capx[c], capy[c]);
1124         add_sector(c, new_x(capx[c] + 2), capy[c]);
1125     }
1126
1127     if (!done) {
1128         qprint("No room for continents\n");
1129         return 0;
1130     }
1131
1132     for (secs = 2; secs < sc && done; secs++) {
1133         for (c = 0; c < nc; ++c) {
1134             if (!grow_one_sector(c))
1135                 done = 0;
1136         }
1137     }
1138
1139     if (!done)
1140         qprint("Only managed to grow %d out of %d sectors.\n",
1141                secs - 1, sc);
1142     return done;
1143 }
1144
1145 /****************************************************************************
1146   GROW THE ISLANDS
1147 ****************************************************************************/
1148
1149 /*
1150  * Place additional island @c's first sector.
1151  * Return 1 on success, 0 on error.
1152  */
1153 static int
1154 place_island(int c, int isiz)
1155 {
1156     int n, x, y, d, w, newx, newy;
1157
1158     n = 0;
1159
1160     for (y = 0; y < WORLD_Y; y++) {
1161         for (x = y % 2; x < WORLD_X; x += 2) {
1162             if (can_grow_at(c, x, y)) {
1163                 d = distance[XYOFFSET(x, y)];
1164                 assert(d > id);
1165                 w = (d - id) * (d - id);
1166                 n += MIN(w, (isiz + 2) / 3);
1167                 if (roll0(n) < w) {
1168                     newx = x;
1169                     newy = y;
1170                 }
1171             }
1172         }
1173     }
1174
1175     if (n)
1176         add_sector(c, newx, newy);
1177     return n;
1178 }
1179
1180 static int
1181 int_cmp(const void *a, const void *b)
1182 {
1183     return *(int *)b - *(int *)a;
1184 }
1185
1186 static int *
1187 size_islands(void)
1188 {
1189     int n = ni / nc;
1190     int *isiz = malloc(n * sizeof(*isiz));
1191     int r0, r1, i;
1192
1193     isiz[0] = n * is;
1194     r1 = roll0(is);
1195     for (i = 1; i < n; i++) {
1196         r0 = r1;
1197         r1 = roll0(is);
1198         isiz[i] = is + r1 - r0;
1199         isiz[0] -= isiz[i];
1200     }
1201
1202     qsort(isiz, n, sizeof(*isiz), int_cmp);
1203     return isiz;
1204 }
1205
1206 /*
1207  * Grow the additional islands.
1208  * Return 1 on success, 0 on error.
1209  */
1210 static int
1211 grow_islands(void)
1212 {
1213     int *island_size = size_islands();
1214     int xzone_valid = 0;
1215     int carry = 0;
1216     int i, j, c, done, secs, isiz, x, y;
1217
1218     init_spheres_of_influence();
1219
1220     for (i = 0; i < ni / nc; i++) {
1221         c = nc + i * nc;
1222
1223         if (!xzone_valid)
1224             xzone_init(c);
1225
1226         carry += island_size[i];
1227         isiz = MIN(2 * is, carry);
1228
1229         for (j = 0; j < nc; j++) {
1230             isecs[c + j] = 0;
1231             if (!place_island(c + j, isiz)) {
1232                 qprint("\nNo room for island #%d\n", c - nc + j + 1);
1233                 free(island_size);
1234                 return 0;
1235             }
1236         }
1237
1238         done = 1;
1239         for (secs = 1; secs < isiz && done; secs++) {
1240             for (j = 0; j < nc; j++) {
1241                 if (!grow_one_sector(c + j))
1242                     done = 0;
1243             }
1244         }
1245
1246         if (!done) {
1247             secs--;
1248             for (j = 0; j < nc; j++) {
1249                 if (isecs[c + j] != secs) {
1250                     isecs[c + j]--;
1251                     assert(isecs[c + j] == secs);
1252                     x = sectx[c + j][secs];
1253                     y = secty[c + j][secs];
1254                     own[XYOFFSET(x, y)] = -1;
1255                     adj_land_update(x, y);
1256                 }
1257             }
1258             xzone_valid = 0;
1259         }
1260
1261         for (j = 0; j < nc; j++)
1262             qprint(" %d(%d)", c - nc + j + 1, isecs[c + j]);
1263
1264         carry -= secs;
1265     }
1266
1267     free(island_size);
1268     qprint("\n");
1269
1270     if (carry)
1271         qprint("Only managed to grow %d out of %d island sectors.\n",
1272                is * ni - carry * nc, is * ni);
1273
1274     return 1;
1275 }
1276
1277 /****************************************************************************
1278   CREATE ELEVATIONS
1279 ****************************************************************************/
1280 static void
1281 create_elevations(void)
1282 {
1283     elevate_prep();
1284     elevate_land();
1285     elevate_sea();
1286 }
1287
1288 static int
1289 elev_cmp(const void *p, const void *q)
1290 {
1291     int a = *(int *)p;
1292     int b = *(int *)q;
1293     int delev = elev[a] - elev[b];
1294
1295     return delev ? delev : a - b;
1296 }
1297
1298 static void
1299 elevate_prep(void)
1300 {
1301     int n = WORLD_SZ() * 8;
1302     int off0, r, sign, elevation, d, x1, y1, off1;
1303     coord x0, y0;
1304     struct hexagon_iter hexit;
1305
1306     init_distance_to_coast();
1307
1308     while (n > 0) {
1309         off0 = roll0(WORLD_SZ());
1310         sctoff2xy(&x0, &y0, off0);
1311         if (own[off0] == -1) {
1312             r = roll(MIN(3, distance[off0]));
1313             sign = -1;
1314         } else {
1315             r = roll(MIN(3, distance[off0]) + 1);
1316             sign = 1;
1317         }
1318         elevation = elev[off0] + sign * r * r;
1319         elev[off0] = LIMIT_TO(elevation, SHRT_MIN, SHRT_MAX);
1320         n--;
1321         for (d = 1; d < r; d++) {
1322             hexagon_first(&hexit, x0, y0, d, &x1, &y1);
1323             do {
1324                 off1 = XYOFFSET(x1, y1);
1325                 elevation = elev[off1] + sign * (r * r - d * d);
1326                 elev[off1] = LIMIT_TO(elevation, SHRT_MIN, SHRT_MAX);
1327                 n--;
1328             } while (hexagon_next(&hexit, &x1, &y1));
1329         }
1330     }
1331 }
1332
1333 static void
1334 elevate_land(void)
1335 {
1336     int *off = malloc(MAX(sc, is * 2) * sizeof(*off));
1337     int max_nm = (pm * MAX(sc, is * 2)) / 100;
1338     int c, nm, i0, n, i;
1339     double elevation, delta;
1340
1341     for (c = 0; c < nc + ni; c++) {
1342         nm = (pm * isecs[c]) / 100;
1343         i0 = c < nc ? 2 : 0;
1344         n = isecs[c] - i0;
1345         for (i = 0; i < i0; i++)
1346             elev[XYOFFSET(sectx[c][i], secty[c][i])] = PLATMIN;
1347         for (i = 0; i < n; i++)
1348             off[i] = XYOFFSET(sectx[c][i0 + i], secty[c][i0 + i]);
1349         qsort(off, n, sizeof(*off), elev_cmp);
1350         delta = (double)(HIGHMIN - LANDMIN - 1) / (n - nm - 1);
1351         elevation = LANDMIN;
1352         for (i = 0; i < n - nm; i++) {
1353             elev[off[i]] = (int)(elevation + 0.5);
1354             elevation += delta;
1355         }
1356         elevation = HIGHMIN;
1357         delta = (127.0 - HIGHMIN) / max_nm;
1358         for (; i < n; i++) {
1359             elevation += delta;
1360             elev[off[i]] = (int)(elevation + 0.5);
1361         }
1362     }
1363
1364     free(off);
1365 }
1366
1367 static void
1368 elevate_sea(void)
1369 {
1370     int i, min;
1371
1372     min = 0;
1373     for (i = 0; i < WORLD_SZ(); i++) {
1374         if (elev[i] < min)
1375             min = elev[i];
1376     }
1377
1378     for (i = 0; i < WORLD_SZ(); i++) {
1379         if (elev[i] < 0)
1380             elev[i] = -1 - 126 * elev[i] / min;
1381     }
1382 }
1383
1384 static int
1385 elev_to_sct_type(int elevation)
1386 {
1387     if (elevation < LANDMIN)
1388         return SCT_WATER;
1389     if (elevation < HIGHMIN)
1390         return SCT_RURAL;
1391     return SCT_MOUNT;
1392 }
1393
1394 /****************************************************************************
1395   ADD THE RESOURCES
1396 ****************************************************************************/
1397
1398 /*
1399  * Map elevation @elev to a resource value according to @conf.
1400  * This is a linear interpolation on the data points in @conf.
1401  */
1402 static int
1403 elev_to_resource(int elev, struct resource_point conf[])
1404 {
1405     int i, elev1, elev2, delev, res1, res2, dres;
1406
1407     for (i = 1; elev > conf[i].elev; i++) ;
1408     assert(conf[i - 1].elev <= elev);
1409
1410     elev1 = conf[i - 1].elev;
1411     elev2 = conf[i].elev;
1412     delev = elev2 - elev1;
1413     res1 = conf[i - 1].res;
1414     res2 = conf[i].res;
1415     dres = res2 - res1;
1416     return (int)(res1 + (double)((elev - elev1) * dres) / delev);
1417 }
1418
1419 static void
1420 add_resources(struct sctstr *sct)
1421 {
1422     sct->sct_min = elev_to_resource(sct->sct_elev, iron_conf);
1423     sct->sct_gmin = elev_to_resource(sct->sct_elev, gold_conf);
1424     sct->sct_fertil = elev_to_resource(sct->sct_elev, fert_conf);
1425     sct->sct_oil = elev_to_resource(sct->sct_elev, oil_conf);
1426     sct->sct_uran = elev_to_resource(sct->sct_elev, uran_conf);
1427 }
1428
1429 /****************************************************************************
1430   DESIGNATE THE SECTORS
1431 ****************************************************************************/
1432
1433 static void
1434 write_sects(void)
1435 {
1436     struct sctstr *sct;
1437     int x, y;
1438
1439     for (y = 0; y < WORLD_Y; y++) {
1440         for (x = y % 2; x < WORLD_X; x += 2) {
1441             sct = getsectp(x, y);
1442             sct->sct_elev = elev[sct->sct_uid];
1443             sct->sct_type = elev_to_sct_type(sct->sct_elev);
1444             sct->sct_newtype = sct->sct_type;
1445             sct->sct_dterr = own[sct->sct_uid] + 1;
1446             sct->sct_coastal = is_coastal(sct->sct_x, sct->sct_y);
1447             add_resources(sct);
1448         }
1449     }
1450 }
1451
1452 /****************************************************************************
1453   PRINT A PICTURE OF THE MAP TO YOUR SCREEN
1454 ****************************************************************************/
1455 static void
1456 output(void)
1457 {
1458     int sx, sy, x, y, off, c, type;
1459
1460     if (quiet == 0) {
1461         for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1462             y = YNORM(sy);
1463             puts("");
1464             if (y % 2)
1465                 printf(" ");
1466             for (sx = -WORLD_X / 2 + y % 2; sx < WORLD_X / 2; sx += 2) {
1467                 x = XNORM(sx);
1468                 off = XYOFFSET(x, y);
1469                 c = own[off];
1470                 type = elev_to_sct_type(elev[off]);
1471                 if (type == SCT_WATER)
1472                     printf(". ");
1473                 else if (type == SCT_MOUNT)
1474                     printf("^ ");
1475                 else if (c >= nc)
1476                     printf("%% ");
1477                 else {
1478                     assert(0 <= c && c < nc);
1479                     if ((x == capx[c] || x == new_x(capx[c] + 2))
1480                         && y == capy[c])
1481                         printf("%c ", numletter[c % 62]);
1482                     else
1483                         printf("# ");
1484                 }
1485             }
1486         }
1487     }
1488 }
1489
1490 /*
1491  * Print a map to help visualize own[].
1492  * This is for debugging.
1493  */
1494 void
1495 print_own_map(void)
1496 {
1497     int sx, sy, x, y, off;
1498
1499     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1500         y = YNORM(sy);
1501         printf("%4d ", sy);
1502         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1503             x = XNORM(sx);
1504             off = XYOFFSET(x, y);
1505             if ((x + y) & 1)
1506                 putchar(' ');
1507             else if (own[off] == -1)
1508                 putchar('.');
1509             else
1510                 putchar(numletter[own[off] % 62]);
1511         }
1512         putchar('\n');
1513     }
1514 }
1515
1516 /*
1517  * Print a map to help visualize elev[].
1518  * This is for debugging.  It expects the terminal to understand
1519  * 24-bit color escape sequences \e[48;2;$red;$green;$blue;m.
1520  */
1521 void
1522 print_elev_map(void)
1523 {
1524     int sx, sy, x, y, off, sat;
1525
1526     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1527         y = YNORM(sy);
1528         printf("%4d ", sy);
1529         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1530             x = XNORM(sx);
1531             off = XYOFFSET(x, y);
1532             if ((x + y) & 1)
1533                 putchar(' ');
1534             else if (!elev[off])
1535                 putchar(' ');
1536             else if (elev[off] < 0) {
1537                 sat = 256 + elev[off] * 2;
1538                 printf("\033[48;2;%d;%d;%dm \033[0m", sat, sat, 255);
1539             } else if (elev[off] < HIGHMIN / 2) {
1540                 sat = (HIGHMIN / 2 - elev[off]) * 4;
1541                 printf("\033[48;2;%d;%d;%dm \033[0m", sat, 255, sat);
1542             } else if (elev[off] < HIGHMIN) {
1543                 sat = 128 + (HIGHMIN - elev[off]) * 2;
1544                 printf("\033[48;2;%d;%d;%dm \033[0m", sat, sat / 2, sat / 4);
1545             } else {
1546                 sat = 128 + (elev[off] - HIGHMIN) * 2;
1547                 printf("\033[48;2;%d;%d;%dm^\033[0m", sat, sat, sat);
1548             }
1549         }
1550         putchar('\n');
1551     }
1552 }
1553
1554 /*
1555  * Print a map to help visualize xzone[].
1556  * This is for debugging.
1557  */
1558 void
1559 print_xzone_map(void)
1560 {
1561     int sx, sy, x, y, off;
1562
1563     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1564         y = YNORM(sy);
1565         printf("%4d ", sy);
1566         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1567             x = XNORM(sx);
1568             off = XYOFFSET(x, y);
1569             if ((x + y) & 1)
1570                 putchar(' ');
1571             else if (own[off] >= 0)
1572                 putchar('-');
1573             else if (xzone[off] >= 0)
1574                 putchar(numletter[xzone[off] % 62]);
1575             else {
1576                 assert(own[off] == -1);
1577                 putchar(xzone[off] == -1 ? '.' : '!');
1578             }
1579         }
1580         putchar('\n');
1581     }
1582 }
1583
1584 /*
1585  * Print a map to help visualize closest[].
1586  * This is for debugging.
1587  */
1588 void
1589 print_closest_map(void)
1590 {
1591     int sx, sy, x, y, off;
1592
1593     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1594         y = YNORM(sy);
1595         printf("%4d ", sy);
1596         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1597             x = XNORM(sx);
1598             off = XYOFFSET(x, y);
1599             if ((x + y) & 1)
1600                 putchar(' ');
1601             else if (closest[off] == (natid)-1)
1602                 putchar('.');
1603             else if (!distance[off]) {
1604                 assert(closest[off] == own[off]);
1605                 putchar('-');
1606             } else {
1607                 putchar(numletter[closest[off] % 62]);
1608             }
1609         }
1610         printf("\n");
1611     }
1612 }
1613
1614 void
1615 print_distance_map(void)
1616 {
1617     int sx, sy, x, y, off;
1618
1619     for (sy = -WORLD_Y / 2; sy < WORLD_Y / 2; sy++) {
1620         y = YNORM(sy);
1621         printf("%4d ", sy);
1622         for (sx = -WORLD_X / 2; sx < WORLD_X / 2; sx++) {
1623             x = XNORM(sx);
1624             off = XYOFFSET(x, y);
1625             if ((x + y) & 1)
1626                 putchar(' ');
1627             else if (closest[off] == (natid)-1)
1628                 putchar('.');
1629             else if (!distance[off]) {
1630                 assert(closest[off] == own[off]);
1631                 putchar('-');
1632             } else {
1633                 putchar(numletter[distance[off] % 62]);
1634             }
1635         }
1636         printf("\n");
1637     }
1638 }
1639
1640
1641 /***************************************************************************
1642   WRITE A SCRIPT FOR PLACING CAPITALS
1643 ****************************************************************************/
1644 static int
1645 write_newcap_script(void)
1646 {
1647     int c;
1648     FILE *script = fopen(outfile, "w");
1649
1650     if (!script) {
1651         fprintf(stderr, "%s: unable to write to %s (%s)\n",
1652                 program_name, outfile, strerror(errno));
1653         return 0;
1654     }
1655
1656     for (c = 0; c < nc; ++c) {
1657         fprintf(script, "add %d %d %d p\n", c + 1, c + 1, c + 1);
1658         fprintf(script, "newcap %d %d,%d\n", c + 1, capx[c], capy[c]);
1659     }
1660     fprintf(script, "add %d visitor visitor v\n", c + 1);
1661     fclose(script);
1662     return 1;
1663 }
1664
1665 static void
1666 qprint(const char *const fmt, ...)
1667 {
1668     va_list ap;
1669
1670     if (!quiet) {
1671         va_start(ap, fmt);
1672         vfprintf(stdout, fmt, ap);
1673         va_end(ap);
1674     }
1675 }