src/layers/transforms.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | |||
| 3 | #include "terraingen/layers/transforms.h" | ||
| 4 | |||
| 5 | #include <algorithm> | ||
| 6 | #include <cmath> | ||
| 7 | #include <stdexcept> | ||
| 8 | #include <utility> | ||
| 9 | |||
| 10 | namespace terraingen { | ||
| 11 | |||
| 12 | 35 | ScaleLayer::ScaleLayer(double scale, double offset) : m_scale(scale), m_offset(offset) { | |
| 13 | 35 | if (!(std::isfinite(scale) && std::isfinite(offset))) { | |
| 14 | 2 | throw std::invalid_argument("Scale and offset must be finite"); | |
| 15 | } | ||
| 16 | 33 | } | |
| 17 | |||
| 18 | 72717 | float ScaleLayer::HeightAt(float height, double /*x*/, double /*y*/, | |
| 19 | const LayerContext& /*context*/) const { | ||
| 20 | 72717 | return static_cast<float>(static_cast<double>(height) * m_scale + m_offset); | |
| 21 | } | ||
| 22 | |||
| 23 | 16 | ClampLayer::ClampLayer(std::optional<double> min, std::optional<double> max) | |
| 24 | 16 | : m_min(min), m_max(max) { | |
| 25 | 16 | if ((min && !std::isfinite(*min)) || (max && !std::isfinite(*max))) { | |
| 26 | 2 | throw std::invalid_argument("Clamp bounds must be finite"); | |
| 27 | } | ||
| 28 | 14 | if (min && max && *min > *max) { | |
| 29 | 3 | throw std::invalid_argument("Clamp min must not exceed max"); | |
| 30 | } | ||
| 31 | 11 | } | |
| 32 | |||
| 33 | 13945 | float ClampLayer::HeightAt(float height, double /*x*/, double /*y*/, | |
| 34 | const LayerContext& /*context*/) const { | ||
| 35 | 13945 | double value = static_cast<double>(height); | |
| 36 | 13945 | if (m_min) { | |
| 37 | 57 | value = std::max(value, *m_min); | |
| 38 | } | ||
| 39 | 13945 | if (m_max) { | |
| 40 | 24285 | value = std::min(value, *m_max); | |
| 41 | } | ||
| 42 | 13945 | return static_cast<float>(value); | |
| 43 | } | ||
| 44 | |||
| 45 | 6 | FunctionLayer::FunctionLayer(HeightFunction function) : m_function(std::move(function)) { | |
| 46 | 6 | if (!m_function) { | |
| 47 | 1 | throw std::invalid_argument("A function layer needs a function"); | |
| 48 | } | ||
| 49 | 6 | } | |
| 50 | |||
| 51 | 131 | float FunctionLayer::HeightAt(float height, double x, double y, const LayerContext& context) const { | |
| 52 | 131 | return static_cast<float>(m_function(x, y, context.spacing, static_cast<double>(height))); | |
| 53 | } | ||
| 54 | |||
| 55 | } // namespace terraingen | ||
| 56 |