./
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
132 / 133
99.2%
Branches:
88 / 95
92.6%
Functions:
10 / 10
100.0%

src/layers/spectral_continuation.cpp
Line Branch Exec Source
1 // SPDX-License-Identifier: BSD-3-Clause
2
3 #include "terraingen/layers/spectral_continuation.h"
4
5 #include "layers/lattice.h"
6 #include "terraingen/layers/layer_fields.h"
7 #include "terraingen/random/stream.h"
8 #include "terraingen/random/streams.h"
9 #include "terraingen/util/bits.h"
10 #include "terraingen/util/parallel.h"
11
12 #include <algorithm>
13 #include <cmath>
14 #include <memory>
15 #include <stdexcept>
16 #include <utility>
17
18 namespace terraingen {
19
20 namespace {
21
22 /// The Gaussian envelope parameter a of a band's impulses over the band's lowest frequency: the
23 /// impulses' spectra are Gaussians of standard deviation a / (2 sqrt(pi)), about a seventh of it.
24 constexpr double kBandwidth = 0.5;
25 /// The envelope's value at the impulse radius, where it is cut and shifted to reach zero.
26 constexpr double kEnvelopeCut = 0.01;
27 constexpr int kImpulsesPerCell = 8;
28 constexpr int kMaxBands = 40;
29
30 /// Grid cells per side of the tiles a grid is evaluated in.
31 constexpr std::size_t kTileCells = 64;
32
33 /// The integral of the squared envelope over the plane, times a^2: the envelope is
34 /// (exp(-pi a^2 d^2) - c) / (1 - c) inside the radius where the Gaussian falls to c.
35 6265 double EnvelopeEnergy() {
36 6265 const double c = kEnvelopeCut;
37 6265 const double u = -std::log(c);
38 6265 return ((1.0 - c * c) / 2.0 - 2.0 * c * (1.0 - c) + c * c * u) / ((1.0 - c) * (1.0 - c));
39 }
40
41 } // namespace
42
43 46 void ValidateSpectralContinuationOptions(const SpectralContinuationOptions& options) {
44 46 CheckRanges(options);
45 31 ValidateResolutionFade(options.fade);
46 29 }
47
48 /// The impulses of one band over a window of its lattice cells.
49 18761 struct SpectralContinuationLayer::ImpulseTable {
50 struct Impulse {
51 double x = 0.0; ///< Center, in meters.
52 double y = 0.0;
53 double kx = 0.0; ///< Angular wave vector, in radians per meter.
54 double ky = 0.0;
55 double phase = 0.0;
56 double amplitude = 0.0; ///< Meters, faded for the sample spacing.
57 };
58
59 const Band* band = nullptr;
60 std::int64_t col0 = 0;
61 std::int64_t row0 = 0;
62 std::int64_t cols = 0;
63 std::vector<Impulse> impulses; ///< `kImpulsesPerCell` per cell, row by row.
64 };
65
66 35 SpectralContinuationLayer::SpectralContinuationLayer(SpectralContinuationOptions options)
67
1/1
✓ Branch 1 taken 27 times.
35 : m_options(options) {
68
1/1
✓ Branch 1 taken 27 times.
35 ValidateSpectralContinuationOptions(m_options);
69 27 const double nyquist = 0.5 / m_options.pixelSize;
70
1/1
✓ Branch 1 taken 27 times.
27 m_coefficient = PowerLawSpectrum{m_options.slope, m_options.octaveRms}.Coefficient(nyquist);
71 27 const double octaves = std::log2(1.0 / (m_options.minWavelength * nyquist));
72 27 const int count = static_cast<int>(
73
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 std::clamp(std::ceil(octaves - 1e-9), 0.0, static_cast<double>(kMaxBands)));
74 27 const double radius = std::sqrt(-std::log(kEnvelopeCut) / kPi);
75
2/2
✓ Branch 0 taken 85 times.
✓ Branch 1 taken 27 times.
112 for (int i = 0; i < count; ++i) {
76 85 Band band;
77 85 band.frequency = std::ldexp(nyquist, i);
78 85 band.bandwidth = kBandwidth * band.frequency;
79 85 band.reach = radius / band.bandwidth;
80 85 band.seed = SubstreamSeed(m_options.seed, kSpectralContinuationStream,
81 static_cast<std::uint32_t>(i));
82
1/1
✓ Branch 1 taken 85 times.
85 m_bands.push_back(band);
83 }
84 35 }
85
86 3 LayerPtr SpectralContinuationLayer::Reseeded(std::uint64_t seed) const {
87 3 SpectralContinuationOptions options = m_options;
88 3 options.seed = ReseedWord(seed, 0);
89 3 return std::make_shared<SpectralContinuationLayer>(options);
90 }
91
92 636359 double SpectralContinuationLayer::TargetPsd(double frequency) const {
93 636359 const double nyquist = 0.5 / m_options.pixelSize;
94
2/4
✓ Branch 0 taken 636359 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 636361 times.
✗ Branch 3 not taken.
636359 if (!(frequency > nyquist) || frequency > 1.0 / m_options.minWavelength) {
95 return 0.0;
96 }
97 636361 const double taper = Smoothstep(std::log2(frequency / nyquist) / m_options.taperOctaves);
98 636401 return m_coefficient * std::pow(frequency, -m_options.slope) * taper;
99 }
100
101 6265 SpectralContinuationLayer::ImpulseTable SpectralContinuationLayer::Table(const Band& band,
102 double minX, double minY,
103 double maxX, double maxY,
104 double spacing) const {
105
1/1
✓ Branch 1 taken 6265 times.
6265 ImpulseTable table;
106 6265 table.band = &band;
107 6265 table.col0 = static_cast<std::int64_t>(std::floor(minX / band.reach)) - 1;
108 6265 table.row0 = static_cast<std::int64_t>(std::floor(minY / band.reach)) - 1;
109 6265 table.cols = static_cast<std::int64_t>(std::floor(maxX / band.reach)) + 2 - table.col0;
110 6265 const std::int64_t rows =
111 6265 static_cast<std::int64_t>(std::floor(maxY / band.reach)) + 2 - table.row0;
112 6265 const double density = kImpulsesPerCell / (band.reach * band.reach);
113 6265 const double weight =
114 6265 4.0 * kPi * std::log(2.0) * band.bandwidth * band.bandwidth / (density * EnvelopeEnergy());
115
1/1
✓ Branch 1 taken 6265 times.
6265 table.impulses.reserve(static_cast<std::size_t>(table.cols * rows * kImpulsesPerCell));
116
2/2
✓ Branch 0 taken 21559 times.
✓ Branch 1 taken 6265 times.
27824 for (std::int64_t row = table.row0; row < table.row0 + rows; ++row) {
117
2/2
✓ Branch 0 taken 79586 times.
✓ Branch 1 taken 21559 times.
101145 for (std::int64_t col = table.col0; col < table.col0 + table.cols; ++col) {
118
1/1
✓ Branch 1 taken 79578 times.
79586 RandomStream random = LatticeStream(band.seed, kSpectralContinuationStream, col, row);
119
2/2
✓ Branch 0 taken 636519 times.
✓ Branch 1 taken 79586 times.
716105 for (int k = 0; k < kImpulsesPerCell; ++k) {
120 636519 ImpulseTable::Impulse impulse;
121
1/1
✓ Branch 1 taken 636414 times.
636519 impulse.x = (static_cast<double>(col) + random.NextDouble()) * band.reach;
122
1/1
✓ Branch 1 taken 636452 times.
636414 impulse.y = (static_cast<double>(row) + random.NextDouble()) * band.reach;
123
1/1
✓ Branch 1 taken 636354 times.
636452 const double frequency = band.frequency * std::exp2(random.NextDouble());
124
1/1
✓ Branch 1 taken 636297 times.
636354 const double angle = 2.0 * kPi * random.NextDouble();
125
1/1
✓ Branch 1 taken 636386 times.
636297 impulse.phase = 2.0 * kPi * random.NextDouble();
126 636386 impulse.kx = 2.0 * kPi * frequency * std::cos(angle);
127 636386 impulse.ky = 2.0 * kPi * frequency * std::sin(angle);
128 1272690 impulse.amplitude =
129
1/1
✓ Branch 1 taken 636396 times.
636386 std::sqrt(weight * frequency * frequency * TargetPsd(frequency)) *
130
1/1
✓ Branch 1 taken 636304 times.
636396 ResolutionWeight(1.0 / frequency, spacing, m_options.fade);
131
1/1
✓ Branch 1 taken 636527 times.
636304 table.impulses.push_back(impulse);
132 }
133 }
134 }
135 6265 return table;
136 }
137
138 2105 void SpectralContinuationLayer::AddDetail(const std::vector<Vec2d>& positions,
139 const std::vector<float*>& heights,
140 double spacing) const {
141
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2105 times.
2105 if (positions.empty()) {
142 ✗ return;
143 }
144 2105 Vec2d low = positions[0];
145 2105 Vec2d high = positions[0];
146
2/2
✓ Branch 0 taken 1985527 times.
✓ Branch 1 taken 2105 times.
1987632 for (const Vec2d& p : positions) {
147
3/4
✗ Branch 0 not taken.
✓ Branch 1 taken 1985527 times.
✓ Branch 2 taken 30662 times.
✓ Branch 3 taken 1954865 times.
1985527 low = {std::min(low.x, p.x), std::min(low.y, p.y)};
148
3/4
✓ Branch 0 taken 30694 times.
✓ Branch 1 taken 1954833 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 1985527 times.
2016221 high = {std::max(high.x, p.x), std::max(high.y, p.y)};
149 }
150 2105 std::vector<ImpulseTable> tables;
151
2/2
✓ Branch 0 taken 6317 times.
✓ Branch 1 taken 2105 times.
8422 for (const Band& band : m_bands) {
152
3/3
✓ Branch 1 taken 6317 times.
✓ Branch 3 taken 6265 times.
✓ Branch 4 taken 52 times.
6317 if (ResolutionWeight(1.0 / band.frequency, spacing, m_options.fade) > 0.0) {
153
1/1
✓ Branch 1 taken 6265 times.
12530 tables.push_back(Table(band, low.x, low.y, high.x, high.y, spacing));
154 }
155 }
156
2/2
✓ Branch 0 taken 1999677 times.
✓ Branch 1 taken 2105 times.
2001782 for (std::size_t i = 0; i < positions.size(); ++i) {
157 1999677 *heights[i] =
158 1999677 static_cast<float>(static_cast<double>(*heights[i]) + DetailAt(tables, positions[i]));
159 }
160 2105 }
161
162 1997976 double SpectralContinuationLayer::DetailAt(const std::vector<ImpulseTable>& tables,
163 const Vec2d& p) {
164 1997976 const double cutScale = 1.0 / (1.0 - kEnvelopeCut);
165 1997976 double detail = 0.0;
166
2/2
✓ Branch 0 taken 5746838 times.
✓ Branch 1 taken 1997976 times.
7744814 for (const ImpulseTable& table : tables) {
167 5746838 const Band& band = *table.band;
168 5746838 const double reach2 = band.reach * band.reach;
169 5746838 const double gauss = kPi * band.bandwidth * band.bandwidth;
170 5746838 const auto col = static_cast<std::int64_t>(std::floor(p.x / band.reach));
171 5746838 const auto row = static_cast<std::int64_t>(std::floor(p.y / band.reach));
172
2/2
✓ Branch 0 taken 16903490 times.
✓ Branch 1 taken 5746838 times.
22650328 for (std::int64_t r = row - 1; r <= row + 1; ++r) {
173
2/2
✓ Branch 0 taken 48648896 times.
✓ Branch 1 taken 16903490 times.
65552386 for (std::int64_t c = col - 1; c <= col + 1; ++c) {
174 48648896 const auto first = static_cast<std::size_t>(
175 48648896 ((r - table.row0) * table.cols + (c - table.col0)) * kImpulsesPerCell);
176
2/2
✓ Branch 0 taken 373215592 times.
✓ Branch 1 taken 48648896 times.
421864488 for (std::size_t k = first; k < first + kImpulsesPerCell; ++k) {
177
2/2
✓ Branch 0 taken 130227612 times.
✓ Branch 1 taken 242987980 times.
373215592 const ImpulseTable::Impulse& impulse = table.impulses[k];
178 373215592 const double dx = p.x - impulse.x;
179 373215592 const double dy = p.y - impulse.y;
180 373215592 const double d2 = dx * dx + dy * dy;
181
4/4
✓ Branch 0 taken 130227612 times.
✓ Branch 1 taken 242987980 times.
✓ Branch 2 taken 682128 times.
✓ Branch 3 taken 129545484 times.
373215592 if (d2 >= reach2 || impulse.amplitude == 0.0) {
182 243670108 continue;
183 }
184 129545484 const double envelope = (std::exp(-gauss * d2) - kEnvelopeCut) * cutScale;
185 129545484 detail += impulse.amplitude * envelope *
186 129545484 std::cos(impulse.kx * dx + impulse.ky * dy + impulse.phase);
187 }
188 }
189 }
190 }
191 1997976 return detail;
192 }
193
194 32 void SpectralContinuationLayer::ApplySamples(SampleBlock& samples,
195 const LayerContext& context) const {
196 32 const Surface& surface = context.SurfaceOrPlane();
197 32 const double spacing = samples.ResolvedSpacing(context.spacing, surface);
198
4/4
✓ Branch 0 taken 31 times.
✓ Branch 1 taken 1 time.
✓ Branch 2 taken 5 times.
✓ Branch 3 taken 26 times.
63 if (m_bands.empty() ||
199 31 !(ResolutionWeight(1.0 / m_bands.front().frequency, spacing, m_options.fade) > 0.0)) {
200 14 return;
201 }
202
2/2
✓ Branch 0 taken 1 time.
✓ Branch 1 taken 25 times.
26 const double unit = surface.UnitLength();
203
2/2
✓ Branch 0 taken 8 times.
✓ Branch 1 taken 18 times.
26 Raster<float>* grid = samples.Grid();
204
2/2
✓ Branch 0 taken 8 times.
✓ Branch 1 taken 18 times.
26 if (!grid) {
205
2/2
✓ Branch 0 taken 1607 times.
✓ Branch 1 taken 8 times.
1615 for (std::size_t i = 0; i < samples.Size(); ++i) {
206
1/2
✓ Branch 1 taken 1607 times.
✗ Branch 2 not taken.
1607 if (!samples.IsNoData(i)) {
207
4/4
✓ Branch 2 taken 1607 times.
✓ Branch 5 taken 1607 times.
✓ Branch 8 taken 1607 times.
✓ Branch 11 taken 1607 times.
1607 AddDetail({samples.Position(i) * unit}, {&samples.Height(i)}, spacing);
208 }
209 }
210 return;
211 }
212 18 const std::size_t tilesX = (grid->Width() + kTileCells - 1) / kTileCells;
213 18 const std::size_t tilesY = (grid->Height() + kTileCells - 1) / kTileCells;
214
1/1
✓ Branch 2 taken 18 times.
36 ParallelFor(tilesX * tilesY, context.threads, [&](std::size_t tile) {
215 498 const std::size_t colBegin = (tile % tilesX) * kTileCells;
216 498 const std::size_t rowBegin = (tile / tilesX) * kTileCells;
217
2/2
✓ Branch 0 taken 10 times.
✓ Branch 1 taken 488 times.
498 const std::size_t colEnd = std::min(colBegin + kTileCells, grid->Width());
218
2/2
✓ Branch 0 taken 10 times.
✓ Branch 1 taken 488 times.
498 const std::size_t rowEnd = std::min(rowBegin + kTileCells, grid->Height());
219 498 std::vector<Vec2d> positions;
220 498 std::vector<float*> heights;
221
2/2
✓ Branch 0 taken 31536 times.
✓ Branch 1 taken 498 times.
32034 for (std::size_t row = rowBegin; row < rowEnd; ++row) {
222
2/2
✓ Branch 0 taken 1999490 times.
✓ Branch 1 taken 31536 times.
2031026 for (std::size_t col = colBegin; col < colEnd; ++col) {
223 1999490 float& height = (*grid)(col, row);
224
2/2
✓ Branch 0 taken 1993668 times.
✓ Branch 1 taken 236 times.
1993904 if (!grid->IsMissing(height)) {
225
1/1
✓ Branch 1 taken 2000688 times.
1993668 positions.push_back(grid->CellCenter(col, row) * unit);
226
1/1
✓ Branch 1 taken 1999254 times.
2000688 heights.push_back(&height);
227 }
228 }
229 }
230
1/1
✓ Branch 1 taken 498 times.
498 AddDetail(positions, heights, spacing);
231 498 });
232 }
233
234 } // namespace terraingen
235