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