载入中...
搜索中...
未找到
BuildLayerStack.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <iomanip>
5#include <limits>
6#include <sstream>
7#include "common/Diagnostic.h"
8#include "procgen/MeshGraph.h"
10
11// BuildLayerStack.cpp
12namespace eve::procgen {
13namespace {
14
15std::string hexEncode(std::string_view value) {
16 constexpr char digits[] = "0123456789abcdef";
17 std::string output;
18 output.reserve(value.size() * 2);
19 for (const unsigned char byte : value) {
20 output.push_back(digits[byte >> 4U]);
21 output.push_back(digits[byte & 15U]);
22 }
23 return output;
24}
25
26Result<std::string> hexDecode(std::string_view value) {
27 if (value.size() % 2 != 0)
29 DiagnosticCode::ParseError, "odd embedded definition size", {}, {}, "procgen.buildLayers"));
30 const auto nibble = [](char c) -> int {
31 if (c >= '0' && c <= '9') return c - '0';
32 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
33 if (c >= 'A' && c <= 'F') return c - 'A' + 10;
34 return -1;
35 };
36 std::string output(value.size() / 2, '\0');
37 for (std::size_t index = 0; index < value.size(); index += 2) {
38 const int high = nibble(value[index]);
39 const int low = nibble(value[index + 1]);
40 if (high < 0 || low < 0)
42 DiagnosticCode::ParseError, "invalid embedded definition", {}, {}, "procgen.buildLayers"));
43 output[index / 2] = char((high << 4) | low);
44 }
45 return Result<std::string>::success(std::move(output));
46}
47
48} // namespace
49
50int BuildLayerExecution::getCount() const noexcept { return int(artifacts_.size()); }
51
52std::string BuildLayerExecution::getId(int index) const {
53 return index >= 0 && index < int(artifacts_.size()) ? artifacts_[std::size_t(index)].id : std::string();
54}
55
56std::string BuildLayerExecution::getType(int index) const {
57 if (index < 0 || index >= int(artifacts_.size())) return {};
58 return std::holds_alternative<MeshBuild>(artifacts_[std::size_t(index)].value) ? "mesh" : "points";
59}
60
62 if (index < 0 || index >= int(artifacts_.size()))
64 DiagnosticCode::InvalidArgument, "artifact index is out of range", {}, {}, "procgen.buildLayers"));
65 const auto* value = std::get_if<MeshBuild>(&artifacts_[std::size_t(index)].value);
66 if (!value)
68 Diagnostic::error(DiagnosticCode::TypeMismatch, "artifact is not a mesh", {}, {}, "procgen.buildLayers"));
70}
71
73 if (index < 0 || index >= int(artifacts_.size()))
75 DiagnosticCode::InvalidArgument, "artifact index is out of range", {}, {}, "procgen.buildLayers"));
76 const auto* value = std::get_if<PointSet>(&artifacts_[std::size_t(index)].value);
77 if (!value)
79 {}, {}, "procgen.buildLayers"));
81}
82
83bool BuildLayerStack::contains(std::string_view id) const {
84 for (const auto& layer : layers_)
85 if (layer.id == id) return true;
86 return false;
87}
88
89Result<void> BuildLayerStack::addTileLayer(std::string id, bool enabled, float cellSize, float height,
90 std::string group) {
91 if (id.empty())
93 Diagnostic::error(DiagnosticCode::InvalidArgument, "layer id is empty", {}, {}, "procgen.buildLayers"));
94 if (contains(id))
96 Diagnostic::error(DiagnosticCode::Conflict, "duplicate layer id", id, {}, "procgen.buildLayers"));
97 if (!std::isfinite(cellSize) || cellSize <= 0.f || !std::isfinite(height))
99 id, {}, "procgen.buildLayers"));
100 layers_.push_back({std::move(id), enabled, TileLayer{cellSize, height, std::move(group)}});
101 return Result<void>::success();
102}
103
105 if (id.empty())
107 Diagnostic::error(DiagnosticCode::InvalidArgument, "layer id is empty", {}, {}, "procgen.buildLayers"));
108 if (contains(id))
110 Diagnostic::error(DiagnosticCode::Conflict, "duplicate layer id", id, {}, "procgen.buildLayers"));
111 layers_.push_back({std::move(id), enabled, layer});
112 return Result<void>::success();
113}
114
116 for (auto& layer : layers_) {
117 if (layer.id != id) continue;
118 layer.enabled = enabled;
119 return Result<void>::success();
120 }
122 Diagnostic::error(DiagnosticCode::NotFound, "unknown layer", std::string(id), {}, "procgen.buildLayers"));
123}
124
125void BuildLayerStack::clear() { layers_.clear(); }
126int BuildLayerStack::getLayerCount() const noexcept { return int(layers_.size()); }
127
128std::string BuildLayerStack::getLayerId(int index) const {
129 return index >= 0 && index < int(layers_.size()) ? layers_[std::size_t(index)].id : std::string();
130}
131
132std::string BuildLayerStack::getLayerType(int index) const {
133 if (index < 0 || index >= int(layers_.size())) return {};
134 return std::holds_alternative<TileLayer>(layers_[std::size_t(index)].definition) ? "tiles" : "objects";
135}
136
137bool BuildLayerStack::isLayerEnabled(int index) const noexcept {
138 return index >= 0 && index < int(layers_.size()) && layers_[std::size_t(index)].enabled;
139}
140
142 const PointSet* orientation) const {
143 return executeRegion(grid, points,
144 {0, 0, grid.getWidth(), grid.getHeight(), -std::numeric_limits<float>::infinity(),
145 -std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity(),
146 std::numeric_limits<float>::infinity()},
147 orientation);
148}
149
152 const PointSet* orientation) const {
153 if (region.minCellX < 0 || region.minCellY < 0 || region.maxCellX < region.minCellX ||
154 region.maxCellY < region.minCellY || region.maxCellX > grid.getWidth() || region.maxCellY > grid.getHeight() ||
155 !(region.minWorldX < region.maxWorldX) || !(region.minWorldZ < region.maxWorldZ))
157 DiagnosticCode::InvalidArgument, "invalid build-layer region", {}, {}, "procgen.buildLayers"));
158 PointSet regionPoints;
159 regionPoints.reserve(points.points().size());
160 for (std::size_t index = 0; index < points.points().size(); ++index) {
161 const auto& point = points.points()[index];
162 if (point.x < region.minWorldX || point.x >= region.maxWorldX || point.z < region.minWorldZ ||
163 point.z >= region.maxWorldZ)
164 continue;
165 auto appended = regionPoints.appendPointFrom(points, index);
166 if (!appended.ok()) return Result<BuildLayerExecution>::failure(appended.status());
167 }
168 BuildLayerExecution execution;
169 execution.artifacts_.reserve(layers_.size());
170 for (const auto& layer : layers_) {
171 if (!layer.enabled) continue;
172 if (const auto* tile = std::get_if<TileLayer>(&layer.definition)) {
174 auto result = graph.addNode("grid", "grid.input");
175 if (result.ok()) result = graph.addNode("tiles", "mesh.grid_tiles");
176 if (result.ok()) result = graph.setNodeGrid("grid", grid);
177 if (result.ok()) result = graph.setNodeFloat("tiles", "cellSize", tile->cellSize);
178 if (result.ok()) result = graph.setNodeFloat("tiles", "height", tile->height);
179 if (result.ok()) result = graph.setNodeFloat("tiles", "minX", float(region.minCellX));
180 if (result.ok()) result = graph.setNodeFloat("tiles", "minY", float(region.minCellY));
181 if (result.ok()) result = graph.setNodeFloat("tiles", "maxX", float(region.maxCellX));
182 if (result.ok()) result = graph.setNodeFloat("tiles", "maxY", float(region.maxCellY));
183 if (result.ok()) result = graph.setNodeString("tiles", "group", tile->group);
184 if (result.ok()) result = graph.connect("grid", "tiles");
185 if (!result.ok()) return Result<BuildLayerExecution>::failure(result.status());
186 auto mesh = graph.execute("tiles");
187 if (!mesh.ok()) return Result<BuildLayerExecution>::failure(mesh.status());
188 execution.artifacts_.push_back({layer.id, std::move(mesh).takeValue()});
189 } else {
190 auto built = std::get<ObjectBuildLayer>(layer.definition).build(regionPoints, orientation);
191 if (!built.ok()) return Result<BuildLayerExecution>::failure(built.status());
192 execution.artifacts_.push_back({layer.id, std::move(built).takeValue()});
193 }
194 }
195 return Result<BuildLayerExecution>::success(std::move(execution));
196}
197
199 std::ostringstream out;
200 out << "EVPCG_BUILD_LAYERS 1\n" << std::setprecision(9);
201 for (const auto& layer : layers_) {
202 if (const auto* tile = std::get_if<TileLayer>(&layer.definition)) {
203 out << "TILE " << std::quoted(layer.id) << ' ' << int(layer.enabled) << ' ' << tile->cellSize << ' '
204 << tile->height << ' ' << std::quoted(tile->group) << '\n';
205 } else {
206 const auto& object = std::get<ObjectBuildLayer>(layer.definition);
207 out << "OBJECT " << std::quoted(layer.id) << ' ' << int(layer.enabled) << ' '
208 << hexEncode(object.serializeDefinition()) << '\n';
209 }
210 }
211 out << "END\n";
212 return out.str();
213}
214
216 BuildLayerStack replacement;
217 std::istringstream input{std::string(definition)};
218 std::string magic;
219 int version = 0;
220 if (!(input >> magic >> version) || magic != "EVPCG_BUILD_LAYERS" || version != 1)
222 Diagnostic::error(DiagnosticCode::ParseError, "invalid build-layer header", {}, {}, "procgen.buildLayers"));
223 std::string line;
224 std::getline(input, line);
225 bool ended = false;
226 while (std::getline(input, line)) {
227 if (line.empty()) continue;
228 std::istringstream record(line);
229 std::string kind;
230 record >> kind;
231 if (kind == "END") {
232 ended = true;
233 break;
234 }
235 std::string id;
236 int enabled = 0;
237 if (kind == "TILE") {
238 float cellSize = 0.f, height = 0.f;
239 std::string group;
240 if (!(record >> std::quoted(id) >> enabled >> cellSize >> height >> std::quoted(group)) ||
241 (enabled != 0 && enabled != 1))
243 {}, "procgen.buildLayers"));
244 auto applied = replacement.addTileLayer(std::move(id), enabled != 0, cellSize, height, std::move(group));
245 if (!applied.ok()) return applied;
246 } else if (kind == "OBJECT") {
247 std::string encoded;
248 if (!(record >> std::quoted(id) >> enabled >> encoded) || (enabled != 0 && enabled != 1))
249 return Result<void>::failure(Diagnostic::error(DiagnosticCode::ParseError, "invalid OBJECT record", {},
250 {}, "procgen.buildLayers"));
251 auto decoded = hexDecode(encoded);
252 if (!decoded.ok()) return Result<void>::failure(decoded.status());
254 auto applied = object.deserializeDefinition(decoded.value());
255 if (!applied.ok()) return applied;
256 auto added = replacement.addObjectLayer(std::move(id), enabled != 0, object);
257 if (!added.ok()) return added;
258 } else {
260 DiagnosticCode::ParseError, "unknown build-layer record: " + kind, {}, {}, "procgen.buildLayers"));
261 }
262 record >> std::ws;
263 if (!record.eof())
265 DiagnosticCode::ParseError, "trailing build-layer record data", {}, {}, "procgen.buildLayers"));
266 }
267 if (!ended)
268 return Result<void>::failure(Diagnostic::error(DiagnosticCode::ParseError, "build-layer END record is missing",
269 {}, {}, "procgen.buildLayers"));
270 *this = std::move(replacement);
271 return Result<void>::success();
272}
273
274} // namespace eve::procgen
275
276// ObjectBuildLayer.cpp
277namespace eve::procgen {
278namespace {
279
280bool finiteRange(float minimum, float maximum) {
281 return std::isfinite(minimum) && std::isfinite(maximum) && minimum <= maximum;
282}
283
284Result<void> validateRange(const ObjectTransformRange& range) {
285 if (!finiteRange(range.minPitch, range.maxPitch) || !finiteRange(range.minYaw, range.maxYaw) ||
286 !finiteRange(range.minRoll, range.maxRoll) || !finiteRange(range.minScaleX, range.maxScaleX) ||
287 !finiteRange(range.minScaleY, range.maxScaleY) || !finiteRange(range.minScaleZ, range.maxScaleZ))
289 "random transform ranges must be finite and ordered",
290 "transform", {}, "procgen.objectBuild"));
291 if (range.minScaleX == 0.f || range.maxScaleX == 0.f || range.minScaleY == 0.f || range.maxScaleY == 0.f ||
292 range.minScaleZ == 0.f || range.maxScaleZ == 0.f)
294 "random scale bounds must be non-zero", "transform.scale", {},
295 "procgen.objectBuild"));
296 return Result<void>::success();
297}
298
299std::uint64_t mix(std::uint64_t value) {
300 value += 0x9e3779b97f4a7c15ULL;
301 value = (value ^ (value >> 30U)) * 0xbf58476d1ce4e5b9ULL;
302 value = (value ^ (value >> 27U)) * 0x94d049bb133111ebULL;
303 return value ^ (value >> 31U);
304}
305
306struct RandomStream {
307 std::uint64_t state;
308 std::uint64_t next() {
309 state = mix(state);
310 return state;
311 }
312 float unit() { return float(next() >> 40U) * (1.f / 16777216.f); }
313 float between(float minimum, float maximum) { return minimum + (maximum - minimum) * unit(); }
314};
315
316std::uint64_t pointKey(const ProcgenPoint& point, std::size_t index, std::uint32_t seed) {
317 if (point.id != 0) return mix(point.id ^ (std::uint64_t(seed) << 32U));
318 const auto qx = std::int64_t(std::llround(double(point.x) * 1000.0));
319 const auto qy = std::int64_t(std::llround(double(point.y) * 1000.0));
320 const auto qz = std::int64_t(std::llround(double(point.z) * 1000.0));
321 return mix(std::uint64_t(qx) ^ (mix(std::uint64_t(qy)) << 1U) ^ (mix(std::uint64_t(qz)) << 2U) ^
322 std::uint64_t(index) ^ (std::uint64_t(seed) << 32U));
323}
324
325float orientedYaw(const ProcgenPoint& point, const PointSet& orientation, float cellSize, bool invert) {
326 struct Direction {
327 float x;
328 float z;
329 float yaw;
330 };
331 const Direction cardinal[] = {
332 {0.f, 1.f, invert ? 90.f : 270.f}, {1.f, 0.f, 0.f}, {0.f, -1.f, invert ? 270.f : 90.f}, {-1.f, 0.f, 180.f}};
333 const float tolerance = std::max(0.0001f, cellSize * 0.01f);
334 const auto matches = [&](float x, float z) {
335 return std::any_of(orientation.points().begin(), orientation.points().end(), [&](const ProcgenPoint& other) {
336 return std::abs(other.x - x) <= tolerance && std::abs(other.z - z) <= tolerance;
337 });
338 };
339 for (const auto& direction : cardinal)
340 if (matches(point.x + direction.x * cellSize, point.z + direction.z * cellSize)) return direction.yaw;
341 const Direction diagonal[] = {{1.f, 1.f, 90.f}, {1.f, -1.f, 0.f}, {-1.f, -1.f, 180.f}, {-1.f, 1.f, 180.f}};
342 for (const auto& direction : diagonal)
343 if (matches(point.x + direction.x * cellSize, point.z + direction.z * cellSize)) return direction.yaw;
344 return 0.f;
345}
346
347void applyRandomTransform(ProcgenPoint& point, const ObjectTransformRange& range, RandomStream& random) {
348 point.pitch += random.between(range.minPitch, range.maxPitch);
349 point.yaw += random.between(range.minYaw, range.maxYaw);
350 point.roll += random.between(range.minRoll, range.maxRoll);
351 if (range.uniformScale) {
352 const float scale = random.between(range.minScaleX, range.maxScaleX);
353 point.scaleX *= scale;
354 point.scaleY *= scale;
355 point.scaleZ *= scale;
356 } else {
357 point.scaleX *= random.between(range.minScaleX, range.maxScaleX);
358 point.scaleY *= random.between(range.minScaleY, range.maxScaleY);
359 point.scaleZ *= random.between(range.minScaleZ, range.maxScaleZ);
360 }
361}
362
363Result<void> tagPoint(PointSet& output, int index, const std::string& asset, std::string role, std::int64_t parent) {
364 auto result = output.trySetStringAttribute(index, "asset", asset);
365 if (!result.ok()) return result;
366 result = output.trySetStringAttribute(index, "object_role", role);
367 if (!result.ok()) return result;
368 return output.trySetIntAttribute(index, "parent_index", parent);
369}
370
371} // namespace
372
374 if (asset.empty())
376 {}, "procgen.objectBuild"));
377 if (!std::isfinite(weight) || weight <= 0.f)
379 "asset weight must be finite and positive", asset, {},
380 "procgen.objectBuild"));
381 assets_.push_back({std::move(asset), weight});
382 return Result<void>::success();
383}
384
385void ObjectBuildLayer::clearAssets() { assets_.clear(); }
386void ObjectBuildLayer::setSeed(std::uint32_t seed) noexcept { seed_ = seed == 0 ? 1 : seed; }
387void ObjectBuildLayer::setLayerOffset(float x, float y, float z) noexcept {
388 offsetX_ = x;
389 offsetY_ = y;
390 offsetZ_ = z;
391}
392
394 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z) || x == 0.f || y == 0.f || z == 0.f)
396 "layer scale must be finite and non-zero", "scale", {},
397 "procgen.objectBuild"));
398 scaleX_ = x;
399 scaleY_ = y;
400 scaleZ_ = z;
401 return Result<void>::success();
402}
403
405 if (!std::isfinite(radius) || radius < 0.f)
407 "position radius must be finite and non-negative", {}, {},
408 "procgen.objectBuild"));
409 positionRadius_ = radius;
410 return Result<void>::success();
411}
412
414 auto valid = validateRange(range);
415 if (!valid.ok()) return valid;
416 transform_ = range;
417 return Result<void>::success();
418}
419
420Result<void> ObjectBuildLayer::setRandomRotation(float minPitch, float maxPitch, float minYaw, float maxYaw,
421 float minRoll, float maxRoll) {
422 auto candidate = transform_;
423 candidate.minPitch = minPitch;
424 candidate.maxPitch = maxPitch;
425 candidate.minYaw = minYaw;
426 candidate.maxYaw = maxYaw;
427 candidate.minRoll = minRoll;
428 candidate.maxRoll = maxRoll;
429 return setRandomTransform(candidate);
430}
431
432Result<void> ObjectBuildLayer::setRandomScale(float minX, float maxX, float minY, float maxY, float minZ, float maxZ,
433 bool uniform) {
434 auto candidate = transform_;
435 candidate.minScaleX = minX;
436 candidate.maxScaleX = maxX;
437 candidate.minScaleY = minY;
438 candidate.maxScaleY = maxY;
439 candidate.minScaleZ = minZ;
440 candidate.maxScaleZ = maxZ;
441 candidate.uniformScale = uniform;
442 return setRandomTransform(candidate);
443}
444
445Result<void> ObjectBuildLayer::setOrientation(float cellSize, float yawOffset, bool invert) {
446 if (!std::isfinite(cellSize) || cellSize <= 0.f)
448 DiagnosticCode::InvalidArgument, "orientation cell size must be positive", {}, {}, "procgen.objectBuild"));
449 if (!std::isfinite(yawOffset))
451 DiagnosticCode::InvalidArgument, "orientation yaw offset must be finite", {}, {}, "procgen.objectBuild"));
452 orient_ = true;
453 orientationCellSize_ = cellSize;
454 orientationYawOffset_ = yawOffset;
455 invertOrientation_ = invert;
456 return Result<void>::success();
457}
458
459void ObjectBuildLayer::disableOrientation() noexcept { orient_ = false; }
460
461void ObjectBuildLayer::setPlaceOnTop(bool enabled, bool useLowest, float topOffset) noexcept {
462 placeOnTop_ = enabled;
463 useLowest_ = useLowest;
464 topOffset_ = std::isfinite(topOffset) ? topOffset : 0.f;
465}
466
469 if (asset.empty())
471 "child.asset", {}, "procgen.objectBuild"));
472 if (count < 0)
474 DiagnosticCode::InvalidArgument, "child count must be non-negative", asset, {}, "procgen.objectBuild"));
475 if (!std::isfinite(radius) || radius < 0.f)
477 "child radius must be finite and non-negative", asset, {},
478 "procgen.objectBuild"));
479 auto valid = validateRange(range);
480 if (!valid.ok()) return valid;
481 children_.push_back({std::move(asset), count, radius, range});
482 return Result<void>::success();
483}
484
485Result<void> ObjectBuildLayer::addChild(std::string asset, int count, float radius, float minScale, float maxScale,
486 float minYaw, float maxYaw) {
488 range.minScaleX = minScale;
489 range.maxScaleX = maxScale;
490 range.minScaleY = minScale;
491 range.maxScaleY = maxScale;
492 range.minScaleZ = minScale;
493 range.maxScaleZ = maxScale;
494 range.uniformScale = true;
495 range.minYaw = minYaw;
496 range.maxYaw = maxYaw;
497 return addChildRule(std::move(asset), count, radius, range);
498}
499
500void ObjectBuildLayer::clearChildRules() { children_.clear(); }
501
503 if (assets_.empty())
505 DiagnosticCode::InvalidArgument, "object build layer has no assets", "assets", {}, "procgen.objectBuild"));
506 if (orient_ && !orientation)
508 DiagnosticCode::InvalidArgument, "orientation is enabled but no orientation layer was supplied", {}, {},
509 "procgen.objectBuild"));
510 float totalWeight = 0.f;
511 for (const auto& asset : assets_) totalWeight += asset.weight;
512 if (!std::isfinite(totalWeight) || totalWeight <= 0.f)
514 DiagnosticCode::InvalidArgument, "total asset weight is invalid", {}, {}, "procgen.objectBuild"));
515
516 std::size_t childCount = 0;
517 for (const auto& child : children_) childCount += std::size_t(child.count);
519 output.reserve(source.points().size() * (childCount + 1));
520 for (std::size_t sourceIndex = 0; sourceIndex < source.points().size(); ++sourceIndex) {
521 const auto& input = source.points()[sourceIndex];
522 RandomStream random{pointKey(input, sourceIndex, seed_)};
523 float selection = random.unit() * totalWeight;
524 const Asset* selected = &assets_.back();
525 for (const auto& asset : assets_) {
526 selection -= asset.weight;
527 if (selection < 0.f) {
528 selected = &asset;
529 break;
530 }
531 }
532
533 auto appended = output.appendPointFrom(source, sourceIndex);
534 if (!appended.ok()) return Result<PointSet>::failure(appended.status());
535 const int parentIndex = appended.value();
536 auto& parent = output.mutablePoint(std::size_t(parentIndex));
537 if (positionRadius_ > 0.f) {
538 const float angle = random.unit() * 6.283185307179586f;
539 const float radius = std::sqrt(random.unit()) * positionRadius_;
540 parent.x += std::cos(angle) * radius;
541 parent.z += std::sin(angle) * radius;
542 }
543 parent.x += offsetX_;
544 parent.y += offsetY_;
545 parent.z += offsetZ_;
546 if (placeOnTop_) {
547 const char* attribute = useLowest_ ? "surface_lowest_y" : "surface_highest_y";
548 if (source.hasFloatAttribute(int(sourceIndex), attribute))
549 parent.y = source.getFloatAttribute(int(sourceIndex), attribute, parent.y) + topOffset_ + offsetY_;
550 }
551 applyRandomTransform(parent, transform_, random);
552 parent.scaleX *= scaleX_;
553 parent.scaleY *= scaleY_;
554 parent.scaleZ *= scaleZ_;
555 if (orient_)
556 parent.yaw = orientedYaw(input, *orientation, orientationCellSize_, invertOrientation_) +
557 orientationYawOffset_ + random.between(transform_.minYaw, transform_.maxYaw);
558 auto tagged = tagPoint(output, parentIndex, selected->id, "parent", -1);
559 if (!tagged.ok()) return Result<PointSet>::failure(tagged.status());
560
561 for (std::size_t ruleIndex = 0; ruleIndex < children_.size(); ++ruleIndex) {
562 const auto& rule = children_[ruleIndex];
563 RandomStream childRandom{mix(pointKey(input, sourceIndex, seed_) ^ (std::uint64_t(ruleIndex + 1) << 32U))};
564 for (int childOrdinal = 0; childOrdinal < rule.count; ++childOrdinal) {
565 ProcgenPoint child = parent;
566 child.id = derivePointId(parent.id != 0 ? parent.id : pointKey(input, sourceIndex, seed_),
567 std::uint64_t(ruleIndex) * 1000000ULL + std::uint64_t(childOrdinal + 1));
568 const float angle = childRandom.unit() * 6.283185307179586f;
569 const float radius = std::sqrt(childRandom.unit()) * rule.radius;
570 child.x += std::cos(angle) * radius;
571 child.z += std::sin(angle) * radius;
572 child.pitch = 0.f;
573 child.yaw = 0.f;
574 child.roll = 0.f;
575 child.scaleX = 1.f;
576 child.scaleY = 1.f;
577 child.scaleZ = 1.f;
578 applyRandomTransform(child, rule.transform, childRandom);
579 const int childIndex = output.appendPoint(child);
580 tagged = tagPoint(output, childIndex, rule.asset, "child", parentIndex);
581 if (!tagged.ok()) return Result<PointSet>::failure(tagged.status());
582 }
583 }
584 }
585 return Result<PointSet>::success(std::move(output));
586}
587
589 std::ostringstream out;
590 out << "EVPCG_OBJECT_LAYER 1\n" << std::setprecision(9);
591 out << "SEED " << seed_ << '\n';
592 out << "OFFSET " << offsetX_ << ' ' << offsetY_ << ' ' << offsetZ_ << '\n';
593 out << "SCALE " << scaleX_ << ' ' << scaleY_ << ' ' << scaleZ_ << '\n';
594 out << "POSITION_RADIUS " << positionRadius_ << '\n';
595 out << "RANDOM " << transform_.minPitch << ' ' << transform_.maxPitch << ' ' << transform_.minYaw << ' '
596 << transform_.maxYaw << ' ' << transform_.minRoll << ' ' << transform_.maxRoll << ' ' << transform_.minScaleX
597 << ' ' << transform_.maxScaleX << ' ' << transform_.minScaleY << ' ' << transform_.maxScaleY << ' '
598 << transform_.minScaleZ << ' ' << transform_.maxScaleZ << ' ' << int(transform_.uniformScale) << '\n';
599 out << "ORIENTATION " << int(orient_) << ' ' << orientationCellSize_ << ' ' << orientationYawOffset_ << ' '
600 << int(invertOrientation_) << '\n';
601 out << "PLACE " << int(placeOnTop_) << ' ' << int(useLowest_) << ' ' << topOffset_ << '\n';
602 for (const auto& asset : assets_) out << "ASSET " << std::quoted(asset.id) << ' ' << asset.weight << '\n';
603 for (const auto& child : children_) {
604 const auto& t = child.transform;
605 out << "CHILD " << std::quoted(child.asset) << ' ' << child.count << ' ' << child.radius << ' ' << t.minPitch
606 << ' ' << t.maxPitch << ' ' << t.minYaw << ' ' << t.maxYaw << ' ' << t.minRoll << ' ' << t.maxRoll << ' '
607 << t.minScaleX << ' ' << t.maxScaleX << ' ' << t.minScaleY << ' ' << t.maxScaleY << ' ' << t.minScaleZ
608 << ' ' << t.maxScaleZ << ' ' << int(t.uniformScale) << '\n';
609 }
610 out << "END\n";
611 return out.str();
612}
613
615 ObjectBuildLayer replacement;
616 std::istringstream input{std::string(definition)};
617 std::string magic;
618 int version = 0;
619 if (!(input >> magic >> version) || magic != "EVPCG_OBJECT_LAYER" || version != 1)
620 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "invalid object layer header",
621 {}, {}, "procgen.objectBuild"));
622 std::string line;
623 std::getline(input, line);
624 bool ended = false;
625 while (std::getline(input, line)) {
626 if (line.empty()) continue;
627 std::istringstream record(line);
628 std::string kind;
629 record >> kind;
630 if (kind == "END") {
631 ended = true;
632 break;
633 }
634 if (kind == "SEED") {
635 std::uint32_t seed = 0;
636 if (!(record >> seed))
638 {}, {}, "procgen.objectBuild"));
639 replacement.setSeed(seed);
640 } else if (kind == "OFFSET") {
641 float x = 0.f, y = 0.f, z = 0.f;
642 if (!(record >> x >> y >> z) || !std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
644 {}, {}, "procgen.objectBuild"));
645 replacement.setLayerOffset(x, y, z);
646 } else if (kind == "SCALE") {
647 float x = 0.f, y = 0.f, z = 0.f;
648 if (!(record >> x >> y >> z))
650 {}, {}, "procgen.objectBuild"));
651 auto applied = replacement.setLayerScale(x, y, z);
652 if (!applied.ok()) return applied;
653 } else if (kind == "POSITION_RADIUS") {
654 float radius = 0.f;
655 if (!(record >> radius))
657 DiagnosticCode::InvalidArgument, "invalid POSITION_RADIUS record", {}, {}, "procgen.objectBuild"));
658 auto applied = replacement.setPositionRadius(radius);
659 if (!applied.ok()) return applied;
660 } else if (kind == "RANDOM") {
662 int uniform = 0;
663 if (!(record >> range.minPitch >> range.maxPitch >> range.minYaw >> range.maxYaw >> range.minRoll >>
664 range.maxRoll >> range.minScaleX >> range.maxScaleX >> range.minScaleY >> range.maxScaleY >>
665 range.minScaleZ >> range.maxScaleZ >> uniform) ||
666 (uniform != 0 && uniform != 1))
668 {}, {}, "procgen.objectBuild"));
669 range.uniformScale = uniform != 0;
670 auto applied = replacement.setRandomTransform(range);
671 if (!applied.ok()) return applied;
672 } else if (kind == "ORIENTATION") {
673 int enabled = 0, invert = 0;
674 float cell = 0.f, offset = 0.f;
675 if (!(record >> enabled >> cell >> offset >> invert) || (enabled != 0 && enabled != 1) ||
676 (invert != 0 && invert != 1))
678 DiagnosticCode::InvalidArgument, "invalid ORIENTATION record", {}, {}, "procgen.objectBuild"));
679 if (enabled) {
680 auto applied = replacement.setOrientation(cell, offset, invert != 0);
681 if (!applied.ok()) return applied;
682 }
683 } else if (kind == "PLACE") {
684 int enabled = 0, lowest = 0;
685 float offset = 0.f;
686 if (!(record >> enabled >> lowest >> offset) || (enabled != 0 && enabled != 1) ||
687 (lowest != 0 && lowest != 1) || !std::isfinite(offset))
689 {}, {}, "procgen.objectBuild"));
690 replacement.setPlaceOnTop(enabled != 0, lowest != 0, offset);
691 } else if (kind == "ASSET") {
692 std::string asset;
693 float weight = 0.f;
694 if (!(record >> std::quoted(asset) >> weight))
696 {}, {}, "procgen.objectBuild"));
697 auto applied = replacement.addAsset(std::move(asset), weight);
698 if (!applied.ok()) return applied;
699 } else if (kind == "CHILD") {
700 std::string asset;
701 int count = 0, uniform = 0;
702 float radius = 0.f;
704 if (!(record >> std::quoted(asset) >> count >> radius >> range.minPitch >> range.maxPitch >> range.minYaw >>
705 range.maxYaw >> range.minRoll >> range.maxRoll >> range.minScaleX >> range.maxScaleX >>
706 range.minScaleY >> range.maxScaleY >> range.minScaleZ >> range.maxScaleZ >> uniform) ||
707 (uniform != 0 && uniform != 1))
709 {}, {}, "procgen.objectBuild"));
710 range.uniformScale = uniform != 0;
711 auto applied = replacement.addChildRule(std::move(asset), count, radius, range);
712 if (!applied.ok()) return applied;
713 } else {
715 "unknown object layer record: " + kind, {}, {},
716 "procgen.objectBuild"));
717 }
718 record >> std::ws;
719 if (!record.eof())
721 DiagnosticCode::InvalidArgument, "trailing object layer record data", {}, {}, "procgen.objectBuild"));
722 }
723 if (!ended)
725 DiagnosticCode::InvalidArgument, "object layer END record is missing", {}, {}, "procgen.objectBuild"));
726 *this = std::move(replacement);
727 return Result<void>::success();
728}
729
730} // namespace eve::procgen
double z
double y
double x
std::string selected
std::string output
float yaw
Definition BushMesh.cpp:37
Stable, structured diagnostics shared by engine modules.
ScriptComponentRecord record
Definition ECS.cpp:228
EvpackChunkInput input
Definition Evpack.cpp:170
ScriptFieldRegion region
float maximum[3]
float minimum[3]
std::int32_t c
std::uint32_t height
const ColourScope * parent
size_t offset
Range range
std::array< float, 3 > scale
std::string id
Poco::JSON::Object::Ptr result
bool ended
bool valid
double radius
Definition MeleeHit.cpp:42
OceanMeshSettings mesh
std::map< std::string, std::vector< std::string > > graph
Definition Package.cpp:173
bool diagonal
TileLayer * layer
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
float t
std::string attribute
RoadLaneDirection direction
unsigned line
ScriptStructure out
std::string_view source
std::string kind
int count
AbilityActivationGroup group
Cell cell
TacticalUnit * unit
Battle::Random random
Json object
uint32_t seed
Definition TreeMesh.cpp:276
float size
Definition TreeMesh.cpp:158
double weight
uint32_t index
glm::vec3 point
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
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Immutable-by-convention result of one complete build-stack execution.
int getCount() const noexcept
Returns the count.
std::string getType(int index) const
Returns the type.
Result< PointSet > getPoints(int index) const
Copy a point artifact, or return a typed failure for a bad index/type.
Result< MeshBuild > getMesh(int index) const
Copy a mesh artifact, or return a typed failure for a bad index/type.
std::string getId(int index) const
Returns the id.
Ordered, versioned executor for procedural tile and object build layers.
Result< BuildLayerExecution > execute(const Grid2D &grid, const PointSet &points, const PointSet *orientation=nullptr) const
Execute every enabled layer in stable insertion order.
Result< void > setEnabled(std::string_view id, bool enabled)
std::string serializeDefinition() const
Serialize ordered definitions using EVPCG_BUILD_LAYERS schema version 1.
bool isLayerEnabled(int index) const noexcept
True when layer enabled.
Result< void > addObjectLayer(std::string id, bool enabled, const ObjectBuildLayer &layer)
Append an object layer by value. Layer ids are unique.
int getLayerCount() const noexcept
Returns the layer count.
Result< void > addTileLayer(std::string id, bool enabled, float cellSize, float height, std::string group)
Append a grid-to-mesh tile layer. Layer ids are unique.
std::string getLayerId(int index) const
Returns the layer id.
std::string getLayerType(int index) const
Returns the layer type.
Result< void > deserializeDefinition(std::string_view definition)
Atomically restore version 1; unknown fields and malformed embedded layers are rejected.
Result< BuildLayerExecution > executeRegion(const Grid2D &grid, const PointSet &points, const BuildLayerRegion &region, const PointSet *orientation=nullptr) const
Execute enabled layers for one half-open cluster region.
Intermediate 2D generation result. cells store semantic ids (see Semantic.h), not tile GIDs — convert...
Definition Grid2D.h:37
Typed procedural mesh graph composing grid, point and topology domains.
Definition MeshGraph.h:22
Result< void > addNode(std::string id, std::string operation)
Adds node.
Deterministic TileWorldCreator-style object build layer.
Result< void > setOrientation(float cellSize, float yawOffset, bool invert)
Enable orientation toward the first matching N/E/S/W then diagonal orientation point.
Result< void > deserializeDefinition(std::string_view definition)
Atomically replace settings from schema version 1; unknown records are rejected.
Result< void > setRandomTransform(const ObjectTransformRange &range)
Configure independent random Euler and scale intervals for parent objects.
Result< void > addChildRule(std::string asset, int count, float radius, const ObjectTransformRange &range)
Add a child-spawn rule with its own deterministic transform stream.
Result< void > addAsset(std::string asset, float weight)
Add a weighted asset candidate. Zero and negative weights are rejected.
std::string serializeDefinition() const
Serialize all layer settings using the versioned EVPCG object-layer schema.
Result< void > setLayerScale(float x, float y, float z)
Set fixed component-wise scale multiplier. Values must be non-zero.
void setPlaceOnTop(bool enabled, bool useLowest, float topOffset) noexcept
Project output Y to surface_lowest_y or surface_highest_y, plus offset, when present.
void setLayerOffset(float x, float y, float z) noexcept
Set fixed layer translation applied after source transforms.
Result< PointSet > build(const PointSet &source, const PointSet *orientation=nullptr) const
Build attributed object points from source points.
Result< void > setRandomScale(float minX, float maxX, float minY, float maxY, float minZ, float maxZ, bool uniform)
Update only the parent scale randomization interval.
void clearChildRules()
Clears child rules.
Result< void > addChild(std::string asset, int count, float radius, float minScale, float maxScale, float minYaw, float maxYaw)
Script-friendly child rule using uniform scale and yaw ranges.
Result< void > setPositionRadius(float radius)
Set circular XZ position jitter radius.
void setSeed(std::uint32_t seed) noexcept
Set the named deterministic random stream seed.
Result< void > setRandomRotation(float minPitch, float maxPitch, float minYaw, float maxYaw, float minRoll, float maxRoll)
Update only the parent Euler randomization interval.
Script-friendly collection of attributed 3D samples.
Definition PointSet.h:59
Result< int > appendPointFrom(const PointSet &source, std::size_t sourceIndex)
Append a point and its attributes from another set.
Definition PointSet.cpp:70
void reserve(std::size_t count)
Reserve point storage without changing point or attribute row counts.
Definition PointSet.cpp:61
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
std::uint64_t derivePointId(std::uint64_t namespaceId, std::uint64_t ordinal)
Deterministically derive a non-zero stable point identity.
Definition PointSet.cpp:470
@ TypeMismatch
A stable reference resolved to a different canonical domain type.
bool enabled
Half-open grid and world-space bounds used for one incremental cluster build.
Random transform interval used by one object build rule.
One deterministic sample used by script-first procedural pipelines.
Definition PointSet.h:17