src/sources/diamond_square.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | |||
| 3 | #include "terraingen/sources/diamond_square.h" | ||
| 4 | |||
| 5 | #include "raster/kernels.h" | ||
| 6 | #include "sources/lattice.h" | ||
| 7 | #include "terraingen/analysis/variogram.h" | ||
| 8 | #include "terraingen/random/samplers.h" | ||
| 9 | #include "terraingen/random/stream.h" | ||
| 10 | #include "terraingen/random/streams.h" | ||
| 11 | #include "util/checks.h" | ||
| 12 | |||
| 13 | #include <algorithm> | ||
| 14 | #include <array> | ||
| 15 | #include <cmath> | ||
| 16 | #include <cstddef> | ||
| 17 | #include <limits> | ||
| 18 | #include <optional> | ||
| 19 | #include <stdexcept> | ||
| 20 | #include <string> | ||
| 21 | #include <utility> | ||
| 22 | #include <vector> | ||
| 23 | |||
| 24 | namespace terraingen { | ||
| 25 | |||
| 26 | namespace { | ||
| 27 | |||
| 28 | /// Levels the posts are refined to at most. | ||
| 29 | constexpr int kMaxLevels = 30; | ||
| 30 | |||
| 31 | /// Most node reads per point at which the points of a batch are refined over one box of nodes. | ||
| 32 | constexpr double kNodesPerPoint = 64.0; | ||
| 33 | |||
| 34 | /// Largest side, in posts, of the window the roughness is estimated from. | ||
| 35 | constexpr std::size_t kEstimateSide = 512; | ||
| 36 | |||
| 37 | /// Side, in posts, of the window the roughness of a lattice without bounds is estimated from. | ||
| 38 | constexpr std::size_t kUnboundedEstimateSide = 256; | ||
| 39 | |||
| 40 | /// The ratio of the standard deviation to the median absolute value of a Gaussian, 1 / Phi^-1(3/4). | ||
| 41 | constexpr double kGaussianMadScale = 1.482602218505602; | ||
| 42 | |||
| 43 | /// Posts beyond a box of nodes, at its own level, that refining it displaces nodes over. | ||
| 44 | constexpr double kScaleMargin = 10.0; | ||
| 45 | |||
| 46 | /// The longest lag, in cells, the fractal dimension is fitted over. | ||
| 47 | constexpr std::size_t kMaxRoughnessLag = 8; | ||
| 48 | |||
| 49 | /// Catmull-Rom weights of four nodes around a midpoint. | ||
| 50 | constexpr std::array<double, 4> kMidpointWeights{-1.0 / 16.0, 9.0 / 16.0, 9.0 / 16.0, -1.0 / 16.0}; | ||
| 51 | |||
| 52 | 12364144 | std::int64_t FloorHalf(std::int64_t value) { | |
| 53 | 12364144 | return value >= 0 ? value / 2 : -((1 - value) / 2); | |
| 54 | } | ||
| 55 | |||
| 56 | 643008 | std::int64_t CeilHalf(std::int64_t value) { | |
| 57 | 643008 | return -FloorHalf(-value); | |
| 58 | } | ||
| 59 | |||
| 60 | 67107718 | bool IsOdd(std::int64_t value) { | |
| 61 | 67107718 | return (value & 1) != 0; | |
| 62 | } | ||
| 63 | |||
| 64 | /// The node at or below `u` and the share of the way to the next; 0 on a node. | ||
| 65 | 8235271 | std::pair<std::int64_t, double> NodeAndShare(double u) { | |
| 66 | 8235271 | if (const std::optional<std::int64_t> node = detail::NearestWhole(u)) { | |
| 67 | 5116079 | return {*node, 0.0}; | |
| 68 | } | ||
| 69 | 3119192 | const double below = std::floor(u); | |
| 70 | 3119192 | return {static_cast<std::int64_t>(below), u - below}; | |
| 71 | } | ||
| 72 | |||
| 73 | /// The box over columns [`col0`, `col1`] and rows [`row0`, `row1`]. | ||
| 74 | 798615 | detail::IndexBox Box(std::int64_t col0, std::int64_t row0, std::int64_t col1, std::int64_t row1) { | |
| 75 | 798615 | detail::IndexBox box; | |
| 76 | 798615 | box.Include(col0, col1, row0, row1); | |
| 77 | 798643 | return box; | |
| 78 | } | ||
| 79 | |||
| 80 | /// The square-step mean of the coarser nodes around the square whose lower-left parent is | ||
| 81 | /// (`left`, `bottom`): its four corners, or Catmull-Rom over the 4 x 4 around it. | ||
| 82 | 5538641 | double SquareMean(const detail::LatticeWindow<double>& parents, std::int64_t left, | |
| 83 | std::int64_t bottom, bool spline) { | ||
| 84 | 5538641 | if (!spline) { | |
| 85 | 3996674 | return 0.25 * (parents.At(left, bottom) + parents.At(left + 1, bottom) + | |
| 86 | 3996674 | parents.At(left, bottom + 1) + parents.At(left + 1, bottom + 1)); | |
| 87 | } | ||
| 88 | double sum = 0.0; | ||
| 89 | 7709595 | for (std::int64_t j = 0; j < 4; ++j) { | |
| 90 | double line = 0.0; | ||
| 91 | 30838156 | for (std::int64_t i = 0; i < 4; ++i) { | |
| 92 | 24670528 | line += kMidpointWeights[static_cast<std::size_t>(i)] * | |
| 93 | 24670528 | parents.At(left - 1 + i, bottom - 1 + j); | |
| 94 | } | ||
| 95 | 6167628 | sum += kMidpointWeights[static_cast<std::size_t>(j)] * line; | |
| 96 | } | ||
| 97 | return sum; | ||
| 98 | } | ||
| 99 | |||
| 100 | /// The diamond-step mean around node (`col`, `row`): its four neighbors, or the mean of the | ||
| 101 | /// Catmull-Rom splines along the two axes. | ||
| 102 | 5772209 | double DiamondMean(const detail::LatticeWindow<double>& squares, std::int64_t col, std::int64_t row, | |
| 103 | bool spline) { | ||
| 104 | 5772209 | if (!spline) { | |
| 105 | 4746159 | return 0.25 * (squares.At(col - 1, row) + squares.At(col + 1, row) + | |
| 106 | 4746159 | squares.At(col, row - 1) + squares.At(col, row + 1)); | |
| 107 | } | ||
| 108 | double alongX = 0.0; | ||
| 109 | double alongY = 0.0; | ||
| 110 | 5130250 | for (std::int64_t k = 0; k < 4; ++k) { | |
| 111 | 4104200 | const double weight = kMidpointWeights[static_cast<std::size_t>(k)]; | |
| 112 | 4104200 | alongX += weight * squares.At(col - 3 + 2 * k, row); | |
| 113 | 4104200 | alongY += weight * squares.At(col, row - 3 + 2 * k); | |
| 114 | } | ||
| 115 | 1026050 | return 0.5 * (alongX + alongY); | |
| 116 | } | ||
| 117 | |||
| 118 | /// The absolute difference of each cell and the mean of its four neighbors one cell away, over | ||
| 119 | /// the cells where all five hold data. | ||
| 120 | 552965 | std::vector<double> AbsoluteResiduals(const Raster<float>& heights) { | |
| 121 | 552965 | std::vector<double> residuals; | |
| 122 | 1435990722 | const auto missing = [&](std::size_t col, std::size_t row) { | |
| 123 | 1435437757 | return heights.IsMissing(heights(col, row)); | |
| 124 | 552965 | }; | |
| 125 | 15114276 | for (std::size_t row = 1; row + 1 < heights.Height(); ++row) { | |
| 126 | 398285812 | for (std::size_t col = 1; col + 1 < heights.Width(); ++col) { | |
| 127 | 1148951513 | if (missing(col, row) || missing(col - 1, row) || missing(col + 1, row) || | |
| 128 | 1148176320 | missing(col, row - 1) || missing(col, row + 1)) { | |
| 129 | 5 | continue; | |
| 130 | } | ||
| 131 | 382834482 | const double mean = 0.25 * (static_cast<double>(heights(col - 1, row)) + | |
| 132 | 382785933 | static_cast<double>(heights(col + 1, row)) + | |
| 133 | 382817437 | static_cast<double>(heights(col, row - 1)) + | |
| 134 | 382916890 | static_cast<double>(heights(col, row + 1))); | |
| 135 | 383292660 | residuals.push_back(std::fabs(static_cast<double>(heights(col, row)) - mean)); | |
| 136 | } | ||
| 137 | } | ||
| 138 | 551226 | return residuals; | |
| 139 | } | ||
| 140 | |||
| 141 | /// The median of `values`, reordering them; the upper of the middle two for an even count, 0 for | ||
| 142 | /// none. | ||
| 143 | 551354 | double Median(std::vector<double>& values) { | |
| 144 | 551354 | if (values.empty()) { | |
| 145 | return 0.0; | ||
| 146 | } | ||
| 147 | 551353 | const auto middle = values.begin() + static_cast<std::ptrdiff_t>(values.size() / 2); | |
| 148 | 551353 | std::nth_element(values.begin(), middle, values.end()); | |
| 149 | 553187 | return *middle; | |
| 150 | } | ||
| 151 | |||
| 152 | /// The Hurst exponent H of `heights`, unclamped: `FitLagLine` of the median absolute difference of | ||
| 153 | /// lag pairs; none from fewer than two lags. | ||
| 154 | 58 | std::optional<double> MedianHurst(const Raster<float>& heights) { | |
| 155 | 58 | const DeviogramFit fit = FitLagLine(kMaxRoughnessLag, [&](std::size_t lag) { | |
| 156 | 226 | std::vector<double> increments; | |
| 157 | 226 | ForEachLagPair(heights, lag, | |
| 158 | 19465064 | [&](double a, double b) { increments.push_back(std::fabs(b - a)); }); | |
| 159 | 452 | return Median(increments); | |
| 160 | 226 | }); | |
| 161 | 58 | return fit.lags >= 2 ? std::optional<double>(fit.slope) : std::nullopt; | |
| 162 | } | ||
| 163 | |||
| 164 | /// Posts [`col0`, `col0` + `width`) x [`row0`, `row0` + `height`) of `posts` as a raster. | ||
| 165 | 552936 | Raster<float> PostRaster(const detail::LatticeWindow<float>& posts, std::int64_t col0, | |
| 166 | std::int64_t row0, std::size_t width, std::size_t height) { | ||
| 167 | 552936 | Raster<float> raster(width, height); | |
| 168 | 16001944 | for (std::size_t row = 0; row < height; ++row) { | |
| 169 | 497601050 | for (std::size_t col = 0; col < width; ++col) { | |
| 170 | 482152000 | raster(col, row) = posts.At(col0 + static_cast<std::int64_t>(col), | |
| 171 | 482152042 | row0 + static_cast<std::int64_t>(row)); | |
| 172 | } | ||
| 173 | } | ||
| 174 | 552942 | return raster; | |
| 175 | } | ||
| 176 | |||
| 177 | /// Whether `options` give a fractal dimension, and a scale or a fit window. | ||
| 178 | 67901 | bool Fitted(const DiamondSquareOptions& options) { | |
| 179 | 67901 | return options.fractalDimension && (options.scale || options.fitWindow > 0); | |
| 180 | } | ||
| 181 | |||
| 182 | /// Node heights at one level over a box of node indices; NaN where the posts have no data. | ||
| 183 | using Nodes = detail::LatticeWindow<double>; | ||
| 184 | |||
| 185 | /// Where the nodes lie: post (0, 0) and the node steps of level 0 along x and y. | ||
| 186 | struct NodeFrame { | ||
| 187 | double originX = 0.0; | ||
| 188 | double originY = 0.0; | ||
| 189 | double stepX = 1.0; | ||
| 190 | double stepY = 1.0; | ||
| 191 | }; | ||
| 192 | |||
| 193 | /// The scales Se over the nodes being refined: one given value, or the fit of each window of | ||
| 194 | /// posts, by window center (`DiamondSquareOptions::fitWindow`). | ||
| 195 | 108708 | struct ScaleField { | |
| 196 | double uniform = 0.0; | ||
| 197 | std::int64_t step = 0; ///< Posts between window centers; 0 for a uniform scale. | ||
| 198 | std::optional<detail::LatticeWindow<double>> windows; | ||
| 199 | }; | ||
| 200 | |||
| 201 | /// The refinement of posts by fitted diamond-square options, whose displacement shrinks by | ||
| 202 | /// `stepFactor` per step. | ||
| 203 | class Refinement { | ||
| 204 | public: | ||
| 205 | 67799 | Refinement(const DiamondSquareOptions& options, double stepFactor) | |
| 206 | 67799 | : m_options(options), m_stepFactor(stepFactor) {} | |
| 207 | |||
| 208 | /// The node frame of `posts`. | ||
| 209 | /// @throws std::invalid_argument for a rotated lattice. | ||
| 210 | static NodeFrame Frame(const PostLattice& posts); | ||
| 211 | /// The posts as nodes of level 0 over `box`. | ||
| 212 | static Nodes BaseNodes(const PostLattice& posts, const detail::IndexBox& box); | ||
| 213 | /// The scales of every node that refining `box` of `level` displaces, each window's the | ||
| 214 | /// `EstimateMidpointScale` of the posts in it, read as every read is, so one reaching past a | ||
| 215 | /// bounded lattice reads its edge posts repeated. | ||
| 216 | ScaleField Scales(const PostLattice& posts, int level, const detail::IndexBox& box) const; | ||
| 217 | /// The scale of node (`col`, `row`) of `level` from `scales`. | ||
| 218 | static double ScaleAt(const ScaleField& scales, std::int64_t col, std::int64_t row, int level); | ||
| 219 | /// The nodes of `level` over `box`, the posts refined `level` times and displaced by `scales`. | ||
| 220 | Nodes Refine(const PostLattice& posts, int level, const detail::IndexBox& box, | ||
| 221 | const ScaleField& scales) const; | ||
| 222 | /// The Gaussian displacement of node (`col`, `row`) made by the square (`diamond` false) or | ||
| 223 | /// diamond step of `level`, for a scale Se of `scale`. | ||
| 224 | double Displacement(std::int64_t col, std::int64_t row, int level, bool diamond, | ||
| 225 | double scale) const; | ||
| 226 | /// The kept coarser nodes and the displaced square-step nodes of `level` over `box`; diamond | ||
| 227 | /// nodes left 0. | ||
| 228 | Nodes SquareStep(const Nodes& parents, int level, const detail::IndexBox& box, | ||
| 229 | const ScaleField& scales) const; | ||
| 230 | /// The nodes of `level` over `box`, adding the displaced diamond-step nodes to `squares`. | ||
| 231 | Nodes DiamondStep(const Nodes& squares, int level, const detail::IndexBox& box, | ||
| 232 | const ScaleField& scales) const; | ||
| 233 | /// The box of nodes of `level` that the samples at `positions` read. | ||
| 234 | detail::IndexBox ReadBox(const NodeFrame& frame, int level, Span<const Vec2d> positions) const; | ||
| 235 | /// The height at (`x`, `y`) from nodes of `level` covering it. | ||
| 236 | double Interpolate(const NodeFrame& frame, const Nodes& nodes, int level, double x, | ||
| 237 | double y) const; | ||
| 238 | |||
| 239 | private: | ||
| 240 | const DiamondSquareOptions& m_options; | ||
| 241 | double m_stepFactor = 1.0; | ||
| 242 | }; | ||
| 243 | |||
| 244 | } // namespace | ||
| 245 | |||
| 246 | 192 | void ValidateDiamondSquareOptions(const DiamondSquareOptions& options) { | |
| 247 | 192 | if (options.fractalDimension) { | |
| 248 | 155 | RequireFinite(*options.fractalDimension, "Diamond-square fractal dimension"); | |
| 249 | 153 | if (*options.fractalDimension < 2.0 || *options.fractalDimension > 3.0) { | |
| 250 | 5 | throw std::invalid_argument("Diamond-square fractal dimension must be in [2, 3]"); | |
| 251 | } | ||
| 252 | } | ||
| 253 | 185 | if (options.scale) { | |
| 254 | 92 | RequireNonNegative(*options.scale, "Diamond-square scale"); | |
| 255 | } | ||
| 256 | 183 | if (options.fitWindow != 0 && | |
| 257 | (options.fitWindow < 4 || options.fitWindow > kMaxDiamondSquareFitWindow)) { | ||
| 258 | 18 | throw std::invalid_argument("Diamond-square fit window must be 0 or 4 to " + | |
| 259 | 36 | std::to_string(kMaxDiamondSquareFitWindow) + " posts"); | |
| 260 | } | ||
| 261 | 174 | RequireNonNegative(options.minPixelSize, "Diamond-square min pixel size"); | |
| 262 | 172 | } | |
| 263 | |||
| 264 | 552928 | double EstimateMidpointScale(const Raster<float>& heights) { | |
| 265 | 552928 | std::vector<double> residuals = AbsoluteResiduals(heights); | |
| 266 | 551000 | return kGaussianMadScale * Median(residuals); | |
| 267 | 552903 | } | |
| 268 | |||
| 269 | 59 | MidpointRoughness EstimateMidpointRoughness(const Raster<float>& heights) { | |
| 270 | 59 | std::vector<double> residuals = AbsoluteResiduals(heights); | |
| 271 | 59 | if (residuals.empty()) { | |
| 272 | 1 | throw std::invalid_argument( | |
| 273 | 1 | "Estimating midpoint roughness needs a cell whose four neighbors hold data"); | |
| 274 | } | ||
| 275 | 58 | MidpointRoughness roughness; | |
| 276 | 58 | roughness.scale = kGaussianMadScale * Median(residuals); | |
| 277 | 58 | if (const std::optional<double> hurst = MedianHurst(heights)) { | |
| 278 | 112 | roughness.fractalDimension = 3.0 - std::clamp(*hurst, 0.0, 1.0); | |
| 279 | } | ||
| 280 | 58 | return roughness; | |
| 281 | 59 | } | |
| 282 | |||
| 283 | 164 | DiamondSquareUpsampler::DiamondSquareUpsampler(DiamondSquareOptions options) | |
| 284 | 164 | : m_options(options), | |
| 285 | 164 | m_stepFactor(std::pow(2.0, -(3.0 - options.fractalDimension.value_or(2.5)) / 2.0)) { | |
| 286 | 164 | ValidateDiamondSquareOptions(m_options); | |
| 287 | 156 | } | |
| 288 | |||
| 289 | 67808 | int DiamondSquareUpsampler::Levels(double postSpacing, double spacing) const { | |
| 290 | 67808 | const double ratio = postSpacing / spacing; | |
| 291 | 67808 | if (!(ratio > 1.0)) { | |
| 292 | return 0; | ||
| 293 | } | ||
| 294 | 43611 | double most = kMaxLevels; | |
| 295 | 43611 | if (m_options.minPixelSize > 0.0) { | |
| 296 | 6 | most = std::clamp(std::floor(std::log2(postSpacing / m_options.minPixelSize) + 1e-9), 0.0, | |
| 297 | 6 | static_cast<double>(kMaxLevels)); | |
| 298 | } | ||
| 299 | 43614 | return static_cast<int>(std::min(std::ceil(std::log2(ratio) - 1e-9), most)); | |
| 300 | } | ||
| 301 | |||
| 302 | 67801 | NodeFrame Refinement::Frame(const PostLattice& posts) { | |
| 303 | 67801 | const GeoTransform transform = posts.Transform(); | |
| 304 | 67801 | if (transform.IsRotated()) { | |
| 305 | 1 | throw std::invalid_argument("Diamond-square cannot refine a rotated lattice of posts"); | |
| 306 | } | ||
| 307 | 67800 | const Vec2d first = transform.PixelToWorld(0.5, 0.5); | |
| 308 | 67800 | return {first.x, first.y, transform.pixelWidth, -transform.pixelHeight}; | |
| 309 | } | ||
| 310 | |||
| 311 | 108694 | Nodes Refinement::BaseNodes(const PostLattice& posts, const detail::IndexBox& box) { | |
| 312 | 108694 | const detail::LatticeWindow<float> read = | |
| 313 | 108694 | detail::ReadPosts(posts, Box(box.col0, -box.row1, box.col1, -box.row0)); | |
| 314 | 108703 | Nodes nodes(box); | |
| 315 | 760198 | for (std::int64_t row = box.row0; row <= box.row1; ++row) { | |
| 316 | 5228101 | for (std::int64_t col = box.col0; col <= box.col1; ++col) { | |
| 317 | 4576608 | nodes.At(col, row) = static_cast<double>(read.At(col, -row)); | |
| 318 | } | ||
| 319 | } | ||
| 320 | 108705 | return nodes; | |
| 321 | 108702 | } | |
| 322 | |||
| 323 | 84512 | ScaleField Refinement::Scales(const PostLattice& posts, int level, | |
| 324 | const detail::IndexBox& box) const { | ||
| 325 | 84512 | ScaleField scales; | |
| 326 | 84512 | if (m_options.scale || m_options.fitWindow == 0) { | |
| 327 | 37658 | scales.uniform = m_options.scale.value_or(0.0); | |
| 328 | 37658 | return scales; | |
| 329 | } | ||
| 330 | 46854 | scales.step = static_cast<std::int64_t>(m_options.fitWindow / 2); | |
| 331 | 46854 | const double step = static_cast<double>(scales.step); | |
| 332 | 46854 | const auto center = [&](double post) { | |
| 333 | 46854 | return static_cast<std::int64_t>(std::floor(post / step)); | |
| 334 | 46854 | }; | |
| 335 | 46854 | detail::IndexBox centers; | |
| 336 | 46854 | centers.Include(center(std::ldexp(static_cast<double>(box.col0), -level) - kScaleMargin), | |
| 337 | 46854 | center(std::ldexp(static_cast<double>(box.col1), -level) + kScaleMargin) + 1, | |
| 338 | 46854 | center(std::ldexp(-static_cast<double>(box.row1), -level) - kScaleMargin), | |
| 339 | 46854 | center(std::ldexp(-static_cast<double>(box.row0), -level) + kScaleMargin) + 1); | |
| 340 | 46848 | const std::size_t side = m_options.fitWindow; | |
| 341 | 46848 | const auto half = static_cast<std::int64_t>(side / 2); | |
| 342 | 46848 | const detail::LatticeWindow<float> read = detail::ReadPosts( | |
| 343 | ✗ | posts, Box(centers.col0 * scales.step - half, centers.row0 * scales.step - half, | |
| 344 | 46848 | centers.col1 * scales.step - half + static_cast<std::int64_t>(side) - 1, | |
| 345 | 46848 | centers.row1 * scales.step - half + static_cast<std::int64_t>(side) - 1)); | |
| 346 | 46853 | detail::LatticeWindow<double> windows(centers); | |
| 347 | 204411 | for (std::int64_t j = centers.row0; j <= centers.row1; ++j) { | |
| 348 | 710519 | for (std::int64_t i = centers.col0; i <= centers.col1; ++i) { | |
| 349 | 552795 | windows.At(i, j) = EstimateMidpointScale( | |
| 350 | 1105921 | PostRaster(read, i * scales.step - half, j * scales.step - half, side, side)); | |
| 351 | } | ||
| 352 | } | ||
| 353 | 46850 | scales.windows = std::move(windows); | |
| 354 | 46851 | return scales; | |
| 355 | 46855 | } | |
| 356 | |||
| 357 | 11265443 | double Refinement::ScaleAt(const ScaleField& scales, std::int64_t col, std::int64_t row, | |
| 358 | int level) { | ||
| 359 | 11265443 | if (!scales.windows) { | |
| 360 | 4274333 | return scales.uniform; | |
| 361 | } | ||
| 362 | 6991110 | const detail::LatticeWindow<double>& windows = *scales.windows; | |
| 363 | 6991110 | const double step = static_cast<double>(scales.step); | |
| 364 | 6991110 | const double u = std::ldexp(static_cast<double>(col), -level) / step; | |
| 365 | 6991110 | const double v = std::ldexp(-static_cast<double>(row), -level) / step; | |
| 366 | 6991110 | const double i0 = std::floor(u); | |
| 367 | 6991110 | const double j0 = std::floor(v); | |
| 368 | 6991110 | const double s = u - i0; | |
| 369 | 6991110 | const double t = v - j0; | |
| 370 | 34788774 | const auto at = [&](double i, double j) { | |
| 371 | 27797664 | const std::int64_t c = | |
| 372 | 27797664 | std::clamp(static_cast<std::int64_t>(i), windows.box.col0, windows.box.col1); | |
| 373 | 27797664 | const std::int64_t r = | |
| 374 | 27797664 | std::clamp(static_cast<std::int64_t>(j), windows.box.row0, windows.box.row1); | |
| 375 | 27797664 | return windows.At(c, r); | |
| 376 | 6991110 | }; | |
| 377 | 6991110 | const double first = at(i0, j0) * (1.0 - s) + at(i0 + 1.0, j0) * s; | |
| 378 | 6991110 | const double second = at(i0, j0 + 1.0) * (1.0 - s) + at(i0 + 1.0, j0 + 1.0) * s; | |
| 379 | 6991110 | return first * (1.0 - t) + second * t; | |
| 380 | } | ||
| 381 | |||
| 382 | 11262721 | double Refinement::Displacement(std::int64_t col, std::int64_t row, int level, bool diamond, | |
| 383 | double scale) const { | ||
| 384 | 11262721 | RandomStream random(m_options.seed, kMidpointDisplacementStream, | |
| 385 | static_cast<std::uint32_t>(col), static_cast<std::uint32_t>(row), | ||
| 386 | 11262721 | static_cast<std::uint32_t>(level) | | |
| 387 | 11262721 | (static_cast<std::uint32_t>((col >> 32) ^ (row >> 32)) << 5)); | |
| 388 | 11311639 | const double step = scale * std::pow(m_stepFactor, diamond ? 2 * level : 2 * level - 1); | |
| 389 | 11311639 | return step * StandardNormal(random); | |
| 390 | } | ||
| 391 | |||
| 392 | 321531 | Nodes Refinement::SquareStep(const Nodes& parents, int level, const detail::IndexBox& box, | |
| 393 | const ScaleField& scales) const { | ||
| 394 | 321531 | const bool spline = m_options.interp == DiamondSquareInterp::CatmullRom; | |
| 395 | 321531 | Nodes squares(box); | |
| 396 | 2646222 | for (std::int64_t row = box.row0; row <= box.row1; ++row) { | |
| 397 | 24453785 | for (std::int64_t col = box.col0; col <= box.col1; ++col) { | |
| 398 | 22129102 | if (!IsOdd(col) && !IsOdd(row)) { | |
| 399 | 5530018 | squares.At(col, row) = parents.At(col / 2, row / 2); | |
| 400 | 16599084 | } else if (IsOdd(col) && IsOdd(row)) { | |
| 401 | 5538870 | squares.At(col, row) = | |
| 402 | 5538870 | SquareMean(parents, FloorHalf(col), FloorHalf(row), spline) + | |
| 403 | 5538875 | Displacement(col, row, level, false, ScaleAt(scales, col, row, level)); | |
| 404 | } | ||
| 405 | } | ||
| 406 | } | ||
| 407 | 321534 | return squares; | |
| 408 | } | ||
| 409 | |||
| 410 | 321534 | Nodes Refinement::DiamondStep(const Nodes& squares, int level, const detail::IndexBox& box, | |
| 411 | const ScaleField& scales) const { | ||
| 412 | 321534 | const bool spline = m_options.interp == DiamondSquareInterp::CatmullRom; | |
| 413 | 321534 | Nodes nodes(box); | |
| 414 | 1852787 | for (std::int64_t row = box.row0; row <= box.row1; ++row) { | |
| 415 | 13083685 | for (std::int64_t col = box.col0; col <= box.col1; ++col) { | |
| 416 | 11552434 | nodes.At(col, row) = | |
| 417 | 11552429 | IsOdd(col) == IsOdd(row) | |
| 418 | 17325922 | ? squares.At(col, row) | |
| 419 | 5773488 | : DiamondMean(squares, col, row, spline) + | |
| 420 | 5773488 | Displacement(col, row, level, true, ScaleAt(scales, col, row, level)); | |
| 421 | } | ||
| 422 | } | ||
| 423 | 321536 | return nodes; | |
| 424 | } | ||
| 425 | |||
| 426 | 430196 | Nodes Refinement::Refine(const PostLattice& posts, int level, const detail::IndexBox& box, | |
| 427 | const ScaleField& scales) const { | ||
| 428 | 430196 | if (level <= 0) { | |
| 429 | 108689 | return BaseNodes(posts, box); | |
| 430 | } | ||
| 431 | 321507 | const bool spline = m_options.interp == DiamondSquareInterp::CatmullRom; | |
| 432 | 321507 | const std::int64_t reach = spline ? 3 : 1; | |
| 433 | 283899 | const std::int64_t margin = spline ? reach : 0; | |
| 434 | 321507 | const Nodes parents = | |
| 435 | Refine(posts, level - 1, | ||
| 436 | 643038 | Box(FloorHalf(box.col0 - margin) - 1, FloorHalf(box.row0 - margin) - 1, | |
| 437 | 321507 | CeilHalf(box.col1 + margin) + 1, CeilHalf(box.row1 + margin) + 1), | |
| 438 | 321507 | scales); | |
| 439 | 321531 | const Nodes squares = SquareStep( | |
| 440 | ✗ | parents, level, Box(box.col0 - reach, box.row0 - reach, box.col1 + reach, box.row1 + reach), | |
| 441 | 321531 | scales); | |
| 442 | 321534 | return DiamondStep(squares, level, box, scales); | |
| 443 | 321529 | } | |
| 444 | |||
| 445 | 111114 | detail::IndexBox Refinement::ReadBox(const NodeFrame& frame, int level, | |
| 446 | Span<const Vec2d> positions) const { | ||
| 447 | 111114 | const double stepX = std::ldexp(frame.stepX, -level); | |
| 448 | 111114 | const double stepY = std::ldexp(frame.stepY, -level); | |
| 449 | 111114 | const std::int64_t before = m_options.interp == DiamondSquareInterp::CatmullRom ? 1 : 0; | |
| 450 | 111114 | const std::int64_t after = m_options.interp == DiamondSquareInterp::CatmullRom ? 2 : 1; | |
| 451 | 111114 | detail::IndexBox box; | |
| 452 | 2200011 | for (const Vec2d& p : positions) { | |
| 453 | 2088899 | const auto [col, u] = NodeAndShare((p.x - frame.originX) / stepX); | |
| 454 | 2088899 | const auto [row, v] = NodeAndShare((p.y - frame.originY) / stepY); | |
| 455 | 2881330 | box.Include(u > 0.0 ? col - before : col, u > 0.0 ? col + after : col, | |
| 456 | 2881330 | v > 0.0 ? row - before : row, v > 0.0 ? row + after : row); | |
| 457 | } | ||
| 458 | 111112 | return box; | |
| 459 | } | ||
| 460 | |||
| 461 | 2047768 | double Refinement::Interpolate(const NodeFrame& frame, const Nodes& nodes, int level, double x, | |
| 462 | double y) const { | ||
| 463 | 2047768 | const auto [col, u] = NodeAndShare((x - frame.originX) / std::ldexp(frame.stepX, -level)); | |
| 464 | 2047768 | const auto [row, v] = NodeAndShare((y - frame.originY) / std::ldexp(frame.stepY, -level)); | |
| 465 | 2047768 | if (m_options.interp == DiamondSquareInterp::CatmullRom) { | |
| 466 | 3647704 | const auto node = [&](double i, double j) { | |
| 467 | 3372515 | return nodes.At(static_cast<std::int64_t>(i), static_cast<std::int64_t>(j)); | |
| 468 | 275189 | }; | |
| 469 | 275189 | return *InterpolateLatticeWeights( | |
| 470 | 275189 | static_cast<double>(col), static_cast<double>(row), | |
| 471 | 275189 | KernelWeights(ResampleMethod::Cubic, u), KernelWeights(ResampleMethod::Cubic, v), | |
| 472 | 275189 | KernelRadius(ResampleMethod::Cubic), node, [](double) { return false; }); | |
| 473 | } | ||
| 474 | 1772579 | double value = nodes.At(col, row); | |
| 475 | 1772579 | if (u > 0.0) { | |
| 476 | 565356 | value = value * (1.0 - u) + nodes.At(col + 1, row) * u; | |
| 477 | } | ||
| 478 | 1772579 | if (v > 0.0) { | |
| 479 | 566313 | double above = nodes.At(col, row + 1); | |
| 480 | 566313 | if (u > 0.0) { | |
| 481 | 539426 | above = above * (1.0 - u) + nodes.At(col + 1, row + 1) * u; | |
| 482 | } | ||
| 483 | 566313 | value = value * (1.0 - v) + above * v; | |
| 484 | } | ||
| 485 | return value; | ||
| 486 | } | ||
| 487 | |||
| 488 | 67804 | void DiamondSquareUpsampler::FillSamples(const PostLattice& posts, SampleBlock& samples, | |
| 489 | double spacing, unsigned threads) const { | ||
| 490 | 67804 | if (!Fitted(m_options)) { | |
| 491 | 3 | throw std::invalid_argument("Diamond-square needs a fractal dimension, and a scale or a " | |
| 492 | 3 | "fit window, given or estimated from the posts"); | |
| 493 | } | ||
| 494 | 67801 | const NodeFrame frame = Refinement::Frame(posts); | |
| 495 | 67800 | const int level = Levels(PostSpacing(posts.Transform()), spacing); | |
| 496 | 67799 | const Refinement refinement(m_options, m_stepFactor); | |
| 497 | 67799 | detail::FillByTiles(samples, threads, [&](Span<const Vec2d> points, Span<float> heights) { | |
| 498 | 67908 | detail::ExpandPoints( | |
| 499 | points, heights, kNodesPerPoint, | ||
| 500 | 111116 | [&](Span<const Vec2d> at) { return refinement.ReadBox(frame, level, at); }, | |
| 501 | 67908 | [&](const detail::IndexBox& box, Span<const Vec2d> at, Span<float> values) { | |
| 502 | 108706 | const Nodes nodes = refinement.Refine( | |
| 503 | posts, level, box, | ||
| 504 | 108706 | level > 0 ? refinement.Scales(posts, level, box) : ScaleField{}); | |
| 505 | 2157087 | for (std::size_t i = 0; i < at.size(); ++i) { | |
| 506 | 2047881 | values[i] = static_cast<float>( | |
| 507 | 2048389 | refinement.Interpolate(frame, nodes, level, at[i].x, at[i].y)); | |
| 508 | } | ||
| 509 | 108706 | }); | |
| 510 | 67909 | }); | |
| 511 | 67800 | } | |
| 512 | |||
| 513 | 17 | int DiamondSquareUpsampler::Reach() const { | |
| 514 | 17 | return m_options.interp == DiamondSquareInterp::CatmullRom ? 8 : 4; | |
| 515 | } | ||
| 516 | |||
| 517 | 97 | std::shared_ptr<const Upsampler> DiamondSquareUpsampler::FitTo(const PostLattice& posts) const { | |
| 518 | 97 | if (Fitted(m_options)) { | |
| 519 | 50 | return nullptr; | |
| 520 | } | ||
| 521 | 47 | detail::IndexBox box; | |
| 522 | 47 | if (const std::optional<PixelWindow> extent = posts.Extent()) { | |
| 523 | 45 | const std::size_t width = std::min(extent->colEnd - extent->colBegin, kEstimateSide); | |
| 524 | 45 | const std::size_t height = std::min(extent->rowEnd - extent->rowBegin, kEstimateSide); | |
| 525 | 45 | const auto colBegin = static_cast<std::int64_t>( | |
| 526 | 45 | extent->colBegin + (extent->colEnd - extent->colBegin - width) / 2); | |
| 527 | 45 | const auto rowBegin = static_cast<std::int64_t>( | |
| 528 | 45 | extent->rowBegin + (extent->rowEnd - extent->rowBegin - height) / 2); | |
| 529 | 45 | box = Box(colBegin, rowBegin, colBegin + static_cast<std::int64_t>(width) - 1, | |
| 530 | 45 | rowBegin + static_cast<std::int64_t>(height) - 1); | |
| 531 | } else { | ||
| 532 | 2 | const auto side = static_cast<std::int64_t>(kUnboundedEstimateSide); | |
| 533 | 2 | box = Box(0, 0, side - 1, side - 1); | |
| 534 | } | ||
| 535 | 47 | const detail::LatticeWindow<float> read = detail::ReadPosts(posts, box); | |
| 536 | 47 | const MidpointRoughness roughness = | |
| 537 | 47 | EstimateMidpointRoughness(PostRaster(read, box.col0, box.row0, box.Columns(), box.Rows())); | |
| 538 | 47 | DiamondSquareOptions fitted = m_options; | |
| 539 | 94 | fitted.fractalDimension = m_options.fractalDimension.value_or(roughness.fractalDimension); | |
| 540 | 47 | if (m_options.fitWindow == 0) { | |
| 541 | 18 | fitted.scale = m_options.scale.value_or(roughness.scale); | |
| 542 | } | ||
| 543 | 47 | return std::make_shared<DiamondSquareUpsampler>(fitted); | |
| 544 | 47 | } | |
| 545 | |||
| 546 | 5 | std::shared_ptr<const Upsampler> DiamondSquareUpsampler::Reseeded(std::uint64_t seed) const { | |
| 547 | 5 | DiamondSquareOptions reseeded = m_options; | |
| 548 | 5 | reseeded.seed = ReseedWord(seed, 0); | |
| 549 | 5 | return std::make_shared<DiamondSquareUpsampler>(reseeded); | |
| 550 | } | ||
| 551 | |||
| 552 | } // namespace terraingen | ||
| 553 |