Remove second template parameter from class GUIList
[openttd/fttd.git] / src / tgp.cpp
blob43b49d6a98c0cc8b263f3e09793830985a20276b
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file tgp.cpp OTTD Perlin Noise Landscape Generator, aka TerraGenesis Perlin */
12 #include "stdafx.h"
13 #include "core/alloc_func.hpp"
14 #include "core/mem_func.hpp"
15 #include <math.h>
16 #include "map/ground.h"
17 #include "genworld.h"
18 #include "core/random_func.hpp"
19 #include "landscape_type.h"
23 * Quickie guide to Perlin Noise
24 * Perlin noise is a predictable pseudo random number sequence. By generating
25 * it in 2 dimensions, it becomes a useful random map that, for a given seed
26 * and starting X & Y, is entirely predictable. On the face of it, that may not
27 * be useful. However, it means that if you want to replay a map in a different
28 * terrain, or just vary the sea level, you just re-run the generator with the
29 * same seed. The seed is an int32, and is randomised on each run of New Game.
30 * The Scenario Generator does not randomise the value, so that you can
31 * experiment with one terrain until you are happy, or click "Random" for a new
32 * random seed.
34 * Perlin Noise is a series of "octaves" of random noise added together. By
35 * reducing the amplitude of the noise with each octave, the first octave of
36 * noise defines the main terrain sweep, the next the ripples on that, and the
37 * next the ripples on that. I use 6 octaves, with the amplitude controlled by
38 * a power ratio, usually known as a persistence or p value. This I vary by the
39 * smoothness selection, as can be seen in the table below. The closer to 1,
40 * the more of that octave is added. Each octave is however raised to the power
41 * of its position in the list, so the last entry in the "smooth" row, 0.35, is
42 * raised to the power of 6, so can only add 0.001838... of the amplitude to
43 * the running total.
45 * In other words; the first p value sets the general shape of the terrain, the
46 * second sets the major variations to that, ... until finally the smallest
47 * bumps are added.
49 * Usefully, this routine is totally scaleable; so when 32bpp comes along, the
50 * terrain can be as bumpy as you like! It is also infinitely expandable; a
51 * single random seed terrain continues in X & Y as far as you care to
52 * calculate. In theory, we could use just one seed value, but randomly select
53 * where in the Perlin XY space we use for the terrain. Personally I prefer
54 * using a simple (0, 0) to (X, Y), with a varying seed.
57 * Other things i have had to do: mountainous wasn't mountainous enough, and
58 * since we only have 0..15 heights available, I add a second generated map
59 * (with a modified seed), onto the original. This generally raises the
60 * terrain, which then needs scaling back down. Overall effect is a general
61 * uplift.
63 * However, the values on the top of mountains are then almost guaranteed to go
64 * too high, so large flat plateaus appeared at height 15. To counter this, I
65 * scale all heights above 12 to proportion up to 15. It still makes the
66 * mountains have flattish tops, rather than craggy peaks, but at least they
67 * aren't smooth as glass.
70 * For a full discussion of Perlin Noise, please visit:
71 * http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
74 * Evolution II
76 * The algorithm as described in the above link suggests to compute each tile height
77 * as composition of several noise waves. Some of them are computed directly by
78 * noise(x, y) function, some are calculated using linear approximation. Our
79 * first implementation of perlin_noise_2D() used 4 noise(x, y) calls plus
80 * 3 linear interpolations. It was called 6 times for each tile. This was a bit
81 * CPU expensive.
83 * The following implementation uses optimized algorithm that should produce
84 * the same quality result with much less computations, but more memory accesses.
85 * The overall speedup should be 300% to 800% depending on CPU and memory speed.
87 * I will try to explain it on the example below:
89 * Have a map of 4 x 4 tiles, our simplified noise generator produces only two
90 * values -1 and +1, use 3 octaves with wave length 1, 2 and 4, with amplitudes
91 * 3, 2, 1. Original algorithm produces:
93 * 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
94 * 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
95 * 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
96 * 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
98 * 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
99 * 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
100 * 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
101 * 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
104 * Optimization 1:
106 * 1) we need to allocate a bit more tiles: (size_x + 1) * (size_y + 1) = (5 * 5):
108 * 2) setup corner values using amplitude 3
109 * { -3.0 X X X 3.0 }
110 * { X X X X X }
111 * { X X X X X }
112 * { X X X X X }
113 * { 3.0 X X X -3.0 }
115 * 3a) interpolate values in the middle
116 * { -3.0 X 0.0 X 3.0 }
117 * { X X X X X }
118 * { 0.0 X 0.0 X 0.0 }
119 * { X X X X X }
120 * { 3.0 X 0.0 X -3.0 }
122 * 3b) add patches with amplitude 2 to them
123 * { -5.0 X 2.0 X 1.0 }
124 * { X X X X X }
125 * { 2.0 X -2.0 X 2.0 }
126 * { X X X X X }
127 * { 1.0 X 2.0 X -5.0 }
129 * 4a) interpolate values in the middle
130 * { -5.0 -1.5 2.0 1.5 1.0 }
131 * { -1.5 -0.75 0.0 0.75 1.5 }
132 * { 2.0 0.0 -2.0 0.0 2.0 }
133 * { 1.5 0.75 0.0 -0.75 -1.5 }
134 * { 1.0 1.5 2.0 -1.5 -5.0 }
136 * 4b) add patches with amplitude 1 to them
137 * { -6.0 -0.5 1.0 2.5 0.0 }
138 * { -0.5 -1.75 1.0 -0.25 2.5 }
139 * { 1.0 1.0 -3.0 1.0 1.0 }
140 * { 2.5 -0.25 1.0 -1.75 -0.5 }
141 * { 0.0 2.5 1.0 -0.5 -6.0 }
145 * Optimization 2:
147 * As you can see above, each noise function was called just once. Therefore
148 * we don't need to use noise function that calculates the noise from x, y and
149 * some prime. The same quality result we can obtain using standard Random()
150 * function instead.
154 /** Fixed point type for heights */
155 typedef int16 height_t;
156 static const int height_decimal_bits = 4;
158 /** Fixed point array for amplitudes (and percent values) */
159 typedef int amplitude_t;
160 static const int amplitude_decimal_bits = 10;
162 /** Height map - allocated array of heights (MapSizeX() + 1) x (MapSizeY() + 1) */
163 struct HeightMap
165 height_t *h; //< array of heights
166 /* Even though the sizes are always positive, there are many cases where
167 * X and Y need to be signed integers due to subtractions. */
168 int dim_x; //< height map size_x MapSizeX() + 1
169 int total_size; //< height map total size
170 int size_x; //< MapSizeX()
171 int size_y; //< MapSizeY()
174 * Height map accessor
175 * @param x X position
176 * @param y Y position
177 * @return height as fixed point number
179 inline height_t &height(uint x, uint y)
181 return h[x + y * dim_x];
185 /** Global height map instance */
186 static HeightMap _height_map = {NULL, 0, 0, 0, 0};
188 /** Conversion: int to height_t */
189 #define I2H(i) ((i) << height_decimal_bits)
190 /** Conversion: height_t to int */
191 #define H2I(i) ((i) >> height_decimal_bits)
193 /** Conversion: int to amplitude_t */
194 #define I2A(i) ((i) << amplitude_decimal_bits)
195 /** Conversion: amplitude_t to int */
196 #define A2I(i) ((i) >> amplitude_decimal_bits)
198 /** Conversion: amplitude_t to height_t */
199 #define A2H(a) ((a) >> (amplitude_decimal_bits - height_decimal_bits))
202 /** Walk through all items of _height_map.h */
203 #define FOR_ALL_TILES_IN_HEIGHT(h) for (h = _height_map.h; h < &_height_map.h[_height_map.total_size]; h++)
205 /** Maximum number of TGP noise frequencies. */
206 static const int MAX_TGP_FREQUENCIES = 10;
208 /** Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes */
209 static const amplitude_t _water_percent[4] = {70, 170, 270, 420};
212 * Gets the maximum allowed height while generating a map based on
213 * mapsize, terraintype, and the maximum height level.
214 * @return The maximum height for the map generation.
215 * @note Values should never be lower than 3 since the minimum snowline height is 2.
217 static height_t TGPGetMaxHeight()
220 * Desired maximum height - indexed by:
221 * - _settings_game.difficulty.terrain_type
222 * - min(MapLogX(), MapLogY()) - MIN_MAP_SIZE_BITS
224 * It is indexed by map size as well as terrain type since the map size limits the height of
225 * a usable mountain. For example, on a 64x64 map a 24 high single peak mountain (as if you
226 * raised land 24 times in the center of the map) will leave only a ring of about 10 tiles
227 * around the mountain to build on. On a 4096x4096 map, it won't cover any major part of the map.
229 static const int max_height[5][MAX_MAP_SIZE_BITS - MIN_MAP_SIZE_BITS + 1] = {
230 /* 64 128 256 512 1024 2048 4096 */
231 { 3, 3, 3, 3, 4, 5, 7 }, ///< Very flat
232 { 5, 7, 8, 9, 14, 19, 31 }, ///< Flat
233 { 8, 9, 10, 15, 23, 37, 61 }, ///< Hilly
234 { 10, 11, 17, 19, 49, 63, 73 }, ///< Mountainous
235 { 12, 19, 25, 31, 67, 75, 87 }, ///< Alpinist
238 int max_height_from_table = max_height[_settings_game.difficulty.terrain_type][min(MapLogX(), MapLogY()) - MIN_MAP_SIZE_BITS];
239 return I2H(min(max_height_from_table, _settings_game.construction.max_heightlevel));
243 * Get the amplitude associated with the currently selected
244 * smoothness and maximum height level.
245 * @param frequency The frequency to get the amplitudes for
246 * @return The amplitudes to apply to the map.
248 static amplitude_t GetAmplitude(int frequency)
250 /* Base noise amplitudes (multiplied by 1024) and indexed by "smoothness setting" and log2(frequency). */
251 static const amplitude_t amplitudes[][7] = {
252 /* lowest frequency ...... highest (every corner) */
253 {16000, 5600, 1968, 688, 240, 16, 16}, ///< Very smooth
254 {24000, 12800, 6400, 2700, 1024, 128, 16}, ///< Smooth
255 {32000, 19200, 12800, 8000, 3200, 256, 64}, ///< Rough
256 {48000, 24000, 19200, 16000, 8000, 512, 320}, ///< Very rough
259 * Extrapolation factors for ranges before the table.
260 * The extrapolation is needed to account for the higher map heights. They need larger
261 * areas with a particular gradient so that we are able to create maps without too
262 * many steep slopes up to the wanted height level. It's definitely not perfect since
263 * it will bring larger rectangles with similar slopes which makes the rectangular
264 * behaviour of TGP more noticable. However, these height differentiations cannot
265 * happen over much smaller areas; we basically double the "range" to give a similar
266 * slope for every doubling of map height.
268 static const double extrapolation_factors[] = { 3.3, 2.8, 2.3, 1.8 };
270 int smoothness = _settings_game.game_creation.tgen_smoothness;
272 /* Get the table index, and return that value if possible. */
273 int index = frequency - MAX_TGP_FREQUENCIES + lengthof(amplitudes[smoothness]);
274 amplitude_t amplitude = amplitudes[smoothness][max(0, index)];
275 if (index >= 0) return amplitude;
277 /* We need to extrapolate the amplitude. */
278 double extrapolation_factor = extrapolation_factors[smoothness];
279 int height_range = I2H(16);
280 do {
281 amplitude = (amplitude_t)(extrapolation_factor * (double)amplitude);
282 height_range <<= 1;
283 index++;
284 } while (index < 0);
286 return Clamp((TGPGetMaxHeight() - height_range) / height_range, 0, 1) * amplitude;
290 * Check if a X/Y set are within the map.
291 * @param x coordinate x
292 * @param y coordinate y
293 * @return true if within the map
295 static inline bool IsValidXY(int x, int y)
297 return x >= 0 && x < _height_map.size_x && y >= 0 && y < _height_map.size_y;
302 * Allocate array of (MapSizeX()+1)*(MapSizeY()+1) heights and init the _height_map structure members
303 * @return true on success
305 static inline bool AllocHeightMap()
307 height_t *h;
309 _height_map.size_x = MapSizeX();
310 _height_map.size_y = MapSizeY();
312 /* Allocate memory block for height map row pointers */
313 _height_map.total_size = (_height_map.size_x + 1) * (_height_map.size_y + 1);
314 _height_map.dim_x = _height_map.size_x + 1;
315 _height_map.h = xcalloct<height_t>(_height_map.total_size);
317 /* Iterate through height map and initialise values. */
318 FOR_ALL_TILES_IN_HEIGHT(h) *h = 0;
320 return true;
323 /** Free height map */
324 static inline void FreeHeightMap()
326 free(_height_map.h);
327 _height_map.h = NULL;
331 * Generates new random height in given amplitude (generated numbers will range from - amplitude to + amplitude)
332 * @param rMax Limit of result
333 * @return generated height
335 static inline height_t RandomHeight(amplitude_t rMax)
337 /* Spread height into range -rMax..+rMax */
338 return A2H(RandomRange(2 * rMax + 1) - rMax);
342 * Base Perlin noise generator - fills height map with raw Perlin noise.
344 * This runs several iterations with increasing precision; the last iteration looks at areas
345 * of 1 by 1 tiles, the second to last at 2 by 2 tiles and the initial 2**MAX_TGP_FREQUENCIES
346 * by 2**MAX_TGP_FREQUENCIES tiles.
348 static void HeightMapGenerate()
350 /* Trying to apply noise to uninitialized height map */
351 assert(_height_map.h != NULL);
353 int start = max(MAX_TGP_FREQUENCIES - (int)min(MapLogX(), MapLogY()), 0);
354 bool first = true;
356 for (int frequency = start; frequency < MAX_TGP_FREQUENCIES; frequency++) {
357 const amplitude_t amplitude = GetAmplitude(frequency);
359 /* Ignore zero amplitudes; it means our map isn't height enough for this
360 * amplitude, so ignore it and continue with the next set of amplitude. */
361 if (amplitude == 0) continue;
363 const int step = 1 << (MAX_TGP_FREQUENCIES - frequency - 1);
365 if (first) {
366 /* This is first round, we need to establish base heights with step = size_min */
367 for (int y = 0; y <= _height_map.size_y; y += step) {
368 for (int x = 0; x <= _height_map.size_x; x += step) {
369 height_t height = (amplitude > 0) ? RandomHeight(amplitude) : 0;
370 _height_map.height(x, y) = height;
373 first = false;
374 continue;
377 /* It is regular iteration round.
378 * Interpolate height values at odd x, even y tiles */
379 for (int y = 0; y <= _height_map.size_y; y += 2 * step) {
380 for (int x = 0; x <= _height_map.size_x - 2 * step; x += 2 * step) {
381 height_t h00 = _height_map.height(x + 0 * step, y);
382 height_t h02 = _height_map.height(x + 2 * step, y);
383 height_t h01 = (h00 + h02) / 2;
384 _height_map.height(x + 1 * step, y) = h01;
388 /* Interpolate height values at odd y tiles */
389 for (int y = 0; y <= _height_map.size_y - 2 * step; y += 2 * step) {
390 for (int x = 0; x <= _height_map.size_x; x += step) {
391 height_t h00 = _height_map.height(x, y + 0 * step);
392 height_t h20 = _height_map.height(x, y + 2 * step);
393 height_t h10 = (h00 + h20) / 2;
394 _height_map.height(x, y + 1 * step) = h10;
398 /* Add noise for next higher frequency (smaller steps) */
399 for (int y = 0; y <= _height_map.size_y; y += step) {
400 for (int x = 0; x <= _height_map.size_x; x += step) {
401 _height_map.height(x, y) += RandomHeight(amplitude);
407 /** Returns min, max and average height from height map */
408 static void HeightMapGetMinMaxAvg(height_t *min_ptr, height_t *max_ptr, height_t *avg_ptr)
410 height_t h_min, h_max, h_avg, *h;
411 int64 h_accu = 0;
412 h_min = h_max = _height_map.height(0, 0);
414 /* Get h_min, h_max and accumulate heights into h_accu */
415 FOR_ALL_TILES_IN_HEIGHT(h) {
416 if (*h < h_min) h_min = *h;
417 if (*h > h_max) h_max = *h;
418 h_accu += *h;
421 /* Get average height */
422 h_avg = (height_t)(h_accu / (_height_map.size_x * _height_map.size_y));
424 /* Return required results */
425 if (min_ptr != NULL) *min_ptr = h_min;
426 if (max_ptr != NULL) *max_ptr = h_max;
427 if (avg_ptr != NULL) *avg_ptr = h_avg;
430 /** Dill histogram and return pointer to its base point - to the count of zero heights */
431 static int *HeightMapMakeHistogram(height_t h_min, height_t h_max, int *hist_buf)
433 int *hist = hist_buf - h_min;
434 height_t *h;
436 /* Count the heights and fill the histogram */
437 FOR_ALL_TILES_IN_HEIGHT(h) {
438 assert(*h >= h_min);
439 assert(*h <= h_max);
440 hist[*h]++;
442 return hist;
445 /** Applies sine wave redistribution onto height map */
446 static void HeightMapSineTransform(height_t h_min, height_t h_max)
448 height_t *h;
450 FOR_ALL_TILES_IN_HEIGHT(h) {
451 double fheight;
453 if (*h < h_min) continue;
455 /* Transform height into 0..1 space */
456 fheight = (double)(*h - h_min) / (double)(h_max - h_min);
457 /* Apply sine transform depending on landscape type */
458 switch (_settings_game.game_creation.landscape) {
459 case LT_TOYLAND:
460 case LT_TEMPERATE:
461 /* Move and scale 0..1 into -1..+1 */
462 fheight = 2 * fheight - 1;
463 /* Sine transform */
464 fheight = sin(fheight * M_PI_2);
465 /* Transform it back from -1..1 into 0..1 space */
466 fheight = 0.5 * (fheight + 1);
467 break;
469 case LT_ARCTIC:
471 /* Arctic terrain needs special height distribution.
472 * Redistribute heights to have more tiles at highest (75%..100%) range */
473 double sine_upper_limit = 0.75;
474 double linear_compression = 2;
475 if (fheight >= sine_upper_limit) {
476 /* Over the limit we do linear compression up */
477 fheight = 1.0 - (1.0 - fheight) / linear_compression;
478 } else {
479 double m = 1.0 - (1.0 - sine_upper_limit) / linear_compression;
480 /* Get 0..sine_upper_limit into -1..1 */
481 fheight = 2.0 * fheight / sine_upper_limit - 1.0;
482 /* Sine wave transform */
483 fheight = sin(fheight * M_PI_2);
484 /* Get -1..1 back to 0..(1 - (1 - sine_upper_limit) / linear_compression) == 0.0..m */
485 fheight = 0.5 * (fheight + 1.0) * m;
488 break;
490 case LT_TROPIC:
492 /* Desert terrain needs special height distribution.
493 * Half of tiles should be at lowest (0..25%) heights */
494 double sine_lower_limit = 0.5;
495 double linear_compression = 2;
496 if (fheight <= sine_lower_limit) {
497 /* Under the limit we do linear compression down */
498 fheight = fheight / linear_compression;
499 } else {
500 double m = sine_lower_limit / linear_compression;
501 /* Get sine_lower_limit..1 into -1..1 */
502 fheight = 2.0 * ((fheight - sine_lower_limit) / (1.0 - sine_lower_limit)) - 1.0;
503 /* Sine wave transform */
504 fheight = sin(fheight * M_PI_2);
505 /* Get -1..1 back to (sine_lower_limit / linear_compression)..1.0 */
506 fheight = 0.5 * ((1.0 - m) * fheight + (1.0 + m));
509 break;
511 default:
512 NOT_REACHED();
513 break;
515 /* Transform it back into h_min..h_max space */
516 *h = (height_t)(fheight * (h_max - h_min) + h_min);
517 if (*h < 0) *h = I2H(0);
518 if (*h >= h_max) *h = h_max - 1;
523 * Additional map variety is provided by applying different curve maps
524 * to different parts of the map. A randomized low resolution grid contains
525 * which curve map to use on each part of the make. This filtered non-linearly
526 * to smooth out transitions between curves, so each tile could have between
527 * 100% of one map applied or 25% of four maps.
529 * The curve maps define different land styles, i.e. lakes, low-lands, hills
530 * and mountain ranges, although these are dependent on the landscape style
531 * chosen as well.
533 * The level parameter dictates the resolution of the grid. A low resolution
534 * grid will result in larger continuous areas of a land style, a higher
535 * resolution grid splits the style into smaller areas.
536 * @param level Rough indication of the size of the grid sections to style. Small level means large grid sections.
538 static void HeightMapCurves(uint level)
540 /** Basically scale height X to height Y. Everything in between is interpolated. */
541 struct control_point_t {
542 float x; ///< The height to scale from.
543 float y; ///< The height to scale to.
546 /* Scaled curve maps; value is in proportion of maximum height_t. */
547 static const control_point_t curve_map_1[] = { { 0, 0 }, { 2.4 / 3, 0.4 / 3 }, { 1, 0.4 } };
548 static const control_point_t curve_map_2[] = { { 0, 0 }, { 1.6 / 3, 0.4 / 3 }, { 2.4 / 3, 0.8 / 3 }, { 1, 0.6 } };
549 static const control_point_t curve_map_3[] = { { 0, 0 }, { 1.6 / 3, 0.8 / 3 }, { 2.4 / 3, 1.8 / 3 }, { 1, 0.8 } };
550 static const control_point_t curve_map_4[] = { { 0, 0 }, { 1.2 / 3, 0.9 / 3 }, { 2.0 / 3, 2.4 / 3 } , { 5.5 / 6, 0.99 }, { 1, 0.99 } };
552 /** Helper structure to index the different curve maps. */
553 static const control_point_t *const curve_maps[] = {
554 curve_map_1, curve_map_2, curve_map_3, curve_map_4,
557 height_t ht[lengthof(curve_maps)];
558 MemSetT(ht, 0, lengthof(ht));
560 /* Set up a grid to choose curve maps based on location; attempt to get a somewhat square grid */
561 float factor = sqrt((float)_height_map.size_x / (float)_height_map.size_y);
562 uint sx = Clamp((int)(((1 << level) * factor) + 0.5), 1, 128);
563 uint sy = Clamp((int)(((1 << level) / factor) + 0.5), 1, 128);
564 byte *c = AllocaM(byte, sx * sy);
566 for (uint i = 0; i < sx * sy; i++) {
567 c[i] = Random() % lengthof(curve_maps);
570 const height_t mh = TGPGetMaxHeight() - I2H(1); // height levels above sea level only
572 /* Apply curves */
573 for (int x = 0; x < _height_map.size_x; x++) {
575 /* Get our X grid positions and bi-linear ratio */
576 float fx = (float)(sx * x) / _height_map.size_x + 1.0f;
577 uint x1 = (uint)fx;
578 uint x2 = x1;
579 float xr = 2.0f * (fx - x1) - 1.0f;
580 xr = sin(xr * M_PI_2);
581 xr = sin(xr * M_PI_2);
582 xr = 0.5f * (xr + 1.0f);
583 float xri = 1.0f - xr;
585 if (x1 > 0) {
586 x1--;
587 if (x2 >= sx) x2--;
590 for (int y = 0; y < _height_map.size_y; y++) {
592 /* Get our Y grid position and bi-linear ratio */
593 float fy = (float)(sy * y) / _height_map.size_y + 1.0f;
594 uint y1 = (uint)fy;
595 uint y2 = y1;
596 float yr = 2.0f * (fy - y1) - 1.0f;
597 yr = sin(yr * M_PI_2);
598 yr = sin(yr * M_PI_2);
599 yr = 0.5f * (yr + 1.0f);
600 float yri = 1.0f - yr;
602 if (y1 > 0) {
603 y1--;
604 if (y2 >= sy) y2--;
607 uint corner_a = c[x1 + sx * y1];
608 uint corner_b = c[x1 + sx * y2];
609 uint corner_c = c[x2 + sx * y1];
610 uint corner_d = c[x2 + sx * y2];
612 /* Bitmask of which curve maps are chosen, so that we do not bother
613 * calculating a curve which won't be used. */
614 uint corner_bits = 0;
615 corner_bits |= 1 << corner_a;
616 corner_bits |= 1 << corner_b;
617 corner_bits |= 1 << corner_c;
618 corner_bits |= 1 << corner_d;
620 height_t *h = &_height_map.height(x, y);
621 assert (*h >= 0);
623 /* Do not touch sea level */
624 if (*h < I2H(1)) continue;
626 /* Only scale above sea level */
627 *h -= I2H(1);
628 assert (*h <= mh);
630 /* Apply all curve maps that are used on this tile. */
631 for (uint t = 0; t < lengthof(curve_maps); t++) {
632 if (!HasBit(corner_bits, t)) continue;
634 const control_point_t *cm = curve_maps[t];
635 assert (cm->x == 0);
636 assert (cm->y == 0);
638 for (;;) {
639 assert (*h >= (height_t)(cm->x * mh));
640 const control_point_t *next = cm + 1;
641 if (*h < (height_t)(next->x * mh)) {
642 ht[t] = (height_t)(cm->y * mh) + (height_t)((*h - (height_t)(cm->x * mh)) * (next->y - cm->y) / (next->x - cm->x));
643 break;
645 cm = next;
646 assert (cm->x <= 1 );
647 if (cm->x == 1) {
648 assert (*h == mh);
649 ht[t] = (height_t)(cm->y * mh);
650 break;
655 /* Apply interpolation of curve map results. */
656 *h = (height_t)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr);
658 /* Readd sea level */
659 *h += I2H(1);
664 /** Adjusts heights in height map to contain required amount of water tiles */
665 static void HeightMapAdjustWaterLevel(amplitude_t water_percent, height_t h_max_new)
667 height_t h_min, h_max, h_avg, h_water_level;
668 int64 water_tiles, desired_water_tiles;
669 height_t *h;
670 int *hist;
672 HeightMapGetMinMaxAvg(&h_min, &h_max, &h_avg);
674 /* Allocate histogram buffer and clear its cells */
675 int *hist_buf = xcalloct<int>(h_max - h_min + 1);
676 /* Fill histogram */
677 hist = HeightMapMakeHistogram(h_min, h_max, hist_buf);
679 /* How many water tiles do we want? */
680 desired_water_tiles = A2I(((int64)water_percent) * (int64)(_height_map.size_x * _height_map.size_y));
682 /* Raise water_level and accumulate values from histogram until we reach required number of water tiles */
683 for (h_water_level = h_min, water_tiles = 0; h_water_level < h_max; h_water_level++) {
684 water_tiles += hist[h_water_level];
685 if (water_tiles >= desired_water_tiles) break;
688 /* We now have the proper water level value.
689 * Transform the height map into new (normalized) height map:
690 * values from range: h_min..h_water_level will become negative so it will be clamped to 0
691 * values from range: h_water_level..h_max are transformed into 0..h_max_new
692 * where h_max_new is depending on terrain type and map size.
694 FOR_ALL_TILES_IN_HEIGHT(h) {
695 /* Transform height from range h_water_level..h_max into 0..h_max_new range */
696 *h = (height_t)(((int)h_max_new) * (*h - h_water_level) / (h_max - h_water_level)) + I2H(1);
697 /* Make sure all values are in the proper range (0..h_max_new) */
698 if (*h < 0) *h = I2H(0);
699 if (*h >= h_max_new) *h = h_max_new - 1;
702 free(hist_buf);
705 static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime);
708 * This routine sculpts in from the edge a random amount, again a Perlin
709 * sequence, to avoid the rigid flat-edge slopes that were present before. The
710 * Perlin noise map doesn't know where we are going to slice across, and so we
711 * often cut straight through high terrain. The smoothing routine makes it
712 * legal, gradually increasing up from the edge to the original terrain height.
713 * By cutting parts of this away, it gives a far more irregular edge to the
714 * map-edge. Sometimes it works beautifully with the existing sea & lakes, and
715 * creates a very realistic coastline. Other times the variation is less, and
716 * the map-edge shows its cliff-like roots.
718 * This routine may be extended to randomly sculpt the height of the terrain
719 * near the edge. This will have the coast edge at low level (1-3), rising in
720 * smoothed steps inland to about 15 tiles in. This should make it look as
721 * though the map has been built for the map size, rather than a slice through
722 * a larger map.
724 * Please note that all the small numbers; 53, 101, 167, etc. are small primes
725 * to help give the perlin noise a bit more of a random feel.
727 static void HeightMapCoastLines(uint8 water_borders)
729 int smallest_size = min(_settings_game.game_creation.map_x, _settings_game.game_creation.map_y);
730 const int margin = 4;
731 int y, x;
732 double max_x;
733 double max_y;
735 /* Lower to sea level */
736 for (y = 0; y <= _height_map.size_y; y++) {
737 if (HasBit(water_borders, BORDER_NE)) {
738 /* Top right */
739 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);
740 max_x = max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
741 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
742 for (x = 0; x < max_x; x++) {
743 _height_map.height(x, y) = 0;
747 if (HasBit(water_borders, BORDER_SW)) {
748 /* Bottom left */
749 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);
750 max_x = max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
751 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
752 for (x = _height_map.size_x; x > (_height_map.size_x - 1 - max_x); x--) {
753 _height_map.height(x, y) = 0;
758 /* Lower to sea level */
759 for (x = 0; x <= _height_map.size_x; x++) {
760 if (HasBit(water_borders, BORDER_NW)) {
761 /* Top left */
762 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);
763 max_y = max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
764 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
765 for (y = 0; y < max_y; y++) {
766 _height_map.height(x, y) = 0;
770 if (HasBit(water_borders, BORDER_SE)) {
771 /* Bottom right */
772 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);
773 max_y = max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
774 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
775 for (y = _height_map.size_y; y > (_height_map.size_y - 1 - max_y); y--) {
776 _height_map.height(x, y) = 0;
782 /** Start at given point, move in given direction, find and Smooth coast in that direction */
783 static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int dir_y)
785 const int max_coast_dist_from_edge = 35;
786 const int max_coast_Smooth_depth = 35;
788 int x, y;
789 int ed; // coast distance from edge
790 int depth;
792 height_t h_prev = I2H(1);
793 height_t h;
795 assert(IsValidXY(org_x, org_y));
797 /* Search for the coast (first non-water tile) */
798 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++) {
799 /* Coast found? */
800 if (_height_map.height(x, y) >= I2H(1)) break;
802 /* Coast found in the neighborhood? */
803 if (IsValidXY(x + dir_y, y + dir_x) && _height_map.height(x + dir_y, y + dir_x) > 0) break;
805 /* Coast found in the neighborhood on the other side */
806 if (IsValidXY(x - dir_y, y - dir_x) && _height_map.height(x - dir_y, y - dir_x) > 0) break;
809 /* Coast found or max_coast_dist_from_edge has been reached.
810 * Soften the coast slope */
811 for (depth = 0; IsValidXY(x, y) && depth <= max_coast_Smooth_depth; depth++, x += dir_x, y += dir_y) {
812 h = _height_map.height(x, y);
813 h = min(h, h_prev + (4 + depth)); // coast softening formula
814 _height_map.height(x, y) = h;
815 h_prev = h;
819 /** Smooth coasts by modulating height of tiles close to map edges with cosine of distance from edge */
820 static void HeightMapSmoothCoasts(uint8 water_borders)
822 int x, y;
823 /* First Smooth NW and SE coasts (y close to 0 and y close to size_y) */
824 for (x = 0; x < _height_map.size_x; x++) {
825 if (HasBit(water_borders, BORDER_NW)) HeightMapSmoothCoastInDirection(x, 0, 0, 1);
826 if (HasBit(water_borders, BORDER_SE)) HeightMapSmoothCoastInDirection(x, _height_map.size_y - 1, 0, -1);
828 /* First Smooth NE and SW coasts (x close to 0 and x close to size_x) */
829 for (y = 0; y < _height_map.size_y; y++) {
830 if (HasBit(water_borders, BORDER_NE)) HeightMapSmoothCoastInDirection(0, y, 1, 0);
831 if (HasBit(water_borders, BORDER_SW)) HeightMapSmoothCoastInDirection(_height_map.size_x - 1, y, -1, 0);
836 * This routine provides the essential cleanup necessary before OTTD can
837 * display the terrain. When generated, the terrain heights can jump more than
838 * one level between tiles. This routine smooths out those differences so that
839 * the most it can change is one level. When OTTD can support cliffs, this
840 * routine may not be necessary.
842 static void HeightMapSmoothSlopes(height_t dh_max)
844 for (int y = 0; y <= (int)_height_map.size_y; y++) {
845 for (int x = 0; x <= (int)_height_map.size_x; x++) {
846 height_t h_max = min(_height_map.height(x > 0 ? x - 1 : x, y), _height_map.height(x, y > 0 ? y - 1 : y)) + dh_max;
847 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
850 for (int y = _height_map.size_y; y >= 0; y--) {
851 for (int x = _height_map.size_x; x >= 0; x--) {
852 height_t h_max = 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;
853 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
859 * Height map terraform post processing:
860 * - water level adjusting
861 * - coast Smoothing
862 * - slope Smoothing
863 * - height histogram redistribution by sine wave transform
865 static void HeightMapNormalize()
867 int sea_level_setting = _settings_game.difficulty.quantity_sea_lakes;
868 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;
869 const height_t h_max_new = TGPGetMaxHeight();
870 const height_t roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness;
872 HeightMapAdjustWaterLevel(water_percent, h_max_new);
874 byte water_borders = _settings_game.construction.freeform_edges ? _settings_game.game_creation.water_borders : 0xF;
875 if (water_borders == BORDERS_RANDOM) water_borders = GB(Random(), 0, 4);
877 HeightMapCoastLines(water_borders);
878 HeightMapSmoothSlopes(roughness);
880 HeightMapSmoothCoasts(water_borders);
881 HeightMapSmoothSlopes(roughness);
883 HeightMapSineTransform(12, h_max_new);
885 if (_settings_game.game_creation.variety > 0) {
886 HeightMapCurves(_settings_game.game_creation.variety);
889 HeightMapSmoothSlopes(16);
893 * The Perlin Noise calculation using large primes
894 * The initial number is adjusted by two values; the generation_seed, and the
895 * passed parameter; prime.
896 * prime is used to allow the perlin noise generator to create useful random
897 * numbers from slightly different series.
899 static double int_noise(const long x, const long y, const int prime)
901 long n = x + y * prime + _settings_game.game_creation.generation_seed;
903 n = (n << 13) ^ n;
905 /* Pseudo-random number generator, using several large primes */
906 return 1.0 - (double)((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0;
911 * This routine determines the interpolated value between a and b
913 static inline double linear_interpolate(const double a, const double b, const double x)
915 return a + x * (b - a);
920 * This routine returns the smoothed interpolated noise for an x and y, using
921 * the values from the surrounding positions.
923 static double interpolated_noise(const double x, const double y, const int prime)
925 const int integer_X = (int)x;
926 const int integer_Y = (int)y;
928 const double fractional_X = x - (double)integer_X;
929 const double fractional_Y = y - (double)integer_Y;
931 const double v1 = int_noise(integer_X, integer_Y, prime);
932 const double v2 = int_noise(integer_X + 1, integer_Y, prime);
933 const double v3 = int_noise(integer_X, integer_Y + 1, prime);
934 const double v4 = int_noise(integer_X + 1, integer_Y + 1, prime);
936 const double i1 = linear_interpolate(v1, v2, fractional_X);
937 const double i2 = linear_interpolate(v3, v4, fractional_X);
939 return linear_interpolate(i1, i2, fractional_Y);
944 * This is a similar function to the main perlin noise calculation, but uses
945 * the value p passed as a parameter rather than selected from the predefined
946 * sequences. as you can guess by its title, i use this to create the indented
947 * coastline, which is just another perlin sequence.
949 static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime)
951 double total = 0.0;
953 for (int i = 0; i < 6; i++) {
954 const double frequency = (double)(1 << i);
955 const double amplitude = pow(p, (double)i);
957 total += interpolated_noise((x * frequency) / 64.0, (y * frequency) / 64.0, prime) * amplitude;
960 return total;
964 /** A small helper function to initialize the terrain */
965 static void TgenSetTileHeight(TileIndex tile, int height)
967 SetTileHeight(tile, height);
969 /* Only clear the tiles within the map area. */
970 if (IsInnerTile(tile)) {
971 MakeClear(tile, GROUND_GRASS, 3);
976 * The main new land generator using Perlin noise. Desert landscape is handled
977 * different to all others to give a desert valley between two high mountains.
978 * Clearly if a low height terrain (flat/very flat) is chosen, then the tropic
979 * areas wont be high enough, and there will be very little tropic on the map.
980 * Thus Tropic works best on Hilly or Mountainous.
982 void GenerateTerrainPerlin()
984 if (!AllocHeightMap()) return;
985 GenerateWorldSetAbortCallback(FreeHeightMap);
987 HeightMapGenerate();
989 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
991 HeightMapNormalize();
993 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
995 /* First make sure the tiles at the north border are void tiles if needed. */
996 if (_settings_game.construction.freeform_edges) {
997 for (int y = 0; y < _height_map.size_y - 1; y++) MakeVoid(_height_map.size_x * y);
998 for (int x = 0; x < _height_map.size_x; x++) MakeVoid(x);
1001 int max_height = H2I(TGPGetMaxHeight());
1003 /* Transfer height map into OTTD map */
1004 for (int y = 0; y < _height_map.size_y; y++) {
1005 for (int x = 0; x < _height_map.size_x; x++) {
1006 TgenSetTileHeight(TileXY(x, y), Clamp(H2I(_height_map.height(x, y)), 0, max_height));
1010 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
1012 FreeHeightMap();
1013 GenerateWorldSetAbortCallback(NULL);