OpenTTD Source 20250205-master-gfd85ab1e2c
tgp.cpp
Go to the documentation of this file.
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 */
7
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"
16
17#include "safeguards.h"
18
19/*
20 *
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.
31 *
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.
42 *
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.
46 *
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.
53 *
54 *
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.
60 *
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.
66 *
67 *
68 * For a full discussion of Perlin Noise, please visit:
69 * http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
70 *
71 *
72 * Evolution II
73 *
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.
80 *
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.
84 *
85 * I will try to explain it on the example below:
86 *
87 * Have a map of 4x4 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:
90 *
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
95 *
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
100 *
101 *
102 * Optimization 1:
103 *
104 * 1) we need to allocate a bit more tiles: (size_x + 1) * (size_y + 1) = (5 * 5):
105 *
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 }
112 *
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 }
119 *
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 }
126 *
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 }
133 *
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 }
140 *
141 *
142 *
143 * Optimization 2:
144 *
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.
149 *
150 */
151
153using Height = int16_t;
154static const int HEIGHT_DECIMAL_BITS = 4;
155
157using Amplitude = int;
158static const int AMPLITUDE_DECIMAL_BITS = 10;
159
162{
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()
169
176 inline Height &height(uint x, uint y)
177 {
178 return h[x + y * dim_x];
179 }
180};
181
183static HeightMap _height_map = { {}, 0, 0, 0 };
184
186static Height I2H(int i)
187{
188 return i << HEIGHT_DECIMAL_BITS;
189}
190
192static int H2I(Height i)
193{
194 return i >> HEIGHT_DECIMAL_BITS;
195}
196
199{
200 return i >> (AMPLITUDE_DECIMAL_BITS - HEIGHT_DECIMAL_BITS);
201}
202
204static const int MAX_TGP_FREQUENCIES = 10;
205
206static constexpr int WATER_PERCENT_FACTOR = 1024;
207
209static const int64_t _water_percent[4] = {70, 170, 270, 420};
210
218{
220 /* TGP never reaches this height; this means that if a user inputs "2",
221 * it would create a flat map without the "+ 1". But that would
222 * overflow on "255". So we reduce it by 1 to get back in range. */
224 }
225
236 static const int max_height[5][MAX_MAP_SIZE_BITS - MIN_MAP_SIZE_BITS + 1] = {
237 /* 64 128 256 512 1024 2048 4096 */
238 { 3, 3, 3, 3, 4, 5, 7 },
239 { 5, 7, 8, 9, 14, 19, 31 },
240 { 8, 9, 10, 15, 23, 37, 61 },
241 { 10, 11, 17, 19, 49, 63, 73 },
242 { 12, 19, 25, 31, 67, 75, 87 },
243 };
244
245 int map_size_bucket = std::min(Map::LogX(), Map::LogY()) - MIN_MAP_SIZE_BITS;
246 int max_height_from_table = max_height[_settings_game.difficulty.terrain_type][map_size_bucket];
247
248 /* If there is a manual map height limit, clamp to it. */
250 max_height_from_table = std::min<uint>(max_height_from_table, _settings_game.construction.map_height_limit);
251 }
252
253 return I2H(max_height_from_table);
254}
255
260{
261 return H2I(TGPGetMaxHeight());
262}
263
270static Amplitude GetAmplitude(int frequency)
271{
272 /* Base noise amplitudes (multiplied by 1024) and indexed by "smoothness setting" and log2(frequency). */
273 static const Amplitude amplitudes[][7] = {
274 /* lowest frequency ...... highest (every corner) */
275 {16000, 5600, 1968, 688, 240, 16, 16},
276 {24000, 12800, 6400, 2700, 1024, 128, 16},
277 {32000, 19200, 12800, 8000, 3200, 256, 64},
278 {48000, 24000, 19200, 16000, 8000, 512, 320},
279 };
280 /*
281 * Extrapolation factors for ranges before the table.
282 * The extrapolation is needed to account for the higher map heights. They need larger
283 * areas with a particular gradient so that we are able to create maps without too
284 * many steep slopes up to the wanted height level. It's definitely not perfect since
285 * it will bring larger rectangles with similar slopes which makes the rectangular
286 * behaviour of TGP more noticeable. However, these height differentiations cannot
287 * happen over much smaller areas; we basically double the "range" to give a similar
288 * slope for every doubling of map height.
289 */
290 static const double extrapolation_factors[] = { 3.3, 2.8, 2.3, 1.8 };
291
293
294 /* Get the table index, and return that value if possible. */
295 int index = frequency - MAX_TGP_FREQUENCIES + static_cast<int>(std::size(amplitudes[smoothness]));
296 Amplitude amplitude = amplitudes[smoothness][std::max(0, index)];
297 if (index >= 0) return amplitude;
298
299 /* We need to extrapolate the amplitude. */
300 double extrapolation_factor = extrapolation_factors[smoothness];
301 int height_range = I2H(16);
302 do {
303 amplitude = (Amplitude)(extrapolation_factor * (double)amplitude);
304 height_range <<= 1;
305 index++;
306 } while (index < 0);
307
308 return Clamp((TGPGetMaxHeight() - height_range) / height_range, 0, 1) * amplitude;
309}
310
317static inline bool IsValidXY(int x, int y)
318{
319 return x >= 0 && x < _height_map.size_x && y >= 0 && y < _height_map.size_y;
320}
321
322
326static inline void AllocHeightMap()
327{
328 assert(_height_map.h.empty());
329
330 _height_map.size_x = Map::SizeX();
331 _height_map.size_y = Map::SizeY();
332
333 /* Allocate memory block for height map row pointers */
334 size_t total_size = static_cast<size_t>(_height_map.size_x + 1) * (_height_map.size_y + 1);
335 _height_map.dim_x = _height_map.size_x + 1;
336 _height_map.h.resize(total_size);
337}
338
340static inline void FreeHeightMap()
341{
342 _height_map.h.clear();
343}
344
350static inline Height RandomHeight(Amplitude r_max)
351{
352 /* Spread height into range -r_max..+r_max */
353 return A2H(RandomRange(2 * r_max + 1) - r_max);
354}
355
363static void HeightMapGenerate()
364{
365 /* Trying to apply noise to uninitialized height map */
366 assert(!_height_map.h.empty());
367
368 int start = std::max(MAX_TGP_FREQUENCIES - (int)std::min(Map::LogX(), Map::LogY()), 0);
369 bool first = true;
370
371 for (int frequency = start; frequency < MAX_TGP_FREQUENCIES; frequency++) {
372 const Amplitude amplitude = GetAmplitude(frequency);
373
374 /* Ignore zero amplitudes; it means our map isn't height enough for this
375 * amplitude, so ignore it and continue with the next set of amplitude. */
376 if (amplitude == 0) continue;
377
378 const int step = 1 << (MAX_TGP_FREQUENCIES - frequency - 1);
379
380 if (first) {
381 /* This is first round, we need to establish base heights with step = size_min */
382 for (int y = 0; y <= _height_map.size_y; y += step) {
383 for (int x = 0; x <= _height_map.size_x; x += step) {
384 Height height = (amplitude > 0) ? RandomHeight(amplitude) : 0;
385 _height_map.height(x, y) = height;
386 }
387 }
388 first = false;
389 continue;
390 }
391
392 /* It is regular iteration round.
393 * Interpolate height values at odd x, even y tiles */
394 for (int y = 0; y <= _height_map.size_y; y += 2 * step) {
395 for (int x = 0; x <= _height_map.size_x - 2 * step; x += 2 * step) {
396 Height h00 = _height_map.height(x + 0 * step, y);
397 Height h02 = _height_map.height(x + 2 * step, y);
398 Height h01 = (h00 + h02) / 2;
399 _height_map.height(x + 1 * step, y) = h01;
400 }
401 }
402
403 /* Interpolate height values at odd y tiles */
404 for (int y = 0; y <= _height_map.size_y - 2 * step; y += 2 * step) {
405 for (int x = 0; x <= _height_map.size_x; x += step) {
406 Height h00 = _height_map.height(x, y + 0 * step);
407 Height h20 = _height_map.height(x, y + 2 * step);
408 Height h10 = (h00 + h20) / 2;
409 _height_map.height(x, y + 1 * step) = h10;
410 }
411 }
412
413 /* Add noise for next higher frequency (smaller steps) */
414 for (int y = 0; y <= _height_map.size_y; y += step) {
415 for (int x = 0; x <= _height_map.size_x; x += step) {
416 _height_map.height(x, y) += RandomHeight(amplitude);
417 }
418 }
419 }
420}
421
423static void HeightMapGetMinMaxAvg(Height *min_ptr, Height *max_ptr, Height *avg_ptr)
424{
425 Height h_min, h_max, h_avg;
426 int64_t h_accu = 0;
427 h_min = h_max = _height_map.height(0, 0);
428
429 /* Get h_min, h_max and accumulate heights into h_accu */
430 for (const Height &h : _height_map.h) {
431 if (h < h_min) h_min = h;
432 if (h > h_max) h_max = h;
433 h_accu += h;
434 }
435
436 /* Get average height */
437 h_avg = (Height)(h_accu / (_height_map.size_x * _height_map.size_y));
438
439 /* Return required results */
440 if (min_ptr != nullptr) *min_ptr = h_min;
441 if (max_ptr != nullptr) *max_ptr = h_max;
442 if (avg_ptr != nullptr) *avg_ptr = h_avg;
443}
444
446static int *HeightMapMakeHistogram(Height h_min, [[maybe_unused]] Height h_max, int *hist_buf)
447{
448 int *hist = hist_buf - h_min;
449
450 /* Count the heights and fill the histogram */
451 for (const Height &h : _height_map.h) {
452 assert(h >= h_min);
453 assert(h <= h_max);
454 hist[h]++;
455 }
456 return hist;
457}
458
460static void HeightMapSineTransform(Height h_min, Height h_max)
461{
462 for (Height &h : _height_map.h) {
463 double fheight;
464
465 if (h < h_min) continue;
466
467 /* Transform height into 0..1 space */
468 fheight = (double)(h - h_min) / (double)(h_max - h_min);
469 /* Apply sine transform depending on landscape type */
471 case LandscapeType::Toyland:
472 case LandscapeType::Temperate:
473 /* Move and scale 0..1 into -1..+1 */
474 fheight = 2 * fheight - 1;
475 /* Sine transform */
476 fheight = sin(fheight * M_PI_2);
477 /* Transform it back from -1..1 into 0..1 space */
478 fheight = 0.5 * (fheight + 1);
479 break;
480
481 case LandscapeType::Arctic:
482 {
483 /* Arctic terrain needs special height distribution.
484 * Redistribute heights to have more tiles at highest (75%..100%) range */
485 double sine_upper_limit = 0.75;
486 double linear_compression = 2;
487 if (fheight >= sine_upper_limit) {
488 /* Over the limit we do linear compression up */
489 fheight = 1.0 - (1.0 - fheight) / linear_compression;
490 } else {
491 double m = 1.0 - (1.0 - sine_upper_limit) / linear_compression;
492 /* Get 0..sine_upper_limit into -1..1 */
493 fheight = 2.0 * fheight / sine_upper_limit - 1.0;
494 /* Sine wave transform */
495 fheight = sin(fheight * M_PI_2);
496 /* Get -1..1 back to 0..(1 - (1 - sine_upper_limit) / linear_compression) == 0.0..m */
497 fheight = 0.5 * (fheight + 1.0) * m;
498 }
499 }
500 break;
501
502 case LandscapeType::Tropic:
503 {
504 /* Desert terrain needs special height distribution.
505 * Half of tiles should be at lowest (0..25%) heights */
506 double sine_lower_limit = 0.5;
507 double linear_compression = 2;
508 if (fheight <= sine_lower_limit) {
509 /* Under the limit we do linear compression down */
510 fheight = fheight / linear_compression;
511 } else {
512 double m = sine_lower_limit / linear_compression;
513 /* Get sine_lower_limit..1 into -1..1 */
514 fheight = 2.0 * ((fheight - sine_lower_limit) / (1.0 - sine_lower_limit)) - 1.0;
515 /* Sine wave transform */
516 fheight = sin(fheight * M_PI_2);
517 /* Get -1..1 back to (sine_lower_limit / linear_compression)..1.0 */
518 fheight = 0.5 * ((1.0 - m) * fheight + (1.0 + m));
519 }
520 }
521 break;
522
523 default:
524 NOT_REACHED();
525 break;
526 }
527 /* Transform it back into h_min..h_max space */
528 h = (Height)(fheight * (h_max - h_min) + h_min);
529 if (h < 0) h = I2H(0);
530 if (h >= h_max) h = h_max - 1;
531 }
532}
533
550static void HeightMapCurves(uint level)
551{
552 Height mh = TGPGetMaxHeight() - I2H(1); // height levels above sea level only
553
555 struct ControlPoint {
556 Height x;
557 Height y;
558 };
559 /* Scaled curve maps; value is in height_ts. */
560#define F(fraction) ((Height)(fraction * mh))
561 const ControlPoint curve_map_1[] = { { F(0.0), F(0.0) }, { F(0.8), F(0.13) }, { F(1.0), F(0.4) } };
562 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) } };
563 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) } };
564 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) } };
565#undef F
566
567 const std::span<const ControlPoint> curve_maps[] = { curve_map_1, curve_map_2, curve_map_3, curve_map_4 };
568
569 std::array<Height, std::size(curve_maps)> ht{};
570
571 /* Set up a grid to choose curve maps based on location; attempt to get a somewhat square grid */
572 float factor = sqrt((float)_height_map.size_x / (float)_height_map.size_y);
573 uint sx = Clamp((int)(((1 << level) * factor) + 0.5), 1, 128);
574 uint sy = Clamp((int)(((1 << level) / factor) + 0.5), 1, 128);
575 std::vector<uint8_t> c(static_cast<size_t>(sx) * sy);
576
577 for (uint i = 0; i < sx * sy; i++) {
578 c[i] = RandomRange(static_cast<uint32_t>(std::size(curve_maps)));
579 }
580
581 /* Apply curves */
582 for (int x = 0; x < _height_map.size_x; x++) {
583
584 /* Get our X grid positions and bi-linear ratio */
585 float fx = (float)(sx * x) / _height_map.size_x + 1.0f;
586 uint x1 = (uint)fx;
587 uint x2 = x1;
588 float xr = 2.0f * (fx - x1) - 1.0f;
589 xr = sin(xr * M_PI_2);
590 xr = sin(xr * M_PI_2);
591 xr = 0.5f * (xr + 1.0f);
592 float xri = 1.0f - xr;
593
594 if (x1 > 0) {
595 x1--;
596 if (x2 >= sx) x2--;
597 }
598
599 for (int y = 0; y < _height_map.size_y; y++) {
600
601 /* Get our Y grid position and bi-linear ratio */
602 float fy = (float)(sy * y) / _height_map.size_y + 1.0f;
603 uint y1 = (uint)fy;
604 uint y2 = y1;
605 float yr = 2.0f * (fy - y1) - 1.0f;
606 yr = sin(yr * M_PI_2);
607 yr = sin(yr * M_PI_2);
608 yr = 0.5f * (yr + 1.0f);
609 float yri = 1.0f - yr;
610
611 if (y1 > 0) {
612 y1--;
613 if (y2 >= sy) y2--;
614 }
615
616 uint corner_a = c[x1 + sx * y1];
617 uint corner_b = c[x1 + sx * y2];
618 uint corner_c = c[x2 + sx * y1];
619 uint corner_d = c[x2 + sx * y2];
620
621 /* Bitmask of which curve maps are chosen, so that we do not bother
622 * calculating a curve which won't be used. */
623 uint corner_bits = 0;
624 corner_bits |= 1 << corner_a;
625 corner_bits |= 1 << corner_b;
626 corner_bits |= 1 << corner_c;
627 corner_bits |= 1 << corner_d;
628
629 Height *h = &_height_map.height(x, y);
630
631 /* Do not touch sea level */
632 if (*h < I2H(1)) continue;
633
634 /* Only scale above sea level */
635 *h -= I2H(1);
636
637 /* Apply all curve maps that are used on this tile. */
638 for (size_t t = 0; t < std::size(curve_maps); t++) {
639 if (!HasBit(corner_bits, static_cast<uint8_t>(t))) continue;
640
641 [[maybe_unused]] bool found = false;
642 auto &cm = curve_maps[t];
643 for (size_t i = 0; i < cm.size() - 1; i++) {
644 const ControlPoint &p1 = cm[i];
645 const ControlPoint &p2 = cm[i + 1];
646
647 if (*h >= p1.x && *h < p2.x) {
648 ht[t] = p1.y + (*h - p1.x) * (p2.y - p1.y) / (p2.x - p1.x);
649#ifdef WITH_ASSERT
650 found = true;
651#endif
652 break;
653 }
654 }
655 assert(found);
656 }
657
658 /* Apply interpolation of curve map results. */
659 *h = (Height)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr);
660
661 /* Readd sea level */
662 *h += I2H(1);
663 }
664 }
665}
666
668static void HeightMapAdjustWaterLevel(int64_t water_percent, Height h_max_new)
669{
670 Height h_min, h_max, h_avg, h_water_level;
671 int64_t water_tiles, desired_water_tiles;
672 int *hist;
673
674 HeightMapGetMinMaxAvg(&h_min, &h_max, &h_avg);
675
676 /* Allocate histogram buffer and clear its cells */
677 std::vector<int> hist_buf(h_max - h_min + 1);
678 /* Fill histogram */
679 hist = HeightMapMakeHistogram(h_min, h_max, hist_buf.data());
680
681 /* How many water tiles do we want? */
682 desired_water_tiles = water_percent * _height_map.size_x * _height_map.size_y / WATER_PERCENT_FACTOR;
683
684 /* Raise water_level and accumulate values from histogram until we reach required number of water tiles */
685 for (h_water_level = h_min, water_tiles = 0; h_water_level < h_max; h_water_level++) {
686 water_tiles += hist[h_water_level];
687 if (water_tiles >= desired_water_tiles) break;
688 }
689
690 /* We now have the proper water level value.
691 * Transform the height map into new (normalized) height map:
692 * values from range: h_min..h_water_level will become negative so it will be clamped to 0
693 * values from range: h_water_level..h_max are transformed into 0..h_max_new
694 * where h_max_new is depending on terrain type and map size.
695 */
696 for (Height &h : _height_map.h) {
697 /* Transform height from range h_water_level..h_max into 0..h_max_new range */
698 h = (Height)(((int)h_max_new) * (h - h_water_level) / (h_max - h_water_level)) + I2H(1);
699 /* Make sure all values are in the proper range (0..h_max_new) */
700 if (h < 0) h = I2H(0);
701 if (h >= h_max_new) h = h_max_new - 1;
702 }
703}
704
705static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime);
706
727static void HeightMapCoastLines(BorderFlags water_borders)
728{
730 const int margin = 4;
731 int y, x;
732 double max_x;
733 double max_y;
734
735 /* Lower to sea level */
736 for (y = 0; y <= _height_map.size_y; y++) {
737 if (water_borders.Test(BorderFlag::NorthEast)) {
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 = std::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;
744 }
745 }
746
747 if (water_borders.Test(BorderFlag::SouthWest)) {
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 = std::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;
754 }
755 }
756 }
757
758 /* Lower to sea level */
759 for (x = 0; x <= _height_map.size_x; x++) {
760 if (water_borders.Test(BorderFlag::NorthWest)) {
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 = std::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;
767 }
768 }
769
770 if (water_borders.Test(BorderFlag::SouthEast)) {
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 = std::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;
777 }
778 }
779 }
780}
781
783static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int dir_y)
784{
785 const int max_coast_dist_from_edge = 35;
786 const int max_coast_smooth_depth = 35;
787
788 int x, y;
789 int ed; // coast distance from edge
790 int depth;
791
792 Height h_prev = I2H(1);
793 Height h;
794
795 assert(IsValidXY(org_x, org_y));
796
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;
801
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;
804
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;
807 }
808
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 = static_cast<Height>(std::min<uint>(h, h_prev + (4 + depth))); // coast softening formula
814 _height_map.height(x, y) = h;
815 h_prev = h;
816 }
817}
818
820static void HeightMapSmoothCoasts(BorderFlags water_borders)
821{
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 (water_borders.Test(BorderFlag::NorthWest)) HeightMapSmoothCoastInDirection(x, 0, 0, 1);
826 if (water_borders.Test(BorderFlag::SouthEast)) HeightMapSmoothCoastInDirection(x, _height_map.size_y - 1, 0, -1);
827 }
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 (water_borders.Test(BorderFlag::NorthEast)) HeightMapSmoothCoastInDirection(0, y, 1, 0);
831 if (water_borders.Test(BorderFlag::SouthWest)) HeightMapSmoothCoastInDirection(_height_map.size_x - 1, y, -1, 0);
832 }
833}
834
842static void HeightMapSmoothSlopes(Height dh_max)
843{
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 h_max = std::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;
848 }
849 }
850 for (int y = _height_map.size_y; y >= 0; y--) {
851 for (int x = _height_map.size_x; x >= 0; x--) {
852 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;
853 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
854 }
855 }
856}
857
866{
868 const Height h_max_new = TGPGetMaxHeight();
869 const Height roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness;
870
871 HeightMapAdjustWaterLevel(water_percent, h_max_new);
872
874 if (water_borders == BorderFlag::Random) water_borders = static_cast<BorderFlags>(GB(Random(), 0, 4));
875
876 HeightMapCoastLines(water_borders);
877 HeightMapSmoothSlopes(roughness);
878
879 HeightMapSmoothCoasts(water_borders);
880 HeightMapSmoothSlopes(roughness);
881
882 HeightMapSineTransform(I2H(1), h_max_new);
883
886 }
887
889}
890
898static double int_noise(const long x, const long y, const int prime)
899{
900 long n = x + y * prime + _settings_game.game_creation.generation_seed;
901
902 n = (n << 13) ^ n;
903
904 /* Pseudo-random number generator, using several large primes */
905 return 1.0 - (double)((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0;
906}
907
908
912static inline double linear_interpolate(const double a, const double b, const double x)
913{
914 return a + x * (b - a);
915}
916
917
922static double interpolated_noise(const double x, const double y, const int prime)
923{
924 const int integer_x = (int)x;
925 const int integer_y = (int)y;
926
927 const double fractional_x = x - (double)integer_x;
928 const double fractional_y = y - (double)integer_y;
929
930 const double v1 = int_noise(integer_x, integer_y, prime);
931 const double v2 = int_noise(integer_x + 1, integer_y, prime);
932 const double v3 = int_noise(integer_x, integer_y + 1, prime);
933 const double v4 = int_noise(integer_x + 1, integer_y + 1, prime);
934
935 const double i1 = linear_interpolate(v1, v2, fractional_x);
936 const double i2 = linear_interpolate(v3, v4, fractional_x);
937
938 return linear_interpolate(i1, i2, fractional_y);
939}
940
941
948static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime)
949{
950 double total = 0.0;
951
952 for (int i = 0; i < 6; i++) {
953 const double frequency = (double)(1 << i);
954 const double amplitude = pow(p, (double)i);
955
956 total += interpolated_noise((x * frequency) / 64.0, (y * frequency) / 64.0, prime) * amplitude;
957 }
958
959 return total;
960}
961
962
964static void TgenSetTileHeight(TileIndex tile, int height)
965{
966 SetTileHeight(tile, height);
967
968 /* Only clear the tiles within the map area. */
969 if (IsInnerTile(tile)) {
970 MakeClear(tile, CLEAR_GRASS, 3);
971 }
972}
973
982{
985
987
989
991
993
994 /* First make sure the tiles at the north border are void tiles if needed. */
996 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, 0));
997 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(0, y));
998 }
999
1000 int max_height = H2I(TGPGetMaxHeight());
1001
1002 /* Transfer height map into OTTD map */
1003 for (int y = 0; y < _height_map.size_y; y++) {
1004 for (int x = 0; x < _height_map.size_x; x++) {
1005 TgenSetTileHeight(TileXY(x, y), Clamp(H2I(_height_map.height(x, y)), 0, max_height));
1006 }
1007 }
1008
1010
1011 FreeHeightMap();
1013}
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool Test(Tenum value) const
Test if the enum value is set.
Map accessors for 'clear' tiles.
@ CLEAR_GRASS
0-3
Definition clear_map.h:20
void MakeClear(Tile t, ClearGround g, uint density)
Make a clear tile.
Definition clear_map.h:259
void GenerateWorldSetAbortCallback(GWAbortProc *proc)
Set here the function, if any, that you want to be called when landscape generation is aborted.
Definition genworld.cpp:246
Functions related to world/map generation.
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
static const uint CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
Value for custom sea level in difficulty settings.
Definition genworld.h:48
@ GWP_LANDSCAPE
Create the landscape.
Definition genworld.h:74
static const uint CUSTOM_TERRAIN_TYPE_NUMBER_DIFFICULTY
Value for custom terrain type in difficulty settings.
Definition genworld.h:46
Types related to the landscape.
static constexpr BorderFlags BORDERFLAGS_ALL
Border on all sides.
@ NorthWest
Border on North West.
@ Random
Randomise borders.
@ NorthEast
Border on North East.
@ SouthEast
Border on South East.
@ SouthWest
Border on South West.
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:373
static const uint MIN_MAP_SIZE_BITS
Minimal and maximal map width and height.
Definition map_type.h:37
static const uint MAX_MAP_SIZE_BITS
Maximal size of map is equal to 2 ^ MAX_MAP_SIZE_BITS.
Definition map_type.h:38
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:57
Definition of base types and functions in a cross-platform compatible way.
bool freeform_edges
allow terraforming the tiles at the map edges
uint8_t map_height_limit
the maximum allowed heightlevel
uint8_t terrain_type
the mountainousness of the landscape
uint8_t quantity_sea_lakes
the amount of seas/lakes
uint8_t custom_sea_level
manually entered percentage of water in the map
uint8_t variety
variety level applied to TGP
uint8_t custom_terrain_type
manually entered height for TGP to aim for
LandscapeType landscape
the landscape we're currently in
uint8_t map_x
X size of map.
uint8_t tgen_smoothness
how rough is the terrain from 0-3
uint8_t map_y
Y size of map.
BorderFlags water_borders
bitset of the borders that are water
uint32_t generation_seed
noise seed for world generation
ConstructionSettings construction
construction of things in-game
DifficultySettings difficulty
settings related to the difficulty
GameCreationSettings game_creation
settings used during the creation of a game (map)
Height map - allocated array of heights (Map::SizeX() + 1) * (Map::SizeY() + 1)
Definition tgp.cpp:162
Height & height(uint x, uint y)
Height map accessor.
Definition tgp.cpp:176
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:279
static debug_inline uint SizeX()
Get the size of the map along the X.
Definition map_func.h:270
static debug_inline uint LogX()
Logarithm of the map size along the X side.
Definition map_func.h:251
static uint LogY()
Logarithm of the map size along the y side.
Definition map_func.h:261
static Height RandomHeight(Amplitude r_max)
Generates new random height in given amplitude (generated numbers will range from - amplitude to + am...
Definition tgp.cpp:350
static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int dir_y)
Start at given point, move in given direction, find and Smooth coast in that direction.
Definition tgp.cpp:783
static Height A2H(Amplitude i)
Conversion: Amplitude to Height.
Definition tgp.cpp:198
static void HeightMapGenerate()
Base Perlin noise generator - fills height map with raw Perlin noise.
Definition tgp.cpp:363
static double linear_interpolate(const double a, const double b, const double x)
This routine determines the interpolated value between a and b.
Definition tgp.cpp:912
static Height TGPGetMaxHeight()
Gets the maximum allowed height while generating a map based on mapsize, terraintype,...
Definition tgp.cpp:217
static void HeightMapCoastLines(BorderFlags water_borders)
This routine sculpts in from the edge a random amount, again a Perlin sequence, to avoid the rigid fl...
Definition tgp.cpp:727
static Height I2H(int i)
Conversion: int to Height.
Definition tgp.cpp:186
static int H2I(Height i)
Conversion: Height to int.
Definition tgp.cpp:192
static void HeightMapGetMinMaxAvg(Height *min_ptr, Height *max_ptr, Height *avg_ptr)
Returns min, max and average height from height map.
Definition tgp.cpp:423
static void HeightMapSmoothSlopes(Height dh_max)
This routine provides the essential cleanup necessary before OTTD can display the terrain.
Definition tgp.cpp:842
static const int64_t _water_percent[4]
Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes.
Definition tgp.cpp:209
int16_t Height
Fixed point type for heights.
Definition tgp.cpp:153
static Amplitude GetAmplitude(int frequency)
Get the amplitude associated with the currently selected smoothness and maximum height level.
Definition tgp.cpp:270
static int * HeightMapMakeHistogram(Height h_min, Height h_max, int *hist_buf)
Dill histogram and return pointer to its base point - to the count of zero heights.
Definition tgp.cpp:446
static void FreeHeightMap()
Free height map.
Definition tgp.cpp:340
int Amplitude
Fixed point array for amplitudes.
Definition tgp.cpp:157
uint GetEstimationTGPMapHeight()
Get an overestimation of the highest peak TGP wants to generate.
Definition tgp.cpp:259
static void HeightMapAdjustWaterLevel(int64_t water_percent, Height h_max_new)
Adjusts heights in height map to contain required amount of water tiles.
Definition tgp.cpp:668
static void HeightMapSineTransform(Height h_min, Height h_max)
Applies sine wave redistribution onto height map.
Definition tgp.cpp:460
static HeightMap _height_map
Global height map instance.
Definition tgp.cpp:183
static void HeightMapNormalize()
Height map terraform post processing:
Definition tgp.cpp:865
static void HeightMapSmoothCoasts(BorderFlags water_borders)
Smooth coasts by modulating height of tiles close to map edges with cosine of distance from edge.
Definition tgp.cpp:820
static bool IsValidXY(int x, int y)
Check if a X/Y set are within the map.
Definition tgp.cpp:317
static const int MAX_TGP_FREQUENCIES
Maximum number of TGP noise frequencies.
Definition tgp.cpp:204
static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime)
This is a similar function to the main perlin noise calculation, but uses the value p passed as a par...
Definition tgp.cpp:948
static void TgenSetTileHeight(TileIndex tile, int height)
A small helper function to initialize the terrain.
Definition tgp.cpp:964
void GenerateTerrainPerlin()
The main new land generator using Perlin noise.
Definition tgp.cpp:981
static double interpolated_noise(const double x, const double y, const int prime)
This routine returns the smoothed interpolated noise for an x and y, using the values from the surrou...
Definition tgp.cpp:922
static double int_noise(const long x, const long y, const int prime)
The Perlin Noise calculation using large primes The initial number is adjusted by two values; the gen...
Definition tgp.cpp:898
static void HeightMapCurves(uint level)
Additional map variety is provided by applying different curve maps to different parts of the map.
Definition tgp.cpp:550
static void AllocHeightMap()
Allocate array of (Map::SizeX() + 1) * (Map::SizeY() + 1) heights and init the _height_map structure ...
Definition tgp.cpp:326
bool IsInnerTile(Tile tile)
Check if a tile is within the map (not a border)
Definition tile_map.h:109
void SetTileHeight(Tile tile, uint height)
Sets the height of a tile.
Definition tile_map.h:57
Map accessors for void tiles.
void MakeVoid(Tile t)
Make a nice void tile ;)
Definition void_map.h:19