Codefix: Documentation comment in IndustryDirectoryWindow (#13059)
[openttd-github.git] / src / tgp.cpp
blob1ce32fda86edade963152773672ad27d358ccc0a
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file tgp.cpp OTTD Perlin Noise Landscape Generator, aka TerraGenesis Perlin */
10 #include "stdafx.h"
11 #include "clear_map.h"
12 #include "void_map.h"
13 #include "genworld.h"
14 #include "core/random_func.hpp"
15 #include "landscape_type.h"
17 #include "safeguards.h"
21 * Quickie guide to Perlin Noise
22 * Perlin noise is a predictable pseudo random number sequence. By generating
23 * it in 2 dimensions, it becomes a useful random map that, for a given seed
24 * and starting X & Y, is entirely predictable. On the face of it, that may not
25 * be useful. However, it means that if you want to replay a map in a different
26 * terrain, or just vary the sea level, you just re-run the generator with the
27 * same seed. The seed is an int32_t, and is randomised on each run of New Game.
28 * The Scenario Generator does not randomise the value, so that you can
29 * experiment with one terrain until you are happy, or click "Random" for a new
30 * random seed.
32 * Perlin Noise is a series of "octaves" of random noise added together. By
33 * reducing the amplitude of the noise with each octave, the first octave of
34 * noise defines the main terrain sweep, the next the ripples on that, and the
35 * next the ripples on that. I use 6 octaves, with the amplitude controlled by
36 * a power ratio, usually known as a persistence or p value. This I vary by the
37 * smoothness selection, as can be seen in the table below. The closer to 1,
38 * the more of that octave is added. Each octave is however raised to the power
39 * of its position in the list, so the last entry in the "smooth" row, 0.35, is
40 * raised to the power of 6, so can only add 0.001838... of the amplitude to
41 * the running total.
43 * In other words; the first p value sets the general shape of the terrain, the
44 * second sets the major variations to that, ... until finally the smallest
45 * bumps are added.
47 * Usefully, this routine is totally scalable; so when 32bpp comes along, the
48 * terrain can be as bumpy as you like! It is also infinitely expandable; a
49 * single random seed terrain continues in X & Y as far as you care to
50 * calculate. In theory, we could use just one seed value, but randomly select
51 * where in the Perlin XY space we use for the terrain. Personally I prefer
52 * using a simple (0, 0) to (X, Y), with a varying seed.
55 * Other things i have had to do: mountainous wasn't mountainous enough, and
56 * since we only have 0..15 heights available, I add a second generated map
57 * (with a modified seed), onto the original. This generally raises the
58 * terrain, which then needs scaling back down. Overall effect is a general
59 * uplift.
61 * However, the values on the top of mountains are then almost guaranteed to go
62 * too high, so large flat plateaus appeared at height 15. To counter this, I
63 * scale all heights above 12 to proportion up to 15. It still makes the
64 * mountains have flattish tops, rather than craggy peaks, but at least they
65 * aren't smooth as glass.
68 * For a full discussion of Perlin Noise, please visit:
69 * http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
72 * Evolution II
74 * The algorithm as described in the above link suggests to compute each tile height
75 * as composition of several noise waves. Some of them are computed directly by
76 * noise(x, y) function, some are calculated using linear approximation. Our
77 * first implementation of perlin_noise_2D() used 4 noise(x, y) calls plus
78 * 3 linear interpolations. It was called 6 times for each tile. This was a bit
79 * CPU expensive.
81 * The following implementation uses optimized algorithm that should produce
82 * the same quality result with much less computations, but more memory accesses.
83 * The overall speedup should be 300% to 800% depending on CPU and memory speed.
85 * I will try to explain it on the example below:
87 * Have a map of 4 x 4 tiles, our simplified noise generator produces only two
88 * values -1 and +1, use 3 octaves with wave length 1, 2 and 4, with amplitudes
89 * 3, 2, 1. Original algorithm produces:
91 * h00 = lerp(lerp(-3, 3, 0/4), lerp(3, -3, 0/4), 0/4) + lerp(lerp(-2, 2, 0/2), lerp( 2, -2, 0/2), 0/2) + -1 = lerp(-3.0, 3.0, 0/4) + lerp(-2, 2, 0/2) + -1 = -3.0 + -2 + -1 = -6.0
92 * h01 = lerp(lerp(-3, 3, 1/4), lerp(3, -3, 1/4), 0/4) + lerp(lerp(-2, 2, 1/2), lerp( 2, -2, 1/2), 0/2) + 1 = lerp(-1.5, 1.5, 0/4) + lerp( 0, 0, 0/2) + 1 = -1.5 + 0 + 1 = -0.5
93 * h02 = lerp(lerp(-3, 3, 2/4), lerp(3, -3, 2/4), 0/4) + lerp(lerp( 2, -2, 0/2), lerp(-2, 2, 0/2), 0/2) + -1 = lerp( 0, 0, 0/4) + lerp( 2, -2, 0/2) + -1 = 0 + 2 + -1 = 1.0
94 * h03 = lerp(lerp(-3, 3, 3/4), lerp(3, -3, 3/4), 0/4) + lerp(lerp( 2, -2, 1/2), lerp(-2, 2, 1/2), 0/2) + 1 = lerp( 1.5, -1.5, 0/4) + lerp( 0, 0, 0/2) + 1 = 1.5 + 0 + 1 = 2.5
96 * h10 = lerp(lerp(-3, 3, 0/4), lerp(3, -3, 0/4), 1/4) + lerp(lerp(-2, 2, 0/2), lerp( 2, -2, 0/2), 1/2) + 1 = lerp(-3.0, 3.0, 1/4) + lerp(-2, 2, 1/2) + 1 = -1.5 + 0 + 1 = -0.5
97 * h11 = lerp(lerp(-3, 3, 1/4), lerp(3, -3, 1/4), 1/4) + lerp(lerp(-2, 2, 1/2), lerp( 2, -2, 1/2), 1/2) + -1 = lerp(-1.5, 1.5, 1/4) + lerp( 0, 0, 1/2) + -1 = -0.75 + 0 + -1 = -1.75
98 * h12 = lerp(lerp(-3, 3, 2/4), lerp(3, -3, 2/4), 1/4) + lerp(lerp( 2, -2, 0/2), lerp(-2, 2, 0/2), 1/2) + 1 = lerp( 0, 0, 1/4) + lerp( 2, -2, 1/2) + 1 = 0 + 0 + 1 = 1.0
99 * h13 = lerp(lerp(-3, 3, 3/4), lerp(3, -3, 3/4), 1/4) + lerp(lerp( 2, -2, 1/2), lerp(-2, 2, 1/2), 1/2) + -1 = lerp( 1.5, -1.5, 1/4) + lerp( 0, 0, 1/2) + -1 = 0.75 + 0 + -1 = -0.25
102 * Optimization 1:
104 * 1) we need to allocate a bit more tiles: (size_x + 1) * (size_y + 1) = (5 * 5):
106 * 2) setup corner values using amplitude 3
107 * { -3.0 X X X 3.0 }
108 * { X X X X X }
109 * { X X X X X }
110 * { X X X X X }
111 * { 3.0 X X X -3.0 }
113 * 3a) interpolate values in the middle
114 * { -3.0 X 0.0 X 3.0 }
115 * { X X X X X }
116 * { 0.0 X 0.0 X 0.0 }
117 * { X X X X X }
118 * { 3.0 X 0.0 X -3.0 }
120 * 3b) add patches with amplitude 2 to them
121 * { -5.0 X 2.0 X 1.0 }
122 * { X X X X X }
123 * { 2.0 X -2.0 X 2.0 }
124 * { X X X X X }
125 * { 1.0 X 2.0 X -5.0 }
127 * 4a) interpolate values in the middle
128 * { -5.0 -1.5 2.0 1.5 1.0 }
129 * { -1.5 -0.75 0.0 0.75 1.5 }
130 * { 2.0 0.0 -2.0 0.0 2.0 }
131 * { 1.5 0.75 0.0 -0.75 -1.5 }
132 * { 1.0 1.5 2.0 -1.5 -5.0 }
134 * 4b) add patches with amplitude 1 to them
135 * { -6.0 -0.5 1.0 2.5 0.0 }
136 * { -0.5 -1.75 1.0 -0.25 2.5 }
137 * { 1.0 1.0 -3.0 1.0 1.0 }
138 * { 2.5 -0.25 1.0 -1.75 -0.5 }
139 * { 0.0 2.5 1.0 -0.5 -6.0 }
143 * Optimization 2:
145 * As you can see above, each noise function was called just once. Therefore
146 * we don't need to use noise function that calculates the noise from x, y and
147 * some prime. The same quality result we can obtain using standard Random()
148 * function instead.
152 /** Fixed point type for heights */
153 using Height = int16_t;
154 static const int height_decimal_bits = 4;
156 /** Fixed point array for amplitudes (and percent values) */
157 using Amplitude = int;
158 static const int amplitude_decimal_bits = 10;
160 /** Height map - allocated array of heights (MapSizeX() + 1) x (MapSizeY() + 1) */
161 struct HeightMap
163 std::vector<Height> h; //< array of heights
164 /* Even though the sizes are always positive, there are many cases where
165 * X and Y need to be signed integers due to subtractions. */
166 int dim_x; //< height map size_x Map::SizeX() + 1
167 int size_x; //< Map::SizeX()
168 int size_y; //< Map::SizeY()
171 * Height map accessor
172 * @param x X position
173 * @param y Y position
174 * @return height as fixed point number
176 inline Height &height(uint x, uint y)
178 return h[x + y * dim_x];
182 /** Global height map instance */
183 static HeightMap _height_map = { {}, 0, 0, 0 };
185 /** Conversion: int to Height */
186 #define I2H(i) ((i) << height_decimal_bits)
187 /** Conversion: Height to int */
188 #define H2I(i) ((i) >> height_decimal_bits)
190 /** Conversion: Amplitude to int */
191 #define A2I(i) ((i) >> amplitude_decimal_bits)
193 /** Conversion: Amplitude to Height */
194 #define A2H(a) ((a) >> (amplitude_decimal_bits - height_decimal_bits))
196 /** Maximum number of TGP noise frequencies. */
197 static const int MAX_TGP_FREQUENCIES = 10;
199 /** Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes */
200 static const Amplitude _water_percent[4] = {70, 170, 270, 420};
203 * Gets the maximum allowed height while generating a map based on
204 * mapsize, terraintype, and the maximum height level.
205 * @return The maximum height for the map generation.
206 * @note Values should never be lower than 3 since the minimum snowline height is 2.
208 static Height TGPGetMaxHeight()
210 if (_settings_game.difficulty.terrain_type == CUSTOM_TERRAIN_TYPE_NUMBER_DIFFICULTY) {
211 /* TGP never reaches this height; this means that if a user inputs "2",
212 * it would create a flat map without the "+ 1". But that would
213 * overflow on "255". So we reduce it by 1 to get back in range. */
214 return I2H(_settings_game.game_creation.custom_terrain_type + 1) - 1;
218 * Desired maximum height - indexed by:
219 * - _settings_game.difficulty.terrain_type
220 * - min(Map::LogX(), Map::LogY()) - MIN_MAP_SIZE_BITS
222 * It is indexed by map size as well as terrain type since the map size limits the height of
223 * a usable mountain. For example, on a 64x64 map a 24 high single peak mountain (as if you
224 * raised land 24 times in the center of the map) will leave only a ring of about 10 tiles
225 * around the mountain to build on. On a 4096x4096 map, it won't cover any major part of the map.
227 static const int max_height[5][MAX_MAP_SIZE_BITS - MIN_MAP_SIZE_BITS + 1] = {
228 /* 64 128 256 512 1024 2048 4096 */
229 { 3, 3, 3, 3, 4, 5, 7 }, ///< Very flat
230 { 5, 7, 8, 9, 14, 19, 31 }, ///< Flat
231 { 8, 9, 10, 15, 23, 37, 61 }, ///< Hilly
232 { 10, 11, 17, 19, 49, 63, 73 }, ///< Mountainous
233 { 12, 19, 25, 31, 67, 75, 87 }, ///< Alpinist
236 int map_size_bucket = std::min(Map::LogX(), Map::LogY()) - MIN_MAP_SIZE_BITS;
237 int max_height_from_table = max_height[_settings_game.difficulty.terrain_type][map_size_bucket];
239 /* If there is a manual map height limit, clamp to it. */
240 if (_settings_game.construction.map_height_limit != 0) {
241 max_height_from_table = std::min<uint>(max_height_from_table, _settings_game.construction.map_height_limit);
244 return I2H(max_height_from_table);
248 * Get an overestimation of the highest peak TGP wants to generate.
250 uint GetEstimationTGPMapHeight()
252 return H2I(TGPGetMaxHeight());
256 * Get the amplitude associated with the currently selected
257 * smoothness and maximum height level.
258 * @param frequency The frequency to get the amplitudes for
259 * @return The amplitudes to apply to the map.
261 static Amplitude GetAmplitude(int frequency)
263 /* Base noise amplitudes (multiplied by 1024) and indexed by "smoothness setting" and log2(frequency). */
264 static const Amplitude amplitudes[][7] = {
265 /* lowest frequency ...... highest (every corner) */
266 {16000, 5600, 1968, 688, 240, 16, 16}, ///< Very smooth
267 {24000, 12800, 6400, 2700, 1024, 128, 16}, ///< Smooth
268 {32000, 19200, 12800, 8000, 3200, 256, 64}, ///< Rough
269 {48000, 24000, 19200, 16000, 8000, 512, 320}, ///< Very rough
272 * Extrapolation factors for ranges before the table.
273 * The extrapolation is needed to account for the higher map heights. They need larger
274 * areas with a particular gradient so that we are able to create maps without too
275 * many steep slopes up to the wanted height level. It's definitely not perfect since
276 * it will bring larger rectangles with similar slopes which makes the rectangular
277 * behaviour of TGP more noticeable. However, these height differentiations cannot
278 * happen over much smaller areas; we basically double the "range" to give a similar
279 * slope for every doubling of map height.
281 static const double extrapolation_factors[] = { 3.3, 2.8, 2.3, 1.8 };
283 int smoothness = _settings_game.game_creation.tgen_smoothness;
285 /* Get the table index, and return that value if possible. */
286 int index = frequency - MAX_TGP_FREQUENCIES + static_cast<int>(std::size(amplitudes[smoothness]));
287 Amplitude amplitude = amplitudes[smoothness][std::max(0, index)];
288 if (index >= 0) return amplitude;
290 /* We need to extrapolate the amplitude. */
291 double extrapolation_factor = extrapolation_factors[smoothness];
292 int height_range = I2H(16);
293 do {
294 amplitude = (Amplitude)(extrapolation_factor * (double)amplitude);
295 height_range <<= 1;
296 index++;
297 } while (index < 0);
299 return Clamp((TGPGetMaxHeight() - height_range) / height_range, 0, 1) * amplitude;
303 * Check if a X/Y set are within the map.
304 * @param x coordinate x
305 * @param y coordinate y
306 * @return true if within the map
308 static inline bool IsValidXY(int x, int y)
310 return x >= 0 && x < _height_map.size_x && y >= 0 && y < _height_map.size_y;
315 * Allocate array of (MapSizeX()+1)*(MapSizeY()+1) heights and init the _height_map structure members
316 * @return true on success
318 static inline bool AllocHeightMap()
320 assert(_height_map.h.empty());
322 _height_map.size_x = Map::SizeX();
323 _height_map.size_y = Map::SizeY();
325 /* Allocate memory block for height map row pointers */
326 size_t total_size = static_cast<size_t>(_height_map.size_x + 1) * (_height_map.size_y + 1);
327 _height_map.dim_x = _height_map.size_x + 1;
328 _height_map.h.resize(total_size);
330 return true;
333 /** Free height map */
334 static inline void FreeHeightMap()
336 _height_map.h.clear();
340 * Generates new random height in given amplitude (generated numbers will range from - amplitude to + amplitude)
341 * @param rMax Limit of result
342 * @return generated height
344 static inline Height RandomHeight(Amplitude rMax)
346 /* Spread height into range -rMax..+rMax */
347 return A2H(RandomRange(2 * rMax + 1) - rMax);
351 * Base Perlin noise generator - fills height map with raw Perlin noise.
353 * This runs several iterations with increasing precision; the last iteration looks at areas
354 * of 1 by 1 tiles, the second to last at 2 by 2 tiles and the initial 2**MAX_TGP_FREQUENCIES
355 * by 2**MAX_TGP_FREQUENCIES tiles.
357 static void HeightMapGenerate()
359 /* Trying to apply noise to uninitialized height map */
360 assert(!_height_map.h.empty());
362 int start = std::max(MAX_TGP_FREQUENCIES - (int)std::min(Map::LogX(), Map::LogY()), 0);
363 bool first = true;
365 for (int frequency = start; frequency < MAX_TGP_FREQUENCIES; frequency++) {
366 const Amplitude amplitude = GetAmplitude(frequency);
368 /* Ignore zero amplitudes; it means our map isn't height enough for this
369 * amplitude, so ignore it and continue with the next set of amplitude. */
370 if (amplitude == 0) continue;
372 const int step = 1 << (MAX_TGP_FREQUENCIES - frequency - 1);
374 if (first) {
375 /* This is first round, we need to establish base heights with step = size_min */
376 for (int y = 0; y <= _height_map.size_y; y += step) {
377 for (int x = 0; x <= _height_map.size_x; x += step) {
378 Height height = (amplitude > 0) ? RandomHeight(amplitude) : 0;
379 _height_map.height(x, y) = height;
382 first = false;
383 continue;
386 /* It is regular iteration round.
387 * Interpolate height values at odd x, even y tiles */
388 for (int y = 0; y <= _height_map.size_y; y += 2 * step) {
389 for (int x = 0; x <= _height_map.size_x - 2 * step; x += 2 * step) {
390 Height h00 = _height_map.height(x + 0 * step, y);
391 Height h02 = _height_map.height(x + 2 * step, y);
392 Height h01 = (h00 + h02) / 2;
393 _height_map.height(x + 1 * step, y) = h01;
397 /* Interpolate height values at odd y tiles */
398 for (int y = 0; y <= _height_map.size_y - 2 * step; y += 2 * step) {
399 for (int x = 0; x <= _height_map.size_x; x += step) {
400 Height h00 = _height_map.height(x, y + 0 * step);
401 Height h20 = _height_map.height(x, y + 2 * step);
402 Height h10 = (h00 + h20) / 2;
403 _height_map.height(x, y + 1 * step) = h10;
407 /* Add noise for next higher frequency (smaller steps) */
408 for (int y = 0; y <= _height_map.size_y; y += step) {
409 for (int x = 0; x <= _height_map.size_x; x += step) {
410 _height_map.height(x, y) += RandomHeight(amplitude);
416 /** Returns min, max and average height from height map */
417 static void HeightMapGetMinMaxAvg(Height *min_ptr, Height *max_ptr, Height *avg_ptr)
419 Height h_min, h_max, h_avg;
420 int64_t h_accu = 0;
421 h_min = h_max = _height_map.height(0, 0);
423 /* Get h_min, h_max and accumulate heights into h_accu */
424 for (const Height &h : _height_map.h) {
425 if (h < h_min) h_min = h;
426 if (h > h_max) h_max = h;
427 h_accu += h;
430 /* Get average height */
431 h_avg = (Height)(h_accu / (_height_map.size_x * _height_map.size_y));
433 /* Return required results */
434 if (min_ptr != nullptr) *min_ptr = h_min;
435 if (max_ptr != nullptr) *max_ptr = h_max;
436 if (avg_ptr != nullptr) *avg_ptr = h_avg;
439 /** Dill histogram and return pointer to its base point - to the count of zero heights */
440 static int *HeightMapMakeHistogram(Height h_min, [[maybe_unused]] Height h_max, int *hist_buf)
442 int *hist = hist_buf - h_min;
444 /* Count the heights and fill the histogram */
445 for (const Height &h : _height_map.h) {
446 assert(h >= h_min);
447 assert(h <= h_max);
448 hist[h]++;
450 return hist;
453 /** Applies sine wave redistribution onto height map */
454 static void HeightMapSineTransform(Height h_min, Height h_max)
456 for (Height &h : _height_map.h) {
457 double fheight;
459 if (h < h_min) continue;
461 /* Transform height into 0..1 space */
462 fheight = (double)(h - h_min) / (double)(h_max - h_min);
463 /* Apply sine transform depending on landscape type */
464 switch (_settings_game.game_creation.landscape) {
465 case LT_TOYLAND:
466 case LT_TEMPERATE:
467 /* Move and scale 0..1 into -1..+1 */
468 fheight = 2 * fheight - 1;
469 /* Sine transform */
470 fheight = sin(fheight * M_PI_2);
471 /* Transform it back from -1..1 into 0..1 space */
472 fheight = 0.5 * (fheight + 1);
473 break;
475 case LT_ARCTIC:
477 /* Arctic terrain needs special height distribution.
478 * Redistribute heights to have more tiles at highest (75%..100%) range */
479 double sine_upper_limit = 0.75;
480 double linear_compression = 2;
481 if (fheight >= sine_upper_limit) {
482 /* Over the limit we do linear compression up */
483 fheight = 1.0 - (1.0 - fheight) / linear_compression;
484 } else {
485 double m = 1.0 - (1.0 - sine_upper_limit) / linear_compression;
486 /* Get 0..sine_upper_limit into -1..1 */
487 fheight = 2.0 * fheight / sine_upper_limit - 1.0;
488 /* Sine wave transform */
489 fheight = sin(fheight * M_PI_2);
490 /* Get -1..1 back to 0..(1 - (1 - sine_upper_limit) / linear_compression) == 0.0..m */
491 fheight = 0.5 * (fheight + 1.0) * m;
494 break;
496 case LT_TROPIC:
498 /* Desert terrain needs special height distribution.
499 * Half of tiles should be at lowest (0..25%) heights */
500 double sine_lower_limit = 0.5;
501 double linear_compression = 2;
502 if (fheight <= sine_lower_limit) {
503 /* Under the limit we do linear compression down */
504 fheight = fheight / linear_compression;
505 } else {
506 double m = sine_lower_limit / linear_compression;
507 /* Get sine_lower_limit..1 into -1..1 */
508 fheight = 2.0 * ((fheight - sine_lower_limit) / (1.0 - sine_lower_limit)) - 1.0;
509 /* Sine wave transform */
510 fheight = sin(fheight * M_PI_2);
511 /* Get -1..1 back to (sine_lower_limit / linear_compression)..1.0 */
512 fheight = 0.5 * ((1.0 - m) * fheight + (1.0 + m));
515 break;
517 default:
518 NOT_REACHED();
519 break;
521 /* Transform it back into h_min..h_max space */
522 h = (Height)(fheight * (h_max - h_min) + h_min);
523 if (h < 0) h = I2H(0);
524 if (h >= h_max) h = h_max - 1;
529 * Additional map variety is provided by applying different curve maps
530 * to different parts of the map. A randomized low resolution grid contains
531 * which curve map to use on each part of the make. This filtered non-linearly
532 * to smooth out transitions between curves, so each tile could have between
533 * 100% of one map applied or 25% of four maps.
535 * The curve maps define different land styles, i.e. lakes, low-lands, hills
536 * and mountain ranges, although these are dependent on the landscape style
537 * chosen as well.
539 * The level parameter dictates the resolution of the grid. A low resolution
540 * grid will result in larger continuous areas of a land style, a higher
541 * resolution grid splits the style into smaller areas.
542 * @param level Rough indication of the size of the grid sections to style. Small level means large grid sections.
544 static void HeightMapCurves(uint level)
546 Height mh = TGPGetMaxHeight() - I2H(1); // height levels above sea level only
548 /** Basically scale height X to height Y. Everything in between is interpolated. */
549 struct ControlPoint {
550 Height x; ///< The height to scale from.
551 Height y; ///< The height to scale to.
553 /* Scaled curve maps; value is in height_ts. */
554 #define F(fraction) ((Height)(fraction * mh))
555 const ControlPoint curve_map_1[] = { { F(0.0), F(0.0) }, { F(0.8), F(0.13) }, { F(1.0), F(0.4) } };
556 const ControlPoint curve_map_2[] = { { F(0.0), F(0.0) }, { F(0.53), F(0.13) }, { F(0.8), F(0.27) }, { F(1.0), F(0.6) } };
557 const ControlPoint curve_map_3[] = { { F(0.0), F(0.0) }, { F(0.53), F(0.27) }, { F(0.8), F(0.57) }, { F(1.0), F(0.8) } };
558 const ControlPoint curve_map_4[] = { { F(0.0), F(0.0) }, { F(0.4), F(0.3) }, { F(0.7), F(0.8) }, { F(0.92), F(0.99) }, { F(1.0), F(0.99) } };
559 #undef F
561 const std::span<const ControlPoint> curve_maps[] = { curve_map_1, curve_map_2, curve_map_3, curve_map_4 };
563 std::array<Height, std::size(curve_maps)> ht{};
565 /* Set up a grid to choose curve maps based on location; attempt to get a somewhat square grid */
566 float factor = sqrt((float)_height_map.size_x / (float)_height_map.size_y);
567 uint sx = Clamp((int)(((1 << level) * factor) + 0.5), 1, 128);
568 uint sy = Clamp((int)(((1 << level) / factor) + 0.5), 1, 128);
569 std::vector<uint8_t> c(static_cast<size_t>(sx) * sy);
571 for (uint i = 0; i < sx * sy; i++) {
572 c[i] = RandomRange(static_cast<uint32_t>(std::size(curve_maps)));
575 /* Apply curves */
576 for (int x = 0; x < _height_map.size_x; x++) {
578 /* Get our X grid positions and bi-linear ratio */
579 float fx = (float)(sx * x) / _height_map.size_x + 1.0f;
580 uint x1 = (uint)fx;
581 uint x2 = x1;
582 float xr = 2.0f * (fx - x1) - 1.0f;
583 xr = sin(xr * M_PI_2);
584 xr = sin(xr * M_PI_2);
585 xr = 0.5f * (xr + 1.0f);
586 float xri = 1.0f - xr;
588 if (x1 > 0) {
589 x1--;
590 if (x2 >= sx) x2--;
593 for (int y = 0; y < _height_map.size_y; y++) {
595 /* Get our Y grid position and bi-linear ratio */
596 float fy = (float)(sy * y) / _height_map.size_y + 1.0f;
597 uint y1 = (uint)fy;
598 uint y2 = y1;
599 float yr = 2.0f * (fy - y1) - 1.0f;
600 yr = sin(yr * M_PI_2);
601 yr = sin(yr * M_PI_2);
602 yr = 0.5f * (yr + 1.0f);
603 float yri = 1.0f - yr;
605 if (y1 > 0) {
606 y1--;
607 if (y2 >= sy) y2--;
610 uint corner_a = c[x1 + sx * y1];
611 uint corner_b = c[x1 + sx * y2];
612 uint corner_c = c[x2 + sx * y1];
613 uint corner_d = c[x2 + sx * y2];
615 /* Bitmask of which curve maps are chosen, so that we do not bother
616 * calculating a curve which won't be used. */
617 uint corner_bits = 0;
618 corner_bits |= 1 << corner_a;
619 corner_bits |= 1 << corner_b;
620 corner_bits |= 1 << corner_c;
621 corner_bits |= 1 << corner_d;
623 Height *h = &_height_map.height(x, y);
625 /* Do not touch sea level */
626 if (*h < I2H(1)) continue;
628 /* Only scale above sea level */
629 *h -= I2H(1);
631 /* Apply all curve maps that are used on this tile. */
632 for (size_t t = 0; t < std::size(curve_maps); t++) {
633 if (!HasBit(corner_bits, static_cast<uint8_t>(t))) continue;
635 [[maybe_unused]] bool found = false;
636 auto &cm = curve_maps[t];
637 for (size_t i = 0; i < cm.size() - 1; i++) {
638 const ControlPoint &p1 = cm[i];
639 const ControlPoint &p2 = cm[i + 1];
641 if (*h >= p1.x && *h < p2.x) {
642 ht[t] = p1.y + (*h - p1.x) * (p2.y - p1.y) / (p2.x - p1.x);
643 #ifdef WITH_ASSERT
644 found = true;
645 #endif
646 break;
649 assert(found);
652 /* Apply interpolation of curve map results. */
653 *h = (Height)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr);
655 /* Readd sea level */
656 *h += I2H(1);
661 /** Adjusts heights in height map to contain required amount of water tiles */
662 static void HeightMapAdjustWaterLevel(Amplitude water_percent, Height h_max_new)
664 Height h_min, h_max, h_avg, h_water_level;
665 int64_t water_tiles, desired_water_tiles;
666 int *hist;
668 HeightMapGetMinMaxAvg(&h_min, &h_max, &h_avg);
670 /* Allocate histogram buffer and clear its cells */
671 std::vector<int> hist_buf(h_max - h_min + 1);
672 /* Fill histogram */
673 hist = HeightMapMakeHistogram(h_min, h_max, hist_buf.data());
675 /* How many water tiles do we want? */
676 desired_water_tiles = A2I(((int64_t)water_percent) * (int64_t)(_height_map.size_x * _height_map.size_y));
678 /* Raise water_level and accumulate values from histogram until we reach required number of water tiles */
679 for (h_water_level = h_min, water_tiles = 0; h_water_level < h_max; h_water_level++) {
680 water_tiles += hist[h_water_level];
681 if (water_tiles >= desired_water_tiles) break;
684 /* We now have the proper water level value.
685 * Transform the height map into new (normalized) height map:
686 * values from range: h_min..h_water_level will become negative so it will be clamped to 0
687 * values from range: h_water_level..h_max are transformed into 0..h_max_new
688 * where h_max_new is depending on terrain type and map size.
690 for (Height &h : _height_map.h) {
691 /* Transform height from range h_water_level..h_max into 0..h_max_new range */
692 h = (Height)(((int)h_max_new) * (h - h_water_level) / (h_max - h_water_level)) + I2H(1);
693 /* Make sure all values are in the proper range (0..h_max_new) */
694 if (h < 0) h = I2H(0);
695 if (h >= h_max_new) h = h_max_new - 1;
699 static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime);
702 * This routine sculpts in from the edge a random amount, again a Perlin
703 * sequence, to avoid the rigid flat-edge slopes that were present before. The
704 * Perlin noise map doesn't know where we are going to slice across, and so we
705 * often cut straight through high terrain. The smoothing routine makes it
706 * legal, gradually increasing up from the edge to the original terrain height.
707 * By cutting parts of this away, it gives a far more irregular edge to the
708 * map-edge. Sometimes it works beautifully with the existing sea & lakes, and
709 * creates a very realistic coastline. Other times the variation is less, and
710 * the map-edge shows its cliff-like roots.
712 * This routine may be extended to randomly sculpt the height of the terrain
713 * near the edge. This will have the coast edge at low level (1-3), rising in
714 * smoothed steps inland to about 15 tiles in. This should make it look as
715 * though the map has been built for the map size, rather than a slice through
716 * a larger map.
718 * Please note that all the small numbers; 53, 101, 167, etc. are small primes
719 * to help give the perlin noise a bit more of a random feel.
721 static void HeightMapCoastLines(uint8_t water_borders)
723 int smallest_size = std::min(_settings_game.game_creation.map_x, _settings_game.game_creation.map_y);
724 const int margin = 4;
725 int y, x;
726 double max_x;
727 double max_y;
729 /* Lower to sea level */
730 for (y = 0; y <= _height_map.size_y; y++) {
731 if (HasBit(water_borders, BORDER_NE)) {
732 /* Top right */
733 max_x = abs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.9, 53) + 0.25) * 5 + (perlin_coast_noise_2D(y, y, 0.35, 179) + 1) * 12);
734 max_x = std::max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
735 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
736 for (x = 0; x < max_x; x++) {
737 _height_map.height(x, y) = 0;
741 if (HasBit(water_borders, BORDER_SW)) {
742 /* Bottom left */
743 max_x = abs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.85, 101) + 0.3) * 6 + (perlin_coast_noise_2D(y, y, 0.45, 67) + 0.75) * 8);
744 max_x = std::max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
745 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
746 for (x = _height_map.size_x; x > (_height_map.size_x - 1 - max_x); x--) {
747 _height_map.height(x, y) = 0;
752 /* Lower to sea level */
753 for (x = 0; x <= _height_map.size_x; x++) {
754 if (HasBit(water_borders, BORDER_NW)) {
755 /* Top left */
756 max_y = abs((perlin_coast_noise_2D(x, _height_map.size_y / 2, 0.9, 167) + 0.4) * 5 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.4, 211) + 0.7) * 9);
757 max_y = std::max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
758 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
759 for (y = 0; y < max_y; y++) {
760 _height_map.height(x, y) = 0;
764 if (HasBit(water_borders, BORDER_SE)) {
765 /* Bottom right */
766 max_y = abs((perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.85, 71) + 0.25) * 6 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.35, 193) + 0.75) * 12);
767 max_y = std::max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
768 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
769 for (y = _height_map.size_y; y > (_height_map.size_y - 1 - max_y); y--) {
770 _height_map.height(x, y) = 0;
776 /** Start at given point, move in given direction, find and Smooth coast in that direction */
777 static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int dir_y)
779 const int max_coast_dist_from_edge = 35;
780 const int max_coast_Smooth_depth = 35;
782 int x, y;
783 int ed; // coast distance from edge
784 int depth;
786 Height h_prev = I2H(1);
787 Height h;
789 assert(IsValidXY(org_x, org_y));
791 /* Search for the coast (first non-water tile) */
792 for (x = org_x, y = org_y, ed = 0; IsValidXY(x, y) && ed < max_coast_dist_from_edge; x += dir_x, y += dir_y, ed++) {
793 /* Coast found? */
794 if (_height_map.height(x, y) >= I2H(1)) break;
796 /* Coast found in the neighborhood? */
797 if (IsValidXY(x + dir_y, y + dir_x) && _height_map.height(x + dir_y, y + dir_x) > 0) break;
799 /* Coast found in the neighborhood on the other side */
800 if (IsValidXY(x - dir_y, y - dir_x) && _height_map.height(x - dir_y, y - dir_x) > 0) break;
803 /* Coast found or max_coast_dist_from_edge has been reached.
804 * Soften the coast slope */
805 for (depth = 0; IsValidXY(x, y) && depth <= max_coast_Smooth_depth; depth++, x += dir_x, y += dir_y) {
806 h = _height_map.height(x, y);
807 h = static_cast<Height>(std::min<uint>(h, h_prev + (4 + depth))); // coast softening formula
808 _height_map.height(x, y) = h;
809 h_prev = h;
813 /** Smooth coasts by modulating height of tiles close to map edges with cosine of distance from edge */
814 static void HeightMapSmoothCoasts(uint8_t water_borders)
816 int x, y;
817 /* First Smooth NW and SE coasts (y close to 0 and y close to size_y) */
818 for (x = 0; x < _height_map.size_x; x++) {
819 if (HasBit(water_borders, BORDER_NW)) HeightMapSmoothCoastInDirection(x, 0, 0, 1);
820 if (HasBit(water_borders, BORDER_SE)) HeightMapSmoothCoastInDirection(x, _height_map.size_y - 1, 0, -1);
822 /* First Smooth NE and SW coasts (x close to 0 and x close to size_x) */
823 for (y = 0; y < _height_map.size_y; y++) {
824 if (HasBit(water_borders, BORDER_NE)) HeightMapSmoothCoastInDirection(0, y, 1, 0);
825 if (HasBit(water_borders, BORDER_SW)) HeightMapSmoothCoastInDirection(_height_map.size_x - 1, y, -1, 0);
830 * This routine provides the essential cleanup necessary before OTTD can
831 * display the terrain. When generated, the terrain heights can jump more than
832 * one level between tiles. This routine smooths out those differences so that
833 * the most it can change is one level. When OTTD can support cliffs, this
834 * routine may not be necessary.
836 static void HeightMapSmoothSlopes(Height dh_max)
838 for (int y = 0; y <= (int)_height_map.size_y; y++) {
839 for (int x = 0; x <= (int)_height_map.size_x; x++) {
840 Height h_max = std::min(_height_map.height(x > 0 ? x - 1 : x, y), _height_map.height(x, y > 0 ? y - 1 : y)) + dh_max;
841 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
844 for (int y = _height_map.size_y; y >= 0; y--) {
845 for (int x = _height_map.size_x; x >= 0; x--) {
846 Height h_max = std::min(_height_map.height(x < _height_map.size_x ? x + 1 : x, y), _height_map.height(x, y < _height_map.size_y ? y + 1 : y)) + dh_max;
847 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
853 * Height map terraform post processing:
854 * - water level adjusting
855 * - coast Smoothing
856 * - slope Smoothing
857 * - height histogram redistribution by sine wave transform
859 static void HeightMapNormalize()
861 int sea_level_setting = _settings_game.difficulty.quantity_sea_lakes;
862 const Amplitude water_percent = sea_level_setting != (int)CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY ? _water_percent[sea_level_setting] : _settings_game.game_creation.custom_sea_level * 1024 / 100;
863 const Height h_max_new = TGPGetMaxHeight();
864 const Height roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness;
866 HeightMapAdjustWaterLevel(water_percent, h_max_new);
868 uint8_t water_borders = _settings_game.construction.freeform_edges ? _settings_game.game_creation.water_borders : 0xF;
869 if (water_borders == BORDERS_RANDOM) water_borders = GB(Random(), 0, 4);
871 HeightMapCoastLines(water_borders);
872 HeightMapSmoothSlopes(roughness);
874 HeightMapSmoothCoasts(water_borders);
875 HeightMapSmoothSlopes(roughness);
877 HeightMapSineTransform(I2H(1), h_max_new);
879 if (_settings_game.game_creation.variety > 0) {
880 HeightMapCurves(_settings_game.game_creation.variety);
883 HeightMapSmoothSlopes(I2H(1));
887 * The Perlin Noise calculation using large primes
888 * The initial number is adjusted by two values; the generation_seed, and the
889 * passed parameter; prime.
890 * prime is used to allow the perlin noise generator to create useful random
891 * numbers from slightly different series.
893 static double int_noise(const long x, const long y, const int prime)
895 long n = x + y * prime + _settings_game.game_creation.generation_seed;
897 n = (n << 13) ^ n;
899 /* Pseudo-random number generator, using several large primes */
900 return 1.0 - (double)((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0;
905 * This routine determines the interpolated value between a and b
907 static inline double linear_interpolate(const double a, const double b, const double x)
909 return a + x * (b - a);
914 * This routine returns the smoothed interpolated noise for an x and y, using
915 * the values from the surrounding positions.
917 static double interpolated_noise(const double x, const double y, const int prime)
919 const int integer_X = (int)x;
920 const int integer_Y = (int)y;
922 const double fractional_X = x - (double)integer_X;
923 const double fractional_Y = y - (double)integer_Y;
925 const double v1 = int_noise(integer_X, integer_Y, prime);
926 const double v2 = int_noise(integer_X + 1, integer_Y, prime);
927 const double v3 = int_noise(integer_X, integer_Y + 1, prime);
928 const double v4 = int_noise(integer_X + 1, integer_Y + 1, prime);
930 const double i1 = linear_interpolate(v1, v2, fractional_X);
931 const double i2 = linear_interpolate(v3, v4, fractional_X);
933 return linear_interpolate(i1, i2, fractional_Y);
938 * This is a similar function to the main perlin noise calculation, but uses
939 * the value p passed as a parameter rather than selected from the predefined
940 * sequences. as you can guess by its title, i use this to create the indented
941 * coastline, which is just another perlin sequence.
943 static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime)
945 double total = 0.0;
947 for (int i = 0; i < 6; i++) {
948 const double frequency = (double)(1 << i);
949 const double amplitude = pow(p, (double)i);
951 total += interpolated_noise((x * frequency) / 64.0, (y * frequency) / 64.0, prime) * amplitude;
954 return total;
958 /** A small helper function to initialize the terrain */
959 static void TgenSetTileHeight(TileIndex tile, int height)
961 SetTileHeight(tile, height);
963 /* Only clear the tiles within the map area. */
964 if (IsInnerTile(tile)) {
965 MakeClear(tile, CLEAR_GRASS, 3);
970 * The main new land generator using Perlin noise. Desert landscape is handled
971 * different to all others to give a desert valley between two high mountains.
972 * Clearly if a low height terrain (flat/very flat) is chosen, then the tropic
973 * areas won't be high enough, and there will be very little tropic on the map.
974 * Thus Tropic works best on Hilly or Mountainous.
976 void GenerateTerrainPerlin()
978 if (!AllocHeightMap()) return;
979 GenerateWorldSetAbortCallback(FreeHeightMap);
981 HeightMapGenerate();
983 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
985 HeightMapNormalize();
987 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
989 /* First make sure the tiles at the north border are void tiles if needed. */
990 if (_settings_game.construction.freeform_edges) {
991 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, 0));
992 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(0, y));
995 int max_height = H2I(TGPGetMaxHeight());
997 /* Transfer height map into OTTD map */
998 for (int y = 0; y < _height_map.size_y; y++) {
999 for (int x = 0; x < _height_map.size_x; x++) {
1000 TgenSetTileHeight(TileXY(x, y), Clamp(H2I(_height_map.height(x, y)), 0, max_height));
1004 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
1006 FreeHeightMap();
1007 GenerateWorldSetAbortCallback(nullptr);