载入中...
搜索中...
未找到
GtsTerrainLodRuntime.cpp
浏览该文件的文档.
2
3#include "common/ECS.h"
6#include "procgen/Procgen.h"
7
8#include <vector>
9
10namespace eve::procgen {
12 std::vector<ecs::EntityHandle> tiles;
13 ecs::EntityHandle sourceTerrain{};
14 bool sourceWasVisible = false;
15 bool hasSource = false;
16 std::uint64_t revision = 0;
17};
18namespace {
19graphics::Renderable3D* resolve(const ecs::EntityHandle& handle) {
20 return dynamic_cast<graphics::Renderable3D*>(ecs::try_get(handle));
21}
22void destroy(std::vector<ecs::EntityHandle>& handles) {
23 for (auto& h : handles)
24 if (auto* entity = resolve(h)) ecs::DestroyEntity(entity);
25 handles.clear();
26}
27void restoreSource(ecs::EntityHandle& handle, bool wasVisible, bool& hasSource) {
28 if (hasSource)
29 if (auto* source = resolve(handle)) source->setVisible(wasVisible);
30 handle = {};
31 hasSource = false;
32}
33} // namespace
36 destroy(impl_->tiles);
37 restoreSource(impl_->sourceTerrain, impl_->sourceWasVisible, impl_->hasSource);
38}
40 graphics::Graphics& gfx, float diameter, float fov, float ox,
41 float oy, float oz) {
42 std::vector<ecs::EntityHandle> candidate(size_t(lods.getTileCount()));
43 for (int i = 0; i < lods.getTileCount(); ++i) {
44 auto* tile = lods.tileAt(i);
45 if (!tile || tile->levels.empty() || tile->levels.front().empty()) continue;
46 auto* entity = graphics::Renderable3D::create();
47 if (!entity) {
48 destroy(candidate);
50 "failed to create GTS terrain tile renderable",
51 "procgen.gtsTerrainLodRuntime"));
52 }
53 entity->setVisible(false);
54 candidate[size_t(i)] = ecs::handle_of(entity);
55 auto configured = procgen.configureGtsTerrainTileLods(lods, i, *entity, gfx, diameter, fov, ox, oy, oz);
56 if (!configured) {
57 destroy(candidate);
58 return Result<std::uint64_t>::failure(*configured.error());
59 }
60 }
61 for (auto& h : impl_->tiles)
62 if (auto* entity = resolve(h)) entity->setVisible(false);
63 for (auto& h : candidate)
64 if (auto* entity = resolve(h)) entity->setVisible(true);
65 destroy(impl_->tiles);
66 impl_->tiles = std::move(candidate);
67 ++impl_->revision;
68 if (impl_->revision == 0) ++impl_->revision;
69 return Result<std::uint64_t>::success(impl_->revision);
70}
73 graphics::Renderable3D& source, float diameter,
74 float fov, float ox, float oy, float oz) {
75 for (const auto& handle : impl_->tiles)
76 if (resolve(handle) == &source)
79 "GTS source terrain cannot be one of the managed LOD tiles", "sourceTerrain"));
80 const auto sourceHandle = ecs::handle_of(&source);
81 const bool sameSource = impl_->hasSource && resolve(impl_->sourceTerrain) == &source;
82 const bool enteringVisibility = sameSource ? impl_->sourceWasVisible : source.getVisible();
83 auto replaced = replace(lods, procgen, gfx, diameter, fov, ox, oy, oz);
84 if (!replaced) return replaced;
85 if (!sameSource) restoreSource(impl_->sourceTerrain, impl_->sourceWasVisible, impl_->hasSource);
86 impl_->sourceTerrain = sourceHandle;
87 impl_->sourceWasVisible = enteringVisibility;
88 impl_->hasSource = true;
89 source.setVisible(false);
90 return replaced;
91}
93 return impl_->hasSource ? resolve(impl_->sourceTerrain) : nullptr;
94}
96 int count = 0;
97 for (auto& h : impl_->tiles)
98 if (resolve(h)) ++count;
99 destroy(impl_->tiles);
100 restoreSource(impl_->sourceTerrain, impl_->sourceWasVisible, impl_->hasSource);
101 ++impl_->revision;
102 if (impl_->revision == 0) ++impl_->revision;
104}
106 int count = 0;
107 for (auto& h : impl_->tiles)
108 if (auto* entity = resolve(h)) {
109 entity->setMaterial(&material);
110 ++count;
111 }
113}
114int GtsTerrainLodRuntime::getTileCount() const { return int(impl_->tiles.size()); }
115std::uint64_t GtsTerrainLodRuntime::getRevision() const { return impl_->revision; }
117 return index >= 0 && index < int(impl_->tiles.size()) ? resolve(impl_->tiles[size_t(index)]) : nullptr;
118}
119} // namespace eve::procgen
120
123
124#include <algorithm>
125#include <cmath>
126#include <limits>
127#include <string_view>
128
129namespace eve::procgen {
130namespace {} // namespace
131
133 float sizeX, float sizeY, float sizeZ) {
134 const int exponent = static_cast<int>(resolution);
135 const int sourceWidth = heightmap.getWidth(), sourceHeight = heightmap.getHeight();
136 if (exponent < 0 || exponent > 4 || sourceWidth < 2 || sourceHeight < 2 || !std::isfinite(sizeX) || sizeX <= 0.f ||
137 !std::isfinite(sizeY) || sizeY <= 0.f || !std::isfinite(sizeZ) || sizeZ <= 0.f)
139 "GTS terrain heightmap or export dimensions are invalid",
140 "procgen.gtsTerrainLod"));
141 const int step = 1 << exponent;
142 if ((sourceWidth - 1) % step != 0 || (sourceHeight - 1) % step != 0)
145 "GTS terrain heightmap intervals must be divisible by the save-resolution stride",
146 "procgen.gtsTerrainLod"));
147 const int columns = (sourceWidth - 1) / step + 1, rows = (sourceHeight - 1) / step + 1;
148 const std::uint64_t vertexCount = std::uint64_t(columns) * std::uint64_t(rows);
149 const std::uint64_t indexCount = std::uint64_t(columns - 1) * std::uint64_t(rows - 1) * 6u;
150 if (vertexCount > 8u * 1024u * 1024u || indexCount > 48u * 1024u * 1024u ||
151 vertexCount > std::uint64_t(std::numeric_limits<int>::max()) ||
152 indexCount > std::uint64_t(std::numeric_limits<int>::max()))
154 "GTS terrain base mesh exceeds the native export budget",
155 "procgen.gtsTerrainLod"));
156 for (float value : heightmap.data())
157 if (!std::isfinite(value))
159 "GTS terrain heightmap contains a non-finite sample",
160 "procgen.gtsTerrainLod"));
161 MeshBuild candidate;
162 candidate.reserve(static_cast<int>(vertexCount), static_cast<int>(indexCount));
163 candidate.setActiveGroup("terrain");
164 for (int z = 0; z < rows; ++z)
165 for (int x = 0; x < columns; ++x) {
166 const int gx = x * step, gz = z * step;
167 candidate.addVertex(sizeX * float(gx) / float(sourceWidth - 1), heightmap.height(gx, gz) * sizeY,
168 sizeZ * float(gz) / float(sourceHeight - 1), 0.f, 0.f, 0.f,
169 float(gx) / float(sourceWidth - 1), float(gz) / float(sourceHeight - 1));
170 }
171 for (int z = 0; z + 1 < rows; ++z)
172 for (int x = 0; x + 1 < columns; ++x) {
173 const std::uint32_t a = std::uint32_t(z * columns + x), b = a + 1, c = a + std::uint32_t(columns),
174 d = c + 1;
175 candidate.addTriangle(a, c, b);
176 candidate.addTriangle(b, c, d);
177 }
178 auto& normals = candidate.normals();
179 const auto& positions = candidate.positions();
180 const auto& indices = candidate.indices();
181 for (size_t i = 0; i < indices.size(); i += 3) {
182 const auto a = indices[i], b = indices[i + 1], c = indices[i + 2];
183 const float abx = positions[b * 3] - positions[a * 3], aby = positions[b * 3 + 1] - positions[a * 3 + 1],
184 abz = positions[b * 3 + 2] - positions[a * 3 + 2];
185 const float acx = positions[c * 3] - positions[a * 3], acy = positions[c * 3 + 1] - positions[a * 3 + 1],
186 acz = positions[c * 3 + 2] - positions[a * 3 + 2];
187 const float nx = aby * acz - abz * acy, ny = abz * acx - abx * acz, nz = abx * acy - aby * acx;
188 for (auto vertex : {a, b, c}) {
189 normals[vertex * 3] += nx;
190 normals[vertex * 3 + 1] += ny;
191 normals[vertex * 3 + 2] += nz;
192 }
193 }
194 for (size_t i = 0; i < normals.size(); i += 3) {
195 const float length =
196 std::sqrt(normals[i] * normals[i] + normals[i + 1] * normals[i + 1] + normals[i + 2] * normals[i + 2]);
197 if (!(length > 0.f) || !std::isfinite(length))
199 "GTS terrain base mesh contains a degenerate vertex normal",
200 "procgen.gtsTerrainLod"));
201 normals[i] /= length;
202 normals[i + 1] /= length;
203 normals[i + 2] /= length;
204 }
205 candidate.setMeta("kind", "gts.terrain.base");
206 candidate.setMeta("saveResolution", std::to_string(exponent));
207 candidate.setMeta("sourceWidth", std::to_string(sourceWidth));
208 candidate.setMeta("sourceHeight", std::to_string(sourceHeight));
209 output = std::move(candidate);
210 return Result<void>::success();
211}
212
214 return index >= 0 && index < static_cast<int>(tiles_.size()) ? &tiles_[index] : nullptr;
215}
216
218 return index >= 0 && index < static_cast<int>(settings_.size()) ? &settings_[index] : nullptr;
219}
220
222 if (value < 0 || value > 4)
224 "GTS save resolution must be in the range 0 through 4",
225 "procgen.gtsTerrainLod"));
226 saveResolution_ = value;
227 return Result<void>::success();
228}
230 if (value < 1 || value > 4)
232 "GTS LOD count must be in the range 1 through 4",
233 "procgen.gtsTerrainLod"));
234 lodCount_ = value;
235 return Result<void>::success();
236}
238 if (value < 0 || value > 5)
240 "GTS sub-tile split count must be in the range 0 through 5",
241 "procgen.gtsTerrainLod"));
242 subTiles_ = value;
243 return Result<void>::success();
244}
246 return index >= 0 && index < 4 ? lodQuality_[index] : -1.f;
247}
249 if (index < 0 || index >= 4 || !std::isfinite(percent) || percent < 0.f || percent > 100.f)
252 "GTS LOD quality requires a slot from 0 through 3 and percentage from 0 through 100",
253 "procgen.gtsTerrainLod"));
254 lodQuality_[index] = percent;
255 return Result<void>::success();
256}
258 if (index < 0 || index >= lodCount_) return -1.f;
259 constexpr float transitions[]{.95f, .7f, .6f, .02f};
260 return index == lodCount_ - 1 ? .02f : transitions[index];
261}
263 std::vector<GtsTerrainLodLevelSettings> levels;
264 levels.reserve(size_t(lodCount_));
265 for (int i = 0; i < lodCount_; ++i) {
267 level.quality = lodQuality_[i] / 100.f;
268 level.screenRelativeTransitionHeight = getLodTransitionHeight(i);
269 levels.push_back(level);
270 }
271 return Result<std::vector<GtsTerrainLodLevelSettings>>::success(std::move(levels));
272}
273
274int GtsTerrainLodSet::selectLevel(float relativeHeight) const {
275 if (!std::isfinite(relativeHeight) || relativeHeight < 0.0f || settings_.empty()) return -2;
276 for (int i = 0; i < static_cast<int>(settings_.size()); ++i)
277 if (relativeHeight >= settings_[i].screenRelativeTransitionHeight) return i;
278 return -1;
279}
280
281float GtsTerrainLodSet::getLevelSwitchDistance(int level, float worldDiameter, float verticalFovDegrees) const {
282 if (level < 0 || level >= static_cast<int>(settings_.size()) || !std::isfinite(worldDiameter) ||
283 worldDiameter <= 0.0f || !std::isfinite(verticalFovDegrees) || verticalFovDegrees <= 0.0f ||
284 verticalFovDegrees >= 180.0f)
285 return -1.0f;
286 constexpr float radiansPerDegree = 0.01745329251994329577f;
287 const float tangent = std::tan(verticalFovDegrees * 0.5f * radiansPerDegree);
288 return worldDiameter / (2.0f * tangent * settings_[level].screenRelativeTransitionHeight);
289}
290
291int GtsTerrainLodSet::selectLevelForCamera(float distance, float worldDiameter, float verticalFovDegrees) const {
292 if (!std::isfinite(distance) || distance <= 0.0f || !std::isfinite(worldDiameter) || worldDiameter <= 0.0f ||
293 !std::isfinite(verticalFovDegrees) || verticalFovDegrees <= 0.0f || verticalFovDegrees >= 180.0f)
294 return -2;
295 constexpr float radiansPerDegree = 0.01745329251994329577f;
296 const float relativeHeight =
297 worldDiameter / (2.0f * distance * std::tan(verticalFovDegrees * 0.5f * radiansPerDegree));
298 return selectLevel(relativeHeight);
299}
300
301std::vector<GtsTerrainLodLevelSettings> defaultGtsTerrainLodLevels() {
302 std::vector<GtsTerrainLodLevelSettings> levels(4);
303 levels[0].quality = 1.0f;
304 levels[1].quality = 0.5f;
305 levels[2].quality = 0.25f;
306 levels[3].quality = 0.125f;
307 levels[0].screenRelativeTransitionHeight = 0.95f;
308 levels[1].screenRelativeTransitionHeight = 0.7f;
309 levels[2].screenRelativeTransitionHeight = 0.6f;
310 levels[3].screenRelativeTransitionHeight = 0.02f;
311 return levels;
312}
313
315 const std::string& terrainName,
316 const std::string& meshFolder) {
317 auto safe = [](const std::string& v, bool folder) {
318 if (v.empty() || v == "." || v == ".." || v.find("..") != std::string::npos) return false;
319 constexpr std::string_view invalid = "\\:*?\"<>|";
320 if (v.find_first_of(invalid) != std::string::npos) return false;
321 return folder || v.find('/') == std::string::npos;
322 };
323 if (!safe(terrainName, false) || !safe(meshFolder, true) || meshFolder.front() == '/' || meshFolder.back() == '/')
324 return Result<std::vector<GtsTerrainLodAssetEntry>>::failure(Diagnostic::error(
325 DiagnosticCode::InvalidArgument, "terrain name or mesh folder is not a safe relative export name",
326 "procgen.gtsTerrainLod"));
327 std::vector<GtsTerrainLodAssetEntry> entries;
328 for (int tileIndex = 0; tileIndex < lods.getTileCount(); ++tileIndex) {
329 auto* tile = lods.tileAt(tileIndex);
330 if (!tile) continue;
331 for (int level = 0; level < static_cast<int>(tile->levels.size()); ++level) {
332 if (tile->levels[size_t(level)].empty()) continue;
334 e.tileIndex = tileIndex;
335 e.levelIndex = level;
336 e.objectName = terrainName + " SubTile" + std::to_string(tileIndex) + "_LOD_" + std::to_string(level);
337 e.meshName = terrainName + "_SubTile_" + std::to_string(tileIndex) + std::to_string(level);
338 e.relativePath = meshFolder + "/" + e.meshName + ".eve.mesh.json";
339 entries.push_back(std::move(e));
340 }
341 }
342 return Result<std::vector<GtsTerrainLodAssetEntry>>::success(std::move(entries));
343}
344int GtsTerrainLodAssetPlan::getEntryCount() const { return static_cast<int>(entries_.size()); }
346 return i >= 0 && i < int(entries_.size()) ? entries_[size_t(i)].tileIndex : -1;
347}
349 return i >= 0 && i < int(entries_.size()) ? entries_[size_t(i)].levelIndex : -1;
350}
352 return i >= 0 && i < int(entries_.size()) ? entries_[size_t(i)].objectName : std::string{};
353}
354std::string GtsTerrainLodAssetPlan::getMeshName(int i) const {
355 return i >= 0 && i < int(entries_.size()) ? entries_[size_t(i)].meshName : std::string{};
356}
358 return i >= 0 && i < int(entries_.size()) ? entries_[size_t(i)].relativePath : std::string{};
359}
361 const std::string& name, const std::string& folder) {
362 auto plan = planGtsTerrainLodAssets(lods, name, folder);
363 if (!plan) return Result<void>::failure(*plan.error());
364 GtsTerrainLodAssetPlan candidate;
365 candidate.entries_ = std::move(plan).takeValue();
366 output = std::move(candidate);
367 return Result<void>::success();
368}
369
371 const std::vector<GtsTerrainLodLevelSettings>& levels) {
372 if (levels.empty())
374 DiagnosticCode::InvalidArgument, "at least one terrain LOD level is required", "procgen.gtsTerrainLod"));
375 float previousTransition = 1.0f;
376 for (const auto& level : levels) {
377 if (!std::isfinite(level.quality) || level.quality < 0.0f || level.quality > 1.0f ||
378 !std::isfinite(level.screenRelativeTransitionHeight) || level.screenRelativeTransitionHeight < 0.0f ||
379 level.screenRelativeTransitionHeight > 1.0f || level.screenRelativeTransitionHeight >= previousTransition) {
381 "LOD quality or transition sequence is invalid",
382 "procgen.gtsTerrainLod"));
383 }
384 previousTransition = level.screenRelativeTransitionHeight;
385 }
386
387 auto split = splitGtsMesh(source, xSplits, zSplits, pivot);
388 if (!split) return Result<GtsTerrainLodSet>::failure(*split.error());
389
391 result.columns_ = split.value().getColumnCount();
392 result.rows_ = split.value().getRowCount();
393 result.settings_ = levels;
394 result.tiles_.reserve(split.value().getTileCount());
395 for (int tileIndex = 0; tileIndex < split.value().getTileCount(); ++tileIndex) {
396 const auto* sourceTile = split.value().tileAt(tileIndex);
398 tile.offsetX = sourceTile->offsetX;
399 tile.offsetZ = sourceTile->offsetZ;
400 tile.levels.reserve(levels.size());
401 MeshBuild previous = sourceTile->mesh;
402 for (const auto& level : levels) {
403 if (previous.empty()) {
404 tile.levels.emplace_back();
405 continue;
406 }
407 MeshBuild simplified;
408 auto simplification = simplifyGtsMesh(simplified, previous, level.quality, level.simplification);
409 if (!simplification) return Result<GtsTerrainLodSet>::failure(*simplification.error());
410 tile.levels.push_back(simplified);
411 previous = std::move(simplified);
412 }
413 result.tiles_.push_back(std::move(tile));
414 }
415 return Result<GtsTerrainLodSet>::success(std::move(result));
416}
417
419 GtsTerrainSaveResolution resolution, float sizeX, float sizeY,
420 float sizeZ, int subTileSplits, GtsMeshPivot pivot,
421 const std::vector<GtsTerrainLodLevelSettings>& levels) {
422 if (subTileSplits < 0 || subTileSplits > 5)
424 DiagnosticCode::InvalidArgument, "GTS sub-tile split count must be in the profile range 0 through 5",
425 "procgen.gtsTerrainLod"));
426 MeshBuild base;
427 auto built = buildGtsTerrainBaseMesh(base, heightmap, resolution, sizeX, sizeY, sizeZ);
428 if (!built) return Result<GtsTerrainLodSet>::failure(*built.error());
429 return buildGtsTerrainLods(base, subTileSplits, subTileSplits, pivot, levels);
430}
431
433 GtsTerrainSaveResolution resolution, float sizeX, float sizeY,
434 float sizeZ, int subTileSplits, GtsMeshPivot pivot) {
435 auto built = buildGtsTerrainLodsFromHeightmap(heightmap, resolution, sizeX, sizeY, sizeZ, subTileSplits, pivot,
437 if (!built) return Result<void>::failure(*built.error());
438 output = std::move(built).takeValue();
439 return Result<void>::success();
440}
441
443 const GtsTerrainMeshSettings& settings, float sizeX, float sizeY,
444 float sizeZ, GtsMeshPivot pivot) {
445 auto levels = settings.compileLevels();
446 if (!levels) return Result<void>::failure(*levels.error());
447 auto built =
448 buildGtsTerrainLodsFromHeightmap(heightmap, static_cast<GtsTerrainSaveResolution>(settings.getSaveResolution()),
449 sizeX, sizeY, sizeZ, settings.getSubTiles(), pivot, levels.value());
450 if (!built) return Result<void>::failure(*built.error());
451 output = std::move(built).takeValue();
452 return Result<void>::success();
453}
454
455} // namespace eve::procgen
456
458
459#include "common/Value.h"
460
461#include <cmath>
462#include <cstdint>
463#include <limits>
464#include <set>
465
466namespace eve::procgen {
467namespace {
468constexpr std::size_t kMaxJsonBytes = 256U * 1024U * 1024U, kMaxTiles = 65536, kMaxLevels = 32,
469 kMaxVertices = 8U * 1024U * 1024U;
470bool exact(const Value::Object& o, std::initializer_list<const char*> names) {
471 if (o.size() != names.size()) return false;
472 for (auto* n : names)
473 if (!o.contains(n)) return false;
474 return true;
475}
476const double* num(const Value& v) { return v.getIf<double>(); }
477Value options(const GtsMeshSimplificationOptions& o) {
478 return Value::Object{{"aggressiveness", o.aggressiveness},
479 {"enableSmartLink", o.enableSmartLink},
480 {"maxIterationCount", o.maxIterationCount},
481 {"preserveBorderEdges", o.preserveBorderEdges},
482 {"preserveSurfaceCurvature", o.preserveSurfaceCurvature},
483 {"preserveUvFoldoverEdges", o.preserveUvFoldoverEdges},
484 {"preserveUvSeamEdges", o.preserveUvSeamEdges},
485 {"vertexLinkDistance", o.vertexLinkDistance}};
486}
487bool decodeOptions(const Value& v, GtsMeshSimplificationOptions& o) {
488 auto* p = v.getIf<Value::Object>();
489 if (!p || !exact(*p, {"aggressiveness", "enableSmartLink", "maxIterationCount", "preserveBorderEdges",
490 "preserveSurfaceCurvature", "preserveUvFoldoverEdges", "preserveUvSeamEdges",
491 "vertexLinkDistance"}))
492 return false;
493 auto ag = num(p->at("aggressiveness")), link = num(p->at("vertexLinkDistance"));
494 auto count = p->at("maxIterationCount").getIf<int64_t>();
495 auto smart = p->at("enableSmartLink").getIf<bool>(), border = p->at("preserveBorderEdges").getIf<bool>(),
496 curve = p->at("preserveSurfaceCurvature").getIf<bool>(), fold = p->at("preserveUvFoldoverEdges").getIf<bool>(),
497 seam = p->at("preserveUvSeamEdges").getIf<bool>();
498 if (!ag || !link || !count || !smart || !border || !curve || !fold || !seam || !std::isfinite(*ag) || *ag <= 0 ||
499 !std::isfinite(*link) || *link < 0 || *count <= 0 || *count > 100000)
500 return false;
501 o.aggressiveness = *ag;
502 o.vertexLinkDistance = *link;
503 o.maxIterationCount = int(*count);
504 o.enableSmartLink = *smart;
505 o.preserveBorderEdges = *border;
506 o.preserveSurfaceCurvature = *curve;
507 o.preserveUvFoldoverEdges = *fold;
508 o.preserveUvSeamEdges = *seam;
509 return true;
510}
511Value encodeMesh(const MeshBuild& m) {
512 Value::Array p, n, u, c, i, g;
513 p.reserve(m.positions().size());
514 n.reserve(m.normals().size());
515 u.reserve(m.uvs().size());
516 c.reserve(m.colors().size());
517 i.reserve(m.indices().size());
518 g.reserve(m.getIndexCount() / 3);
519 for (float x : m.positions()) p.emplace_back(x);
520 for (float x : m.normals()) n.emplace_back(x);
521 for (float x : m.uvs()) u.emplace_back(x);
522 for (float x : m.colors()) c.emplace_back(x);
523 for (auto x : m.indices()) i.emplace_back(int64_t(x));
524 for (int t = 0; t < m.getIndexCount() / 3; ++t) {
525 int group = m.getTriangleGroup(t);
526 g.emplace_back(group >= 0 ? m.getGroupName(group) : std::string{});
527 }
528 return Value::Object{{"colors", std::move(c)}, {"groups", std::move(g)}, {"indices", std::move(i)},
529 {"normals", std::move(n)}, {"positions", std::move(p)}, {"uvs", std::move(u)}};
530}
531bool decodeFloatArray(const Value& v, std::vector<float>& out, std::size_t max) {
532 auto* a = v.getIf<Value::Array>();
533 if (!a || a->size() > max) return false;
534 out.reserve(a->size());
535 for (auto& x : *a) {
536 auto* d = num(x);
537 if (!d || !std::isfinite(*d) || *d < -std::numeric_limits<float>::max() ||
538 *d > std::numeric_limits<float>::max())
539 return false;
540 out.push_back(float(*d));
541 }
542 return true;
543}
544bool decodeMesh(const Value& v, MeshBuild& out, bool legacy) {
545 auto* o = v.getIf<Value::Object>();
546 if (!o || !(legacy ? exact(*o, {"groups", "indices", "normals", "positions", "uvs"})
547 : exact(*o, {"colors", "groups", "indices", "normals", "positions", "uvs"})))
548 return false;
549 std::vector<float> p, n, u, c;
550 if (!decodeFloatArray(o->at("positions"), p, kMaxVertices * 3) ||
551 !decodeFloatArray(o->at("normals"), n, kMaxVertices * 3) ||
552 !decodeFloatArray(o->at("uvs"), u, kMaxVertices * 2) ||
553 (!legacy && !decodeFloatArray(o->at("colors"), c, kMaxVertices * 4)) || p.size() % 3 || u.size() % 2 ||
554 n.size() != p.size() || u.size() / 2 != p.size() / 3 || (!c.empty() && c.size() / 4 != p.size() / 3))
555 return false;
556 auto* indices = o->at("indices").getIf<Value::Array>();
557 auto* groups = o->at("groups").getIf<Value::Array>();
558 if (!indices || indices->size() % 3 || indices->size() > kMaxVertices * 6 || !groups ||
559 groups->size() != indices->size() / 3)
560 return false;
561 MeshBuild m;
562 for (size_t x = 0; x < p.size() / 3; ++x)
563 m.addVertex(p[x * 3], p[x * 3 + 1], p[x * 3 + 2], n[x * 3], n[x * 3 + 1], n[x * 3 + 2], u[x * 2], u[x * 2 + 1]);
564 if (!c.empty() && !m.setVertexColors(std::move(c)).ok()) return false;
565 for (size_t t = 0; t < groups->size(); ++t) {
566 auto* name = (*groups)[t].getIf<std::string>();
567 if (!name || name->size() > 1024) return false;
568 uint32_t ids[3];
569 for (int corner = 0; corner < 3; ++corner) {
570 auto* id = (*indices)[t * 3 + corner].getIf<int64_t>();
571 if (!id || *id < 0 || *id >= int64_t(p.size() / 3)) return false;
572 ids[corner] = uint32_t(*id);
573 }
574 if (ids[0] == ids[1] || ids[1] == ids[2] || ids[0] == ids[2]) return false;
575 m.setActiveGroup(*name);
576 m.addTriangle(ids[0], ids[1], ids[2]);
577 }
578 out = std::move(m);
579 return true;
580}
581} // namespace
582
584 Value::Array qualities;
585 for (float quality : lodQuality_) qualities.emplace_back(quality);
586 return Value(Value::Object{{"lodCount", lodCount_},
587 {"lodQuality", std::move(qualities)},
588 {"saveResolution", saveResolution_},
589 {"schema", "eve.procgen.gts-terrain-mesh-settings"},
590 {"subTiles", subTiles_},
591 {"version", 1}})
592 .toJson();
593}
594
596 if (json.size() > 64U * 1024U)
598 "GTS terrain mesh settings JSON exceeds size limit",
599 "procgen.gtsTerrainLod.codec"));
600 auto parsed = Value::fromJson(json);
601 if (!parsed) return Result<void>::failure(parsed.status());
602 auto* root = parsed.value().getIf<Value::Object>();
603 if (!root || !exact(*root, {"lodCount", "lodQuality", "saveResolution", "schema", "subTiles", "version"}))
605 "GTS terrain mesh settings fields are invalid",
606 "procgen.gtsTerrainLod.codec"));
607 auto* schema = root->at("schema").getIf<std::string>();
608 auto* version = root->at("version").getIf<int64_t>();
609 auto* resolution = root->at("saveResolution").getIf<int64_t>();
610 auto* count = root->at("lodCount").getIf<int64_t>();
611 auto* subTiles = root->at("subTiles").getIf<int64_t>();
612 auto* qualities = root->at("lodQuality").getIf<Value::Array>();
613 if (!schema || *schema != "eve.procgen.gts-terrain-mesh-settings" || !version || *version != 1 || !resolution ||
614 *resolution < 0 || *resolution > 4 || !count || *count < 1 || *count > 4 || !subTiles || *subTiles < 0 ||
615 *subTiles > 5 || !qualities || qualities->size() != 4)
617 "GTS terrain mesh settings schema or values are invalid",
618 "procgen.gtsTerrainLod.codec"));
619 GtsTerrainMeshSettings candidate;
620 auto a = candidate.setSaveResolution(int(*resolution));
621 if (!a) return a;
622 auto b = candidate.setLodCount(int(*count));
623 if (!b) return b;
624 auto c = candidate.setSubTiles(int(*subTiles));
625 if (!c) return c;
626 for (int i = 0; i < 4; ++i) {
627 auto* quality = num((*qualities)[size_t(i)]);
628 if (!quality)
630 "GTS terrain mesh LOD quality is invalid",
631 "procgen.gtsTerrainLod.codec"));
632 auto set = candidate.setLodQuality(i, float(*quality));
633 if (!set) return set;
634 }
635 *this = std::move(candidate);
636 return Result<void>::success();
637}
638
640 if (tiles_.size() > kMaxTiles || settings_.empty() || settings_.size() > kMaxLevels)
642 "GTS terrain LOD set exceeds codec limits",
643 "procgen.gtsTerrainLod.codec"));
645 for (auto& s : settings_)
646 settings.emplace_back(Value::Object{{"options", options(s.simplification)},
647 {"quality", s.quality},
648 {"transitionHeight", s.screenRelativeTransitionHeight}});
649 for (auto& t : tiles_) {
650 Value::Array levels;
651 for (auto& m : t.levels) levels.emplace_back(encodeMesh(m));
652 tiles.emplace_back(
653 Value::Object{{"levels", std::move(levels)}, {"offsetX", t.offsetX}, {"offsetZ", t.offsetZ}});
654 }
655 auto json = Value(Value::Object{{"columns", columns_},
656 {"rows", rows_},
657 {"schema", "eve.procgen.gts-terrain-lod"},
658 {"settings", std::move(settings)},
659 {"tiles", std::move(tiles)},
660 {"version", 2}})
661 .toJson();
662 if (!json) return json;
663 if (json.value().size() > kMaxJsonBytes)
665 DiagnosticCode::InvalidArgument, "GTS terrain LOD JSON exceeds size limit", "procgen.gtsTerrainLod.codec"));
666 return json;
667}
668
669Result<void> GtsTerrainLodSet::restoreJson(const std::string& json) {
670 if (json.size() > kMaxJsonBytes)
672 DiagnosticCode::InvalidArgument, "GTS terrain LOD JSON exceeds size limit", "procgen.gtsTerrainLod.codec"));
673 auto parsed = Value::fromJson(json);
674 if (!parsed) return Result<void>::failure(parsed.status());
675 auto* root = parsed.value().getIf<Value::Object>();
676 if (!root || !exact(*root, {"columns", "rows", "schema", "settings", "tiles", "version"}))
678 DiagnosticCode::InvalidArgument, "GTS terrain LOD root fields are invalid", "procgen.gtsTerrainLod.codec"));
679 auto* schema = root->at("schema").getIf<std::string>();
680 auto* version = root->at("version").getIf<int64_t>();
681 auto* columns = root->at("columns").getIf<int64_t>();
682 auto* rows = root->at("rows").getIf<int64_t>();
683 auto* settings = root->at("settings").getIf<Value::Array>();
684 auto* tiles = root->at("tiles").getIf<Value::Array>();
685 if (!schema || *schema != "eve.procgen.gts-terrain-lod" || !version || (*version != 1 && *version != 2) ||
686 !columns || !rows || *columns <= 0 || *rows <= 0 || *columns > 65536 || *rows > 65536 || !settings ||
687 settings->empty() || settings->size() > kMaxLevels || !tiles || tiles->size() > kMaxTiles ||
688 uint64_t(*columns) * uint64_t(*rows) != tiles->size())
690 "GTS terrain LOD schema, layout or counts are invalid",
691 "procgen.gtsTerrainLod.codec"));
692 GtsTerrainLodSet candidate;
693 candidate.columns_ = int(*columns);
694 candidate.rows_ = int(*rows);
695 float previous = 1;
696 for (auto& encoded : *settings) {
697 auto* o = encoded.getIf<Value::Object>();
698 if (!o || !exact(*o, {"options", "quality", "transitionHeight"}))
700 "GTS terrain LOD setting fields are invalid",
701 "procgen.gtsTerrainLod.codec"));
702 auto * q = num(o->at("quality")), *h = num(o->at("transitionHeight"));
704 if (!q || !h || !std::isfinite(*q) || *q < 0 || *q > 1 || !std::isfinite(*h) || *h < 0 || *h >= previous ||
705 !decodeOptions(o->at("options"), s.simplification))
707 "GTS terrain LOD setting values are invalid",
708 "procgen.gtsTerrainLod.codec"));
709 s.quality = float(*q);
710 s.screenRelativeTransitionHeight = float(*h);
711 previous = s.screenRelativeTransitionHeight;
712 candidate.settings_.push_back(s);
713 }
714 for (auto& encoded : *tiles) {
715 auto* o = encoded.getIf<Value::Object>();
716 if (!o || !exact(*o, {"levels", "offsetX", "offsetZ"}))
718 "GTS terrain LOD tile fields are invalid",
719 "procgen.gtsTerrainLod.codec"));
720 auto *x = num(o->at("offsetX")), *z = num(o->at("offsetZ"));
721 auto* levels = o->at("levels").getIf<Value::Array>();
722 if (!x || !z || !std::isfinite(*x) || !std::isfinite(*z) || !levels ||
723 levels->size() != candidate.settings_.size())
725 "GTS terrain LOD tile values are invalid",
726 "procgen.gtsTerrainLod.codec"));
728 tile.offsetX = float(*x);
729 tile.offsetZ = float(*z);
730 for (auto& m : *levels) {
731 MeshBuild decoded;
732 if (!decodeMesh(m, decoded, *version == 1))
734 DiagnosticCode::InvalidArgument, "GTS terrain LOD mesh is invalid", "procgen.gtsTerrainLod.codec"));
735 tile.levels.push_back(std::move(decoded));
736 }
737 candidate.tiles_.push_back(std::move(tile));
738 }
739 *this = std::move(candidate);
740 return Result<void>::success();
741}
742} // namespace eve::procgen
743
745
746#include "common/Value.h"
747#include "image/ImageData.h"
749
750#include <algorithm>
751#include <cmath>
752#include <iomanip>
753#include <limits>
754#include <locale>
755#include <sstream>
756#include <utility>
757
758namespace eve::procgen {
759namespace {
760bool enumRange(int value, int last) { return value >= 0 && value <= last; }
761bool textureResolutionValid(int value) {
762 for (int candidate = 32; candidate <= 8192; candidate *= 2)
763 if (value == candidate) return true;
764 return false;
765}
766Result<void> validateList(const std::vector<GtsTerrainExportLodSettings>& levels) {
767 if (levels.size() > 32)
769 "GTS terrain export supports at most 32 LOD records",
770 "procgen.gtsTerrainExportSettings"));
771 float previous = 1.0f;
772 for (const auto& level : levels) {
773 auto valid = level.validate();
774 if (!valid) return valid;
775 if (level.screenRelativeTransitionHeight >= previous)
777 "GTS terrain export transition heights must descend",
778 "procgen.gtsTerrainExportSettings"));
779 previous = level.screenRelativeTransitionHeight;
780 }
781 return Result<void>::success();
782}
783Value encodeOptions(const GtsMeshSimplificationOptions& value) {
784 return Value::Object{{"aggressiveness", value.aggressiveness},
785 {"enableSmartLink", value.enableSmartLink},
786 {"maxIterationCount", value.maxIterationCount},
787 {"preserveBorderEdges", value.preserveBorderEdges},
788 {"preserveSurfaceCurvature", value.preserveSurfaceCurvature},
789 {"preserveUvFoldoverEdges", value.preserveUvFoldoverEdges},
790 {"preserveUvSeamEdges", value.preserveUvSeamEdges},
791 {"vertexLinkDistance", value.vertexLinkDistance}};
792}
793Value encodeLod(const GtsTerrainExportLodSettings& value) {
794 return Value::Object{{"alphaChannel", int(value.alphaChannel)},
795 {"bakeLayerMask", int64_t(value.bakeLayerMask)},
796 {"bakeLighting", int(value.bakeLighting)},
797 {"bakeVertexColors", value.bakeVertexColors},
798 {"captureBaseMapTextures", value.captureBaseMapTextures},
799 {"createMaterials", value.createMaterials},
800 {"exportNormalMaps", value.exportNormalMaps},
801 {"exportSplatmaps", value.exportSplatmaps},
802 {"exportTextures", value.exportTextures},
803 {"materialShader", int(value.materialShader)},
804 {"mode", int(value.mode)},
805 {"namePrefix", value.namePrefix},
806 {"normalEdgeMode", int(value.normalEdgeMode)},
807 {"saveResolution", int(value.saveResolution)},
808 {"screenRelativeTransitionHeight", value.screenRelativeTransitionHeight},
809 {"simplification", encodeOptions(value.simplification)},
810 {"simplifyQuality", value.simplifyQuality},
811 {"textureExportMethod", int(value.textureExportMethod)},
812 {"textureExportResolution", value.textureExportResolution},
813 {"vertexColorSmoothing", value.vertexColorSmoothing}};
814}
815Value encodeWorkflow(const GtsTerrainExportWorkflow& value) {
816 return Value::Object{{"action", int(value.action)},
817 {"addMeshColliderToImpostor", value.addMeshColliderToImpostor},
818 {"addObjectColliders", value.addObjectColliders},
819 {"addTerrainCollider", value.addTerrainCollider},
820 {"addTreeColliders", value.addTreeColliders},
821 {"bakeCombinedCollisionMesh", value.bakeCombinedCollisionMesh},
822 {"colliderResolution", int(value.colliderResolution)},
823 {"colliderSimplifyQuality", value.colliderSimplifyQuality},
824 {"colliderType", int(value.colliderType)},
825 {"convertSourceTerrains", value.convertSourceTerrains},
826 {"convertTreesToObjects", value.convertTreesToObjects},
827 {"copyPcgObjects", value.copyPcgObjects},
828 {"copyPcgObjectsToImpostor", value.copyPcgObjectsToImpostor},
829 {"createColliderScenes", value.createColliderScenes},
830 {"createImpostorScenes", value.createImpostorScenes},
831 {"impostorRange", value.impostorRange},
832 {"invertExportMask", value.invertExportMask},
833 {"objFaceMode", int(value.objFaceMode)},
834 {"selection", int(value.selection)},
835 {"sourceTreatment", int(value.sourceTreatment)}};
836}
837bool exportSettingsExact(const Value::Object& object, std::initializer_list<const char*> names) {
838 if (object.size() != names.size()) return false;
839 for (auto* name : names)
840 if (!object.contains(name)) return false;
841 return true;
842}
843const double* number(const Value& value) { return value.getIf<double>(); }
844bool exportSettingsDecodeOptions(const Value& encoded, GtsMeshSimplificationOptions& output) {
845 auto* object = encoded.getIf<Value::Object>();
846 if (!object ||
847 !exportSettingsExact(*object, {"aggressiveness", "enableSmartLink", "maxIterationCount", "preserveBorderEdges",
848 "preserveSurfaceCurvature", "preserveUvFoldoverEdges", "preserveUvSeamEdges",
849 "vertexLinkDistance"}))
850 return false;
851 auto* aggressiveness = number(object->at("aggressiveness"));
852 auto* distance = number(object->at("vertexLinkDistance"));
853 auto* iterations = object->at("maxIterationCount").getIf<int64_t>();
854 auto* smart = object->at("enableSmartLink").getIf<bool>();
855 auto* border = object->at("preserveBorderEdges").getIf<bool>();
856 auto* curvature = object->at("preserveSurfaceCurvature").getIf<bool>();
857 auto* foldover = object->at("preserveUvFoldoverEdges").getIf<bool>();
858 auto* seam = object->at("preserveUvSeamEdges").getIf<bool>();
859 if (!aggressiveness || !distance || !iterations || !smart || !border || !curvature || !foldover || !seam)
860 return false;
861 output.aggressiveness = *aggressiveness;
862 output.vertexLinkDistance = *distance;
863 output.maxIterationCount = int(*iterations);
864 output.enableSmartLink = *smart;
865 output.preserveBorderEdges = *border;
866 output.preserveSurfaceCurvature = *curvature;
867 output.preserveUvFoldoverEdges = *foldover;
868 output.preserveUvSeamEdges = *seam;
869 return true;
870}
871bool decodeLod(const Value& encoded, GtsTerrainExportLodSettings& output) {
872 auto* object = encoded.getIf<Value::Object>();
873 if (!object || !exportSettingsExact(*object, {"alphaChannel",
874 "bakeLayerMask",
875 "bakeLighting",
876 "bakeVertexColors",
877 "captureBaseMapTextures",
878 "createMaterials",
879 "exportNormalMaps",
880 "exportSplatmaps",
881 "exportTextures",
882 "materialShader",
883 "mode",
884 "namePrefix",
885 "normalEdgeMode",
886 "saveResolution",
887 "screenRelativeTransitionHeight",
888 "simplification",
889 "simplifyQuality",
890 "textureExportMethod",
891 "textureExportResolution",
892 "vertexColorSmoothing"}))
893 return false;
894 auto integer = [&](const char* name) { return object->at(name).getIf<int64_t>(); };
895 auto boolean = [&](const char* name) { return object->at(name).getIf<bool>(); };
896 auto* alpha = integer("alphaChannel");
897 auto* mask = integer("bakeLayerMask");
898 auto* lighting = integer("bakeLighting");
899 auto* shader = integer("materialShader");
900 auto* mode = integer("mode");
901 auto* edge = integer("normalEdgeMode");
902 auto* resolution = integer("saveResolution");
903 auto* textureMethod = integer("textureExportMethod");
904 auto* textureResolution = integer("textureExportResolution");
905 auto* smoothing = integer("vertexColorSmoothing");
906 auto* transition = number(object->at("screenRelativeTransitionHeight"));
907 auto* quality = number(object->at("simplifyQuality"));
908 auto* prefix = object->at("namePrefix").getIf<std::string>();
909 auto* vertexColors = boolean("bakeVertexColors");
910 auto* capture = boolean("captureBaseMapTextures");
911 auto* materials = boolean("createMaterials");
912 auto* normals = boolean("exportNormalMaps");
913 auto* splats = boolean("exportSplatmaps");
914 auto* textures = boolean("exportTextures");
915 if (!alpha || *alpha < 0 || *alpha > 1 || !mask || *mask < 0 || *mask > std::numeric_limits<std::uint32_t>::max() ||
916 !lighting || *lighting < 0 || *lighting > 1 || !shader || *shader < 0 || *shader > 1 || !mode || *mode < 0 ||
917 *mode > 2 || !edge || *edge < 0 || *edge > 1 || !resolution || *resolution < 0 || *resolution > 4 ||
918 !textureMethod || *textureMethod < 0 || *textureMethod > 1 || !textureResolution || *textureResolution < 32 ||
919 *textureResolution > 8192 || !smoothing || *smoothing < 0 || *smoothing > 128 || !transition || !quality ||
920 !prefix || prefix->size() > 256 || !vertexColors || !capture || !materials || !normals || !splats ||
921 !textures || !exportSettingsDecodeOptions(object->at("simplification"), output.simplification))
922 return false;
923 output.alphaChannel = static_cast<GtsTerrainAlphaChannel>(*alpha);
924 output.bakeLayerMask = std::uint32_t(*mask);
925 output.bakeLighting = static_cast<GtsTerrainBakeLighting>(*lighting);
926 output.materialShader = static_cast<GtsTerrainExportShader>(*shader);
927 output.mode = static_cast<GtsTerrainLodMode>(*mode);
928 output.normalEdgeMode = static_cast<GtsTerrainNormalEdgeMode>(*edge);
929 output.saveResolution = static_cast<GtsTerrainSaveResolution>(*resolution);
930 output.textureExportMethod = static_cast<GtsTerrainTextureExportMethod>(*textureMethod);
931 output.textureExportResolution = int(*textureResolution);
932 output.vertexColorSmoothing = int(*smoothing);
933 output.screenRelativeTransitionHeight = float(*transition);
934 output.simplifyQuality = float(*quality);
935 output.namePrefix = *prefix;
936 output.bakeVertexColors = *vertexColors;
937 output.captureBaseMapTextures = *capture;
938 output.createMaterials = *materials;
939 output.exportNormalMaps = *normals;
940 output.exportSplatmaps = *splats;
941 output.exportTextures = *textures;
942 return output.validate().ok();
943}
944bool decodeWorkflow(const Value& encoded, GtsTerrainExportWorkflow& output, bool legacyV2 = false) {
945 auto* object = encoded.getIf<Value::Object>();
946 if (!object ||
947 (!exportSettingsExact(*object, {"action",
948 "addMeshColliderToImpostor",
949 "addObjectColliders",
950 "addTerrainCollider",
951 "addTreeColliders",
952 "bakeCombinedCollisionMesh",
953 "colliderResolution",
954 "colliderSimplifyQuality",
955 "colliderType",
956 "convertSourceTerrains",
957 "convertTreesToObjects",
958 "copyPcgObjects",
959 "copyPcgObjectsToImpostor",
960 "createColliderScenes",
961 "createImpostorScenes",
962 "impostorRange",
963 "invertExportMask",
964 "objFaceMode",
965 "selection",
966 "sourceTreatment"}) &&
967 !(legacyV2 &&
968 exportSettingsExact(
969 *object, {"action", "addMeshColliderToImpostor", "addObjectColliders", "addTerrainCollider",
970 "addTreeColliders", "bakeCombinedCollisionMesh", "colliderResolution",
971 "colliderSimplifyQuality", "colliderType", "convertSourceTerrains", "convertTreesToObjects",
972 "copyPcgObjects", "copyPcgObjectsToImpostor", "createColliderScenes", "createImpostorScenes",
973 "impostorRange", "invertExportMask", "selection", "sourceTreatment"}))))
974 return false;
975 auto integer = [&](const char* name) { return object->at(name).getIf<int64_t>(); };
976 auto boolean = [&](const char* name) { return object->at(name).getIf<bool>(); };
977 auto *action = integer("action"), *resolution = integer("colliderResolution"), *type = integer("colliderType"),
978 *selection = integer("selection"), *treatment = integer("sourceTreatment");
979 const int64_t defaultFace = 0;
980 auto* face = legacyV2 ? &defaultFace : integer("objFaceMode");
981 auto* quality = number(object->at("colliderSimplifyQuality"));
982 auto* range = number(object->at("impostorRange"));
983 auto * addImpostor = boolean("addMeshColliderToImpostor"), *addObjects = boolean("addObjectColliders"),
984 *addTerrain = boolean("addTerrainCollider"), *addTrees = boolean("addTreeColliders"),
985 *combined = boolean("bakeCombinedCollisionMesh"), *convert = boolean("convertSourceTerrains"),
986 *convertTrees = boolean("convertTreesToObjects"), *copy = boolean("copyPcgObjects"),
987 *copyImpostor = boolean("copyPcgObjectsToImpostor"), *colliderScenes = boolean("createColliderScenes"),
988 *impostorScenes = boolean("createImpostorScenes"), *invert = boolean("invertExportMask");
989 if (!action || *action < 0 || *action > 2 || !resolution || *resolution < 0 || *resolution > 4 || !type ||
990 *type < 0 || *type > 1 || !selection || *selection < 0 || *selection > 1 || !treatment || *treatment < 0 ||
991 *treatment > 3 || !face || *face < 0 || *face > 1 || !quality || !range || !std::isfinite(*quality) ||
992 *quality < 0 || *quality > 1 || !std::isfinite(*range) || *range < 0 || !addImpostor || !addObjects ||
993 !addTerrain || !addTrees || !combined || !convert || !convertTrees || !copy || !copyImpostor ||
994 !colliderScenes || !impostorScenes || !invert)
995 return false;
996 output.action = static_cast<GtsTerrainConversionAction>(*action);
997 output.colliderResolution = static_cast<GtsTerrainSaveResolution>(*resolution);
998 output.colliderType = static_cast<GtsTerrainColliderType>(*type);
999 output.selection = static_cast<GtsTerrainExportSelection>(*selection);
1000 output.objFaceMode = static_cast<GtsTerrainObjFaceMode>(*face);
1001 output.sourceTreatment = static_cast<GtsSourceTerrainTreatment>(*treatment);
1002 output.colliderSimplifyQuality = float(*quality);
1003 output.impostorRange = *range;
1004 output.addMeshColliderToImpostor = *addImpostor;
1005 output.addObjectColliders = *addObjects;
1006 output.addTerrainCollider = *addTerrain;
1007 output.addTreeColliders = *addTrees;
1008 output.bakeCombinedCollisionMesh = *combined;
1009 output.convertSourceTerrains = *convert;
1010 output.convertTreesToObjects = *convertTrees;
1011 output.copyPcgObjects = *copy;
1012 output.copyPcgObjectsToImpostor = *copyImpostor;
1013 output.createColliderScenes = *colliderScenes;
1014 output.createImpostorScenes = *impostorScenes;
1015 output.invertExportMask = *invert;
1016 return true;
1017}
1018} // namespace
1019
1021 if (!enumRange(int(saveResolution), 4) || !enumRange(int(normalEdgeMode), 1) || !enumRange(int(mode), 2) ||
1022 !enumRange(int(materialShader), 1) || !enumRange(int(textureExportMethod), 1) ||
1023 !enumRange(int(alphaChannel), 1) || !enumRange(int(bakeLighting), 1))
1025 "GTS terrain export enum value is invalid",
1026 "procgen.gtsTerrainExportSettings"));
1027 if (!std::isfinite(simplifyQuality) || simplifyQuality < 0.0f || simplifyQuality > 1.0f ||
1029 screenRelativeTransitionHeight >= 1.0f || vertexColorSmoothing < 0 || vertexColorSmoothing > 128 ||
1030 !textureResolutionValid(textureExportResolution) || namePrefix.size() > 256 ||
1032 !std::isfinite(simplification.aggressiveness) || simplification.aggressiveness <= 0.0 ||
1035 "GTS terrain export LOD value is outside its supported range",
1036 "procgen.gtsTerrainExportSettings"));
1037 return Result<void>::success();
1038}
1046 if (level < 0)
1048 Diagnostic::error(DiagnosticCode::InvalidArgument, "GTS impostor LOD index must be non-negative",
1049 "procgen.gtsTerrainExportSettings"));
1051 value.namePrefix = "LOD" + std::to_string(level) + "_";
1053 value.normalEdgeMode = GtsTerrainNormalEdgeMode::Smooth;
1055 if (level == 0) {
1056 value.saveResolution = GtsTerrainSaveResolution::Half;
1057 value.textureExportResolution = 2048;
1058 } else if (level == 1) {
1060 value.textureExportResolution = 1024;
1061 } else if (level == 2) {
1062 value.saveResolution = GtsTerrainSaveResolution::Eighth;
1063 value.textureExportResolution = 512;
1064 } else {
1066 value.textureExportResolution = 256;
1067 }
1068 value.bakeVertexColors = false;
1069 value.alphaChannel = GtsTerrainAlphaChannel::None;
1070 value.exportSplatmaps = false;
1071 value.materialShader = GtsTerrainExportShader::Standard;
1073}
1075 if (level < 0)
1077 Diagnostic::error(DiagnosticCode::InvalidArgument, "GTS low-poly LOD index must be non-negative",
1078 "procgen.gtsTerrainExportSettings"));
1080 value.namePrefix = "LOD" + std::to_string(level) + "_";
1083 value.normalEdgeMode = GtsTerrainNormalEdgeMode::Sharp;
1085 value.bakeVertexColors = true;
1086 value.vertexColorSmoothing = 3;
1087 value.alphaChannel = GtsTerrainAlphaChannel::None;
1088 value.exportNormalMaps = false;
1089 value.exportSplatmaps = false;
1092}
1093namespace {
1094Result<GtsTerrainExportLodSettings> preset(int mode, int level, float quality, float transition) {
1097 : mode == int(GtsTerrainLodMode::LowPoly)
1099 : Result<GtsTerrainExportLodSettings>::failure(Diagnostic::error(
1100 DiagnosticCode::InvalidArgument, "GTS terrain preset mode must be Impostor or LowPoly",
1101 "procgen.gtsTerrainExportSettings"));
1102 if (!made) return made;
1103 made.value().simplifyQuality = quality;
1104 made.value().screenRelativeTransitionHeight = transition;
1105 auto valid = made.value().validate();
1107 return made;
1108}
1109} // namespace
1110Result<void> GtsTerrainExportSettings::appendSourcePreset(int mode, int level, float quality, float transitionHeight) {
1111 auto made = preset(mode, level, quality, transitionHeight);
1112 if (!made) return Result<void>::failure(made.status());
1113 auto candidate = sourceLods_;
1114 candidate.push_back(std::move(made).takeValue());
1115 return setSourceLods(std::move(candidate));
1116}
1118 float transitionHeight) {
1119 auto made = preset(mode, level, quality, transitionHeight);
1120 if (!made) return Result<void>::failure(made.status());
1121 auto candidate = impostorLods_;
1122 candidate.push_back(std::move(made).takeValue());
1123 return setImpostorLods(std::move(candidate));
1124}
1125Result<void> GtsTerrainExportSettings::setSourceLods(std::vector<GtsTerrainExportLodSettings> levels) {
1126 auto valid = validateList(levels);
1127 if (!valid) return valid;
1128 sourceLods_ = std::move(levels);
1129 return Result<void>::success();
1130}
1132 if (!enumRange(int(workflow.action), 2) || !enumRange(int(workflow.sourceTreatment), 3) ||
1133 !enumRange(int(workflow.selection), 1) || !enumRange(int(workflow.colliderType), 1) ||
1134 !enumRange(int(workflow.objFaceMode), 1) || !enumRange(int(workflow.colliderResolution), 4) ||
1135 !std::isfinite(workflow.colliderSimplifyQuality) || workflow.colliderSimplifyQuality < 0.f ||
1136 workflow.colliderSimplifyQuality > 1.f || !std::isfinite(workflow.impostorRange) ||
1137 workflow.impostorRange < 0.0)
1139 "GTS terrain export workflow value is invalid",
1140 "procgen.gtsTerrainExportSettings"));
1141 workflow_ = workflow;
1142 return Result<void>::success();
1143}
1145Result<void> GtsTerrainExportSettings::setImpostorLods(std::vector<GtsTerrainExportLodSettings> levels) {
1146 auto valid = validateList(levels);
1147 if (!valid) return valid;
1148 impostorLods_ = std::move(levels);
1149 return Result<void>::success();
1150}
1151int GtsTerrainExportSettings::getSourceLodCount() const noexcept { return int(sourceLods_.size()); }
1152int GtsTerrainExportSettings::getImpostorLodCount() const noexcept { return int(impostorLods_.size()); }
1154 return index >= 0 && index < int(sourceLods_.size()) ? &sourceLods_[std::size_t(index)] : nullptr;
1155}
1157 return index >= 0 && index < int(impostorLods_.size()) ? &impostorLods_[std::size_t(index)] : nullptr;
1158}
1160 auto valid = validateList(sourceLods_);
1161 if (!valid) return Result<std::vector<GtsTerrainLodLevelSettings>>::failure(valid.status());
1162 if (sourceLods_.empty())
1164 Diagnostic::error(DiagnosticCode::InvalidArgument, "GTS source export requires at least one LOD",
1165 "procgen.gtsTerrainExportSettings"));
1166 std::vector<GtsTerrainLodLevelSettings> output;
1167 output.reserve(sourceLods_.size());
1168 for (const auto& source : sourceLods_) {
1169 auto level = source.compileLevel();
1170 if (!level) return Result<std::vector<GtsTerrainLodLevelSettings>>::failure(level.status());
1171 output.push_back(std::move(level).takeValue());
1172 }
1173 return Result<std::vector<GtsTerrainLodLevelSettings>>::success(std::move(output));
1174}
1176 auto sourceValid = validateList(sourceLods_);
1177 if (!sourceValid) return Result<std::string>::failure(sourceValid.status());
1178 auto impostorValid = validateList(impostorLods_);
1179 if (!impostorValid) return Result<std::string>::failure(impostorValid.status());
1180 Value::Array source, impostor;
1181 for (const auto& level : sourceLods_) source.emplace_back(encodeLod(level));
1182 for (const auto& level : impostorLods_) impostor.emplace_back(encodeLod(level));
1183 return Value(Value::Object{{"impostorLods", std::move(impostor)},
1184 {"schema", "eve.procgen.gts-terrain-export-settings"},
1185 {"sourceLods", std::move(source)},
1186 {"version", 3},
1187 {"workflow", encodeWorkflow(workflow_)}})
1188 .toJson();
1189}
1191 if (json.size() > 1024U * 1024U)
1193 "GTS terrain export settings JSON exceeds size limit",
1194 "procgen.gtsTerrainExportSettings"));
1195 auto parsed = Value::fromJson(json);
1196 if (!parsed) return Result<void>::failure(parsed.status());
1197 auto* root = parsed.value().getIf<Value::Object>();
1198 if (!root || !root->contains("schema") || !root->contains("version") || !root->contains("sourceLods") ||
1199 !root->contains("impostorLods"))
1201 "GTS terrain export settings fields are invalid",
1202 "procgen.gtsTerrainExportSettings"));
1203 auto* schema = root->at("schema").getIf<std::string>();
1204 auto* version = root->at("version").getIf<int64_t>();
1205 if (!version || (*version < 1 || *version > 3) ||
1206 (*version == 1 && !exportSettingsExact(*root, {"impostorLods", "schema", "sourceLods", "version"})) ||
1207 (*version >= 2 && !exportSettingsExact(*root, {"impostorLods", "schema", "sourceLods", "version", "workflow"})))
1209 "GTS terrain export settings fields or version are invalid",
1210 "procgen.gtsTerrainExportSettings"));
1211 auto* source = root->at("sourceLods").getIf<Value::Array>();
1212 auto* impostor = root->at("impostorLods").getIf<Value::Array>();
1213 if (!schema || *schema != "eve.procgen.gts-terrain-export-settings" || !source || !impostor ||
1214 source->size() > 32 || impostor->size() > 32)
1216 "GTS terrain export settings schema or counts are invalid",
1217 "procgen.gtsTerrainExportSettings"));
1218 GtsTerrainExportWorkflow decodedWorkflow;
1219 if (*version >= 2 && !decodeWorkflow(root->at("workflow"), decodedWorkflow, *version == 2))
1221 "GTS terrain export workflow is invalid",
1222 "procgen.gtsTerrainExportSettings"));
1223 std::vector<GtsTerrainExportLodSettings> decodedSource, decodedImpostor;
1224 for (const auto& encoded : *source) {
1226 if (!decodeLod(encoded, value))
1228 "GTS source export LOD is invalid",
1229 "procgen.gtsTerrainExportSettings"));
1230 decodedSource.push_back(std::move(value));
1231 }
1232 for (const auto& encoded : *impostor) {
1234 if (!decodeLod(encoded, value))
1236 "GTS impostor export LOD is invalid",
1237 "procgen.gtsTerrainExportSettings"));
1238 decodedImpostor.push_back(std::move(value));
1239 }
1240 auto sourceValid = validateList(decodedSource);
1241 if (!sourceValid) return sourceValid;
1242 auto impostorValid = validateList(decodedImpostor);
1243 if (!impostorValid) return impostorValid;
1244 auto workflowValid = configureWorkflow(decodedWorkflow);
1245 if (!workflowValid) return workflowValid;
1246 sourceLods_ = std::move(decodedSource);
1247 impostorLods_ = std::move(decodedImpostor);
1248 return Result<void>::success();
1249}
1250
1251
1253 const GtsTerrainExportSettings& settings, float sizeX,
1254 float sizeY, float sizeZ, int subTiles, GtsMeshPivot pivot) {
1255 auto levels = settings.compileSourceLevels();
1256 if (!levels) return Result<void>::failure(levels.status());
1257 const auto* first = settings.sourceLodAt(0);
1258 if (!first)
1260 "GTS source export requires at least one LOD",
1261 "procgen.gtsTerrainExportSettings"));
1262 MeshBuild base;
1263 auto built = buildGtsTerrainBaseMesh(base, heightmap, first->saveResolution, sizeX, sizeY, sizeZ);
1264 if (!built) return built;
1265 auto lods = buildGtsTerrainLods(base, subTiles, subTiles, pivot, levels.value());
1266 if (!lods) return Result<void>::failure(lods.status());
1267 output = std::move(lods).takeValue();
1268 return Result<void>::success();
1269}
1271 const GtsTerrainExportWorkflow& workflow, float sizeX,
1272 float sizeY, float sizeZ) {
1273 GtsTerrainExportSettings validator;
1274 auto valid = validator.configureWorkflow(workflow);
1275 if (!valid) return valid;
1278 "GTS workflow does not request a terrain MeshCollider",
1279 "procgen.gtsTerrainExportSettings"));
1280 MeshBuild base;
1281 auto built = buildGtsTerrainBaseMesh(base, heightmap, workflow.colliderResolution, sizeX, sizeY, sizeZ);
1282 if (!built) return built;
1283 MeshBuild simplified;
1284 auto reduced = simplifyGtsMesh(simplified, base, workflow.colliderSimplifyQuality);
1285 if (!reduced) return Result<void>::failure(reduced.status());
1286 output = std::move(simplified);
1287 return Result<void>::success();
1288}
1289
1291 float sizeY, float sizeZ, GtsTerrainObjFaceMode faceMode) {
1292 if (!enumRange(int(faceMode), 1))
1294 "GTS terrain OBJ face mode is invalid",
1295 "procgen.gtsTerrainExportSettings"));
1296 MeshBuild validated;
1297 auto built = buildGtsTerrainBaseMesh(validated, heightmap, resolution, sizeX, sizeY, sizeZ);
1298 if (!built) return Result<std::string>::failure(built.status());
1299 const int stride = 1 << int(resolution), width = (heightmap.getWidth() - 1) / stride + 1,
1300 height = (heightmap.getHeight() - 1) / stride + 1;
1301 std::ostringstream stream;
1302 stream.imbue(std::locale::classic());
1303 stream << std::setprecision(std::numeric_limits<float>::max_digits10);
1304 stream << "# Unity terrain OBJ File\n";
1305 for (int y = 0; y < height; ++y)
1306 for (int x = 0; x < width; ++x) {
1307 const float u = float(x * stride) / float(heightmap.getWidth() - 1),
1308 v = float(y * stride) / float(heightmap.getHeight() - 1);
1309 stream << "v " << (-v * sizeZ) << ' ' << (heightmap.height(x * stride, y * stride) * sizeY) << ' '
1310 << (u * sizeX) << '\n';
1311 }
1312 for (int y = 0; y < height; ++y)
1313 for (int x = 0; x < width; ++x) {
1314 const float u = float(x * stride) / float(heightmap.getWidth() - 1),
1315 v = float(y * stride) / float(heightmap.getHeight() - 1);
1316 stream << "vt " << v << ' ' << u << '\n';
1317 }
1318 for (int y = 0; y < height - 1; ++y)
1319 for (int x = 0; x < width - 1; ++x) {
1320 const int a = y * width + x + 1, b = (y + 1) * width + x + 1, c = (y + 1) * width + x + 2,
1321 d = y * width + x + 2;
1322 if (faceMode == GtsTerrainObjFaceMode::Triangles)
1323 stream << "f " << a << '/' << a << ' ' << b << '/' << b << ' ' << d << '/' << d << "\nf " << b << '/'
1324 << b << ' ' << c << '/' << c << ' ' << d << '/' << d << '\n';
1325 else
1326 stream << "f " << a << '/' << a << ' ' << b << '/' << b << ' ' << c << '/' << c << ' ' << d << '/' << d
1327 << '\n';
1328 }
1329 auto text = stream.str();
1330 if (text.size() > 512U * 1024U * 1024U)
1332 DiagnosticCode::InvalidArgument, "GTS terrain OBJ exceeds size limit", "procgen.gtsTerrainExportSettings"));
1333 return Result<std::string>::success(std::move(text));
1334}
1335
1337 GtsTerrainSaveResolution resolution, float sizeX, float sizeY,
1338 float sizeZ, GtsTerrainObjFaceMode faceMode, float threshold,
1339 bool invert) {
1340 if (!enumRange(int(faceMode), 1) || !std::isfinite(threshold) || threshold < 0.f || threshold > 1.f)
1342 "GTS masked terrain OBJ settings are invalid",
1343 "procgen.gtsTerrainExportSettings"));
1344 MeshBuild validated;
1345 auto built = buildGtsTerrainBaseMesh(validated, heightmap, resolution, sizeX, sizeY, sizeZ);
1346 if (!built) return Result<std::string>::failure(built.status());
1347 if (maskmap.getWidth() < 1 || maskmap.getHeight() < 1)
1349 "GTS masked terrain OBJ mask is empty",
1350 "procgen.gtsTerrainExportSettings"));
1351 const int terrainResolution = heightmap.getWidth(), stride = 1 << int(resolution);
1352 std::vector<int> vertexIndices(std::size_t(terrainResolution) * std::size_t(terrainResolution), -1);
1353 struct Vertex {
1354 float x, y, z, u, v;
1355 };
1356 std::vector<Vertex> vertices;
1357 std::vector<int> indices;
1358 auto sampleNormalized = [](const Heightmap& map, float x, float z) {
1359 return map.sampleBilinear(x * float(map.getWidth()), z * float(map.getHeight()));
1360 };
1361 auto vertexIndex = [&](int x, int z, float height) {
1362 auto& index = vertexIndices[std::size_t(z) * std::size_t(terrainResolution) + std::size_t(x)];
1363 if (index < 0) {
1364 index = int(vertices.size());
1365 vertices.push_back({-float(x) * sizeX / float(terrainResolution - 1), height * sizeY,
1366 float(z) * sizeZ / float(terrainResolution - 1), float(x) / float(terrainResolution),
1367 float(z) / float(terrainResolution)});
1368 }
1369 return index;
1370 };
1371 auto addTriangle = [&](int a, int b, int c) {
1372 indices.push_back(c);
1373 indices.push_back(b);
1374 indices.push_back(a);
1375 };
1376 auto addQuad = [&](int a, int b, int c, int d) {
1377 indices.push_back(a);
1378 indices.push_back(c);
1379 indices.push_back(d);
1380 indices.push_back(b);
1381 };
1382 for (int z = 0; z < terrainResolution - stride; z += stride) {
1383 const float z0 = float(z) / float(terrainResolution), z1 = float(z + stride) / float(terrainResolution);
1384 for (int x = 0; x < terrainResolution - stride; x += stride) {
1385 const float x0 = float(x) / float(terrainResolution), x1 = float(x + stride) / float(terrainResolution);
1386 const bool outside = sampleNormalized(maskmap, x0, z0) < threshold;
1387 if (outside != invert) continue;
1388 const int v1 = vertexIndex(x, z + stride, sampleNormalized(heightmap, z1, x0));
1389 const int v2 = vertexIndex(x + stride, z + stride, sampleNormalized(heightmap, z1, x1));
1390 const int v3 = vertexIndex(x, z, sampleNormalized(heightmap, z0, x0));
1391 const int v4 = vertexIndex(x + stride, z, sampleNormalized(heightmap, z0, x1));
1392 if (faceMode == GtsTerrainObjFaceMode::Triangles) {
1393 addTriangle(v3, v1, v2);
1394 addTriangle(v3, v2, v4);
1395 } else
1396 addQuad(v1, v2, v3, v4);
1397 }
1398 }
1399 std::ostringstream stream;
1400 stream.imbue(std::locale::classic());
1401 stream << std::setprecision(std::numeric_limits<float>::max_digits10);
1402 stream << "# Unity terrain OBJ File\n";
1403 for (const auto& vertex : vertices) stream << "v " << vertex.x << ' ' << vertex.y << ' ' << vertex.z << '\n';
1404 for (const auto& vertex : vertices) stream << "vt " << vertex.u << ' ' << vertex.v << '\n';
1405 const int faceSize = faceMode == GtsTerrainObjFaceMode::Triangles ? 3 : 4;
1406 for (std::size_t i = 0; i < indices.size(); i += std::size_t(faceSize)) {
1407 stream << "f";
1408 for (int j = 0; j < faceSize; ++j) {
1409 const int index = indices[i + std::size_t(j)] + 1;
1410 stream << ' ' << index << '/' << index;
1411 }
1412 stream << '\n';
1413 }
1414 auto text = stream.str();
1415 if (text.size() > 512U * 1024U * 1024U)
1417 "GTS masked terrain OBJ exceeds size limit",
1418 "procgen.gtsTerrainExportSettings"));
1419 return Result<std::string>::success(std::move(text));
1420}
1421
1423 const image::ImageData& bakedTexture, GtsTerrainNormalEdgeMode edgeMode,
1424 int smoothingIterations, float terrainSizeX, float terrainSizeZ,
1425 bool linearize) {
1426 if (!enumRange(int(edgeMode), 1) || smoothingIterations < 0 || smoothingIterations > 128 || source.empty() ||
1427 source.getIndexCount() % 3 || !std::isfinite(terrainSizeX) || terrainSizeX <= 0.f ||
1428 !std::isfinite(terrainSizeZ) || terrainSizeZ <= 0.f || bakedTexture.getWidth() < 1 ||
1429 bakedTexture.getHeight() < 1 || !bakedTexture.getData() || !bakedTexture.getPixelGetFunction())
1431 "GTS terrain vertex-color bake input is invalid",
1432 "procgen.gtsTerrainExportSettings"));
1433 const std::size_t pixelSize = bakedTexture.getPixelSize();
1434 if (!pixelSize || std::size_t(bakedTexture.getWidth()) * std::size_t(bakedTexture.getHeight()) >
1435 bakedTexture.getSize() / pixelSize)
1437 "GTS terrain vertex-color texture storage is invalid",
1438 "procgen.gtsTerrainExportSettings"));
1439 using ExportColor = image::ImageData::Colorf;
1440 const int width = bakedTexture.getWidth(), height = bakedTexture.getHeight();
1441 std::vector<ExportColor> colors;
1442 colors.reserve(std::size_t(width) * std::size_t(height));
1443 for (int y = 0; y < height; ++y)
1444 for (int x = 0; x < width; ++x) colors.push_back(bakedTexture.getPixel(x, y));
1445 auto safe = [&](const std::vector<ExportColor>& values, int x, int y) {
1446 x = std::clamp(x, 0, width - 1);
1447 y = std::clamp(y, 0, height - 1);
1448 return values[std::size_t(y) * std::size_t(width) + std::size_t(x)];
1449 };
1450 for (int iteration = 0; iteration < smoothingIterations; ++iteration) {
1451 auto next = colors;
1452 for (int y = 0; y < height; ++y)
1453 for (int x = 0; x < width; ++x) {
1454 const auto a = safe(colors, x, y - 1), b = safe(colors, x, y + 1), c = safe(colors, x - 1, y),
1455 d = safe(colors, x + 1, y);
1456 next[std::size_t(y) * std::size_t(width) + std::size_t(x)] = {
1457 (a.r + b.r + c.r + d.r) * .25f, (a.g + b.g + c.g + d.g) * .25f, (a.b + b.b + c.b + d.b) * .25f,
1458 (a.a + b.a + c.a + d.a) * .25f};
1459 }
1460 colors = std::move(next);
1461 }
1462 auto linear = [](float value) {
1463 return value <= .04045f ? value / 12.92f : std::pow((value + .055f) / 1.055f, 2.4f);
1464 };
1465 auto sample = [&](float x, float z) {
1466 const int tx = std::max(0, int(std::round(x / terrainSizeX * float(width))) - 1);
1467 const int tz = std::max(0, int(std::round(z / terrainSizeZ * float(width))) - 1);
1468 ExportColor color = safe(colors, tx, tz);
1469 if (linearize) {
1470 color.r = linear(color.r);
1471 color.g = linear(color.g);
1472 color.b = linear(color.b);
1473 }
1474 return color;
1475 };
1476 MeshBuild candidate;
1477 std::vector<float> vertexColors;
1478 if (edgeMode == GtsTerrainNormalEdgeMode::Smooth) {
1479 candidate = source;
1480 vertexColors.reserve(std::size_t(source.getVertexCount()) * 4u);
1481 for (int vertex = 0; vertex < source.getVertexCount(); ++vertex) {
1482 const auto color = sample(source.getPositionX(vertex), source.getPositionZ(vertex));
1483 vertexColors.insert(vertexColors.end(), {color.r, color.g, color.b, color.a});
1484 }
1485 } else {
1486 candidate.reserve(source.getIndexCount(), source.getIndexCount());
1487 vertexColors.reserve(std::size_t(source.getIndexCount()) * 4u);
1488 for (int i = 0; i < source.getIndexCount(); i += 3) {
1489 const int group = source.getTriangleGroup(i / 3);
1490 candidate.setActiveGroup(group >= 0 ? source.getGroupName(group) : "");
1491 ExportColor triangle[3];
1492 for (int corner = 0; corner < 3; ++corner) {
1493 const int src = source.getIndex(i + corner);
1494 triangle[corner] = sample(source.getPositionX(src), source.getPositionZ(src));
1495 candidate.addVertex(source.getPositionX(src), source.getPositionY(src), source.getPositionZ(src), 0, 0,
1496 0, source.getUvU(src), source.getUvV(src));
1497 }
1498 const ExportColor average{(triangle[0].r + triangle[1].r + triangle[2].r) / 3.f,
1499 (triangle[0].g + triangle[1].g + triangle[2].g) / 3.f,
1500 (triangle[0].b + triangle[1].b + triangle[2].b) / 3.f,
1501 (triangle[0].a + triangle[1].a + triangle[2].a) / 3.f};
1502 for (int corner = 0; corner < 3; ++corner)
1503 vertexColors.insert(vertexColors.end(), {average.r, average.g, average.b, average.a});
1504 const std::uint32_t base = std::uint32_t(i);
1505 candidate.addTriangle(base, base + 1, base + 2);
1506 }
1507 auto& normals = candidate.normals();
1508 const auto& positions = candidate.positions();
1509 for (int i = 0; i < candidate.getIndexCount(); i += 3) {
1510 const auto a = candidate.indices()[std::size_t(i)], b = candidate.indices()[std::size_t(i + 1)],
1511 c = candidate.indices()[std::size_t(i + 2)];
1512 const float abx = positions[b * 3] - positions[a * 3], aby = positions[b * 3 + 1] - positions[a * 3 + 1],
1513 abz = positions[b * 3 + 2] - positions[a * 3 + 2];
1514 const float acx = positions[c * 3] - positions[a * 3], acy = positions[c * 3 + 1] - positions[a * 3 + 1],
1515 acz = positions[c * 3 + 2] - positions[a * 3 + 2];
1516 float nx = aby * acz - abz * acy, ny = abz * acx - abx * acz, nz = abx * acy - aby * acx;
1517 const float length = std::sqrt(nx * nx + ny * ny + nz * nz);
1518 if (!(length > 0.f) || !std::isfinite(length))
1520 "GTS sharp terrain mesh contains a degenerate triangle",
1521 "procgen.gtsTerrainExportSettings"));
1522 nx /= length;
1523 ny /= length;
1524 nz /= length;
1525 for (auto vertex : {a, b, c}) {
1526 normals[vertex * 3] = nx;
1527 normals[vertex * 3 + 1] = ny;
1528 normals[vertex * 3 + 2] = nz;
1529 }
1530 }
1531 for (const auto& [key, value] : source.metadata()) candidate.setMeta(key, value);
1532 }
1533 auto applied = candidate.setVertexColors(std::move(vertexColors));
1534 if (!applied) return Result<int>::failure(applied.status());
1535 candidate.setMeta("gts.vertexColors", edgeMode == GtsTerrainNormalEdgeMode::Sharp ? "sharp" : "smooth");
1536 output = std::move(candidate);
1537 return Result<int>::success(output.getVertexCount());
1538}
1539} // namespace eve::procgen
double z
double y
double m[16]
double x
int root
Definition AnimSmr.cpp:119
std::string output
const std::string & s
std::unordered_map< std::string, QuestRuntime > entries
int mask
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
int rows
int pixelSize
int triangle
Definition FluidSdf.cpp:554
float linear
std::uint32_t vertexCount
std::uint32_t indexCount
tensor::Graph g
Definition GpuGraph.cpp:7
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
bool foldover
std::array< double, 10 > q
bool seam
bool border
std::vector< std::uint32_t > indices
std::vector< float > normals
std::vector< float > positions
float v
std::int32_t c
std::int32_t first
int h
std::uint32_t height
std::uint32_t width
void(* destroy)(void *)
float length
PhysicsJointLink link
Range range
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
int level
ScriptMotionSinkStore< ScriptMotionSink< MotionColorTraits > > colors
OceanWakeSettings settings
std::shared_ptr< const OceanSprayFrame > previous
uint32_t groups
Definition OnnxGpgpu.cpp:39
std::string error
Definition Package.cpp:174
std::array< uint32_t, 16 > material
std::string action
Definition PlayHost.cpp:118
PrimitiveHandle handle
std::set< std::string > values
Object::Ptr value
float d
float t
const EntityFact * entity
Shader * shader
Lighting3DPack lighting
std::vector< WfcTile > tiles
double number
std::string text
ScriptStructure out
std::string_view source
bool boolean
std::string string
const SquirrelValueOptions & options
int count
AbilityActivationGroup group
Heightmap curve
std::array< double, 2 > vertices[3]
int columns
Json object
int iterations
Definition TreeMesh.cpp:448
float step
Definition TreeMesh.cpp:451
float size
Definition TreeMesh.cpp:158
uint32_t index
double oy
double ox
Owning, renderer-independent dynamic values.
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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
const T & value() const &
Borrow the value from a const lvalue after checking success.
Definition Result.h:339
const Status & status() const noexcept
Inspect the structured operation status.
Definition Result.h:300
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
Packages shading method + surface parameters into one attachable asset.
Definition Material.h:38
EVENGINE_API_BACKENDS public API.
Represents raw pixel data.
Definition ImageData.h:38
void getPixel(int x, int y, Colorf &c) const
Gets the pixel at location (x,y).
medialoader::Colorf Colorf
Definition ImageData.h:41
size_t getSize() const
void * getData() const
PixelGetFunction getPixelGetFunction() const
Definition ImageData.h:174
size_t getPixelSize() const
Schema-versioned source/impostor terrain export profile.
Result< void > appendSourcePreset(int mode, int level, float quality, float transitionHeight)
Append one source preset after validating the complete resulting sequence.
const GtsTerrainExportLodSettings * sourceLodAt(int index) const noexcept
Return an immutable source LOD record, or nullptr for an invalid index. @ownership The export setting...
Result< void > setImpostorLods(std::vector< GtsTerrainExportLodSettings > levels)
Replace impostor LOD records only after every record validates.
int getImpostorLodCount() const noexcept
Return the number of impostor LOD records.
Result< std::vector< GtsTerrainLodLevelSettings > > compileSourceLevels() const
Compile source records for the existing sequential LOD mesh builder.
GtsTerrainExportWorkflow getWorkflow() const noexcept
Return a value copy of the current validated workflow.
Result< void > configureWorkflow(const GtsTerrainExportWorkflow &workflow)
Atomically configure all top-level conversion and collider workflow controls.
Result< void > restoreJson(const std::string &json)
Atomically restore a strict version-1 terrain export profile.
const GtsTerrainExportLodSettings * impostorLodAt(int index) const noexcept
Return an immutable impostor LOD record, or nullptr for an invalid index. @ownership The export setti...
Result< std::string > snapshotJson() const
Serialize as strict eve.procgen.gts-terrain-export-settings version 1 JSON.
Result< void > setSourceLods(std::vector< GtsTerrainExportLodSettings > levels)
Replace source-terrain LOD records only after every record validates.
int getSourceLodCount() const noexcept
Return the number of source-terrain LOD records.
Result< void > appendImpostorPreset(int mode, int level, float quality, float transitionHeight)
Append one impostor preset after validating the complete resulting sequence.
Owned script-friendly GTS terrain LOD export manifest.
int getLevelIndex(int index) const
Return an entry LOD index, or -1.
std::string getMeshName(int index) const
Return an entry mesh name, or empty.
std::string getObjectName(int index) const
Return an entry object name, or empty.
std::string getRelativePath(int index) const
Return an entry relative path, or empty.
int getTileIndex(int index) const
Return an entry tile index, or -1.
int getEntryCount() const
Return the number of export entries.
GtsTerrainLodRuntime()
Gts terrain lod runtime.
int getTileCount() const
Return the number of row-major tile slots, including empty cells.
Result< int > clear()
Destroy every live tile entity and advance the revision.
Result< std::uint64_t > replaceAndHideSource(const GtsTerrainLodSet &lods, Procgen &procgen, graphics::Graphics &gfx, graphics::Renderable3D &sourceTerrain, float worldDiameter, float verticalFovDegrees, float originX=0.f, float originY=0.f, float originZ=0.f)
Replace the mesh batch and hide one source terrain only after successful publication.
graphics::Renderable3D * getRenderable(int tileIndex) const
Borrow a live tile renderable or return nullptr for empty, stale or invalid slots....
std::uint64_t getRevision() const
Return the current committed revision.
Result< std::uint64_t > replace(const GtsTerrainLodSet &lods, Procgen &procgen, graphics::Graphics &gfx, float worldDiameter, float verticalFovDegrees, float originX=0.f, float originY=0.f, float originZ=0.f)
Replace the complete tile batch after configuring every non-empty candidate.
graphics::Renderable3D * getSourceTerrain() const
Resolve the currently hidden source terrain, or null after source destruction.
~GtsTerrainLodRuntime()
Gts terrain lod runtime.
Result< int > applyMaterial(graphics::Material &material)
Assign one Graphics-owned material to every live tile renderable.
Owned result of the GTS split-and-sequential-simplify pipeline.
Result< std::string > snapshotJson() const
Serialize the complete owned LOD set as schema-versioned JSON.
float getLevelSwitchDistance(int level, float worldDiameter, float verticalFovDegrees) const
Convert one level's screen-relative threshold to a perspective-camera distance.
const GtsTerrainLodLevelSettings * levelAt(int index) const
Return one level setting or nullptr for an invalid index. @ownership The LOD set retains ownership; t...
int getTileCount() const
Return the number of tiles, including empty source cells.
const GtsTerrainLodTile * tileAt(int index) const
Return one tile or nullptr for an invalid index. @ownership The LOD set retains ownership; the caller...
int selectLevelForCamera(float distance, float worldDiameter, float verticalFovDegrees) const
Select a level directly from perspective-camera distance and bounds diameter.
int selectLevel(float relativeHeight) const
Select the active level for a projected screen-relative height.
Schema-versioned native counterpart of GTSMeshSettings.
Result< std::vector< GtsTerrainLodLevelSettings > > compileLevels() const
Compile active profile slots into sequential native LOD settings.
Result< void > setLodQuality(int index, float percent)
Set one of the four simplification percentages in the range 0 through 100.
float getLodQuality(int index) const noexcept
Return one stored simplification percentage, or -1 for an invalid slot.
Result< void > setSaveResolution(int value)
Atomically set the SaveResolution enum value.
Result< void > setLodCount(int value)
Atomically set the active LOD count.
float getLodTransitionHeight(int index) const noexcept
Return the effective fixed GTS transition height for an active LOD, or -1.
Result< std::string > snapshotJson() const
Serialize as strict eve.procgen.gts-terrain-mesh-settings version 1 JSON.
Result< void > setSubTiles(int value)
Atomically set the equal X/Z split-plane count.
Result< void > restoreJson(const std::string &json)
Atomically restore settings from strict schema-versioned JSON.
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
float sampleBilinear(float x, float y) const
Bilinear height at continuous coordinate within [0, w) x [0, h).
Definition Heightmap.cpp:37
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
const std::vector< float > & positions() const
Positions.
Definition MeshBuild.h:126
void addVertex(float px, float py, float pz, float nx, float ny, float nz, float u, float v)
Adds vertex.
Definition MeshBuild.cpp:35
const std::vector< float > & normals() const
Normals.
Definition MeshBuild.h:128
void addTriangle(uint32_t i0, uint32_t i1, uint32_t i2)
Adds triangle.
Definition MeshBuild.cpp:48
void reserve(int vertexCount, int indexCount)
Reserve.
Definition MeshBuild.cpp:22
void setMeta(const std::string &key, const std::string &value)
Sets the meta.
int setActiveGroup(const std::string &name)
Select/create the named group assigned to subsequently added triangles.
Definition MeshBuild.cpp:55
int getIndexCount() const
Returns the index count.
eve::Result< void > setVertexColors(std::vector< float > colors)
Atomically replace the optional packed RGBA stream; empty removes it.
const std::vector< uint32_t > & indices() const
Indices.
Definition MeshBuild.h:134
Procedural generation module. Phase A: runtime maps (semantic Grid2D → TileLayer)....
Definition Procgen.h:159
eve::Result< void > configureGtsTerrainTileLods(const GtsTerrainLodSet &lods, int tileIndex, graphics::Renderable3D &renderable, graphics::Graphics &gfx, float worldDiameter, float verticalFovDegrees, float originX=0.f, float originY=0.f, float originZ=0.f)
Upload and atomically attach one GTS tile's LOD chain to a renderable.
Definition Procgen.cpp:1316
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
eve::Value encodeMesh(const MeshBuild &mesh)
double sample(const Heightmap &map, double u, double v)
Sample.
Result< int > invalid(std::string message)
Invalid.
Result< GtsMeshSplitResult > splitGtsMesh(const MeshBuild &source, int xSplits, int zSplits, GtsMeshPivot pivot)
Split every source triangle against a regular X/Z grid like GTSMeshSplitter.
EVENGINE_API_DOMAINS Result< GtsTerrainLodSet > buildGtsTerrainLods(const MeshBuild &source, int xSplits, int zSplits, GtsMeshPivot pivot, const std::vector< GtsTerrainLodLevelSettings > &levels)
Split a terrain mesh and generate each tile's sequential GTS LOD chain.
GtsTerrainSaveResolution
Pcg/GTS power-of-two sampling reduction used before terrain mesh export.
GtsTerrainAlphaChannel
Optional channel placed in the exported texture alpha channel.
Result< int > simplifyGtsMesh(MeshBuild &output, const MeshBuild &source, float quality, const GtsMeshSimplificationOptions &o)
Simplify a mesh with deterministic quadric edge collapse.
GtsTerrainExportShader
Native material family created for an exported terrain level.
GtsMeshPivot
Pivot translation applied independently to each GTS split mesh.
GtsTerrainConversionAction
Operation performed for the selected source terrain.
EVENGINE_API_DOMAINS Result< void > buildGtsTerrainExportLodsFromHeightmapInto(GtsTerrainLodSet &output, const Heightmap &heightmap, const GtsTerrainExportSettings &settings, float sizeX, float sizeY, float sizeZ, int subTiles, GtsMeshPivot pivot=GtsMeshPivot::None)
Build source-terrain LODs using the first export record's SaveResolution and the complete sequential ...
Result< GtsTerrainLodSet > buildGtsTerrainLodsFromHeightmap(const Heightmap &heightmap, GtsTerrainSaveResolution resolution, float sizeX, float sizeY, float sizeZ, int subTileSplits, GtsMeshPivot pivot, const std::vector< GtsTerrainLodLevelSettings > &levels)
Execute the complete GTS heightmap-to-split-LOD conversion as one atomic operation.
EVENGINE_API_DOMAINS Result< std::string > encodeGtsTerrainObj(const Heightmap &heightmap, GtsTerrainSaveResolution resolution, float sizeX, float sizeY, float sizeZ, GtsTerrainObjFaceMode faceMode)
Encode the original Pcg unmasked terrain OBJ coordinate, UV and face convention.
GtsTerrainColliderType
Collider representation requested by the export workflow.
GtsTerrainBakeLighting
Lighting state used while baking exported textures.
EVENGINE_API_DOMAINS Result< GtsTerrainExportLodSettings > makeGtsTerrainLowPolyLod(int level)
Construct the exact GTS low-poly preset for a zero-based LOD index.
EVENGINE_API_DOMAINS Result< std::string > encodeGtsMaskedTerrainObj(const Heightmap &heightmap, const Heightmap &maskmap, GtsTerrainSaveResolution resolution, float sizeX, float sizeY, float sizeZ, GtsTerrainObjFaceMode faceMode, float threshold=0.2f, bool invert=false)
Encode Pcg's cell-classified masked terrain OBJ convention.
EVENGINE_API_DOMAINS Result< GtsTerrainExportLodSettings > makeGtsTerrainImpostorLod(int level)
Construct the exact GTS impostor preset for a zero-based LOD index.
GtsTerrainExportSelection
Source selection scope used by a terrain export.
EVENGINE_API_DOMAINS Result< void > buildGtsTerrainColliderMeshFromHeightmapInto(MeshBuild &output, const Heightmap &heightmap, const GtsTerrainExportWorkflow &workflow, float sizeX, float sizeY, float sizeZ)
Build the independently sampled and simplified MeshCollider geometry requested by a workflow.
GtsSourceTerrainTreatment
Treatment applied to a source terrain after a successful conversion commit.
GtsTerrainTextureExportMethod
Texture source used by a terrain export level.
GtsTerrainLodMode
Purpose assigned to one exported terrain LOD.
EVENGINE_API_DOMAINS Result< int > bakeGtsTerrainVertexColorsInto(MeshBuild &output, const MeshBuild &source, const image::ImageData &bakedTexture, GtsTerrainNormalEdgeMode edgeMode, int smoothingIterations, float terrainSizeX, float terrainSizeZ, bool linearize=false)
Apply Pcg low-poly edge processing and baked texture vertex colors atomically.
EVENGINE_API_DOMAINS Result< void > buildGtsTerrainBaseMesh(MeshBuild &output, const Heightmap &heightmap, GtsTerrainSaveResolution resolution, float sizeX, float sizeY, float sizeZ)
Build the local-space base mesh consumed by the GTS split and LOD pipeline.
EVENGINE_API_DOMAINS std::vector< GtsTerrainLodLevelSettings > defaultGtsTerrainLodLevels()
Return the four-level quality and transition profile used by GTSMeshSettings.
EVENGINE_API_DOMAINS Result< std::vector< GtsTerrainLodAssetEntry > > planGtsTerrainLodAssets(const GtsTerrainLodSet &lods, const std::string &terrainName, const std::string &meshFolder="Meshes")
Build the deterministic object and mesh naming plan used by GTS terrain export.
EVENGINE_API_DOMAINS Result< void > planGtsTerrainLodAssetsInto(GtsTerrainLodAssetPlan &output, const GtsTerrainLodSet &lods, const std::string &terrainName, const std::string &meshFolder="Meshes")
Atomically replace a script-friendly export plan.
EVENGINE_API_DOMAINS Result< void > buildDefaultGtsTerrainLodsFromHeightmapInto(GtsTerrainLodSet &output, const Heightmap &heightmap, GtsTerrainSaveResolution resolution, float sizeX, float sizeY, float sizeZ, int subTileSplits, GtsMeshPivot pivot=GtsMeshPivot::None)
Atomically replace output with the complete default four-level GTS terrain conversion.
GtsTerrainNormalEdgeMode
Edge-normal treatment requested for an exported terrain mesh.
GtsTerrainObjFaceMode
Polygon representation written by the Pcg terrain OBJ exporter.
EVENGINE_API_DOMAINS Result< void > buildGtsTerrainLodsFromHeightmapInto(GtsTerrainLodSet &output, const Heightmap &heightmap, const GtsTerrainMeshSettings &settings, float sizeX, float sizeY, float sizeZ, GtsMeshPivot pivot=GtsMeshPivot::None)
Atomically build a complete heightmap conversion using persisted GTS mesh settings.
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Complete native counterpart of one GTSExportTerrainLODSettings record.
Result< void > validate() const
Validate all persisted and executable values in this record.
Result< GtsTerrainLodLevelSettings > compileLevel() const
Convert this export record to the sequential mesh-LOD contract.
Validated execution plan compiled from top-level Pcg terrain export controls.
Deterministic native export identity for one GTS tile LOD mesh.
Configuration for one sequential GTS terrain mesh LOD.
One split terrain tile and all of its local-space LOD meshes.
std::vector< MeshBuild > levels
glm::vec4 color