./
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
161 / 161
100.0%
Branches:
78 / 86
90.7%
Functions:
9 / 9, 2 excl
100.0%

include/terraingen/noise/fractal.h
Line Branch Exec Source
1 // SPDX-License-Identifier: BSD-3-Clause
2
3 /// @file
4 /// @brief Fractals (fBm, ridged, billow, hybrid) built from octaves of a basis noise.
5 #pragma once
6
7 #include "terraingen/noise/hash.h"
8 #include "terraingen/noise/perlin.h"
9 #include "terraingen/noise/simplex.h"
10 #include "terraingen/noise/value.h"
11 #include "terraingen/noise/worley.h"
12
13 #ifndef __SLANG__
14 #include <cstring>
15 #endif
16
17 namespace terraingen {
18
19 /// Single-octave noise function a fractal is built from.
20 enum class NoiseBasis : uint32_t {
21 Perlin = 0, ///< Improved gradient noise (`PerlinNoise2`).
22 Simplex = 1, ///< Simplex noise (`SimplexNoise2`).
23 Value = 2, ///< Value noise (`ValueNoise2`).
24 WorleyF1 = 3, ///< Distance to the nearest feature point; cones and basins.
25 WorleyF2 = 4, ///< Distance to the second-nearest feature point.
26 WorleyF2MinusF1 = 5, ///< F2 - F1; ridges along cell borders, like cracked ground.
27 Voronoi = 6, ///< Value of the nearest feature point's cell; flat polygonal plateaus.
28 };
29
30 /// Number of `NoiseBasis` values.
31 static const uint32_t kNoiseBasisCount = 7;
32
33 /// How octaves of the basis noise are combined.
34 enum class FractalType : uint32_t {
35 Fbm = 0, ///< Weighted sum of octaves (fractional Brownian motion).
36 Ridged = 1, ///< Ridged multifractal: sharp crests from inverted |noise|.
37 Billow = 2, ///< Sum of |noise| octaves: rounded, puffy forms.
38 HybridMultifractal = 3, ///< Smooth lowlands and rough highlands.
39 };
40
41 /// Number of `FractalType` values.
42 static const uint32_t kFractalTypeCount = 4;
43
44 /// Most octaves a fractal may have (`FractalParams::octaves`).
45 static const int kMaxFractalOctaves = 32;
46
47 /// Parameters of a fractal built from octaves of a basis noise.
48 ///
49 /// Octave i has wavelength `wavelength / lacunarity^i` and weight `gain^i`;
50 /// `gain = lacunarity^(-H)` gives Hurst exponent H (`GainFromHurst`). Checked on the host by
51 /// `ValidateFractalParams`.
52 struct FractalParams {
53 uint32_t seed = 0; ///< Seed; each octave derives its own seed and lattice offset.
54 float wavelength = 1000.0f; ///< Wavelength of the first octave, in world units (meters).
55 float amplitude = 100.0f; ///< Maximum absolute height, in world units (meters).
56 int octaves = 8; ///< Number of octaves; 1 to `kMaxFractalOctaves`.
57 float lacunarity = 2.0f; ///< Frequency ratio between successive octaves; greater than 1.
58 float gain = 0.5f; ///< Weight ratio between successive octaves; greater than 0.
59 NoiseBasis basis = NoiseBasis::Perlin; ///< Single-octave noise.
60 FractalType type = FractalType::Fbm; ///< How octaves combine.
61 float offset = 1.0f; ///< Ridge offset for `Ridged` and `HybridMultifractal`; > 0.
62
63 #ifndef __SLANG__
64 /// Memberwise equality.
65 15 bool operator==(const FractalParams& other) const {
66
2/2
✓ Branch 0 taken 12 times.
✓ Branch 1 taken 1 time.
13 return seed == other.seed && wavelength == other.wavelength &&
67
4/4
✓ Branch 0 taken 11 times.
✓ Branch 1 taken 1 time.
✓ Branch 2 taken 10 times.
✓ Branch 3 taken 1 time.
12 amplitude == other.amplitude && octaves == other.octaves &&
68
6/6
✓ Branch 0 taken 9 times.
✓ Branch 1 taken 1 time.
✓ Branch 2 taken 8 times.
✓ Branch 3 taken 1 time.
✓ Branch 4 taken 7 times.
✓ Branch 5 taken 1 time.
10 lacunarity == other.lacunarity && gain == other.gain && basis == other.basis &&
69
6/6
✓ Branch 0 taken 13 times.
✓ Branch 1 taken 2 times.
✓ Branch 2 taken 6 times.
✓ Branch 3 taken 1 time.
✓ Branch 4 taken 1 time.
✓ Branch 5 taken 5 times.
22 type == other.type && offset == other.offset;
70 }
71 bool operator!=(const FractalParams& other) const {
72 return !(*this == other);
73 }
74 #endif
75 };
76
77 /// Octave gain `lacunarity^(-hurst)` for a Hurst exponent; evaluated on the host, kernels only
78 /// get the gain.
79 /// @param hurst Hurst exponent H, usually in (0, 1].
80 /// @param lacunarity Frequency ratio between octaves, > 1.
81 23 inline float GainFromHurst(float hurst, float lacunarity) {
82
2/2
<unknown function 81>:
✓ Branch 1 taken 1 time.
<unknown function 82>:
✓ Branch 1 taken 1 time.
28 return pow(lacunarity, -hurst);
83 }
84
85 /// One octave of 2D `basis` noise; Worley distances are mapped linearly from [0, bound] to
86 /// [-1, 1], and Voronoi gives the cell value.
87 /// @param basis The basis; unknown values fall back to Perlin.
88 /// @return Noise in [-1, 1].
89 40683046 inline float BasisNoise2(NoiseBasis basis, float x, float y, uint32_t seed) {
90 40683048 constexpr float kInvSqrt2 = 0.707106781186547524f;
91 40683043 constexpr float kInvSqrt5 = 0.447213595499957939f;
92
7/7
✓ Branch 0 taken 257266 times.
✓ Branch 1 taken 225761 times.
✓ Branch 2 taken 486129 times.
✓ Branch 3 taken 209377 times.
✓ Branch 4 taken 205401 times.
✓ Branch 5 taken 184808 times.
✓ Branch 6 taken 39114302 times.
40683044 switch (basis) {
93 257266 case NoiseBasis::Simplex:
94
2/2
✓ Branch 0 taken 129579 times.
✓ Branch 1 taken 127687 times.
386845 return SimplexNoise2(x, y, seed);
95 225761 case NoiseBasis::Value:
96 225761 return ValueNoise2(x, y, seed);
97 486129 case NoiseBasis::WorleyF1:
98
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 486129 times.
486129 return 2.0f * min(Worley2(x, y, seed).f1 * kInvSqrt2, 1.0f) - 1.0f;
99 209377 case NoiseBasis::WorleyF2:
100
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 209377 times.
209377 return 2.0f * min(Worley2(x, y, seed).f2 * kInvSqrt5, 1.0f) - 1.0f;
101 205401 case NoiseBasis::WorleyF2MinusF1: {
102 205401 const WorleyDistances d = Worley2(x, y, seed);
103
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 205401 times.
205401 return 2.0f * min((d.f2 - d.f1) * kInvSqrt5, 1.0f) - 1.0f;
104 }
105 184810 case NoiseBasis::Voronoi:
106 184810 return Worley2(x, y, seed).value;
107 39114302 default:
108 39114302 return PerlinNoise2(x, y, seed);
109 }
110 }
111
112 /// One octave of 3D `basis` noise, mapped like `BasisNoise2` with the 3D Worley bounds sqrt(3)
113 /// for F1 and sqrt(6) for F2; unknown values fall back to Perlin.
114 /// @return Noise in [-1, 1].
115 29112984 inline float BasisNoise3(NoiseBasis basis, LatticePoint3 point, uint32_t seed) {
116 29112984 constexpr float kInvSqrt3 = 0.577350269189625765f;
117 29112984 constexpr float kInvSqrt6 = 0.408248290463863016f;
118
7/7
✓ Branch 0 taken 1753735 times.
✓ Branch 1 taken 2016 times.
✓ Branch 2 taken 4065 times.
✓ Branch 3 taken 2017 times.
✓ Branch 4 taken 2025 times.
✓ Branch 5 taken 2026 times.
✓ Branch 6 taken 27342999 times.
29112979 switch (basis) {
119 1753736 case NoiseBasis::Simplex:
120
1/1
✓ Branch 1 taken 1 time.
1753736 return SimplexNoise3(point, seed);
121 6113 case NoiseBasis::Value:
122
1/1
✓ Branch 1 taken 1 time.
6113 return ValueNoise3(point, seed);
123 4065 case NoiseBasis::WorleyF1:
124
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 4065 times.
4065 return 2.0f * min(Worley3(point, seed).f1 * kInvSqrt3, 1.0f) - 1.0f;
125 2017 case NoiseBasis::WorleyF2:
126
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 2017 times.
2017 return 2.0f * min(Worley3(point, seed).f2 * kInvSqrt6, 1.0f) - 1.0f;
127 2025 case NoiseBasis::WorleyF2MinusF1: {
128 2025 const WorleyDistances d = Worley3(point, seed);
129
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2025 times.
2025 return 2.0f * min((d.f2 - d.f1) * kInvSqrt6, 1.0f) - 1.0f;
130 }
131 2027 case NoiseBasis::Voronoi:
132 2027 return Worley3(point, seed).value;
133 27343001 default:
134
1/1
✓ Branch 2 taken 1 time.
27343001 return PerlinNoise3(point, seed);
135 }
136 }
137
138 namespace detail {
139
140 /// Cosine of the golden-angle turn between successive 2D octave lattices, accumulated by
141 /// multiplication for bit-identical results.
142 static const float kOctaveTurnCos = -0.7373688780783197f;
143 /// Sine of the golden-angle turn; see `kOctaveTurnCos`.
144 static const float kOctaveTurnSin = 0.6754902942615238f;
145
146 /// The golden-angle turn about the axis (1, 2, 3) / sqrt(14) between successive 3D octave
147 /// lattices, row-major, in single precision for `Fractal3Float`.
148 static const float kOctaveTurn3[3][3] = {
149 {-0.6132711010727254f, -0.293401570821183f, 0.7333580809050306f},
150 {0.7897926788435601f, -0.24097777005594262f, 0.5640542870894418f},
151 {0.011228581128535142f, 0.9251190369776896f, 0.37951111497202883f}};
152
153 /// The running sums of a fractal over its octaves.
154 struct FractalSums {
155 float weight = 1.0f; ///< Weight of the next octave, `gain^i`.
156 float sum = 0.0f; ///< Weighted sum of octave signals so far.
157 float totalWeight = 0.0f; ///< Sum of the weights so far, for normalization.
158 float feedback = 1.0f; ///< Previous signal weighting the next (ridged and hybrid).
159 };
160
161 /// Adds one octave to a fractal's running sums.
162 /// @param octave The octave, from 0.
163 /// @param n The octave's basis noise, in [-1, 1].
164 132071489 inline FractalSums AddFractalOctave(FractalSums sums, FractalParams params, int octave, float n) {
165
4/4
✓ Branch 0 taken 400853 times.
✓ Branch 1 taken 1218256 times.
✓ Branch 2 taken 428436 times.
✓ Branch 3 taken 130023944 times.
132071489 switch (params.type) {
166 400853 case FractalType::Billow:
167 400853 sums.sum += sums.weight * (2.0f * abs(n) - 1.0f);
168 400853 break;
169 1218256 case FractalType::Ridged: {
170
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1218256 times.
1218256 float signal = params.offset - abs(n);
171 1218256 signal *= signal * sums.feedback;
172
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1218256 times.
1218256 sums.feedback = clamp(2.0f * signal, 0.0f, 1.0f);
173 1218256 sums.sum += sums.weight * signal;
174 1218256 break;
175 }
176 428436 case FractalType::HybridMultifractal: {
177 428436 const float signal = (n + params.offset) * sums.weight;
178
2/2
✓ Branch 0 taken 72888 times.
✓ Branch 1 taken 355548 times.
428436 if (octave == 0) {
179 72888 sums.sum = signal;
180 72888 sums.feedback = signal;
181 } else {
182
2/2
✓ Branch 0 taken 12481 times.
✓ Branch 1 taken 343067 times.
355548 sums.feedback = clamp(sums.feedback, 0.0f, 1.0f);
183 355548 sums.sum += sums.feedback * signal;
184 355548 sums.feedback *= signal;
185 }
186 break;
187 }
188 130023944 default:
189 130023944 sums.sum += sums.weight * n;
190 130023944 break;
191 }
192 132071489 sums.totalWeight += sums.weight;
193 132071489 sums.weight *= params.gain;
194 132071489 return sums;
195 }
196
197 /// The fractal height in [-amplitude, amplitude] world units from its sums over every octave,
198 /// normalized by its largest value.
199 28743101 inline float FinishFractal(FractalSums sums, FractalParams params) {
200
3/3
✓ Branch 0 taken 233290 times.
✓ Branch 1 taken 72888 times.
✓ Branch 2 taken 28436923 times.
28743101 switch (params.type) {
201 233290 case FractalType::Ridged: {
202
2/2
✓ Branch 0 taken 11200 times.
✓ Branch 1 taken 222090 times.
233290 const float ridgeScale = max(params.offset, 1.0f - params.offset);
203 233290 return params.amplitude *
204 233290 (2.0f * sums.sum / (ridgeScale * ridgeScale * sums.totalWeight) - 1.0f);
205 }
206 72888 case FractalType::HybridMultifractal:
207 72888 return params.amplitude * sums.sum / ((1.0f + params.offset) * sums.totalWeight);
208 28436923 default:
209 28436923 return params.amplitude * sums.sum / sums.totalWeight;
210 }
211 }
212
213 } // namespace detail
214
215 /// 2D fractal height; each octave has its own seed, lattice offset and golden-angle turn.
216 /// @param x, y World coordinates in meters.
217 /// @param params The fractal, assumed valid (`ValidateFractalParams` checks it on the host).
218 /// @return Height in [-amplitude, amplitude] world units, for any parameters.
219 9580247 inline float Fractal2(float x, float y, FractalParams params) {
220 9580247 float frequency = 1.0f / params.wavelength;
221 9580247 float turnCos = 1.0f;
222 9580247 float turnSin = 0.0f;
223 9580247 detail::FractalSums sums = {};
224
2/2
✓ Branch 0 taken 39972095 times.
✓ Branch 1 taken 9595014 times.
49567109 for (int octave = 0; octave < params.octaves; ++octave) {
225 39972095 const UVec3 h = Pcg3dHash(detail::OctaveKey(params.seed, uint32_t(octave), 0u));
226 39972095 const float offsetX = HashToUnitFloat(h.y);
227 39972095 const float offsetY = HashToUnitFloat(h.z);
228 39972095 const float rx = x * turnCos - y * turnSin;
229 39972095 const float ry = x * turnSin + y * turnCos;
230 39972095 const float n =
231 39972095 BasisNoise2(params.basis, rx * frequency + offsetX, ry * frequency + offsetY, h.x);
232 39986862 sums = detail::AddFractalOctave(sums, params, octave, n);
233 39986862 frequency *= params.lacunarity;
234 39986862 const float nextCos = turnCos * detail::kOctaveTurnCos - turnSin * detail::kOctaveTurnSin;
235 39986862 turnSin = turnSin * detail::kOctaveTurnCos + turnCos * detail::kOctaveTurnSin;
236 39986862 turnCos = nextCos;
237 }
238 9595014 return detail::FinishFractal(sums, params);
239 }
240
241 /// `Fractal3` in single precision, for kernels: the same octaves, turns and offsets, to within
242 /// float rounding for coordinates of moderate size, such as a crater's local frame.
243 /// @return Height in [-amplitude, amplitude] world units.
244 7190461 inline float Fractal3Float(float x, float y, float z, FractalParams params) {
245 7190461 float turn[3][3] = {{1.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}};
246 7190461 float frequency = 1.0f / params.wavelength;
247 7190461 detail::FractalSums sums = {};
248
2/2
✓ Branch 0 taken 21386779 times.
✓ Branch 1 taken 7190458 times.
28577237 for (int octave = 0; octave < params.octaves; ++octave) {
249 21386779 const UVec3 h = Pcg3dHash(detail::OctaveKey(params.seed, uint32_t(octave), 0u));
250 21386779 const UVec3 g = Pcg3dHash(detail::OctaveKey(params.seed, uint32_t(octave), 1u));
251 21386779 const float rx = turn[0][0] * x + turn[0][1] * y + turn[0][2] * z;
252 21386779 const float ry = turn[1][0] * x + turn[1][1] * y + turn[1][2] * z;
253 21386779 const float rz = turn[2][0] * x + turn[2][1] * y + turn[2][2] * z;
254 42773555 const float n = BasisNoise3(params.basis,
255 21386779 SplitLattice3(rx * frequency + HashToUnitFloat(h.y),
256 21386779 ry * frequency + HashToUnitFloat(h.z),
257 21386779 rz * frequency + HashToUnitFloat(g.x)),
258 21386779 h.x);
259 21386776 sums = detail::AddFractalOctave(sums, params, octave, n);
260 21386776 frequency *= params.lacunarity;
261 21386776 float next[3][3] = {{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}};
262
2/2
✓ Branch 0 taken 64159689 times.
✓ Branch 1 taken 21386776 times.
85546465 for (int row = 0; row < 3; ++row) {
263
2/2
✓ Branch 0 taken 192479094 times.
✓ Branch 1 taken 64159689 times.
256638783 for (int column = 0; column < 3; ++column) {
264 192479094 next[row][column] = detail::kOctaveTurn3[row][0] * turn[0][column] +
265 192479094 detail::kOctaveTurn3[row][1] * turn[1][column] +
266 192479094 detail::kOctaveTurn3[row][2] * turn[2][column];
267 }
268 }
269
2/2
✓ Branch 0 taken 64160316 times.
✓ Branch 1 taken 21386776 times.
85547092 for (int row = 0; row < 3; ++row) {
270
2/2
✓ Branch 0 taken 192480957 times.
✓ Branch 1 taken 64160316 times.
256641273 for (int column = 0; column < 3; ++column) {
271 192480957 turn[row][column] = next[row][column];
272 }
273 }
274 }
275 7190458 return detail::FinishFractal(sums, params);
276 }
277
278 #ifndef __SLANG__
279 /// `Fractal2` in 3D, for noise on a sphere; lattice coordinates are split in double
280 /// precision so noise stays exact at a planet's radius.
281 /// @param x, y, z World coordinates in meters.
282 /// @param params The fractal, assumed valid.
283 /// @return Height in [-amplitude, amplitude] world units.
284 1973319 inline float Fractal3(double x, double y, double z, FractalParams params) {
285 /// The golden angle about the axis (1, 2, 3) / sqrt(14), which lies along no lattice axis.
286 1973319 static constexpr double kTurn[3][3] = {
287 {-0.6132711010727254, -0.293401570821183, 0.7333580809050306},
288 {0.7897926788435601, -0.24097777005594262, 0.5640542870894418},
289 {0.011228581128535142, 0.9251190369776896, 0.37951111497202883}};
290 1973319 double frequency = 1.0 / static_cast<double>(params.wavelength);
291 1973319 double turn[3][3] = {{1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}};
292 1973319 detail::FractalSums sums = {};
293
2/2
✓ Branch 0 taken 7703333 times.
✓ Branch 1 taken 1973290 times.
9676623 for (int octave = 0; octave < params.octaves; ++octave) {
294 7703333 const UVec3 h = Pcg3dHash(detail::OctaveKey(params.seed, uint32_t(octave), 0u));
295 7703333 const UVec3 g = Pcg3dHash(detail::OctaveKey(params.seed, uint32_t(octave), 1u));
296 7703333 const double rx = turn[0][0] * x + turn[0][1] * y + turn[0][2] * z;
297 7703333 const double ry = turn[1][0] * x + turn[1][1] * y + turn[1][2] * z;
298 7703333 const double rz = turn[2][0] * x + turn[2][1] * y + turn[2][2] * z;
299 7703333 const double px = rx * frequency + static_cast<double>(HashToUnitFloat(h.y));
300 7703333 const double py = ry * frequency + static_cast<double>(HashToUnitFloat(h.z));
301 7703333 const double pz = rz * frequency + static_cast<double>(HashToUnitFloat(g.x));
302 7703333 const float n = BasisNoise3(params.basis, SplitLatticePrecise3(px, py, pz), h.x);
303 7703304 sums = detail::AddFractalOctave(sums, params, octave, n);
304 7703304 frequency *= static_cast<double>(params.lacunarity);
305 7703304 double next[3][3] = {};
306
2/2
✓ Branch 0 taken 22299255 times.
✓ Branch 1 taken 7703304 times.
30002559 for (int row = 0; row < 3; ++row) {
307
2/2
✓ Branch 0 taken 66897918 times.
✓ Branch 1 taken 22299255 times.
89197173 for (int column = 0; column < 3; ++column) {
308 66897918 next[row][column] = kTurn[row][0] * turn[0][column] +
309 66897918 kTurn[row][1] * turn[1][column] +
310 66897918 kTurn[row][2] * turn[2][column];
311 }
312 }
313 7703304 std::memcpy(turn, next, sizeof(turn));
314 }
315 1973290 return detail::FinishFractal(sums, params);
316 }
317 #endif
318
319 } // namespace terraingen
320