Doc: Clarify comment that SND_05_TRAIN_THROUGH_TUNNEL is only for steam engines ...
[openttd-github.git] / src / tgp.cpp
blob190499cbc1c2eb7f8df90fdbda44c7ecfee36d31
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 <math.h>
12 #include "clear_map.h"
13 #include "void_map.h"
14 #include "genworld.h"
15 #include "core/random_func.hpp"
16 #include "landscape_type.h"
18 #include "safeguards.h"
22 * Quickie guide to Perlin Noise
23 * Perlin noise is a predictable pseudo random number sequence. By generating
24 * it in 2 dimensions, it becomes a useful random map that, for a given seed
25 * and starting X & Y, is entirely predictable. On the face of it, that may not
26 * be useful. However, it means that if you want to replay a map in a different
27 * terrain, or just vary the sea level, you just re-run the generator with the
28 * same seed. The seed is an int32, and is randomised on each run of New Game.
29 * The Scenario Generator does not randomise the value, so that you can
30 * experiment with one terrain until you are happy, or click "Random" for a new
31 * random seed.
33 * Perlin Noise is a series of "octaves" of random noise added together. By
34 * reducing the amplitude of the noise with each octave, the first octave of
35 * noise defines the main terrain sweep, the next the ripples on that, and the
36 * next the ripples on that. I use 6 octaves, with the amplitude controlled by
37 * a power ratio, usually known as a persistence or p value. This I vary by the
38 * smoothness selection, as can be seen in the table below. The closer to 1,
39 * the more of that octave is added. Each octave is however raised to the power
40 * of its position in the list, so the last entry in the "smooth" row, 0.35, is
41 * raised to the power of 6, so can only add 0.001838... of the amplitude to
42 * the running total.
44 * In other words; the first p value sets the general shape of the terrain, the
45 * second sets the major variations to that, ... until finally the smallest
46 * bumps are added.
48 * Usefully, this routine is totally scalable; so when 32bpp comes along, the
49 * terrain can be as bumpy as you like! It is also infinitely expandable; a
50 * single random seed terrain continues in X & Y as far as you care to
51 * calculate. In theory, we could use just one seed value, but randomly select
52 * where in the Perlin XY space we use for the terrain. Personally I prefer
53 * using a simple (0, 0) to (X, Y), with a varying seed.
56 * Other things i have had to do: mountainous wasn't mountainous enough, and
57 * since we only have 0..15 heights available, I add a second generated map
58 * (with a modified seed), onto the original. This generally raises the
59 * terrain, which then needs scaling back down. Overall effect is a general
60 * uplift.
62 * However, the values on the top of mountains are then almost guaranteed to go
63 * too high, so large flat plateaus appeared at height 15. To counter this, I
64 * scale all heights above 12 to proportion up to 15. It still makes the
65 * mountains have flattish tops, rather than craggy peaks, but at least they
66 * aren't smooth as glass.
69 * For a full discussion of Perlin Noise, please visit:
70 * http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
73 * Evolution II
75 * The algorithm as described in the above link suggests to compute each tile height
76 * as composition of several noise waves. Some of them are computed directly by
77 * noise(x, y) function, some are calculated using linear approximation. Our
78 * first implementation of perlin_noise_2D() used 4 noise(x, y) calls plus
79 * 3 linear interpolations. It was called 6 times for each tile. This was a bit
80 * CPU expensive.
82 * The following implementation uses optimized algorithm that should produce
83 * the same quality result with much less computations, but more memory accesses.
84 * The overall speedup should be 300% to 800% depending on CPU and memory speed.
86 * I will try to explain it on the example below:
88 * Have a map of 4 x 4 tiles, our simplified noise generator produces only two
89 * values -1 and +1, use 3 octaves with wave length 1, 2 and 4, with amplitudes
90 * 3, 2, 1. Original algorithm produces:
92 * 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
93 * 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
94 * 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
95 * 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
97 * 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
98 * 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
99 * 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
100 * 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
103 * Optimization 1:
105 * 1) we need to allocate a bit more tiles: (size_x + 1) * (size_y + 1) = (5 * 5):
107 * 2) setup corner values using amplitude 3
108 * { -3.0 X X X 3.0 }
109 * { X X X X X }
110 * { X X X X X }
111 * { X X X X X }
112 * { 3.0 X X X -3.0 }
114 * 3a) interpolate values in the middle
115 * { -3.0 X 0.0 X 3.0 }
116 * { X X X X X }
117 * { 0.0 X 0.0 X 0.0 }
118 * { X X X X X }
119 * { 3.0 X 0.0 X -3.0 }
121 * 3b) add patches with amplitude 2 to them
122 * { -5.0 X 2.0 X 1.0 }
123 * { X X X X X }
124 * { 2.0 X -2.0 X 2.0 }
125 * { X X X X X }
126 * { 1.0 X 2.0 X -5.0 }
128 * 4a) interpolate values in the middle
129 * { -5.0 -1.5 2.0 1.5 1.0 }
130 * { -1.5 -0.75 0.0 0.75 1.5 }
131 * { 2.0 0.0 -2.0 0.0 2.0 }
132 * { 1.5 0.75 0.0 -0.75 -1.5 }
133 * { 1.0 1.5 2.0 -1.5 -5.0 }
135 * 4b) add patches with amplitude 1 to them
136 * { -6.0 -0.5 1.0 2.5 0.0 }
137 * { -0.5 -1.75 1.0 -0.25 2.5 }
138 * { 1.0 1.0 -3.0 1.0 1.0 }
139 * { 2.5 -0.25 1.0 -1.75 -0.5 }
140 * { 0.0 2.5 1.0 -0.5 -6.0 }
144 * Optimization 2:
146 * As you can see above, each noise function was called just once. Therefore
147 * we don't need to use noise function that calculates the noise from x, y and
148 * some prime. The same quality result we can obtain using standard Random()
149 * function instead.
153 /** Fixed point type for heights */
154 typedef int16 height_t;
155 static const int height_decimal_bits = 4;
157 /** Fixed point array for amplitudes (and percent values) */
158 typedef int amplitude_t;
159 static const int amplitude_decimal_bits = 10;
161 /** Height map - allocated array of heights (MapSizeX() + 1) x (MapSizeY() + 1) */
162 struct HeightMap
164 height_t *h; //< array of heights
165 /* Even though the sizes are always positive, there are many cases where
166 * X and Y need to be signed integers due to subtractions. */
167 int dim_x; //< height map size_x MapSizeX() + 1
168 int total_size; //< height map total size
169 int size_x; //< MapSizeX()
170 int size_y; //< MapSizeY()
173 * Height map accessor
174 * @param x X position
175 * @param y Y position
176 * @return height as fixed point number
178 inline height_t &height(uint x, uint y)
180 return h[x + y * dim_x];
184 /** Global height map instance */
185 static HeightMap _height_map = {nullptr, 0, 0, 0, 0};
187 /** Conversion: int to height_t */
188 #define I2H(i) ((i) << height_decimal_bits)
189 /** Conversion: height_t to int */
190 #define H2I(i) ((i) >> height_decimal_bits)
192 /** Conversion: int to amplitude_t */
193 #define I2A(i) ((i) << amplitude_decimal_bits)
194 /** Conversion: amplitude_t to int */
195 #define A2I(i) ((i) >> amplitude_decimal_bits)
197 /** Conversion: amplitude_t to height_t */
198 #define A2H(a) ((a) >> (amplitude_decimal_bits - height_decimal_bits))
201 /** Walk through all items of _height_map.h */
202 #define FOR_ALL_TILES_IN_HEIGHT(h) for (h = _height_map.h; h < &_height_map.h[_height_map.total_size]; h++)
204 /** Maximum number of TGP noise frequencies. */
205 static const int MAX_TGP_FREQUENCIES = 10;
207 /** Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes */
208 static const amplitude_t _water_percent[4] = {70, 170, 270, 420};
211 * Gets the maximum allowed height while generating a map based on
212 * mapsize, terraintype, and the maximum height level.
213 * @return The maximum height for the map generation.
214 * @note Values should never be lower than 3 since the minimum snowline height is 2.
216 static height_t TGPGetMaxHeight()
219 * Desired maximum height - indexed by:
220 * - _settings_game.difficulty.terrain_type
221 * - min(MapLogX(), MapLogY()) - MIN_MAP_SIZE_BITS
223 * It is indexed by map size as well as terrain type since the map size limits the height of
224 * a usable mountain. For example, on a 64x64 map a 24 high single peak mountain (as if you
225 * raised land 24 times in the center of the map) will leave only a ring of about 10 tiles
226 * around the mountain to build on. On a 4096x4096 map, it won't cover any major part of the map.
228 static const int max_height[5][MAX_MAP_SIZE_BITS - MIN_MAP_SIZE_BITS + 1] = {
229 /* 64 128 256 512 1024 2048 4096 */
230 { 3, 3, 3, 3, 4, 5, 7 }, ///< Very flat
231 { 5, 7, 8, 9, 14, 19, 31 }, ///< Flat
232 { 8, 9, 10, 15, 23, 37, 61 }, ///< Hilly
233 { 10, 11, 17, 19, 49, 63, 73 }, ///< Mountainous
234 { 12, 19, 25, 31, 67, 75, 87 }, ///< Alpinist
237 int map_size_bucket = std::min(MapLogX(), MapLogY()) - MIN_MAP_SIZE_BITS;
238 int max_height_from_table = max_height[_settings_game.difficulty.terrain_type][map_size_bucket];
240 /* Arctic needs snow to have all industries, so make sure we allow TGP to generate this high. */
241 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
242 max_height_from_table += _settings_newgame.game_creation.snow_line_height;
243 /* Make flat a bit more flat by removing "very flat" from it, to somewhat compensate for the increase we just did. */
244 if (_settings_game.difficulty.terrain_type > 0) {
245 max_height_from_table -= max_height[_settings_game.difficulty.terrain_type - 1][map_size_bucket];
248 /* Tropic needs tropical forest to have all industries, so make sure we allow TGP to generate this high.
249 * Tropic forest always starts at 1/4th of the max height. */
250 if (_settings_game.game_creation.landscape == LT_TROPIC) {
251 max_height_from_table += CeilDiv(_settings_game.construction.max_heightlevel, 4);
252 /* Make flat a bit more flat by removing "very flat" from it, to somewhat compensate for the increase we just did. */
253 if (_settings_game.difficulty.terrain_type > 0) {
254 max_height_from_table -= max_height[_settings_game.difficulty.terrain_type - 1][map_size_bucket];
258 return I2H(std::min<uint>(max_height_from_table, _settings_game.construction.max_heightlevel));
262 * Get the amplitude associated with the currently selected
263 * smoothness and maximum height level.
264 * @param frequency The frequency to get the amplitudes for
265 * @return The amplitudes to apply to the map.
267 static amplitude_t GetAmplitude(int frequency)
269 /* Base noise amplitudes (multiplied by 1024) and indexed by "smoothness setting" and log2(frequency). */
270 static const amplitude_t amplitudes[][7] = {
271 /* lowest frequency ...... highest (every corner) */
272 {16000, 5600, 1968, 688, 240, 16, 16}, ///< Very smooth
273 {24000, 12800, 6400, 2700, 1024, 128, 16}, ///< Smooth
274 {32000, 19200, 12800, 8000, 3200, 256, 64}, ///< Rough
275 {48000, 24000, 19200, 16000, 8000, 512, 320}, ///< Very rough
278 * Extrapolation factors for ranges before the table.
279 * The extrapolation is needed to account for the higher map heights. They need larger
280 * areas with a particular gradient so that we are able to create maps without too
281 * many steep slopes up to the wanted height level. It's definitely not perfect since
282 * it will bring larger rectangles with similar slopes which makes the rectangular
283 * behaviour of TGP more noticeable. However, these height differentiations cannot
284 * happen over much smaller areas; we basically double the "range" to give a similar
285 * slope for every doubling of map height.
287 static const double extrapolation_factors[] = { 3.3, 2.8, 2.3, 1.8 };
289 int smoothness = _settings_game.game_creation.tgen_smoothness;
291 /* Get the table index, and return that value if possible. */
292 int index = frequency - MAX_TGP_FREQUENCIES + lengthof(amplitudes[smoothness]);
293 amplitude_t amplitude = amplitudes[smoothness][std::max(0, index)];
294 if (index >= 0) return amplitude;
296 /* We need to extrapolate the amplitude. */
297 double extrapolation_factor = extrapolation_factors[smoothness];
298 int height_range = I2H(16);
299 do {
300 amplitude = (amplitude_t)(extrapolation_factor * (double)amplitude);
301 height_range <<= 1;
302 index++;
303 } while (index < 0);
305 return Clamp((TGPGetMaxHeight() - height_range) / height_range, 0, 1) * amplitude;
309 * Check if a X/Y set are within the map.
310 * @param x coordinate x
311 * @param y coordinate y
312 * @return true if within the map
314 static inline bool IsValidXY(int x, int y)
316 return x >= 0 && x < _height_map.size_x && y >= 0 && y < _height_map.size_y;
321 * Allocate array of (MapSizeX()+1)*(MapSizeY()+1) heights and init the _height_map structure members
322 * @return true on success
324 static inline bool AllocHeightMap()
326 height_t *h;
328 _height_map.size_x = MapSizeX();
329 _height_map.size_y = MapSizeY();
331 /* Allocate memory block for height map row pointers */
332 _height_map.total_size = (_height_map.size_x + 1) * (_height_map.size_y + 1);
333 _height_map.dim_x = _height_map.size_x + 1;
334 _height_map.h = CallocT<height_t>(_height_map.total_size);
336 /* Iterate through height map and initialise values. */
337 FOR_ALL_TILES_IN_HEIGHT(h) *h = 0;
339 return true;
342 /** Free height map */
343 static inline void FreeHeightMap()
345 free(_height_map.h);
346 _height_map.h = nullptr;
350 * Generates new random height in given amplitude (generated numbers will range from - amplitude to + amplitude)
351 * @param rMax Limit of result
352 * @return generated height
354 static inline height_t RandomHeight(amplitude_t rMax)
356 /* Spread height into range -rMax..+rMax */
357 return A2H(RandomRange(2 * rMax + 1) - rMax);
361 * Base Perlin noise generator - fills height map with raw Perlin noise.
363 * This runs several iterations with increasing precision; the last iteration looks at areas
364 * of 1 by 1 tiles, the second to last at 2 by 2 tiles and the initial 2**MAX_TGP_FREQUENCIES
365 * by 2**MAX_TGP_FREQUENCIES tiles.
367 static void HeightMapGenerate()
369 /* Trying to apply noise to uninitialized height map */
370 assert(_height_map.h != nullptr);
372 int start = std::max(MAX_TGP_FREQUENCIES - (int)std::min(MapLogX(), MapLogY()), 0);
373 bool first = true;
375 for (int frequency = start; frequency < MAX_TGP_FREQUENCIES; frequency++) {
376 const amplitude_t amplitude = GetAmplitude(frequency);
378 /* Ignore zero amplitudes; it means our map isn't height enough for this
379 * amplitude, so ignore it and continue with the next set of amplitude. */
380 if (amplitude == 0) continue;
382 const int step = 1 << (MAX_TGP_FREQUENCIES - frequency - 1);
384 if (first) {
385 /* This is first round, we need to establish base heights with step = size_min */
386 for (int y = 0; y <= _height_map.size_y; y += step) {
387 for (int x = 0; x <= _height_map.size_x; x += step) {
388 height_t height = (amplitude > 0) ? RandomHeight(amplitude) : 0;
389 _height_map.height(x, y) = height;
392 first = false;
393 continue;
396 /* It is regular iteration round.
397 * Interpolate height values at odd x, even y tiles */
398 for (int y = 0; y <= _height_map.size_y; y += 2 * step) {
399 for (int x = 0; x <= _height_map.size_x - 2 * step; x += 2 * step) {
400 height_t h00 = _height_map.height(x + 0 * step, y);
401 height_t h02 = _height_map.height(x + 2 * step, y);
402 height_t h01 = (h00 + h02) / 2;
403 _height_map.height(x + 1 * step, y) = h01;
407 /* Interpolate height values at odd y tiles */
408 for (int y = 0; y <= _height_map.size_y - 2 * step; y += 2 * step) {
409 for (int x = 0; x <= _height_map.size_x; x += step) {
410 height_t h00 = _height_map.height(x, y + 0 * step);
411 height_t h20 = _height_map.height(x, y + 2 * step);
412 height_t h10 = (h00 + h20) / 2;
413 _height_map.height(x, y + 1 * step) = h10;
417 /* Add noise for next higher frequency (smaller steps) */
418 for (int y = 0; y <= _height_map.size_y; y += step) {
419 for (int x = 0; x <= _height_map.size_x; x += step) {
420 _height_map.height(x, y) += RandomHeight(amplitude);
426 /** Returns min, max and average height from height map */
427 static void HeightMapGetMinMaxAvg(height_t *min_ptr, height_t *max_ptr, height_t *avg_ptr)
429 height_t h_min, h_max, h_avg, *h;
430 int64 h_accu = 0;
431 h_min = h_max = _height_map.height(0, 0);
433 /* Get h_min, h_max and accumulate heights into h_accu */
434 FOR_ALL_TILES_IN_HEIGHT(h) {
435 if (*h < h_min) h_min = *h;
436 if (*h > h_max) h_max = *h;
437 h_accu += *h;
440 /* Get average height */
441 h_avg = (height_t)(h_accu / (_height_map.size_x * _height_map.size_y));
443 /* Return required results */
444 if (min_ptr != nullptr) *min_ptr = h_min;
445 if (max_ptr != nullptr) *max_ptr = h_max;
446 if (avg_ptr != nullptr) *avg_ptr = h_avg;
449 /** Dill histogram and return pointer to its base point - to the count of zero heights */
450 static int *HeightMapMakeHistogram(height_t h_min, height_t h_max, int *hist_buf)
452 int *hist = hist_buf - h_min;
453 height_t *h;
455 /* Count the heights and fill the histogram */
456 FOR_ALL_TILES_IN_HEIGHT(h) {
457 assert(*h >= h_min);
458 assert(*h <= h_max);
459 hist[*h]++;
461 return hist;
464 /** Applies sine wave redistribution onto height map */
465 static void HeightMapSineTransform(height_t h_min, height_t h_max)
467 height_t *h;
469 FOR_ALL_TILES_IN_HEIGHT(h) {
470 double fheight;
472 if (*h < h_min) continue;
474 /* Transform height into 0..1 space */
475 fheight = (double)(*h - h_min) / (double)(h_max - h_min);
476 /* Apply sine transform depending on landscape type */
477 switch (_settings_game.game_creation.landscape) {
478 case LT_TOYLAND:
479 case LT_TEMPERATE:
480 /* Move and scale 0..1 into -1..+1 */
481 fheight = 2 * fheight - 1;
482 /* Sine transform */
483 fheight = sin(fheight * M_PI_2);
484 /* Transform it back from -1..1 into 0..1 space */
485 fheight = 0.5 * (fheight + 1);
486 break;
488 case LT_ARCTIC:
490 /* Arctic terrain needs special height distribution.
491 * Redistribute heights to have more tiles at highest (75%..100%) range */
492 double sine_upper_limit = 0.75;
493 double linear_compression = 2;
494 if (fheight >= sine_upper_limit) {
495 /* Over the limit we do linear compression up */
496 fheight = 1.0 - (1.0 - fheight) / linear_compression;
497 } else {
498 double m = 1.0 - (1.0 - sine_upper_limit) / linear_compression;
499 /* Get 0..sine_upper_limit into -1..1 */
500 fheight = 2.0 * fheight / sine_upper_limit - 1.0;
501 /* Sine wave transform */
502 fheight = sin(fheight * M_PI_2);
503 /* Get -1..1 back to 0..(1 - (1 - sine_upper_limit) / linear_compression) == 0.0..m */
504 fheight = 0.5 * (fheight + 1.0) * m;
507 break;
509 case LT_TROPIC:
511 /* Desert terrain needs special height distribution.
512 * Half of tiles should be at lowest (0..25%) heights */
513 double sine_lower_limit = 0.5;
514 double linear_compression = 2;
515 if (fheight <= sine_lower_limit) {
516 /* Under the limit we do linear compression down */
517 fheight = fheight / linear_compression;
518 } else {
519 double m = sine_lower_limit / linear_compression;
520 /* Get sine_lower_limit..1 into -1..1 */
521 fheight = 2.0 * ((fheight - sine_lower_limit) / (1.0 - sine_lower_limit)) - 1.0;
522 /* Sine wave transform */
523 fheight = sin(fheight * M_PI_2);
524 /* Get -1..1 back to (sine_lower_limit / linear_compression)..1.0 */
525 fheight = 0.5 * ((1.0 - m) * fheight + (1.0 + m));
528 break;
530 default:
531 NOT_REACHED();
532 break;
534 /* Transform it back into h_min..h_max space */
535 *h = (height_t)(fheight * (h_max - h_min) + h_min);
536 if (*h < 0) *h = I2H(0);
537 if (*h >= h_max) *h = h_max - 1;
542 * Additional map variety is provided by applying different curve maps
543 * to different parts of the map. A randomized low resolution grid contains
544 * which curve map to use on each part of the make. This filtered non-linearly
545 * to smooth out transitions between curves, so each tile could have between
546 * 100% of one map applied or 25% of four maps.
548 * The curve maps define different land styles, i.e. lakes, low-lands, hills
549 * and mountain ranges, although these are dependent on the landscape style
550 * chosen as well.
552 * The level parameter dictates the resolution of the grid. A low resolution
553 * grid will result in larger continuous areas of a land style, a higher
554 * resolution grid splits the style into smaller areas.
555 * @param level Rough indication of the size of the grid sections to style. Small level means large grid sections.
557 static void HeightMapCurves(uint level)
559 height_t mh = TGPGetMaxHeight() - I2H(1); // height levels above sea level only
561 /** Basically scale height X to height Y. Everything in between is interpolated. */
562 struct control_point_t {
563 height_t x; ///< The height to scale from.
564 height_t y; ///< The height to scale to.
566 /* Scaled curve maps; value is in height_ts. */
567 #define F(fraction) ((height_t)(fraction * mh))
568 const control_point_t curve_map_1[] = { { F(0.0), F(0.0) }, { F(0.8), F(0.13) }, { F(1.0), F(0.4) } };
569 const control_point_t 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) } };
570 const control_point_t 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) } };
571 const control_point_t 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) } };
572 #undef F
574 /** Helper structure to index the different curve maps. */
575 struct control_point_list_t {
576 size_t length; ///< The length of the curve map.
577 const control_point_t *list; ///< The actual curve map.
579 const control_point_list_t curve_maps[] = {
580 { lengthof(curve_map_1), curve_map_1 },
581 { lengthof(curve_map_2), curve_map_2 },
582 { lengthof(curve_map_3), curve_map_3 },
583 { lengthof(curve_map_4), curve_map_4 },
586 height_t ht[lengthof(curve_maps)];
587 MemSetT(ht, 0, lengthof(ht));
589 /* Set up a grid to choose curve maps based on location; attempt to get a somewhat square grid */
590 float factor = sqrt((float)_height_map.size_x / (float)_height_map.size_y);
591 uint sx = Clamp((int)(((1 << level) * factor) + 0.5), 1, 128);
592 uint sy = Clamp((int)(((1 << level) / factor) + 0.5), 1, 128);
593 byte *c = AllocaM(byte, sx * sy);
595 for (uint i = 0; i < sx * sy; i++) {
596 c[i] = Random() % lengthof(curve_maps);
599 /* Apply curves */
600 for (int x = 0; x < _height_map.size_x; x++) {
602 /* Get our X grid positions and bi-linear ratio */
603 float fx = (float)(sx * x) / _height_map.size_x + 1.0f;
604 uint x1 = (uint)fx;
605 uint x2 = x1;
606 float xr = 2.0f * (fx - x1) - 1.0f;
607 xr = sin(xr * M_PI_2);
608 xr = sin(xr * M_PI_2);
609 xr = 0.5f * (xr + 1.0f);
610 float xri = 1.0f - xr;
612 if (x1 > 0) {
613 x1--;
614 if (x2 >= sx) x2--;
617 for (int y = 0; y < _height_map.size_y; y++) {
619 /* Get our Y grid position and bi-linear ratio */
620 float fy = (float)(sy * y) / _height_map.size_y + 1.0f;
621 uint y1 = (uint)fy;
622 uint y2 = y1;
623 float yr = 2.0f * (fy - y1) - 1.0f;
624 yr = sin(yr * M_PI_2);
625 yr = sin(yr * M_PI_2);
626 yr = 0.5f * (yr + 1.0f);
627 float yri = 1.0f - yr;
629 if (y1 > 0) {
630 y1--;
631 if (y2 >= sy) y2--;
634 uint corner_a = c[x1 + sx * y1];
635 uint corner_b = c[x1 + sx * y2];
636 uint corner_c = c[x2 + sx * y1];
637 uint corner_d = c[x2 + sx * y2];
639 /* Bitmask of which curve maps are chosen, so that we do not bother
640 * calculating a curve which won't be used. */
641 uint corner_bits = 0;
642 corner_bits |= 1 << corner_a;
643 corner_bits |= 1 << corner_b;
644 corner_bits |= 1 << corner_c;
645 corner_bits |= 1 << corner_d;
647 height_t *h = &_height_map.height(x, y);
649 /* Do not touch sea level */
650 if (*h < I2H(1)) continue;
652 /* Only scale above sea level */
653 *h -= I2H(1);
655 /* Apply all curve maps that are used on this tile. */
656 for (uint t = 0; t < lengthof(curve_maps); t++) {
657 if (!HasBit(corner_bits, t)) continue;
659 bool found = false;
660 const control_point_t *cm = curve_maps[t].list;
661 for (uint i = 0; i < curve_maps[t].length - 1; i++) {
662 const control_point_t &p1 = cm[i];
663 const control_point_t &p2 = cm[i + 1];
665 if (*h >= p1.x && *h < p2.x) {
666 ht[t] = p1.y + (*h - p1.x) * (p2.y - p1.y) / (p2.x - p1.x);
667 found = true;
668 break;
671 assert(found);
674 /* Apply interpolation of curve map results. */
675 *h = (height_t)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr);
677 /* Readd sea level */
678 *h += I2H(1);
683 /** Adjusts heights in height map to contain required amount of water tiles */
684 static void HeightMapAdjustWaterLevel(amplitude_t water_percent, height_t h_max_new)
686 height_t h_min, h_max, h_avg, h_water_level;
687 int64 water_tiles, desired_water_tiles;
688 height_t *h;
689 int *hist;
691 HeightMapGetMinMaxAvg(&h_min, &h_max, &h_avg);
693 /* Allocate histogram buffer and clear its cells */
694 int *hist_buf = CallocT<int>(h_max - h_min + 1);
695 /* Fill histogram */
696 hist = HeightMapMakeHistogram(h_min, h_max, hist_buf);
698 /* How many water tiles do we want? */
699 desired_water_tiles = A2I(((int64)water_percent) * (int64)(_height_map.size_x * _height_map.size_y));
701 /* Raise water_level and accumulate values from histogram until we reach required number of water tiles */
702 for (h_water_level = h_min, water_tiles = 0; h_water_level < h_max; h_water_level++) {
703 water_tiles += hist[h_water_level];
704 if (water_tiles >= desired_water_tiles) break;
707 /* We now have the proper water level value.
708 * Transform the height map into new (normalized) height map:
709 * values from range: h_min..h_water_level will become negative so it will be clamped to 0
710 * values from range: h_water_level..h_max are transformed into 0..h_max_new
711 * where h_max_new is depending on terrain type and map size.
713 FOR_ALL_TILES_IN_HEIGHT(h) {
714 /* Transform height from range h_water_level..h_max into 0..h_max_new range */
715 *h = (height_t)(((int)h_max_new) * (*h - h_water_level) / (h_max - h_water_level)) + I2H(1);
716 /* Make sure all values are in the proper range (0..h_max_new) */
717 if (*h < 0) *h = I2H(0);
718 if (*h >= h_max_new) *h = h_max_new - 1;
721 free(hist_buf);
724 static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime);
727 * This routine sculpts in from the edge a random amount, again a Perlin
728 * sequence, to avoid the rigid flat-edge slopes that were present before. The
729 * Perlin noise map doesn't know where we are going to slice across, and so we
730 * often cut straight through high terrain. The smoothing routine makes it
731 * legal, gradually increasing up from the edge to the original terrain height.
732 * By cutting parts of this away, it gives a far more irregular edge to the
733 * map-edge. Sometimes it works beautifully with the existing sea & lakes, and
734 * creates a very realistic coastline. Other times the variation is less, and
735 * the map-edge shows its cliff-like roots.
737 * This routine may be extended to randomly sculpt the height of the terrain
738 * near the edge. This will have the coast edge at low level (1-3), rising in
739 * smoothed steps inland to about 15 tiles in. This should make it look as
740 * though the map has been built for the map size, rather than a slice through
741 * a larger map.
743 * Please note that all the small numbers; 53, 101, 167, etc. are small primes
744 * to help give the perlin noise a bit more of a random feel.
746 static void HeightMapCoastLines(uint8 water_borders)
748 int smallest_size = std::min(_settings_game.game_creation.map_x, _settings_game.game_creation.map_y);
749 const int margin = 4;
750 int y, x;
751 double max_x;
752 double max_y;
754 /* Lower to sea level */
755 for (y = 0; y <= _height_map.size_y; y++) {
756 if (HasBit(water_borders, BORDER_NE)) {
757 /* Top right */
758 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);
759 max_x = std::max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
760 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
761 for (x = 0; x < max_x; x++) {
762 _height_map.height(x, y) = 0;
766 if (HasBit(water_borders, BORDER_SW)) {
767 /* Bottom left */
768 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);
769 max_x = std::max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
770 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
771 for (x = _height_map.size_x; x > (_height_map.size_x - 1 - max_x); x--) {
772 _height_map.height(x, y) = 0;
777 /* Lower to sea level */
778 for (x = 0; x <= _height_map.size_x; x++) {
779 if (HasBit(water_borders, BORDER_NW)) {
780 /* Top left */
781 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);
782 max_y = std::max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
783 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
784 for (y = 0; y < max_y; y++) {
785 _height_map.height(x, y) = 0;
789 if (HasBit(water_borders, BORDER_SE)) {
790 /* Bottom right */
791 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);
792 max_y = std::max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
793 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
794 for (y = _height_map.size_y; y > (_height_map.size_y - 1 - max_y); y--) {
795 _height_map.height(x, y) = 0;
801 /** Start at given point, move in given direction, find and Smooth coast in that direction */
802 static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int dir_y)
804 const int max_coast_dist_from_edge = 35;
805 const int max_coast_Smooth_depth = 35;
807 int x, y;
808 int ed; // coast distance from edge
809 int depth;
811 height_t h_prev = I2H(1);
812 height_t h;
814 assert(IsValidXY(org_x, org_y));
816 /* Search for the coast (first non-water tile) */
817 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++) {
818 /* Coast found? */
819 if (_height_map.height(x, y) >= I2H(1)) break;
821 /* Coast found in the neighborhood? */
822 if (IsValidXY(x + dir_y, y + dir_x) && _height_map.height(x + dir_y, y + dir_x) > 0) break;
824 /* Coast found in the neighborhood on the other side */
825 if (IsValidXY(x - dir_y, y - dir_x) && _height_map.height(x - dir_y, y - dir_x) > 0) break;
828 /* Coast found or max_coast_dist_from_edge has been reached.
829 * Soften the coast slope */
830 for (depth = 0; IsValidXY(x, y) && depth <= max_coast_Smooth_depth; depth++, x += dir_x, y += dir_y) {
831 h = _height_map.height(x, y);
832 h = std::min<uint>(h, h_prev + (4 + depth)); // coast softening formula
833 _height_map.height(x, y) = h;
834 h_prev = h;
838 /** Smooth coasts by modulating height of tiles close to map edges with cosine of distance from edge */
839 static void HeightMapSmoothCoasts(uint8 water_borders)
841 int x, y;
842 /* First Smooth NW and SE coasts (y close to 0 and y close to size_y) */
843 for (x = 0; x < _height_map.size_x; x++) {
844 if (HasBit(water_borders, BORDER_NW)) HeightMapSmoothCoastInDirection(x, 0, 0, 1);
845 if (HasBit(water_borders, BORDER_SE)) HeightMapSmoothCoastInDirection(x, _height_map.size_y - 1, 0, -1);
847 /* First Smooth NE and SW coasts (x close to 0 and x close to size_x) */
848 for (y = 0; y < _height_map.size_y; y++) {
849 if (HasBit(water_borders, BORDER_NE)) HeightMapSmoothCoastInDirection(0, y, 1, 0);
850 if (HasBit(water_borders, BORDER_SW)) HeightMapSmoothCoastInDirection(_height_map.size_x - 1, y, -1, 0);
855 * This routine provides the essential cleanup necessary before OTTD can
856 * display the terrain. When generated, the terrain heights can jump more than
857 * one level between tiles. This routine smooths out those differences so that
858 * the most it can change is one level. When OTTD can support cliffs, this
859 * routine may not be necessary.
861 static void HeightMapSmoothSlopes(height_t dh_max)
863 for (int y = 0; y <= (int)_height_map.size_y; y++) {
864 for (int x = 0; x <= (int)_height_map.size_x; x++) {
865 height_t h_max = std::min(_height_map.height(x > 0 ? x - 1 : x, y), _height_map.height(x, y > 0 ? y - 1 : y)) + dh_max;
866 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
869 for (int y = _height_map.size_y; y >= 0; y--) {
870 for (int x = _height_map.size_x; x >= 0; x--) {
871 height_t 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;
872 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
878 * Height map terraform post processing:
879 * - water level adjusting
880 * - coast Smoothing
881 * - slope Smoothing
882 * - height histogram redistribution by sine wave transform
884 static void HeightMapNormalize()
886 int sea_level_setting = _settings_game.difficulty.quantity_sea_lakes;
887 const amplitude_t 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;
888 const height_t h_max_new = TGPGetMaxHeight();
889 const height_t roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness;
891 HeightMapAdjustWaterLevel(water_percent, h_max_new);
893 byte water_borders = _settings_game.construction.freeform_edges ? _settings_game.game_creation.water_borders : 0xF;
894 if (water_borders == BORDERS_RANDOM) water_borders = GB(Random(), 0, 4);
896 HeightMapCoastLines(water_borders);
897 HeightMapSmoothSlopes(roughness);
899 HeightMapSmoothCoasts(water_borders);
900 HeightMapSmoothSlopes(roughness);
902 HeightMapSineTransform(I2H(1), h_max_new);
904 if (_settings_game.game_creation.variety > 0) {
905 HeightMapCurves(_settings_game.game_creation.variety);
908 HeightMapSmoothSlopes(I2H(1));
912 * The Perlin Noise calculation using large primes
913 * The initial number is adjusted by two values; the generation_seed, and the
914 * passed parameter; prime.
915 * prime is used to allow the perlin noise generator to create useful random
916 * numbers from slightly different series.
918 static double int_noise(const long x, const long y, const int prime)
920 long n = x + y * prime + _settings_game.game_creation.generation_seed;
922 n = (n << 13) ^ n;
924 /* Pseudo-random number generator, using several large primes */
925 return 1.0 - (double)((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0;
930 * This routine determines the interpolated value between a and b
932 static inline double linear_interpolate(const double a, const double b, const double x)
934 return a + x * (b - a);
939 * This routine returns the smoothed interpolated noise for an x and y, using
940 * the values from the surrounding positions.
942 static double interpolated_noise(const double x, const double y, const int prime)
944 const int integer_X = (int)x;
945 const int integer_Y = (int)y;
947 const double fractional_X = x - (double)integer_X;
948 const double fractional_Y = y - (double)integer_Y;
950 const double v1 = int_noise(integer_X, integer_Y, prime);
951 const double v2 = int_noise(integer_X + 1, integer_Y, prime);
952 const double v3 = int_noise(integer_X, integer_Y + 1, prime);
953 const double v4 = int_noise(integer_X + 1, integer_Y + 1, prime);
955 const double i1 = linear_interpolate(v1, v2, fractional_X);
956 const double i2 = linear_interpolate(v3, v4, fractional_X);
958 return linear_interpolate(i1, i2, fractional_Y);
963 * This is a similar function to the main perlin noise calculation, but uses
964 * the value p passed as a parameter rather than selected from the predefined
965 * sequences. as you can guess by its title, i use this to create the indented
966 * coastline, which is just another perlin sequence.
968 static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime)
970 double total = 0.0;
972 for (int i = 0; i < 6; i++) {
973 const double frequency = (double)(1 << i);
974 const double amplitude = pow(p, (double)i);
976 total += interpolated_noise((x * frequency) / 64.0, (y * frequency) / 64.0, prime) * amplitude;
979 return total;
983 /** A small helper function to initialize the terrain */
984 static void TgenSetTileHeight(TileIndex tile, int height)
986 SetTileHeight(tile, height);
988 /* Only clear the tiles within the map area. */
989 if (IsInnerTile(tile)) {
990 MakeClear(tile, CLEAR_GRASS, 3);
995 * The main new land generator using Perlin noise. Desert landscape is handled
996 * different to all others to give a desert valley between two high mountains.
997 * Clearly if a low height terrain (flat/very flat) is chosen, then the tropic
998 * areas won't be high enough, and there will be very little tropic on the map.
999 * Thus Tropic works best on Hilly or Mountainous.
1001 void GenerateTerrainPerlin()
1003 if (!AllocHeightMap()) return;
1004 GenerateWorldSetAbortCallback(FreeHeightMap);
1006 HeightMapGenerate();
1008 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
1010 HeightMapNormalize();
1012 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
1014 /* First make sure the tiles at the north border are void tiles if needed. */
1015 if (_settings_game.construction.freeform_edges) {
1016 for (uint x = 0; x < MapSizeX(); x++) MakeVoid(TileXY(x, 0));
1017 for (uint y = 0; y < MapSizeY(); y++) MakeVoid(TileXY(0, y));
1020 int max_height = H2I(TGPGetMaxHeight());
1022 /* Transfer height map into OTTD map */
1023 for (int y = 0; y < _height_map.size_y; y++) {
1024 for (int x = 0; x < _height_map.size_x; x++) {
1025 TgenSetTileHeight(TileXY(x, y), Clamp(H2I(_height_map.height(x, y)), 0, max_height));
1029 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
1031 FreeHeightMap();
1032 GenerateWorldSetAbortCallback(nullptr);