载入中...
搜索中...
未找到
TerrainSurface.cpp
浏览该文件的文档.
1// CPU terrain surface generation, streaming and terrace analysis.
2// Kept outside the grass/script adapter so native logic tests need no renderer.
3#include <algorithm>
4#include <array>
5#include <cmath>
6#include <queue>
7#include <tuple>
8#include <vector>
14
15// TerrainMesh.cpp
16namespace eve::procgen {
17namespace {
18float smoothstep(float a, float b, float v) {
19 const float t = std::clamp((v - a) / (b - a), 0.f, 1.f);
20 return t * t * (3.f - 2.f * t);
21}
22
23std::array<float, 3> normalAt(const Heightmap &hm, int x, int y, float cell, float heightScale) {
24 const int x0 = std::max(0, x - 1), x1 = std::min(hm.getWidth() - 1, x + 1);
25 const int y0 = std::max(0, y - 1), y1 = std::min(hm.getHeight() - 1, y + 1);
26 const float dx = (hm.height(x1, y) - hm.height(x0, y)) * heightScale / (float(std::max(1, x1 - x0)) * cell);
27 const float dz = (hm.height(x, y1) - hm.height(x, y0)) * heightScale / (float(std::max(1, y1 - y0)) * cell);
28 const float inv = 1.f / std::sqrt(dx * dx + 1.f + dz * dz);
29 return {-dx * inv, inv, -dz * inv};
30}
31
32std::array<float, 4> weightsAt(const Heightmap &hm, const TerrainLayers *layers, int x, int y,
33 const std::array<float, 3> &normal, float minH, float rangeH) {
34 std::array<float, 4> w{0.05f, 0.05f, 0.05f, 0.05f};
35 auto addBiome = [](std::array<float, 4> &target, Biome biome, float scale) {
36 switch (biome) {
37 case Biome::Ocean:
38 case Biome::Beach:
39 case Biome::Desert: target[0] += 0.9f * scale; break;
40 case Biome::River:
41 // Exposed mountain reaches are wet rock/riverbank rather than a
42 // bright sand stripe. Calm reaches receive a separate water mesh.
43 target[0] += 0.10f * scale;
44 target[1] += 0.34f * scale;
45 target[2] += 0.46f * scale;
46 break;
47 case Biome::Lake:
48 target[0] += 0.75f * scale;
49 target[1] += 0.15f * scale;
50 break;
51 case Biome::Wetland:
52 target[1] += 0.68f * scale;
53 target[0] += 0.22f * scale;
54 break;
56 case Biome::Forest:
57 case Biome::Rainforest: target[1] += 0.9f * scale; break;
58 case Biome::Tundra:
59 case Biome::Taiga:
60 target[3] += 0.75f * scale;
61 target[1] += 0.15f * scale;
62 break;
63 case Biome::Alpine:
64 target[2] += 0.85f * scale;
65 target[3] += 0.1f * scale;
66 break;
67 }
68 };
69 if (layers) {
70 // Biomes remain categorical for gameplay, but their material response
71 // is a compact Gaussian blend. This removes chessboard boundaries at
72 // climate thresholds without washing out slope-driven rock or snow.
73 float kernelSum = 0.f;
74 for (int oy = -1; oy <= 1; ++oy)
75 for (int ox = -1; ox <= 1; ++ox) {
76 const int sx = std::clamp(x + ox, 0, hm.getWidth() - 1);
77 const int sy = std::clamp(y + oy, 0, hm.getHeight() - 1);
78 const float kernel = float((ox == 0 ? 2 : 1) * (oy == 0 ? 2 : 1));
79 const int biome = std::clamp(layers->getBiome(sx, sy), 0, int(Biome::Wetland));
80 addBiome(w, Biome(biome), kernel);
81 kernelSum += kernel;
82 }
83 for (float &value : w) value /= kernelSum;
84 } else
85 addBiome(w, Biome::Grassland, 1.f);
86 const float slope = 1.f - normal[1];
87 w[2] += smoothstep(0.08f, 0.42f, slope) * 1.2f;
88 if (layers) {
89 const float drainage = std::log1p(std::max(0.f, layers->getFlowAccumulation(x, y))) /
90 std::log1p(float(std::max(2, hm.getWidth() * hm.getHeight())));
91 const float lowGradient = 1.f - smoothstep(0.025f, 0.16f, slope);
92 const float alluvium = smoothstep(0.42f, 0.72f, drainage) * lowGradient;
93 // Mature, low-gradient drainage corridors expose silt, gravel and
94 // point-bar sediment even when the surrounding biome is humid. Without
95 // this counter-signal the widened floodplain is painted as one uniform
96 // green carpet and its geomorphic break in slope becomes invisible.
97 w[0] += alluvium * 0.72f;
98 w[2] += alluvium * 0.10f;
99 }
100 const float elevation = rangeH > 0.f ? (hm.height(x, y) - minH) / rangeH : 0.f;
101 w[2] += smoothstep(0.62f, 0.82f, elevation) * 0.35f;
102 w[3] += smoothstep(0.78f, 0.96f, elevation) * 0.65f;
103 if (layers) w[1] += layers->getMoisture(x, y) * (1.f - smoothstep(0.05f, 0.3f, slope)) * 0.25f;
104 const float sum = w[0] + w[1] + w[2] + w[3];
105 for (float &value : w) value /= sum;
106 return w;
107}
108
109std::vector<int> sampleAxis(int begin, int cells, int step) {
110 std::vector<int> axis;
111 for (int v = begin; v < begin + cells; v += step) axis.push_back(v);
112 axis.push_back(begin + cells);
113 return axis;
114}
115} // namespace
116
117float TerrainMeshChunk::getMaterialWeight(int vertex, int channel) const {
118 if (vertex < 0 || vertex >= getVertexCount() || channel < 0 || channel >= 4) return 0.f;
119 return weights_[size_t(vertex) * 4u + size_t(channel)];
120}
121
122int TerrainMeshChunk::getBiome(int vertex) const {
123 if (vertex < 0 || size_t(vertex) >= biomes_.size()) return -1;
124 return int(biomes_[size_t(vertex)]);
125}
126
128 TerrainMeshChunk &out, std::string *error) {
129 if (s.cellsX <= 0 || s.cellsY <= 0 || s.originX < 0 || s.originY < 0 || s.originX + s.cellsX >= hm.getWidth() ||
130 s.originY + s.cellsY >= hm.getHeight() || s.lod < 0 || s.lod > 20 || !std::isfinite(s.cellSize) ||
131 s.cellSize <= 0.f || !std::isfinite(s.heightScale) || !std::isfinite(s.skirtDepth) || s.skirtDepth < 0.f) {
132 if (error) *error = "terrain mesh: invalid bounds or settings";
133 return false;
134 }
135 if (layers && (layers->getWidth() != hm.getWidth() || layers->getHeight() != hm.getHeight())) {
136 if (error) *error = "terrain mesh: layer dimensions do not match heightmap";
137 return false;
138 }
139 const int step = 1 << s.lod;
140 const std::vector<int> xs = sampleAxis(s.originX, s.cellsX, step);
141 const std::vector<int> ys = sampleAxis(s.originY, s.cellsY, step);
142 const auto [minIt, maxIt] = std::minmax_element(hm.data().begin(), hm.data().end());
143 const float minH = *minIt, rangeH = *maxIt - *minIt;
144 out = {};
145 out.lodStep_ = step;
146 out.originX_ = s.originX;
147 out.originY_ = s.originY;
148 out.geometricError_ = estimateGeometricError(hm, s);
149 const int cols = int(xs.size()), rows = int(ys.size());
150 out.splatWidth_ = cols;
151 out.splatHeight_ = rows;
152 out.mesh_.reserve(cols * rows + (cols + rows) * 4, (cols - 1) * (rows - 1) * 6);
153 auto addVertex = [&](int gx, int gy, float yOffset, const std::array<float, 3> &n) {
154 out.mesh_.addVertex(float(gx - s.originX) * s.cellSize, hm.height(gx, gy) * s.heightScale + yOffset,
155 float(gy - s.originY) * s.cellSize, n[0], n[1], n[2],
156 float(gx - s.originX) / float(s.cellsX), float(gy - s.originY) / float(s.cellsY));
157 const auto weights =
158 weightsAt(hm, layers, gx, gy, normalAt(hm, gx, gy, s.cellSize, s.heightScale), minH, rangeH);
159 out.weights_.insert(out.weights_.end(), weights.begin(), weights.end());
160 out.biomes_.push_back(
161 uint8_t(layers ? std::clamp(layers->getBiome(gx, gy), 0, int(Biome::Wetland)) : int(Biome::Grassland)));
162 };
163 for (int gy : ys)
164 for (int gx : xs) addVertex(gx, gy, 0.f, normalAt(hm, gx, gy, s.cellSize, s.heightScale));
165 out.baseVertexCount_ = out.mesh_.getVertexCount();
166 for (int y = 0; y + 1 < rows; ++y)
167 for (int x = 0; x + 1 < cols; ++x) {
168 const uint32_t a = uint32_t(y * cols + x), b = a + 1, c = a + uint32_t(cols), d = c + 1;
169 out.mesh_.addTriangle(a, c, b);
170 out.mesh_.addTriangle(b, c, d);
171 }
172
173 if (s.skirtDepth > 0.f) {
174 struct Edge {
175 std::vector<std::pair<int, int>> points;
176 std::array<float, 3> normal;
177 };
178 std::array<Edge, 4> edges;
179 for (int gx : xs) edges[0].points.emplace_back(gx, ys.front());
180 for (int gy : ys) edges[1].points.emplace_back(xs.back(), gy);
181 for (auto it = xs.rbegin(); it != xs.rend(); ++it) edges[2].points.emplace_back(*it, ys.back());
182 for (auto it = ys.rbegin(); it != ys.rend(); ++it) edges[3].points.emplace_back(xs.front(), *it);
183 edges[0].normal = {0.f, 0.f, -1.f};
184 edges[1].normal = {1.f, 0.f, 0.f};
185 edges[2].normal = {0.f, 0.f, 1.f};
186 edges[3].normal = {-1.f, 0.f, 0.f};
187 for (const Edge &edge : edges) {
188 const uint32_t start = uint32_t(out.mesh_.getVertexCount());
189 for (const auto &[gx, gy] : edge.points) {
190 addVertex(gx, gy, 0.f, edge.normal);
191 addVertex(gx, gy, -s.skirtDepth, edge.normal);
192 }
193 for (uint32_t i = 0; i + 1 < edge.points.size(); ++i) {
194 const uint32_t topA = start + i * 2, bottomA = topA + 1, topB = topA + 2, bottomB = topB + 1;
195 out.mesh_.addTriangle(topA, topB, bottomA);
196 out.mesh_.addTriangle(topB, bottomB, bottomA);
197 }
198 }
199 }
200 out.mesh_.setMeta("kind", "terrain.chunk");
201 out.mesh_.setMeta("lod", std::to_string(s.lod));
202 out.mesh_.setMeta("originX", std::to_string(s.originX));
203 out.mesh_.setMeta("originY", std::to_string(s.originY));
204 return true;
205}
206
208 if (s.lod <= 0 || s.originX < 0 || s.originY < 0 || s.cellsX <= 0 || s.cellsY <= 0 ||
209 s.originX + s.cellsX >= hm.getWidth() || s.originY + s.cellsY >= hm.getHeight() ||
210 !std::isfinite(s.heightScale))
211 return 0.f;
212 const int step = 1 << std::min(s.lod, 20);
213 float maxError = 0.f;
214 for (int by = 0; by < s.cellsY; by += step) {
215 const int y0 = s.originY + by;
216 const int y1 = s.originY + std::min(by + step, s.cellsY);
217 for (int bx = 0; bx < s.cellsX; bx += step) {
218 const int x0 = s.originX + bx;
219 const int x1 = s.originX + std::min(bx + step, s.cellsX);
220 const float h00 = hm.height(x0, y0), h10 = hm.height(x1, y0);
221 const float h01 = hm.height(x0, y1), h11 = hm.height(x1, y1);
222 for (int y = y0; y <= y1; ++y)
223 for (int x = x0; x <= x1; ++x) {
224 const float tx = x1 > x0 ? float(x - x0) / float(x1 - x0) : 0.f;
225 const float ty = y1 > y0 ? float(y - y0) / float(y1 - y0) : 0.f;
226 const float approximation = std::lerp(std::lerp(h00, h10, tx), std::lerp(h01, h11, tx), ty);
227 maxError = std::max(maxError, std::abs(hm.height(x, y) - approximation) * std::abs(s.heightScale));
228 }
229 }
230 }
231 return maxError;
232}
233
234int TerrainLodSelector::select(const Heightmap &hm, TerrainMeshSettings s, int maxLod, float distanceToCamera,
235 float viewportHeight, float verticalFovDegrees, float targetPixelError) {
236 if (maxLod < 0 || maxLod > 20 || !std::isfinite(distanceToCamera) || distanceToCamera <= 0.f ||
237 !std::isfinite(viewportHeight) || viewportHeight <= 0.f || !std::isfinite(verticalFovDegrees) ||
238 verticalFovDegrees <= 1.f || verticalFovDegrees >= 179.f || !std::isfinite(targetPixelError) ||
239 targetPixelError <= 0.f || s.originX < 0 || s.originY < 0 || s.cellsX <= 0 || s.cellsY <= 0 ||
240 s.originX + s.cellsX >= hm.getWidth() || s.originY + s.cellsY >= hm.getHeight() ||
241 !std::isfinite(s.heightScale))
242 return -1;
243 const float radians = verticalFovDegrees * 0.01745329251994329577f;
244 const float projectionScale = viewportHeight / (2.f * std::tan(radians * 0.5f));
245 for (int lod = maxLod; lod >= 0; --lod) {
246 s.lod = lod;
247 const float projected = TerrainMeshBuilder::estimateGeometricError(hm, s) * projectionScale / distanceToCamera;
248 if (projected <= targetPixelError) return lod;
249 }
250 return 0;
251}
252
254 MeshBuild &out, std::string *error) {
255 if (s.cellsX <= 0 || s.cellsY <= 0 || s.originX < 0 || s.originY < 0 || s.originX + s.cellsX >= hm.getWidth() ||
256 s.originY + s.cellsY >= hm.getHeight() || layers.getWidth() != hm.getWidth() ||
257 layers.getHeight() != hm.getHeight() || !std::isfinite(s.cellSize) || s.cellSize <= 0.f ||
258 !std::isfinite(s.heightScale) || !std::isfinite(s.minWidth) || !std::isfinite(s.maxWidth) ||
259 s.minWidth <= 0.f || s.maxWidth < s.minWidth || !std::isfinite(s.heightOffset) ||
260 !std::isfinite(s.minSurfaceSlope) || !std::isfinite(s.maxSurfaceSlope) || s.minSurfaceSlope < 0.f ||
261 s.maxSurfaceSlope <= s.minSurfaceSlope) {
262 if (error) *error = "terrain river mesh: invalid bounds or settings";
263 return false;
264 }
265 out = {};
266 static constexpr std::array<int, 8> flowDx{-1, 0, 1, -1, 1, -1, 0, 1};
267 static constexpr std::array<int, 8> flowDy{-1, -1, -1, 0, 0, 1, 1, 1};
268 const size_t layerCells = size_t(layers.getWidth()) * size_t(layers.getHeight());
269 std::vector<float> channelFlow(layerCells, 0.f);
270 std::vector<uint16_t> riverIndegree(layerCells, 0);
271 for (int y = 0; y < layers.getHeight(); ++y)
272 for (int x = 0; x < layers.getWidth(); ++x) {
273 const size_t i = size_t(y * layers.getWidth() + x);
274 if (!layers.isRiver(x, y)) continue;
275 channelFlow[i] = std::max(0.f, layers.getFlowAccumulation(x, y));
276 const int direction = layers.getFlowDirection(x, y);
277 if (direction < 0 || direction >= 8) continue;
278 const int rx = x + flowDx[size_t(direction)], ry = y + flowDy[size_t(direction)];
279 if (rx >= 0 && ry >= 0 && rx < layers.getWidth() && ry < layers.getHeight() && layers.isRiver(rx, ry))
280 ++riverIndegree[size_t(ry * layers.getWidth() + rx)];
281 }
282 std::queue<size_t> riverQueue;
283 for (size_t i = 0; i < layerCells; ++i)
284 if (channelFlow[i] > 0.f && riverIndegree[i] == 0) riverQueue.push(i);
285 while (!riverQueue.empty()) {
286 const size_t i = riverQueue.front();
287 riverQueue.pop();
288 const int x = int(i % size_t(layers.getWidth()));
289 const int y = int(i / size_t(layers.getWidth()));
290 const int direction = layers.getFlowDirection(x, y);
291 if (direction < 0 || direction >= 8) continue;
292 const int rx = x + flowDx[size_t(direction)], ry = y + flowDy[size_t(direction)];
293 if (rx < 0 || ry < 0 || rx >= layers.getWidth() || ry >= layers.getHeight() || !layers.isRiver(rx, ry))
294 continue;
295 const size_t receiver = size_t(ry * layers.getWidth() + rx);
296 channelFlow[receiver] = std::max(channelFlow[receiver], channelFlow[i]);
297 if (riverIndegree[receiver] > 0 && --riverIndegree[receiver] == 0) riverQueue.push(receiver);
298 }
299 float maxFlow = 1.f;
300 for (float flow : channelFlow) maxFlow = std::max(maxFlow, flow);
301 std::vector<uint8_t> calmReach(layerCells, 0);
302 for (int y = 0; y < layers.getHeight(); ++y)
303 for (int x = 0; x < layers.getWidth(); ++x) {
304 const int d = layers.getFlowDirection(x, y);
305 if (!layers.isRiver(x, y) || d < 0 || d >= 8) continue;
306 const int rx = x + flowDx[size_t(d)], ry = y + flowDy[size_t(d)];
307 if (rx < 0 || ry < 0 || rx >= hm.getWidth() || ry >= hm.getHeight()) continue;
308 const float run =
309 s.cellSize *
310 std::sqrt(float(flowDx[size_t(d)] * flowDx[size_t(d)] + flowDy[size_t(d)] * flowDy[size_t(d)]));
311 const float rise = std::abs(hm.height(rx, ry) - hm.height(x, y)) * s.heightScale;
312 const float grade = rise / run;
313 calmReach[size_t(y * layers.getWidth() + x)] =
314 uint8_t(grade >= s.minSurfaceSlope && grade < s.maxSurfaceSlope);
315 }
316 // Close isolated one-cell grade spikes only when a calm upstream segment
317 // and calm downstream segment both exist. Long cascades remain suppressed.
318 std::vector<uint8_t> closedReach = calmReach;
319 for (int y = 1; y + 1 < layers.getHeight(); ++y)
320 for (int x = 1; x + 1 < layers.getWidth(); ++x) {
321 const size_t i = size_t(y * layers.getWidth() + x);
322 const int d = layers.getFlowDirection(x, y);
323 if (calmReach[i] || !layers.isRiver(x, y) || d < 0 || d >= 8) continue;
324 const int rx = x + flowDx[size_t(d)], ry = y + flowDy[size_t(d)];
325 const size_t receiver = size_t(ry * layers.getWidth() + rx);
326 if (!calmReach[receiver]) continue;
327 bool calmDonor = false;
328 for (int incoming = 0; incoming < 8 && !calmDonor; ++incoming) {
329 const int nx = x + flowDx[size_t(incoming)], ny = y + flowDy[size_t(incoming)];
330 const int nd = layers.getFlowDirection(nx, ny);
331 if (nd < 0 || nd >= 8) continue;
332 const size_t n = size_t(ny * layers.getWidth() + nx);
333 calmDonor = calmReach[n] && nx + flowDx[size_t(nd)] == x && ny + flowDy[size_t(nd)] == y;
334 }
335 if (calmDonor) closedReach[i] = 1;
336 }
337 auto strongestDonor = [&](int sx, int sy) {
338 float donorFlow = -1.f;
339 int donorX = sx, donorY = sy;
340 for (int candidate = 0; candidate < 8; ++candidate) {
341 const int dxCell = sx + flowDx[size_t(candidate)];
342 const int dyCell = sy + flowDy[size_t(candidate)];
343 if (dxCell < 0 || dyCell < 0 || dxCell >= layers.getWidth() || dyCell >= layers.getHeight()) continue;
344 const int donorDirection = layers.getFlowDirection(dxCell, dyCell);
345 if (donorDirection < 0 || donorDirection >= 8 || dxCell + flowDx[size_t(donorDirection)] != sx ||
346 dyCell + flowDy[size_t(donorDirection)] != sy)
347 continue;
348 const float flow = layers.getFlowAccumulation(dxCell, dyCell);
349 if (flow > donorFlow) {
350 donorFlow = flow;
351 donorX = dxCell;
352 donorY = dyCell;
353 }
354 }
355 return std::array<int, 2>{donorX, donorY};
356 };
357 auto receiver = [&](int sx, int sy) {
358 const int direction = layers.getFlowDirection(sx, sy);
359 if (direction < 0 || direction >= 8) return std::array<int, 2>{sx, sy};
360 const int receiverX = sx + flowDx[size_t(direction)];
361 const int receiverY = sy + flowDy[size_t(direction)];
362 if (receiverX < 0 || receiverY < 0 || receiverX >= layers.getWidth() || receiverY >= layers.getHeight())
363 return std::array<int, 2>{sx, sy};
364 return std::array<int, 2>{receiverX, receiverY};
365 };
366 auto smoothCenter = [&](int sx, int sy) {
367 // Binomial five-point filtering follows the highest-discharge donor
368 // through the cell and two receivers downstream. It suppresses the
369 // one-cell D8 staircase while retaining confluences and is deterministic
370 // across independently generated chunks. The weights sum to one and
371 // preserve straight reaches exactly.
372 const auto pMinus1 = strongestDonor(sx, sy);
373 const auto pMinus2 = strongestDonor(pMinus1[0], pMinus1[1]);
374 const auto pPlus1 = receiver(sx, sy);
375 const auto pPlus2 = receiver(pPlus1[0], pPlus1[1]);
376 return std::array<float, 2>{(float(pMinus2[0]) + 4.f * float(pMinus1[0]) + 6.f * float(sx) +
377 4.f * float(pPlus1[0]) + float(pPlus2[0])) /
378 16.f,
379 (float(pMinus2[1]) + 4.f * float(pMinus1[1]) + 6.f * float(sy) +
380 4.f * float(pPlus1[1]) + float(pPlus2[1])) /
381 16.f};
382 };
383 auto sampleHeight = [&](float sx, float sy) {
384 sx = std::clamp(sx, 0.f, float(hm.getWidth() - 1));
385 sy = std::clamp(sy, 0.f, float(hm.getHeight() - 1));
386 const int x0 = int(std::floor(sx)), y0 = int(std::floor(sy));
387 const int x1 = std::min(x0 + 1, hm.getWidth() - 1);
388 const int y1 = std::min(y0 + 1, hm.getHeight() - 1);
389 const float tx = sx - float(x0), ty = sy - float(y0);
390 return std::lerp(std::lerp(hm.height(x0, y0), hm.height(x1, y0), tx),
391 std::lerp(hm.height(x0, y1), hm.height(x1, y1), tx), ty);
392 };
393 for (int y = s.originY; y <= s.originY + s.cellsY; ++y) {
394 for (int x = s.originX; x <= s.originX + s.cellsX; ++x) {
395 const int direction = layers.getFlowDirection(x, y);
396 if (!layers.isRiver(x, y) || direction < 0 || direction >= 8) continue;
397 if (!closedReach[size_t(y * layers.getWidth() + x)]) continue;
398 const int receiverX = x + flowDx[size_t(direction)];
399 const int receiverY = y + flowDy[size_t(direction)];
400 const auto startCenter = smoothCenter(x, y);
401 const auto endCenter = smoothCenter(receiverX, receiverY);
402 const float tx0 = endCenter[0] - startCenter[0];
403 const float tz0 = endCenter[1] - startCenter[1];
404 const float tangentLengthSquared = tx0 * tx0 + tz0 * tz0;
405 if (tangentLengthSquared <= 1e-8f) continue;
406 const float invLength = 1.f / std::sqrt(tangentLengthSquared);
407 const float tx = tx0 * invLength, tz = tz0 * invLength;
408 auto widthAt = [&](int sampleX, int sampleY) {
409 // Downstream hydraulic geometry is commonly approximated by a
410 // discharge power law. The 0.36 exponent retains readable head
411 // streams while producing gradual main-stem widening.
412 const float discharge = channelFlow[size_t(sampleY * layers.getWidth() + sampleX)];
413 const float areaScale =
414 maxFlow > 1.f ? std::pow(std::clamp(discharge / maxFlow, 0.f, 1.f), 0.36f) : 0.f;
415 const float orderScale =
416 std::clamp((float(layers.getStreamOrder(sampleX, sampleY)) - 1.f) / 4.f, 0.f, 1.f);
417 const float flowScale = std::max(areaScale, orderScale * 0.82f);
418 return 0.5f * std::lerp(s.minWidth, s.maxWidth, flowScale);
419 };
420 const float startWidth = widthAt(x, y);
421 const float endWidth = layers.isRiver(receiverX, receiverY) ? widthAt(receiverX, receiverY) : startWidth;
422 float startFlowX = layers.getFlowVectorX(x, y);
423 float startFlowY = layers.getFlowVectorY(x, y);
424 float endFlowX = layers.getFlowVectorX(receiverX, receiverY);
425 float endFlowY = layers.getFlowVectorY(receiverX, receiverY);
426 if (std::hypot(startFlowX, startFlowY) < 0.1f) {
427 startFlowX = tx;
428 startFlowY = tz;
429 }
430 if (std::hypot(endFlowX, endFlowY) < 0.1f) {
431 endFlowX = tx;
432 endFlowY = tz;
433 }
434 const float chordCells = std::sqrt(tangentLengthSquared);
435 auto curvePoint = [&](float t) {
436 const float t2 = t * t, t3 = t2 * t;
437 const float h00 = 2.f * t3 - 3.f * t2 + 1.f;
438 const float h10 = t3 - 2.f * t2 + t;
439 const float h01 = -2.f * t3 + 3.f * t2;
440 const float h11 = t3 - t2;
441 return std::array<float, 2>{h00 * startCenter[0] + h10 * startFlowX * chordCells + h01 * endCenter[0] +
442 h11 * endFlowX * chordCells,
443 h00 * startCenter[1] + h10 * startFlowY * chordCells + h01 * endCenter[1] +
444 h11 * endFlowY * chordCells};
445 };
446 constexpr int curveSegments = 5;
447 std::array<std::array<float, 2>, curveSegments + 1> curve{};
448 for (int point = 0; point <= curveSegments; ++point)
449 curve[size_t(point)] = curvePoint(float(point) / float(curveSegments));
450 const uint32_t stripStart = uint32_t(out.getVertexCount());
451 for (int point = 0; point <= curveSegments; ++point) {
452 const int previous = std::max(0, point - 1);
453 const int following = std::min(curveSegments, point + 1);
454 const float qdx = curve[size_t(following)][0] - curve[size_t(previous)][0];
455 const float qdy = curve[size_t(following)][1] - curve[size_t(previous)][1];
456 const float t = float(point) / float(curveSegments);
457 // Every independently emitted reach that meets at a drainage
458 // cell must produce the same bank pair at that cell. Using the
459 // finite-difference tangent of each Hermite span made the two
460 // reaches disagree at their shared endpoint, leaving the
461 // scalloped/saw-tooth silhouette visible in rendered rivers.
462 // The stored continuous flow vector is cell-local and therefore
463 // identical on both sides of the join. Blend it inside the span,
464 // but snap endpoint frames exactly to the corresponding cell.
465 float frameX = std::lerp(startFlowX, endFlowX, t);
466 float frameY = std::lerp(startFlowY, endFlowY, t);
467 if (point == 0) {
468 frameX = startFlowX;
469 frameY = startFlowY;
470 }
471 if (point == curveSegments) {
472 frameX = endFlowX;
473 frameY = endFlowY;
474 }
475 float frameLength = std::hypot(frameX, frameY);
476 if (frameLength < 1e-5f) {
477 frameX = qdx;
478 frameY = qdy;
479 frameLength = std::max(1e-5f, std::hypot(frameX, frameY));
480 }
481 const float qpx = -frameY / frameLength;
482 const float qpz = frameX / frameLength;
483 const float width = std::lerp(startWidth, endWidth, t);
484 const auto &q = curve[size_t(point)];
485 const float qx = (q[0] - float(s.originX)) * s.cellSize;
486 const float qz = (q[1] - float(s.originY)) * s.cellSize;
487 const float widthCells = width / s.cellSize;
488 const float centerBed = sampleHeight(q[0], q[1]);
489 const float leftBed = sampleHeight(q[0] - qpx * widthCells, q[1] - qpz * widthCells);
490 const float rightBed = sampleHeight(q[0] + qpx * widthCells, q[1] + qpz * widthCells);
491 // One transverse water level must clear both banks. Sampling
492 // only the center buried the uphill half of ribbons whenever
493 // a smoothed centerline crossed a sloping raster triangle,
494 // which appeared as broken rectangular river segments.
495 const float qy = std::max({centerBed, leftBed, rightBed}) * s.heightScale + s.heightOffset;
496 out.addVertex(qx - qpx * width, qy, qz - qpz * width, 0.f, 1.f, 0.f, 0.f, t);
497 out.addVertex(qx + qpx * width, qy, qz + qpz * width, 0.f, 1.f, 0.f, 1.f, t);
498 }
499 for (int segment = 0; segment < curveSegments; ++segment) {
500 const uint32_t a = stripStart + uint32_t(segment * 2);
501 const uint32_t b = a + 1u, c = a + 2u, dVertex = a + 3u;
502 out.addTriangle(a, c, b);
503 out.addTriangle(b, c, dVertex);
504 }
505 }
506 }
507 out.setMeta("kind", "terrain.rivers");
508 return true;
509}
510
512 MeshBuild &out, std::string *error) {
513 if (s.cellsX <= 0 || s.cellsY <= 0 || s.originX < 0 || s.originY < 0 || s.originX + s.cellsX >= hm.getWidth() ||
514 s.originY + s.cellsY >= hm.getHeight() || layers.getWidth() != hm.getWidth() ||
515 layers.getHeight() != hm.getHeight() || !std::isfinite(s.cellSize) || s.cellSize <= 0.f ||
516 !std::isfinite(s.heightScale) || !std::isfinite(s.minimumDepth) || s.minimumDepth < 0.f ||
517 !std::isfinite(s.heightOffset)) {
518 if (error) *error = "terrain lake mesh: invalid bounds or settings";
519 return false;
520 }
521 out = {};
522 struct ShoreVertex {
523 float x, y, z, depth;
524 };
525 for (int y = s.originY; y < s.originY + s.cellsY; ++y) {
526 for (int x = s.originX; x < s.originX + s.cellsX; ++x) {
527 const float d00 = layers.getLakeDepth(x, y);
528 const float d10 = layers.getLakeDepth(x + 1, y);
529 const float d01 = layers.getLakeDepth(x, y + 1);
530 const float d11 = layers.getLakeDepth(x + 1, y + 1);
531 if (std::max({d00, d10, d01, d11}) < s.minimumDepth) continue;
532 auto surface = [&](int sx, int sy, float depth) {
533 return (hm.height(sx, sy) + depth) * s.heightScale + s.heightOffset;
534 };
535 const float x0 = float(x - s.originX) * s.cellSize;
536 const float x1 = float(x + 1 - s.originX) * s.cellSize;
537 const float z0 = float(y - s.originY) * s.cellSize;
538 const float z1 = float(y + 1 - s.originY) * s.cellSize;
539 // Clip the cell polygon against the requested depth contour. This
540 // is the filled equivalent of marching squares and places shoreline
541 // vertices inside cells instead of producing staircase coastlines.
542 std::vector<ShoreVertex> polygon{
543 {x0, surface(x, y, d00), z0, d00},
544 {x1, surface(x + 1, y, d10), z0, d10},
545 {x1, surface(x + 1, y + 1, d11), z1, d11},
546 {x0, surface(x, y + 1, d01), z1, d01},
547 };
548 std::vector<ShoreVertex> clipped;
549 for (size_t edge = 0; edge < polygon.size(); ++edge) {
550 const ShoreVertex &a = polygon[edge];
551 const ShoreVertex &b = polygon[(edge + 1) % polygon.size()];
552 const bool aInside = a.depth >= s.minimumDepth;
553 const bool bInside = b.depth >= s.minimumDepth;
554 if (aInside) clipped.push_back(a);
555 if (aInside == bInside) continue;
556 const float t = std::clamp((s.minimumDepth - a.depth) / (b.depth - a.depth), 0.f, 1.f);
557 clipped.push_back(
558 {std::lerp(a.x, b.x, t), std::lerp(a.y, b.y, t), std::lerp(a.z, b.z, t), s.minimumDepth});
559 }
560 if (clipped.size() < 3) continue;
561 const uint32_t first = uint32_t(out.getVertexCount());
562 for (const ShoreVertex &v : clipped) {
563 const float u = (v.x / (float(s.cellsX) * s.cellSize));
564 const float texV = (v.z / (float(s.cellsY) * s.cellSize));
565 out.addVertex(v.x, v.y, v.z, 0.f, 1.f, 0.f, u, texV);
566 }
567 for (uint32_t vertex = 1; vertex + 1 < clipped.size(); ++vertex)
568 out.addTriangle(first, first + vertex + 1, first + vertex);
569 }
570 }
571 out.setMeta("kind", "terrain.lakes");
572 return true;
573}
574
575} // namespace eve::procgen
576
577// TerrainStreaming.cpp
578namespace eve::procgen {
579
580uint64_t TerrainStreamingCache::key(int chunkX, int chunkY) {
581 return uint64_t(uint32_t(chunkX)) | (uint64_t(uint32_t(chunkY)) << 32);
582}
583
584bool TerrainStreamingCache::open(const uint8_t *data, size_t size, std::string *error) {
585 TerrainAsset next;
586 if (!next.open(data, size, error)) return false;
587 asset_ = std::move(next);
588 resident_.clear();
589 return true;
590}
591
592Result<void> TerrainStreamingCache::openSource(std::shared_ptr<const ITerrainArchiveSource> source) {
593 TerrainAsset next;
594 auto opened = next.openSource(std::move(source));
595 if (!opened) return opened;
596 asset_ = std::move(next);
597 resident_.clear();
598 return Result<void>::success();
599}
600
601void TerrainStreamingCache::clear() { resident_.clear(); }
602
603TerrainStreamStats TerrainStreamingCache::streamAround(int worldX, int worldY, int radius, int maxLoads,
604 std::string *error) {
606 if (radius < 0 || asset_.getChunkSize() <= 0) {
608 return stats;
609 }
610 const int chunkSize = asset_.getChunkSize();
611 const int centerX = worldX >= 0 ? worldX / chunkSize : -((-worldX - 1) / chunkSize) - 1;
612 const int centerY = worldY >= 0 ? worldY / chunkSize : -((-worldY - 1) / chunkSize) - 1;
613 const int64_t radiusSq = int64_t(radius) * radius;
614
615 for (auto it = resident_.begin(); it != resident_.end();) {
616 const int cx = int32_t(uint32_t(it->first));
617 const int cy = int32_t(uint32_t(it->first >> 32));
618 const int64_t dx = int64_t(cx) - centerX, dy = int64_t(cy) - centerY;
619 if (dx * dx + dy * dy > radiusSq) {
620 it = resident_.erase(it);
621 ++stats.evicted;
622 } else
623 ++it;
624 }
625
626 struct Request {
627 int x, y;
628 int64_t distanceSq;
629 };
630 std::vector<Request> requests;
631 for (int dy = -radius; dy <= radius; ++dy) {
632 for (int dx = -radius; dx <= radius; ++dx) {
633 const int64_t distanceSq = int64_t(dx) * dx + int64_t(dy) * dy;
634 if (distanceSq > radiusSq) continue;
635 const int chunkX = centerX + dx, chunkY = centerY + dy;
636 if (asset_.findChunk(chunkX, chunkY) && !getChunk(chunkX, chunkY))
637 requests.push_back({chunkX, chunkY, distanceSq});
638 }
639 }
640 std::sort(requests.begin(), requests.end(), [](const Request &a, const Request &b) {
641 return std::tie(a.distanceSq, a.y, a.x) < std::tie(b.distanceSq, b.y, b.x);
642 });
643 const size_t loadCount = maxLoads > 0 ? std::min(requests.size(), size_t(maxLoads)) : requests.size();
644 for (size_t i = 0; i < loadCount; ++i) {
645 TerrainChunkData chunk;
646 std::string chunkError;
647 if (!asset_.loadChunk(requests[i].x, requests[i].y, chunk, &chunkError)) {
648 ++stats.failed;
649 if (error && error->empty()) *error = chunkError;
650 continue;
651 }
652 resident_.emplace(key(requests[i].x, requests[i].y), std::move(chunk));
653 ++stats.loaded;
654 }
655 stats.pending = int(requests.size() - loadCount);
656 stats.resident = getResidentCount();
657 return stats;
658}
659
660const TerrainChunkData *TerrainStreamingCache::getChunk(int chunkX, int chunkY) const {
661 const auto it = resident_.find(key(chunkX, chunkY));
662 return it == resident_.end() ? nullptr : &it->second;
663}
664
665bool TerrainStreamingCache::sampleCell(int worldX, int worldY, TerrainSample &out) const {
666 if (worldX < 0 || worldY < 0 || worldX >= asset_.getWidth() || worldY >= asset_.getHeight()) return false;
667 const int cs = asset_.getChunkSize(), cx = worldX / cs, cy = worldY / cs;
668 const TerrainChunkData *chunk = getChunk(cx, cy);
669 if (!chunk) return false;
670 const int lx = worldX - cx * cs, ly = worldY - cy * cs;
671 if (lx >= chunk->width || ly >= chunk->height) return false;
672 const size_t i = size_t(ly) * size_t(chunk->width) + size_t(lx);
673 out.height = chunk->heights.data()[i];
674 out.flowAccumulation = chunk->flowAccumulation[i];
675 out.flowDirection = int(chunk->flowDirection[i]);
676 out.flowVectorX = chunk->flowVectorX[i];
677 out.flowVectorY = chunk->flowVectorY[i];
678 out.streamOrder = int(chunk->streamOrder[i]);
679 out.lakeDepth = chunk->lakeDepth[i];
680 out.lake = out.lakeDepth > 0.001f;
681 out.temperature = chunk->temperature[i];
682 out.moisture = chunk->moisture[i];
683 out.river = chunk->rivers[i] != 0;
684 out.biome = chunk->biomes[i];
685 return true;
686}
687
688bool TerrainStreamingCache::getReceiver(int worldX, int worldY, int &receiverX, int &receiverY) const {
689 static constexpr int dx[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
690 static constexpr int dy[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
692 if (!sampleCell(worldX, worldY, source) || source.flowDirection < 0 || source.flowDirection >= 8) return false;
693 receiverX = worldX + dx[source.flowDirection];
694 receiverY = worldY + dy[source.flowDirection];
695 TerrainSample receiver;
696 return sampleCell(receiverX, receiverY, receiver);
697}
698
699bool TerrainStreamingCache::traceFlow(int worldX, int worldY, int maxSteps,
700 std::vector<std::pair<int, int>> &out) const {
701 out.clear();
703 if (maxSteps <= 0 || !sampleCell(worldX, worldY, start)) return false;
704 out.emplace_back(worldX, worldY);
705 for (int step = 0; step < maxSteps; ++step) {
707 if (!sampleCell(worldX, worldY, current)) return false;
708 if (current.flowDirection < 0) return true;
709 int nextX = 0, nextY = 0;
710 if (!getReceiver(worldX, worldY, nextX, nextY)) return false;
711 if (std::find(out.begin(), out.end(), std::pair<int, int>{nextX, nextY}) != out.end()) return false;
712 out.emplace_back(nextX, nextY);
713 worldX = nextX;
714 worldY = nextY;
715 }
717 return sampleCell(worldX, worldY, current) && current.flowDirection < 0;
718}
719
720bool TerrainStreamingCache::buildWindow(int originX, int originY, int width, int height,
722 if (width <= 0 || height <= 0 || originX < 0 || originY < 0 || int64_t(originX) + width > asset_.getWidth() ||
723 int64_t(originY) + height > asset_.getHeight())
724 return false;
726 next.originX = originX;
727 next.originY = originY;
728 next.heights = Heightmap(width, height);
729 next.hydrology.width = width;
730 next.hydrology.height = height;
731 next.climate.width = width;
732 next.climate.height = height;
733 const size_t count = size_t(width) * size_t(height);
734 next.hydrology.flowDirection.resize(count);
735 next.hydrology.flowVectorX.resize(count);
736 next.hydrology.flowVectorY.resize(count);
737 next.hydrology.flowAccumulation.resize(count);
738 next.hydrology.lakeDepth.resize(count);
739 next.hydrology.rivers.resize(count);
740 next.hydrology.streamOrder.resize(count);
741 next.climate.temperature.resize(count);
742 next.climate.moisture.resize(count);
743 next.climate.biomes.resize(count);
744 for (int y = 0; y < height; ++y)
745 for (int x = 0; x < width; ++x) {
747 if (!sampleCell(originX + x, originY + y, sample)) return false;
748 const size_t i = size_t(y) * size_t(width) + size_t(x);
749 next.heights.setHeight(x, y, sample.height);
750 next.hydrology.flowDirection[i] = int8_t(sample.flowDirection);
751 next.hydrology.flowVectorX[i] = sample.flowVectorX;
752 next.hydrology.flowVectorY[i] = sample.flowVectorY;
753 next.hydrology.flowAccumulation[i] = sample.flowAccumulation;
754 next.hydrology.lakeDepth[i] = sample.lakeDepth;
755 next.hydrology.rivers[i] = uint8_t(sample.river);
756 next.hydrology.streamOrder[i] = uint8_t(sample.streamOrder);
757 next.climate.temperature[i] = sample.temperature;
758 next.climate.moisture[i] = sample.moisture;
759 next.climate.biomes[i] = sample.biome;
760 }
761 out = std::move(next);
762 return true;
763}
764
765bool TerrainStreamingCache::sampleHeight(float worldX, float worldY, float &out) const {
766 if (!std::isfinite(worldX) || !std::isfinite(worldY) || worldX < 0.f || worldY < 0.f ||
767 worldX > float(asset_.getWidth() - 1) || worldY > float(asset_.getHeight() - 1))
768 return false;
769 const int x0 = int(std::floor(worldX)), y0 = int(std::floor(worldY));
770 const int x1 = std::min(x0 + 1, asset_.getWidth() - 1), y1 = std::min(y0 + 1, asset_.getHeight() - 1);
771 TerrainSample a, b, c, d;
772 if (!sampleCell(x0, y0, a) || !sampleCell(x1, y0, b) || !sampleCell(x0, y1, c) || !sampleCell(x1, y1, d))
773 return false;
774 const float tx = worldX - float(x0), ty = worldY - float(y0);
775 const float top = a.height + (b.height - a.height) * tx;
776 const float bottom = c.height + (d.height - c.height) * tx;
777 out = top + (bottom - top) * ty;
778 return true;
779}
780
781} // namespace eve::procgen
782
783// TerrainTerraceRemover.cpp
784namespace eve::procgen {
785namespace {
786bool valid(const TerrainTerraceRemovalSettings &s) {
787 const std::array<float, 7> values = {s.perlinScale,
788 s.perlinStrength,
789 s.slopeTerraceThreshold,
790 s.flatThreshold,
791 s.verticalGradientThreshold,
792 s.minimumTerraceThreshold,
793 s.maximumTerraceThreshold};
794 return std::all_of(values.begin(), values.end(), [](float value) { return std::isfinite(value) && value >= 0; }) &&
795 s.minimumTerraceThreshold <= s.maximumTerraceThreshold && s.noiseSeed >= 0;
796}
797bool matching(const Heightmap &a, const Heightmap &b) {
798 return raster_detail::validRaster(a) && raster_detail::validRaster(b) && a.getWidth() == b.getWidth() &&
799 a.getHeight() == b.getHeight();
800}
801} // namespace
802
804 using namespace raster_detail;
805 if (&target == &source || !matching(target, source) || !valid(s))
806 return invalid(
807 "terrain.terraceRemoval.analyze: distinct matching finite rasters and valid thresholds required");
808 const int width = source.getWidth(), height = source.getHeight();
809 std::vector<float> output(size_t(width) * height, float(TerrainTerraceClass::Black));
810 auto at = [width](int x, int y) { return size_t(y) * width + x; };
811 for (int y = 1; y < height - 1; ++y)
812 for (int x = 1; x < width - 1; ++x) {
813 const float current = source.data()[at(x, y)];
814 const float gradientX =
815 std::abs(current - source.data()[at(x - 1, y)]) + std::abs(current - source.data()[at(x + 1, y)]);
816 const float gradientY =
817 std::abs(current - source.data()[at(x, y - 1)]) + std::abs(current - source.data()[at(x, y + 1)]);
818 const float gradient = gradientX + gradientY;
819 const float vertical = std::abs(source.data()[at(x, y - 1)] - source.data()[at(x, y + 1)]);
820 bool slope = false;
821 if (gradient < s.slopeTerraceThreshold && vertical < s.verticalGradientThreshold)
822 slope = std::abs(source.data()[at(x - 1, y)] - current) < s.slopeTerraceThreshold &&
823 std::abs(source.data()[at(x + 1, y)] - current) < s.slopeTerraceThreshold &&
824 std::abs(source.data()[at(x, y - 1)] - current) < s.slopeTerraceThreshold &&
825 std::abs(source.data()[at(x, y + 1)] - current) < s.slopeTerraceThreshold;
826 const bool flat = gradient < s.flatThreshold;
827 const bool mountain = vertical > s.verticalGradientThreshold;
828 const bool terrace = vertical >= s.minimumTerraceThreshold && vertical <= s.maximumTerraceThreshold;
829 output[at(x, y)] = float(terrace ? TerrainTerraceClass::Green
831 : mountain ? TerrainTerraceClass::Red
834 }
835 return publish(target, std::move(output));
836}
837
840 using namespace raster_detail;
841 if (&target == &classes || !matching(target, source) || !matching(source, classes) || !valid(s))
842 return invalid(
843 "terrain.terraceRemoval.apply: matching finite rasters, distinct class output and valid settings required");
844 const int width = source.getWidth(), height = source.getHeight();
845 const auto& original = source.data();
846 auto index = [width](int x, int y) { return size_t(y) * width + x; };
847 std::vector<unsigned char> mask(original.size(), 0);
848 for (int y = 1; y < height - 1; ++y)
849 for (int x = 1; x < width - 1; ++x) {
850 const float category = classes.data()[index(x, y)];
851 if ((s.excludeRed && category == float(TerrainTerraceClass::Red)) ||
852 (s.excludeBlack && category == float(TerrainTerraceClass::Black)))
853 continue;
854 const float current = original[index(x, y)];
855 mask[index(x, y)] = std::abs(current - original[index(x + 1, y)]) < 0.01F &&
856 std::abs(current - original[index(x, y + 1)]) < 0.01F;
857 }
858 auto smooth = original;
859 for (int y = 1; y < height - 1; ++y)
860 for (int x = 1; x < width - 1; ++x)
861 if (mask[index(x, y)]) {
862 double sum = 0;
863 for (int dy = -1; dy <= 1; ++dy)
864 for (int dx = -1; dx <= 1; ++dx) sum += original[index(x + dx, y + dy)];
865 smooth[index(x, y)] = float(sum / 9.0);
866 }
867 auto noisy = smooth;
868 NoiseField noise{static_cast<unsigned int>(s.noiseSeed)};
869 const float workflowScale = s.terrainWorkflow ? 0.00042F / 0.0035F : 1.F;
870 for (int y = 1; y < height - 1; ++y)
871 for (int x = 1; x < width - 1; ++x)
872 if (mask[index(x, y)]) {
873 const float dx = std::abs(smooth[index(x + 1, y)] - smooth[index(x - 1, y)]);
874 const float dy = std::abs(smooth[index(x, y + 1)] - smooth[index(x, y - 1)]);
875 const float gradient = std::sqrt(dx * dx + dy * dy);
876 const float strength = s.perlinStrength * workflowScale * (1.F - std::clamp(gradient * 10.F, 0.F, 1.F));
877 const double value =
878 double(smooth[index(x, y)]) + noise.perlinNoise(x * s.perlinScale, y * s.perlinScale) * strength;
880 return invalid("terrain.terraceRemoval.apply: noise result exceeds float range");
881 noisy[index(x, y)] = float(value);
882 }
883 auto directional = noisy;
884 constexpr int weights[3][3] = {{1, 2, 1}, {2, 4, 2}, {1, 2, 1}};
885 for (int y = 1; y < height - 1; ++y)
886 for (int x = 1; x < width - 1; ++x) {
887 double sum = 0;
888 for (int dy = -1; dy <= 1; ++dy)
889 for (int dx = -1; dx <= 1; ++dx) sum += noisy[index(x + dx, y + dy)] * weights[dy + 1][dx + 1];
890 directional[index(x, y)] = float(sum / 16.0);
891 }
892 std::array<double, 25> kernel{};
893 double kernelSum = 0;
894 for (int ky = -2; ky <= 2; ++ky)
895 for (int kx = -2; kx <= 2; ++kx) {
896 const double weight = std::exp(-(kx * kx + ky * ky) / 2.0);
897 kernel[size_t(ky + 2) * 5 + kx + 2] = weight;
898 kernelSum += weight;
899 }
900 auto output = directional;
901 for (int y = 2; y < height - 2; ++y)
902 for (int x = 2; x < width - 2; ++x) {
903 double sum = 0;
904 for (int ky = -2; ky <= 2; ++ky)
905 for (int kx = -2; kx <= 2; ++kx)
906 sum += directional[index(x + kx, y + ky)] * kernel[size_t(ky + 2) * 5 + kx + 2];
907 const double value = sum / kernelSum;
909 return invalid("terrain.terraceRemoval.apply: filtered result exceeds float range");
910 output[index(x, y)] = float(value);
911 }
912 return publish(target, std::move(output));
913}
914} // namespace eve::procgen
double z
double y
double x
LogicalId target
Duration start
float w
Definition AnimClip.cpp:738
std::string output
const std::string & s
int mask
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
SQObjectPtr key
Definition ECS.cpp:155
int rows
int cols
float strength
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
float v
std::int32_t c
std::int32_t first
float elevation
int biome
std::uint32_t height
std::uint32_t width
JointPoint2D axis
std::array< float, 3 > scale
std::vector< Edge > edges
bool valid
double maxError
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
glm::dvec3 dx
glm::dvec3 dz
std::shared_ptr< const OceanSprayFrame > previous
std::weak_ptr< Run > run
Definition OnnxGpgpu.cpp:25
std::string error
Definition Package.cpp:174
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::shared_ptr< const std::vector< glm::vec2 > > points
std::set< std::string > values
Object::Ptr value
float d
float t
std::vector< EquipmentStat > stats
int lod
RoadLaneDirection direction
ScriptStructure out
std::string_view source
size_t begin
double current
float dy
Definition Shadow.cpp:151
int count
Cell cell
Heightmap curve
float weights[3]
float step
Definition TreeMesh.cpp:451
float size
Definition TreeMesh.cpp:158
const char * category
std::uint32_t depth
std::size_t at
double weight
uint32_t index
double oy
double ox
glm::vec3 point
float heightScale
float frameY
float frameX
float bottom
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
In-memory terrain heightmap: a dense float grid (row-major, index = y * width + x) materialized from ...
Definition Heightmap.h:21
int getHeight() const
Returns the height.
Definition Heightmap.cpp:17
const std::vector< float > & data() const
Data.
Definition Heightmap.h:48
float height(int x, int y) const
Height.
Definition Heightmap.cpp:28
int getWidth() const
Returns the width.
Definition Heightmap.cpp:16
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Definition MeshBuild.h:20
Versioned, random-access terrain archive.
const TerrainChunkEntry * findChunk(int chunkX, int chunkY) const noexcept
Find one chunk directory entry without scanning the full directory.
bool loadChunk(int chunkX, int chunkY, TerrainChunkData &out, std::string *error=nullptr) const
Compatibility operation that loads and verifies one chunk.
int getChunkSize() const
Returns the chunk size.
int getHeight() const
Returns the height.
int getWidth() const
Returns the width.
static bool build(const Heightmap &heightmap, const TerrainLayers &layers, const TerrainLakeMeshSettings &settings, MeshBuild &out, std::string *error=nullptr)
Compatibility operation that builds lake surface geometry.
Script-friendly ownership wrapper for baked hydrology and climate layers.
int getStreamOrder(int x, int y) const
Return Strahler river order, or zero outside the river network.
int getBiome(int x, int y) const
Returns the biome.
int getWidth() const
Returns the width.
int getHeight() const
Returns the height.
bool isRiver(int x, int y) const
True when river.
int getFlowDirection(int x, int y) const
Return the D8 receiver direction for one cell, or -1 at an outlet/out of bounds.
float getFlowAccumulation(int x, int y) const
Returns the flow accumulation.
float getFlowVectorY(int x, int y) const
Return the continuous normalized downslope Y component.
float getLakeDepth(int x, int y) const
Return filled-depression water depth, or zero outside a lake.
float getFlowVectorX(int x, int y) const
Return the continuous normalized downslope X component.
static int select(const Heightmap &heightmap, TerrainMeshSettings settings, int maxLod, float distance, float viewportHeight, float verticalFovDegrees, float targetPixelError)
Select the coarsest LOD whose projected geometric error is within budget.
static bool build(const Heightmap &heightmap, const TerrainLayers *layers, const TerrainMeshSettings &settings, TerrainMeshChunk &out, std::string *error=nullptr)
Compatibility operation that builds a terrain mesh chunk.
static float estimateGeometricError(const Heightmap &heightmap, const TerrainMeshSettings &settings)
Maximum world-space deviation between a LOD grid and the source heightfield.
One renderable heightfield chunk plus four ecological material weights.
Definition TerrainMesh.h:27
int getBiome(int vertex) const
Return the biome id stored for one mesh vertex, or -1 when out of range.
float getMaterialWeight(int vertex, int channel) const
Returns the material weight.
int getVertexCount() const
Returns the vertex count.
Definition TerrainMesh.h:34
static bool build(const Heightmap &heightmap, const TerrainLayers &layers, const TerrainRiverMeshSettings &settings, MeshBuild &out, std::string *error=nullptr)
Compatibility operation that builds river surface geometry.
const TerrainChunkData * getChunk(int chunkX, int chunkY) const
Borrow a resident chunk. @lifetime Pointer remains valid until cache mutation.
bool getReceiver(int worldX, int worldY, int &receiverX, int &receiverY) const
Resolve a cell's D8 receiver in global coordinates, including an adjacent chunk.
int getResidentCount() const
Returns the resident count.
bool buildWindow(int originX, int originY, int width, int height, TerrainStreamingWindow &out) const
Compatibility operation that assembles a dense hydrology window.
bool open(const uint8_t *data, size_t size, std::string *error=nullptr)
Compatibility operation that opens EVTR and clears decoded chunks.
bool traceFlow(int worldX, int worldY, int maxSteps, std::vector< std::pair< int, int > > &out) const
Compatibility operation that follows D8 receivers across chunks.
bool sampleHeight(float worldX, float worldY, float &out) const
Compatibility operation for cross-chunk bilinear height sampling.
Result< void > openSource(std::shared_ptr< const ITerrainArchiveSource > source)
Open EVTR through a retained random-access source without loading chunk payloads.
TerrainStreamStats streamAround(int worldX, int worldY, int radiusChunks, int maxLoads=0, std::string *error=nullptr)
Stream chunks around a world-space sample coordinate.
bool sampleCell(int worldX, int worldY, TerrainSample &out) const
Compatibility operation that reads a resident integer world cell.
SQInteger top
Definition Snapshot.cpp:115
float smoothstep(float edge0, float edge1, float value)
double sample(const Heightmap &map, double u, double v)
Sample.
Result< int > publish(Heightmap &target, std::vector< float > candidate)
Publish.
bool validRaster(const Heightmap &map)
Valid raster.
Result< int > invalid(std::string message)
Invalid.
bool isRepresentable(double value)
True when representable.
Result< int > analyzeTerrainTerraces(Heightmap &target, const Heightmap &source, const TerrainTerraceRemovalSettings &s)
Classify a heightmap into Pcg's black/red/green/blue important-detail categories.
Biome
Biome public API.
Result< int > removeTerrainTerraces(Heightmap &target, const Heightmap &source, const Heightmap &classes, const TerrainTerraceRemovalSettings &s)
Apply Pcg's adaptive smoothing, gradient noise, 3x3 filter, and fixed 5x5 Gaussian blur.
Deterministic 2D noise helpers for pixel textures and masks.
Definition NoiseField.h:24
Decoded terrain chunk containing all baked runtime layers.
std::vector< float > flowAccumulation
std::vector< float > moisture
std::vector< float > lakeDepth
std::vector< float > flowVectorX
std::vector< uint8_t > rivers
std::vector< Biome > biomes
std::vector< uint8_t > streamOrder
std::vector< int8_t > flowDirection
std::vector< float > flowVectorY
std::vector< float > temperature
TerrainLakeMeshSettings public API.
TerrainMeshSettings public API.
Definition TerrainMesh.h:12
TerrainRiverMeshSettings public API.
Definition TerrainMesh.h:91
TerrainSample public API.
TerrainStreamStats public API.
A rectangular, globally addressed terrain window assembled from resident chunks.
Portable controls for Pcg HeightmapTerraceRemover's analysis and processing pipeline.