载入中...
搜索中...
未找到
GeneratedArtifact.cpp
浏览该文件的文档.
3#include "common/ValueRead.h"
5
6
7#include <algorithm>
8#include <array>
9#include <charconv>
10#include <cmath>
11#include <limits>
12#include <memory>
13#include <type_traits>
14#include <unordered_map>
15#include <unordered_set>
16#include <utility>
17
18namespace eve::procgen {
19namespace {
20
21#include "procgen/GeneratedArtifactDiagnostics.inc"
22
23bool typeMatches(ArtifactType type, const ArtifactLeafPayload &payload) noexcept {
24 switch (type) {
25 case ArtifactType::Grid: return std::holds_alternative<Grid2D>(payload);
26 case ArtifactType::PointSet: return std::holds_alternative<PointSet>(payload);
27 case ArtifactType::MeshData: return std::holds_alternative<MeshData>(payload);
28 case ArtifactType::ImageData: return std::holds_alternative<ImageData>(payload);
29 case ArtifactType::Collider: return std::holds_alternative<Collider>(payload);
30 case ArtifactType::Composite: return false;
31 }
32 return false;
33}
34
35bool typeMatches(ArtifactType type, const GeneratedArtifact::Payload &payload) noexcept {
36 return type == artifactType(payload);
37}
38
39bool finiteBounds(const Bounds &bounds) noexcept {
40 return bounds.valid && std::isfinite(bounds.minX) && std::isfinite(bounds.minY) && std::isfinite(bounds.minZ) &&
41 std::isfinite(bounds.maxX) && std::isfinite(bounds.maxY) && std::isfinite(bounds.maxZ) &&
42 bounds.minX <= bounds.maxX && bounds.minY <= bounds.maxY && bounds.minZ <= bounds.maxZ;
43}
44
45
46bool validLeaf(ArtifactType type, const ArtifactLeafPayload &payload) noexcept {
47 if (!typeMatches(type, payload)) return false;
48 return std::visit(
49 [](const auto &value) {
50 using T = std::decay_t<decltype(value)>;
51 if constexpr (std::is_same_v<T, Grid2D>)
52 return value.getWidth() > 0 && value.getHeight() > 0;
53 else if constexpr (std::is_same_v<T, PointSet>)
54 return !value.points().empty() &&
55 std::all_of(value.points().begin(), value.points().end(), [](const auto &point) {
56 return std::isfinite(point.x) && std::isfinite(point.y) && std::isfinite(point.z);
57 });
58 else if constexpr (std::is_same_v<T, MeshData>)
60 else
61 return value.isValid();
62 },
63 payload);
64}
65
66bool validDependencies(ArtifactId self, const std::vector<ArtifactId> &dependencies) {
67 std::unordered_set<ArtifactId> seen;
68 for (ArtifactId dependency : dependencies) {
69 if (dependency.isNil() || dependency == self || !seen.emplace(dependency).second) return false;
70 }
71 return true;
72}
73
74bool validPart(const ArtifactPart &part) {
75 return !part.role.empty() && !part.id.isNil() && !part.schemaVersion.isZero() && !part.buildKey.empty() &&
76 finiteBounds(part.bounds) && validDependencies(part.id, part.dependencies) &&
77 validLeaf(part.type, part.payload);
78}
79
80bool validArtifact(const GeneratedArtifact &artifact) {
81 if (artifact.id.isNil() || artifact.schemaVersion.isZero() || artifact.buildKey.empty() ||
82 !finiteBounds(artifact.bounds) || !validDependencies(artifact.id, artifact.dependencies) ||
83 !typeMatches(artifact.type, artifact.payload))
84 return false;
85 if (artifact.type != ArtifactType::Composite) {
86 return std::visit(
87 [&](const auto &value) {
88 using T = std::decay_t<decltype(value)>;
89 if constexpr (std::is_same_v<T, CompositeArtifact>)
90 return false;
91 else
92 return validLeaf(artifact.type, ArtifactLeafPayload(value));
93 },
94 artifact.payload);
95 }
96 const auto &composite = std::get<CompositeArtifact>(artifact.payload);
97 if (composite.children.empty()) return false;
98 std::unordered_set<ArtifactId> identities;
99 std::unordered_set<std::string> roles;
100 for (const ArtifactPart &child : composite.children) {
101 if (child.id == artifact.id || !validPart(child) || !identities.emplace(child.id).second ||
102 !roles.emplace(child.role).second)
103 return false;
104 }
105 return true;
106}
107
108eve::Result<void> validateBatchAgainstStore(const ArtifactStore &store,
109 const std::vector<GeneratedArtifact> &artifacts) {
110 if (artifacts.empty())
112 eve::DiagnosticCode::InvalidArgument, "artifact publish batch must not be empty", "artifacts"));
113
114 std::unordered_map<ArtifactId, ArtifactType> batch;
115 batch.reserve(artifacts.size() * 5u);
116 for (const GeneratedArtifact &artifact : artifacts) {
117 if (!validArtifact(artifact))
119 eve::DiagnosticCode::InvalidArgument, "artifact structure or typed payload is invalid", "artifact"));
120 if (store.typeOf(artifact.id).has_value() || !batch.emplace(artifact.id, artifact.type).second)
122 eve::DiagnosticCode::Conflict, "artifact identity is already published", "artifact.id"));
123 if (artifact.type == ArtifactType::Composite) {
124 for (const ArtifactPart &part : std::get<CompositeArtifact>(artifact.payload).children) {
125 if (store.typeOf(part.id).has_value() || !batch.emplace(part.id, part.type).second)
127 eve::DiagnosticCode::Conflict, "composite part identity conflicts", "artifact.children.id"));
128 }
129 }
130 }
131
132 const auto typeFor = [&store, &batch](ArtifactId id) -> std::optional<ArtifactType> {
133 const auto inBatch = batch.find(id);
134 if (inBatch != batch.end()) return inBatch->second;
135 return store.typeOf(id);
136 };
137 const auto checkDependencies =
138 [&typeFor](ArtifactType type, const std::vector<ArtifactId> &dependencies) -> std::optional<eve::Diagnostic> {
139 bool meshDependency = false;
140 for (ArtifactId dependency : dependencies) {
141 const auto found = typeFor(dependency);
142 if (!found)
144 "artifact dependency is not published or in batch",
145 "artifact.dependencies");
146 meshDependency = meshDependency || *found == ArtifactType::MeshData;
147 }
148 if (type == ArtifactType::Collider && !meshDependency)
150 "collider must depend on a mesh artifact", "artifact.dependencies");
151 return std::nullopt;
152 };
153 for (const GeneratedArtifact &artifact : artifacts) {
154 if (auto error = checkDependencies(artifact.type, artifact.dependencies))
155 return eve::Result<void>::failure(std::move(*error));
156 if (artifact.type == ArtifactType::Composite) {
157 for (const ArtifactPart &part : std::get<CompositeArtifact>(artifact.payload).children) {
158 if (auto error = checkDependencies(part.type, part.dependencies))
159 return eve::Result<void>::failure(std::move(*error));
160 }
161 }
162 }
164}
165
166const eve::Value *stateMember(const eve::Value::Object &object, const char *name) noexcept {
167 const auto found = object.find(name);
168 return found == object.end() ? nullptr : &found->second;
169}
170
171eve::Value encodeFloatArray(const std::vector<float> &values) {
173 result.reserve(values.size());
174 for (const float value : values) result.emplace_back(value);
175 return eve::Value(std::move(result));
176}
177
178eve::Value encodeUInt32Array(const std::vector<std::uint32_t> &values) {
180 result.reserve(values.size());
181 for (const std::uint32_t value : values) result.emplace_back(std::int64_t(value));
182 return eve::Value(std::move(result));
183}
184
185eve::Value encodeUInt8Array(const std::vector<std::uint8_t> &values) {
187 result.reserve(values.size());
188 for (const std::uint8_t value : values) result.emplace_back(std::int64_t(value));
189 return eve::Value(std::move(result));
190}
191
192eve::Value encodeIntArray(const std::vector<int> &values) {
194 result.reserve(values.size());
195 for (const int value : values) result.emplace_back(std::int64_t(value));
196 return eve::Value(std::move(result));
197}
198
199eve::Value encodeBounds(const Bounds &bounds) {
201 result.emplace("minX", eve::Value(bounds.minX));
202 result.emplace("minY", eve::Value(bounds.minY));
203 result.emplace("minZ", eve::Value(bounds.minZ));
204 result.emplace("maxX", eve::Value(bounds.maxX));
205 result.emplace("maxY", eve::Value(bounds.maxY));
206 result.emplace("maxZ", eve::Value(bounds.maxZ));
207 result.emplace("valid", eve::Value(bounds.valid));
208 return eve::Value(std::move(result));
209}
210
211eve::Value encodeMetadata(const eve::Value::Object &metadata) { return eve::Value(metadata); }
212
213eve::Value encodeDependencies(const std::vector<ArtifactId> &dependencies) {
215 result.reserve(dependencies.size());
216 for (const ArtifactId dependency : dependencies) result.emplace_back(dependency.format());
217 return eve::Value(std::move(result));
218}
219
220eve::Value encodeStringMap(const std::unordered_map<std::string, std::string> &values) {
222 for (const auto &[key, value] : values) result.emplace(key, eve::Value(value));
223 return eve::Value(std::move(result));
224}
225
226eve::Value encodeFloatMap(const std::unordered_map<std::string, float> &values) {
228 for (const auto &[key, value] : values) result.emplace(key, eve::Value(value));
229 return eve::Value(std::move(result));
230}
231
232eve::Value encodeIntMap(const std::unordered_map<std::string, std::int64_t> &values) {
234 for (const auto &[key, value] : values) result.emplace(key, eve::Value(value));
235 return eve::Value(std::move(result));
236}
237
238eve::Value encodeBoolMap(const std::unordered_map<std::string, bool> &values) {
240 for (const auto &[key, value] : values) result.emplace(key, eve::Value(value));
241 return eve::Value(std::move(result));
242}
243
244eve::Value encodeVectorMap(const std::unordered_map<std::string, ProcgenAttributeVector> &values) {
246 for (const auto &[key, value] : values) {
248 result.emplace(key, eve::Value(std::move(encoded)));
249 }
250 return eve::Value(std::move(result));
251}
252
253eve::Value encodeGrid(const Grid2D &grid) {
255 result.emplace("width", eve::Value(grid.getWidth()));
256 result.emplace("height", eve::Value(grid.getHeight()));
257 result.emplace("cells", encodeUInt32Array(grid.cells()));
258 result.emplace("detail", encodeUInt8Array(grid.detail()));
259 result.emplace("metadata", encodeStringMap(grid.metadata()));
261 objects.reserve(grid.objects().size());
262 for (const GridObject &object : grid.objects()) {
263 eve::Value::Object encoded;
264 encoded.emplace("name", eve::Value(object.name));
265 encoded.emplace("type", eve::Value(object.type));
266 encoded.emplace("x", eve::Value(object.x));
267 encoded.emplace("y", eve::Value(object.y));
268 encoded.emplace("width", eve::Value(object.width));
269 encoded.emplace("height", eve::Value(object.height));
270 encoded.emplace("gid", eve::Value(std::int64_t(object.gid)));
271 objects.emplace_back(std::move(encoded));
272 }
273 result.emplace("objects", eve::Value(std::move(objects)));
274 return eve::Value(std::move(result));
275}
276
277eve::Value encodePointSet(const PointSet &points) {
279 eve::Value::Array encodedPoints;
280 encodedPoints.reserve(points.points().size());
281 for (std::size_t index = 0; index < points.points().size(); ++index) {
282 const ProcgenPoint& point = points.points()[index];
283 eve::Value::Object encoded;
284 encoded.emplace("x", eve::Value(point.x));
285 encoded.emplace("y", eve::Value(point.y));
286 encoded.emplace("z", eve::Value(point.z));
287 encoded.emplace("normalX", eve::Value(point.normalX));
288 encoded.emplace("normalY", eve::Value(point.normalY));
289 encoded.emplace("normalZ", eve::Value(point.normalZ));
290 encoded.emplace("pitch", eve::Value(point.pitch));
291 encoded.emplace("yaw", eve::Value(point.yaw));
292 encoded.emplace("roll", eve::Value(point.roll));
293 encoded.emplace("scaleX", eve::Value(point.scaleX));
294 encoded.emplace("scaleY", eve::Value(point.scaleY));
295 encoded.emplace("scaleZ", eve::Value(point.scaleZ));
296 encoded.emplace("density", eve::Value(point.density));
297 encoded.emplace("seed", eve::Value(std::int64_t(point.seed)));
298 encoded.emplace("id", eve::Value(std::to_string(point.id)));
299 encoded.emplace("boundsMinX", eve::Value(point.boundsMinX));
300 encoded.emplace("boundsMinY", eve::Value(point.boundsMinY));
301 encoded.emplace("boundsMinZ", eve::Value(point.boundsMinZ));
302 encoded.emplace("boundsMaxX", eve::Value(point.boundsMaxX));
303 encoded.emplace("boundsMaxY", eve::Value(point.boundsMaxY));
304 encoded.emplace("boundsMaxZ", eve::Value(point.boundsMaxZ));
305 encoded.emplace("colorR", eve::Value(point.colorR));
306 encoded.emplace("colorG", eve::Value(point.colorG));
307 encoded.emplace("colorB", eve::Value(point.colorB));
308 encoded.emplace("colorA", eve::Value(point.colorA));
309 encoded.emplace("steepness", eve::Value(point.steepness));
310 eve::Value::Object floatAttributes;
311 eve::Value::Object intAttributes;
312 eve::Value::Object boolAttributes;
313 eve::Value::Object vectorAttributes;
314 eve::Value::Object stringAttributes;
315 for (std::size_t column = 0; column < points.attributes().columnCount(); ++column) {
316 const std::string name(points.attributes().columnName(column));
317 if (!points.attributes().has(index, name)) continue;
318 switch (*points.attributes().typeOf(name)) {
320 floatAttributes.emplace(name, eve::Value(*points.attributes().getFloat(index, name)));
321 break;
323 intAttributes.emplace(name, eve::Value(*points.attributes().getInt(index, name)));
324 break;
326 boolAttributes.emplace(name, eve::Value(*points.attributes().getBool(index, name)));
327 break;
329 const auto value = *points.attributes().getVector(index, name);
331 vectorAttributes.emplace(name, eve::Value(std::move(components)));
332 break;
333 }
335 stringAttributes.emplace(name,
336 eve::Value(std::string(*points.attributes().getString(index, name))));
337 break;
338 }
339 }
340 encoded.emplace("floatAttributes", eve::Value(std::move(floatAttributes)));
341 encoded.emplace("intAttributes", eve::Value(std::move(intAttributes)));
342 encoded.emplace("boolAttributes", eve::Value(std::move(boolAttributes)));
343 encoded.emplace("vectorAttributes", eve::Value(std::move(vectorAttributes)));
344 encoded.emplace("stringAttributes", eve::Value(std::move(stringAttributes)));
345 encodedPoints.emplace_back(std::move(encoded));
346 }
347 result.emplace("points", eve::Value(std::move(encodedPoints)));
348 return eve::Value(std::move(result));
349}
350
351
352eve::Value encodeImage(const ImageData &image) {
354 result.emplace("width", eve::Value(image.width));
355 result.emplace("height", eve::Value(image.height));
356 result.emplace("channels", eve::Value(image.channels));
357 result.emplace("format", eve::Value(image.format));
358 result.emplace("pixels", encodeUInt8Array(image.pixels));
359 return eve::Value(std::move(result));
360}
361
362eve::Value encodeCollider(const Collider &collider) {
364 result.emplace("vertices", encodeFloatArray(collider.vertices));
365 result.emplace("indices", encodeUInt32Array(collider.indices));
366 result.emplace("bounds", encodeBounds(collider.bounds));
367 result.emplace("shape", eve::Value(collider.shape));
368 return eve::Value(std::move(result));
369}
370
371eve::Value encodeLeafPayload(ArtifactType type, const ArtifactLeafPayload &payload) {
373 result.emplace("kind", eve::Value(artifactTypeName(type)));
374 result.emplace("data", std::visit(
375 [](const auto &value) -> eve::Value {
376 using T = std::decay_t<decltype(value)>;
377 if constexpr (std::is_same_v<T, Grid2D>)
378 return encodeGrid(value);
379 else if constexpr (std::is_same_v<T, PointSet>)
380 return encodePointSet(value);
381 else if constexpr (std::is_same_v<T, MeshData>)
383 else if constexpr (std::is_same_v<T, ImageData>)
384 return encodeImage(value);
385 else if constexpr (std::is_same_v<T, Collider>)
386 return encodeCollider(value);
387 else {
388 static_assert(std::is_same_v<T, void>, "unhandled artifact leaf payload");
389 return eve::Value{};
390 }
391 },
392 payload));
393 return eve::Value(std::move(result));
394}
395
396eve::Value encodePart(const ArtifactPart &part) {
398 result.emplace("role", eve::Value(part.role));
399 result.emplace("artifactId", eve::Value(part.id.format()));
400 result.emplace("type", eve::Value(artifactTypeName(part.type)));
401 result.emplace("schemaVersion", eve::Value(std::to_string(part.schemaVersion.value())));
402 result.emplace("buildKey", eve::Value(part.buildKey.format()));
403 result.emplace("bounds", encodeBounds(part.bounds));
404 result.emplace("dependencies", encodeDependencies(part.dependencies));
405 result.emplace("metadata", encodeMetadata(part.metadata));
406 result.emplace("payload", encodeLeafPayload(part.type, part.payload));
407 return eve::Value(std::move(result));
408}
409
410eve::Value encodeArtifact(const GeneratedArtifact &artifact) {
412 result.emplace("artifactId", eve::Value(artifact.id.format()));
413 result.emplace("type", eve::Value(artifactTypeName(artifact.type)));
414 result.emplace("schemaVersion", eve::Value(std::to_string(artifact.schemaVersion.value())));
415 result.emplace("buildKey", eve::Value(artifact.buildKey.format()));
416 result.emplace("bounds", encodeBounds(artifact.bounds));
417 result.emplace("dependencies", encodeDependencies(artifact.dependencies));
418 result.emplace("metadata", encodeMetadata(artifact.metadata));
419 if (artifact.type == ArtifactType::Composite) {
421 const auto &composite = std::get<CompositeArtifact>(artifact.payload);
422 children.reserve(composite.children.size());
423 for (const ArtifactPart &part : composite.children) children.emplace_back(encodePart(part));
425 payload.emplace("kind", eve::Value("composite"));
426 payload.emplace("children", eve::Value(std::move(children)));
427 result.emplace("payload", eve::Value(std::move(payload)));
428 } else {
429 result.emplace("payload", std::visit(
430 [&artifact](const auto &value) -> eve::Value {
431 using T = std::decay_t<decltype(value)>;
432 if constexpr (std::is_same_v<T, CompositeArtifact>)
433 return eve::Value{};
434 else
435 return encodeLeafPayload(artifact.type, ArtifactLeafPayload(value));
436 },
437 artifact.payload));
438 }
439 return eve::Value(std::move(result));
440}
441
442bool readStringValue(const eve::Value::Object &object, const char *name, std::string &output, bool allowEmpty = false) {
443 auto parsed = allowEmpty ? eve::readStringMember(object, name) : eve::readNonEmptyStringMember(object, name);
444 if (!parsed) return false;
445 output = std::move(parsed.value());
446 return true;
447}
448
449bool readIntValue(const eve::Value::Object &object, const char *name, std::int64_t &output) {
450 const auto *value = stateMember(object, name);
451 if (!value) return false;
452 auto parsed = eve::readInt64Value(*value);
453 if (!parsed) return false;
454 output = parsed.value();
455 return true;
456}
457
458bool readFloatValue(const eve::Value::Object &object, const char *name, float &output) {
459 const eve::Value *value = stateMember(object, name);
460 if (!value) return false;
461 if (const auto *number = value->getIf<double>()) {
462 if (!std::isfinite(*number) || *number < -std::numeric_limits<float>::max() ||
463 *number > std::numeric_limits<float>::max())
464 return false;
465 output = static_cast<float>(*number);
466 return std::isfinite(output);
467 }
468 if (const auto *integer = value->getIf<std::int64_t>()) {
469 output = static_cast<float>(*integer);
470 return std::isfinite(output);
471 }
472 return false;
473}
474
475bool readBoolValue(const eve::Value::Object &object, const char *name, bool &output) {
476 const auto *value = stateMember(object, name);
477 if (!value) return false;
478 auto parsed = eve::readBoolValue(*value);
479 if (!parsed) return false;
480 output = parsed.value();
481 return true;
482}
483
484template <class T>
485bool decodeNumericArray(const eve::Value *encoded, std::vector<T> &output) {
486 const auto *array = encoded ? encoded->getIf<eve::Value::Array>() : nullptr;
487 if (!array) return false;
488 output.clear();
489 output.reserve(array->size());
490 for (const eve::Value &value : *array) {
491 if constexpr (std::is_same_v<T, float>) {
492 if (const auto *number = value.getIf<double>()) {
493 if (!std::isfinite(*number) || *number < -std::numeric_limits<float>::max() ||
494 *number > std::numeric_limits<float>::max())
495 return false;
496 output.push_back(static_cast<float>(*number));
497 } else if (const auto *integer = value.getIf<std::int64_t>()) {
498 const float converted = static_cast<float>(*integer);
499 if (!std::isfinite(converted)) return false;
500 output.push_back(converted);
501 } else {
502 return false;
503 }
504 } else if constexpr (std::is_same_v<T, std::uint8_t> || std::is_same_v<T, std::uint32_t>) {
505 const auto *integer = value.getIf<std::int64_t>();
506 if (!integer || *integer < 0 || static_cast<std::uint64_t>(*integer) > std::numeric_limits<T>::max())
507 return false;
508 output.push_back(static_cast<T>(*integer));
509 } else {
510 const auto *integer = value.getIf<std::int64_t>();
511 if (!integer || *integer < std::numeric_limits<T>::min() || *integer > std::numeric_limits<T>::max())
512 return false;
513 output.push_back(static_cast<T>(*integer));
514 }
515 }
516 return true;
517}
518
519bool decodeBounds(const eve::Value *encoded, Bounds &bounds) {
520 const auto *object = encoded ? encoded->getIf<eve::Value::Object>() : nullptr;
521 if (!object || !readFloatValue(*object, "minX", bounds.minX) || !readFloatValue(*object, "minY", bounds.minY) ||
522 !readFloatValue(*object, "minZ", bounds.minZ) || !readFloatValue(*object, "maxX", bounds.maxX) ||
523 !readFloatValue(*object, "maxY", bounds.maxY) || !readFloatValue(*object, "maxZ", bounds.maxZ) ||
524 !readBoolValue(*object, "valid", bounds.valid))
525 return false;
526 return finiteBounds(bounds);
527}
528
529bool decodeStringMap(const eve::Value *encoded, std::unordered_map<std::string, std::string> &output) {
530 const auto *object = encoded ? encoded->getIf<eve::Value::Object>() : nullptr;
531 if (!object) return false;
532 output.clear();
533 for (const auto &[key, value] : *object) {
534 const auto *text = value.getIf<std::string>();
535 if (!text) return false;
536 output.emplace(key, *text);
537 }
538 return true;
539}
540
541bool decodeFloatMap(const eve::Value *encoded, std::unordered_map<std::string, float> &output) {
542 const auto *object = encoded ? encoded->getIf<eve::Value::Object>() : nullptr;
543 if (!object) return false;
544 output.clear();
545 for (const auto &[key, value] : *object) {
546 if (const auto *number = value.getIf<double>()) {
547 if (!std::isfinite(*number) || *number < -std::numeric_limits<float>::max() ||
548 *number > std::numeric_limits<float>::max())
549 return false;
550 output.emplace(key, static_cast<float>(*number));
551 } else if (const auto *integer = value.getIf<std::int64_t>()) {
552 const float converted = static_cast<float>(*integer);
553 if (!std::isfinite(converted)) return false;
554 output.emplace(key, converted);
555 } else {
556 return false;
557 }
558 }
559 return true;
560}
561
562bool decodeOptionalIntMap(const eve::Value *encoded,
563 std::unordered_map<std::string, std::int64_t> &output) {
564 output.clear();
565 if (!encoded) return true;
566 const auto *object = encoded->getIf<eve::Value::Object>();
567 if (!object) return false;
568 for (const auto &[key, value] : *object) {
569 const auto *integer = value.getIf<std::int64_t>();
570 if (!integer) return false;
571 output.emplace(key, *integer);
572 }
573 return true;
574}
575
576bool decodeOptionalBoolMap(const eve::Value *encoded,
577 std::unordered_map<std::string, bool> &output) {
578 output.clear();
579 if (!encoded) return true;
580 const auto *object = encoded->getIf<eve::Value::Object>();
581 if (!object) return false;
582 for (const auto &[key, value] : *object) {
583 const auto *boolean = value.getIf<bool>();
584 if (!boolean) return false;
585 output.emplace(key, *boolean);
586 }
587 return true;
588}
589
590bool decodeOptionalVectorMap(
591 const eve::Value *encoded,
592 std::unordered_map<std::string, ProcgenAttributeVector> &output) {
593 output.clear();
594 if (!encoded) return true;
595 const auto *object = encoded->getIf<eve::Value::Object>();
596 if (!object) return false;
597 for (const auto &[key, value] : *object) {
598 std::vector<float> components;
599 if (!decodeNumericArray(&value, components) || components.size() != 3) return false;
600 output.emplace(key, ProcgenAttributeVector{components[0], components[1], components[2]});
601 }
602 return true;
603}
604
605bool readOptionalFloatValue(const eve::Value::Object &object, const char *name, float &output) {
606 const eve::Value *value = stateMember(object, name);
607 return !value || readFloatValue(object, name, output);
608}
609
610bool decodeMetadata(const eve::Value *encoded, eve::Value::Object &output) {
611 const auto *object = encoded ? encoded->getIf<eve::Value::Object>() : nullptr;
612 if (!object) return false;
613 output = *object;
614 return true;
615}
616
617bool decodeDependencies(const eve::Value *encoded, std::vector<ArtifactId> &output) {
618 const auto *array = encoded ? encoded->getIf<eve::Value::Array>() : nullptr;
619 if (!array) return false;
620 output.clear();
621 output.reserve(array->size());
622 for (const eve::Value &value : *array) {
623 const auto *text = value.getIf<std::string>();
624 const auto parsed = text ? ArtifactId::parse(*text) : std::nullopt;
625 if (!parsed || parsed->isNil()) return false;
626 output.push_back(*parsed);
627 }
628 return true;
629}
630
631std::optional<ArtifactType> decodeArtifactType(const eve::Value::Object &object, const char *name = "type") {
632 std::string text;
633 if (!readStringValue(object, name, text)) return std::nullopt;
636 if (text == artifactTypeName(type)) return type;
637 return std::nullopt;
638}
639
640bool decodeSchemaVersion(const eve::Value::Object &object, eve::SchemaVersion &version) {
641 std::string text;
642 if (!readStringValue(object, "schemaVersion", text)) return false;
643 std::uint64_t value = 0;
644 const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
645 if (error != std::errc{} || end != text.data() + text.size() || value == 0) return false;
647 return true;
648}
649
650bool decodePayload(ArtifactType type, const eve::Value *encoded, ArtifactLeafPayload &output) {
651 const auto *wrapper = encoded ? encoded->getIf<eve::Value::Object>() : nullptr;
652 std::string kind;
653 const eve::Value *data = wrapper ? stateMember(*wrapper, "data") : nullptr;
654 if (!wrapper || !readStringValue(*wrapper, "kind", kind) || kind != artifactTypeName(type) || !data) return false;
655 const auto *object = data->getIf<eve::Value::Object>();
656 if (!object) return false;
657 if (type == ArtifactType::Grid) {
658 std::int64_t width = 0, height = 0;
659 std::vector<std::uint32_t> cells;
660 std::vector<std::uint8_t> detail;
661 std::unordered_map<std::string, std::string> metadata;
662 const auto *objectsValue = stateMember(*object, "objects");
663 const auto *objects = objectsValue ? objectsValue->getIf<eve::Value::Array>() : nullptr;
664 if (!readIntValue(*object, "width", width) || !readIntValue(*object, "height", height) || width <= 0 ||
665 height <= 0 || width > std::numeric_limits<int>::max() || height > std::numeric_limits<int>::max() ||
666 !decodeNumericArray(stateMember(*object, "cells"), cells) ||
667 !decodeNumericArray(stateMember(*object, "detail"), detail) || !objects ||
668 !decodeStringMap(stateMember(*object, "metadata"), metadata))
669 return false;
670 const auto expected = static_cast<std::uint64_t>(width) * static_cast<std::uint64_t>(height);
671 if (expected != cells.size() || expected != detail.size()) return false;
672 Grid2D grid;
673 grid.resize(static_cast<int>(width), static_cast<int>(height));
674 grid.cells() = std::move(cells);
675 grid.detail() = std::move(detail);
676 for (const auto &[key, value] : metadata) grid.setMeta(key, value);
677 for (const eve::Value &encodedObject : *objects) {
678 const auto *item = encodedObject.getIf<eve::Value::Object>();
679 std::string name, objectType;
680 float x = 0.f, y = 0.f, objectWidth = 0.f, objectHeight = 0.f;
681 std::int64_t gid = 0;
682 if (!item || !readStringValue(*item, "name", name, true) ||
683 !readStringValue(*item, "type", objectType, true) || !readFloatValue(*item, "x", x) ||
684 !readFloatValue(*item, "y", y) || !readFloatValue(*item, "width", objectWidth) ||
685 !readFloatValue(*item, "height", objectHeight) || !readIntValue(*item, "gid", gid) || gid < 0 ||
686 gid > std::numeric_limits<std::uint32_t>::max())
687 return false;
688 grid.addObject(name, objectType, x, y, objectWidth, objectHeight, static_cast<int>(gid));
689 }
690 output = std::move(grid);
691 return true;
692 }
694 const auto *encodedPointsValue = stateMember(*object, "points");
695 const auto *encodedPoints = encodedPointsValue ? encodedPointsValue->getIf<eve::Value::Array>() : nullptr;
696 if (!encodedPoints) return false;
698 for (const eve::Value &encodedPoint : *encodedPoints) {
699 const auto* item = encodedPoint.getIf<eve::Value::Object>();
700 ProcgenPoint point;
701 std::int64_t seed = 0;
702 std::string pointIdText;
703 std::unordered_map<std::string, float> floatAttributes;
704 std::unordered_map<std::string, std::int64_t> intAttributes;
705 std::unordered_map<std::string, bool> boolAttributes;
706 std::unordered_map<std::string, ProcgenAttributeVector> vectorAttributes;
707 std::unordered_map<std::string, std::string> stringAttributes;
708 if (!item || !readFloatValue(*item, "x", point.x) || !readFloatValue(*item, "y", point.y) ||
709 !readFloatValue(*item, "z", point.z) || !readFloatValue(*item, "normalX", point.normalX) ||
710 !readFloatValue(*item, "normalY", point.normalY) || !readFloatValue(*item, "normalZ", point.normalZ) ||
711 !readOptionalFloatValue(*item, "pitch", point.pitch) ||
712 !readFloatValue(*item, "yaw", point.yaw) ||
713 !readOptionalFloatValue(*item, "roll", point.roll) || !readFloatValue(*item, "scaleX", point.scaleX) ||
714 !readFloatValue(*item, "scaleY", point.scaleY) || !readFloatValue(*item, "scaleZ", point.scaleZ) ||
715 !readFloatValue(*item, "density", point.density) || !readIntValue(*item, "seed", seed) || seed < 0 ||
716 seed > std::numeric_limits<std::uint32_t>::max() ||
717 !readOptionalFloatValue(*item, "boundsMinX", point.boundsMinX) ||
718 !readOptionalFloatValue(*item, "boundsMinY", point.boundsMinY) ||
719 !readOptionalFloatValue(*item, "boundsMinZ", point.boundsMinZ) ||
720 !readOptionalFloatValue(*item, "boundsMaxX", point.boundsMaxX) ||
721 !readOptionalFloatValue(*item, "boundsMaxY", point.boundsMaxY) ||
722 !readOptionalFloatValue(*item, "boundsMaxZ", point.boundsMaxZ) ||
723 !readOptionalFloatValue(*item, "colorR", point.colorR) ||
724 !readOptionalFloatValue(*item, "colorG", point.colorG) ||
725 !readOptionalFloatValue(*item, "colorB", point.colorB) ||
726 !readOptionalFloatValue(*item, "colorA", point.colorA) ||
727 !readOptionalFloatValue(*item, "steepness", point.steepness) ||
728 !decodeFloatMap(stateMember(*item, "floatAttributes"), floatAttributes) ||
729 !decodeOptionalIntMap(stateMember(*item, "intAttributes"), intAttributes) ||
730 !decodeOptionalBoolMap(stateMember(*item, "boolAttributes"), boolAttributes) ||
731 !decodeOptionalVectorMap(stateMember(*item, "vectorAttributes"), vectorAttributes) ||
732 !decodeStringMap(stateMember(*item, "stringAttributes"), stringAttributes))
733 return false;
734 point.seed = static_cast<std::uint32_t>(seed);
735 if (const eve::Value* encodedId = stateMember(*item, "id")) {
736 const auto* text = encodedId->getIf<std::string>();
737 if (!text) return false;
738 const auto [end, error] = std::from_chars(text->data(), text->data() + text->size(), point.id);
739 if (error != std::errc{} || end != text->data() + text->size()) return false;
740 }
741 const int pointIndex = points.appendPoint(std::move(point));
742 for (const auto& [name, value] : floatAttributes)
743 if (!points.trySetFloatAttribute(pointIndex, name, value).ok()) return false;
744 for (const auto& [name, value] : intAttributes)
745 if (!points.trySetIntAttribute(pointIndex, name, value).ok()) return false;
746 for (const auto& [name, value] : boolAttributes)
747 if (!points.trySetBoolAttribute(pointIndex, name, value).ok()) return false;
748 for (const auto& [name, value] : vectorAttributes)
749 if (!points.trySetVectorAttribute(pointIndex, name, value.x, value.y, value.z).ok()) return false;
750 for (const auto& [name, value] : stringAttributes)
751 if (!points.trySetStringAttribute(pointIndex, name, value).ok()) return false;
752 }
753 output = std::move(points);
754 return true;
755 }
758 std::vector<std::string> names;
759 std::vector<int> assignments;
760 std::int64_t activeGroup = -1;
761 const auto *encodedNamesValue = stateMember(*object, "groupNames");
762 const auto *encodedNames = encodedNamesValue ? encodedNamesValue->getIf<eve::Value::Array>() : nullptr;
763 const auto *encodedMetadata = stateMember(*object, "metadata");
764 std::unordered_map<std::string, std::string> metadata;
765 if (!decodeNumericArray(stateMember(*object, "positions"), mesh.positions()) ||
766 !decodeNumericArray(stateMember(*object, "normals"), mesh.normals()) ||
767 !decodeNumericArray(stateMember(*object, "uvs"), mesh.uvs()) ||
768 !decodeNumericArray(stateMember(*object, "indices"), mesh.indices()) || !encodedNames ||
769 !decodeNumericArray(stateMember(*object, "triangleGroups"), assignments) ||
770 !readIntValue(*object, "activeGroup", activeGroup) || activeGroup < std::numeric_limits<int>::min() ||
771 activeGroup > std::numeric_limits<int>::max() || !decodeStringMap(encodedMetadata, metadata))
772 return false;
773 auto colors = artifact_mesh::decodeColors(*object, mesh.positions().size() / 3u);
774 if (!colors.ok()) return false;
775 auto restoredColors = mesh.setVertexColors(std::move(colors).takeValue());
776 if (!restoredColors.ok()) return false;
777 for (const eve::Value &encodedName : *encodedNames) {
778 const auto *name = encodedName.getIf<std::string>();
779 if (!name) return false;
780 names.push_back(*name);
781 }
782 auto restoredGroups =
783 mesh.restoreGroupData(std::move(names), std::move(assignments), static_cast<int>(activeGroup));
784 if (!restoredGroups.ok()) return false;
785 for (const auto &[key, value] : metadata) mesh.setMeta(key, value);
786 output = std::move(mesh);
787 return true;
788 }
791 std::int64_t width = 0, height = 0, channels = 0;
792 if (!readIntValue(*object, "width", width) || !readIntValue(*object, "height", height) ||
793 !readIntValue(*object, "channels", channels) || width <= 0 || height <= 0 || channels <= 0 ||
794 width > std::numeric_limits<int>::max() || height > std::numeric_limits<int>::max() ||
795 channels > std::numeric_limits<int>::max() || !readStringValue(*object, "format", image.format) ||
796 !decodeNumericArray(stateMember(*object, "pixels"), image.pixels))
797 return false;
798 image.width = static_cast<int>(width);
799 image.height = static_cast<int>(height);
800 image.channels = static_cast<int>(channels);
801 if (!image.isValid()) return false;
802 output = std::move(image);
803 return true;
804 }
806 Collider collider;
807 if (!decodeNumericArray(stateMember(*object, "vertices"), collider.vertices) ||
808 !decodeNumericArray(stateMember(*object, "indices"), collider.indices) ||
809 !decodeBounds(stateMember(*object, "bounds"), collider.bounds) ||
810 !readStringValue(*object, "shape", collider.shape) || !collider.isValid())
811 return false;
812 output = std::move(collider);
813 return true;
814 }
815 return false;
816}
817
818bool decodePart(const eve::Value &encoded, ArtifactPart &output) {
819 const auto *object = encoded.getIf<eve::Value::Object>();
820 std::string role, idText, buildKeyText;
821 eve::SchemaVersion schemaVersion;
822 Bounds bounds;
823 std::vector<ArtifactId> dependencies;
824 eve::Value::Object metadata;
825 const auto type = object ? decodeArtifactType(*object) : std::nullopt;
826 const auto parsedId =
827 object && readStringValue(*object, "artifactId", idText) ? ArtifactId::parse(idText) : std::nullopt;
828 if (!object || !readStringValue(*object, "role", role) || !parsedId || parsedId->isNil() || !type ||
829 *type == ArtifactType::Composite || !decodeSchemaVersion(*object, schemaVersion) ||
830 !readStringValue(*object, "buildKey", buildKeyText) || !decodeBounds(stateMember(*object, "bounds"), bounds) ||
831 !decodeDependencies(stateMember(*object, "dependencies"), dependencies) ||
832 !decodeMetadata(stateMember(*object, "metadata"), metadata))
833 return false;
834 const auto key = BuildKey::fromCanonical(buildKeyText);
835 if (!key) return false;
837 if (!decodePayload(*type, stateMember(*object, "payload"), payload)) return false;
838 auto result = makeArtifactPart(std::move(role), *parsedId, *type, schemaVersion, *key, bounds,
839 std::move(dependencies), std::move(metadata), std::move(payload));
840 if (!result.ok()) return false;
841 output = std::move(result).takeValue();
842 return true;
843}
844
845bool decodeArtifact(const eve::Value &encoded, GeneratedArtifact &output) {
846 const auto *object = encoded.getIf<eve::Value::Object>();
847 std::string idText, buildKeyText;
848 eve::SchemaVersion schemaVersion;
849 Bounds bounds;
850 std::vector<ArtifactId> dependencies;
851 eve::Value::Object metadata;
852 const auto type = object ? decodeArtifactType(*object) : std::nullopt;
853 const auto parsedId =
854 object && readStringValue(*object, "artifactId", idText) ? ArtifactId::parse(idText) : std::nullopt;
855 if (!object || !parsedId || parsedId->isNil() || !type || !decodeSchemaVersion(*object, schemaVersion) ||
856 !readStringValue(*object, "buildKey", buildKeyText) || !decodeBounds(stateMember(*object, "bounds"), bounds) ||
857 !decodeDependencies(stateMember(*object, "dependencies"), dependencies) ||
858 !decodeMetadata(stateMember(*object, "metadata"), metadata))
859 return false;
860 const auto key = BuildKey::fromCanonical(buildKeyText);
861 if (!key) return false;
864 const auto *payloadObjectValue = stateMember(*object, "payload");
865 const auto *payloadObject = payloadObjectValue ? payloadObjectValue->getIf<eve::Value::Object>() : nullptr;
866 std::string kind;
867 const auto *encodedChildren = payloadObject ? stateMember(*payloadObject, "children") : nullptr;
868 const auto *children = encodedChildren ? encodedChildren->getIf<eve::Value::Array>() : nullptr;
869 CompositeArtifact composite;
870 if (!payloadObject || !readStringValue(*payloadObject, "kind", kind) || kind != "composite" || !children)
871 return false;
872 composite.children.reserve(children->size());
873 for (const eve::Value &encodedPart : *children) {
874 ArtifactPart part;
875 if (!decodePart(encodedPart, part)) return false;
876 composite.children.push_back(std::move(part));
877 }
878 payload = std::move(composite);
879 } else {
881 if (!decodePayload(*type, stateMember(*object, "payload"), leaf)) return false;
882 payload = std::visit(
883 [](auto &&value) -> GeneratedArtifact::Payload {
884 return GeneratedArtifact::Payload(std::forward<decltype(value)>(value));
885 },
886 std::move(leaf));
887 }
888 auto result = makeArtifact(*parsedId, *type, schemaVersion, *key, bounds, std::move(dependencies),
889 std::move(metadata), std::move(payload));
890 if (!result.ok()) return false;
891 output = std::move(result).takeValue();
892 return true;
893}
894
895} // namespace
896
898public:
899 ArtifactStoreStage(ArtifactStore &owner, std::vector<GeneratedArtifact> artifacts)
900 : owner_(&owner), artifacts_(std::move(artifacts)) {}
901
903
904 void commit() noexcept override {
905 if (!owner_) return;
906 owner_->commitStaged(std::move(artifacts_));
907 owner_ = nullptr;
908 }
909
910 void rollback() noexcept override {
911 if (!owner_) return;
912 owner_->rollbackStaged();
913 owner_ = nullptr;
914 artifacts_.clear();
915 }
916
917private:
918 ArtifactStore *owner_ = nullptr;
919 std::vector<GeneratedArtifact> artifacts_;
920};
921
922void Bounds::include(float x, float y, float z) noexcept {
923 if (!valid) {
924 minX = maxX = x;
925 minY = maxY = y;
926 minZ = maxZ = z;
927 valid = true;
928 return;
929 }
930 minX = std::min(minX, x);
931 minY = std::min(minY, y);
932 minZ = std::min(minZ, z);
933 maxX = std::max(maxX, x);
934 maxY = std::max(maxY, y);
935 maxZ = std::max(maxZ, z);
936}
937
938bool ImageData::isValid() const noexcept {
939 if (width <= 0 || height <= 0 || channels <= 0) return false;
940 const auto expected =
941 static_cast<std::uint64_t>(width) * static_cast<std::uint64_t>(height) * static_cast<std::uint64_t>(channels);
942 return expected == pixels.size() && !format.empty();
943}
944
945bool Collider::isValid() const noexcept {
946 return finiteBounds(bounds) && !shape.empty() && vertices.size() % 3u == 0u && indices.size() % 3u == 0u &&
947 !vertices.empty() && !indices.empty() &&
948 std::all_of(vertices.begin(), vertices.end(), [](float value) { return std::isfinite(value); }) &&
949 std::all_of(indices.begin(), indices.end(),
950 [&](std::uint32_t index) { return index < vertices.size() / 3u; });
951}
952
953const ArtifactPart *CompositeArtifact::find(std::string_view role) const noexcept {
954 const auto found =
955 std::find_if(children.begin(), children.end(), [&](const ArtifactPart &part) { return part.role == role; });
956 return found == children.end() ? nullptr : &*found;
957}
958
960 return std::visit(
961 [](const auto &value) -> ArtifactType {
962 using T = std::decay_t<decltype(value)>;
963 if constexpr (std::is_same_v<T, Grid2D>) return ArtifactType::Grid;
964 if constexpr (std::is_same_v<T, PointSet>) return ArtifactType::PointSet;
965 if constexpr (std::is_same_v<T, MeshData>) return ArtifactType::MeshData;
966 if constexpr (std::is_same_v<T, ImageData>) return ArtifactType::ImageData;
967 if constexpr (std::is_same_v<T, Collider>) return ArtifactType::Collider;
969 },
970 payload);
971}
972
973const char *artifactTypeName(ArtifactType type) noexcept {
974 switch (type) {
975 case ArtifactType::Grid: return "grid";
976 case ArtifactType::PointSet: return "point_set";
977 case ArtifactType::MeshData: return "mesh_data";
978 case ArtifactType::ImageData: return "image_data";
979 case ArtifactType::Collider: return "collider";
980 case ArtifactType::Composite: return "composite";
981 }
982 return "unknown";
983}
984
986 BuildKey buildKey, Bounds bounds, std::vector<ArtifactId> dependencies,
989 result.id = id;
990 result.type = type;
991 result.schemaVersion = schemaVersion;
992 result.buildKey = std::move(buildKey);
993 result.bounds = bounds;
994 result.dependencies = std::move(dependencies);
995 result.metadata = std::move(metadata);
996 result.payload = std::move(payload);
997 if (!validArtifact(result))
998 return rejectedArtifact(eve::DiagnosticCode::InvalidArgument, "artifact structure or typed payload is invalid");
1000}
1001
1003 eve::SchemaVersion schemaVersion, BuildKey buildKey, Bounds bounds,
1004 std::vector<ArtifactId> dependencies, eve::Value::Object metadata,
1007 result.role = std::move(role);
1008 result.id = id;
1009 result.type = type;
1010 result.schemaVersion = schemaVersion;
1011 result.buildKey = std::move(buildKey);
1012 result.bounds = bounds;
1013 result.dependencies = std::move(dependencies);
1014 result.metadata = std::move(metadata);
1015 result.payload = std::move(payload);
1016 if (!validPart(result))
1017 return rejectedPart(eve::DiagnosticCode::InvalidArgument,
1018 "artifact part '" + result.role + "' structure or typed payload is invalid");
1019 return eve::Result<ArtifactPart>::success(std::move(result));
1020}
1021
1023 auto published = publishBatch({std::move(artifact)});
1024 if (!published.ok()) return eve::Result<ArtifactId>::failure(published.status());
1025 auto ids = std::move(published).takeValue();
1026 return eve::Result<ArtifactId>::success(ids.front());
1027}
1028
1029eve::Result<std::vector<ArtifactId>> ArtifactStore::publishBatch(std::vector<GeneratedArtifact> artifacts) {
1030 if (stageActive_)
1031 return eve::Result<std::vector<ArtifactId>>::failure(
1032 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "artifact store already has a pending stage"));
1033 if (artifacts.empty())
1035 eve::DiagnosticCode::InvalidArgument, "artifact publish batch must not be empty", "artifacts"));
1036
1037 std::unordered_map<ArtifactId, ArtifactType> available;
1038 available.reserve(artifacts_.size() + partOwners_.size() + artifacts.size() * 5u);
1039 for (const auto &[id, artifact] : artifacts_) available.emplace(id, artifact.type);
1040 for (const auto &[partId, ownerId] : partOwners_) {
1041 const GeneratedArtifact *owner = find(ownerId);
1042 if (!owner || owner->type != ArtifactType::Composite) continue;
1043 const auto &children = std::get<CompositeArtifact>(owner->payload).children;
1044 const auto found = std::find_if(children.begin(), children.end(),
1045 [partId](const ArtifactPart &part) { return part.id == partId; });
1046 if (found != children.end()) available.emplace(partId, found->type);
1047 }
1048
1049 std::vector<ArtifactId> ids;
1050 ids.reserve(artifacts.size());
1051 for (const GeneratedArtifact &artifact : artifacts) {
1052 if (!validArtifact(artifact))
1053 return eve::Result<std::vector<ArtifactId>>::failure(eve::Diagnostic::error(
1054 eve::DiagnosticCode::InvalidArgument, "artifact structure or typed payload is invalid", "artifact"));
1055 if (!available.emplace(artifact.id, artifact.type).second)
1056 return eve::Result<std::vector<ArtifactId>>::failure(eve::Diagnostic::error(
1057 eve::DiagnosticCode::Conflict, "artifact or part identity is already published", "artifact.id"));
1058 ids.push_back(artifact.id);
1059 if (artifact.type == ArtifactType::Composite) {
1060 for (const ArtifactPart &part : std::get<CompositeArtifact>(artifact.payload).children) {
1061 if (!available.emplace(part.id, part.type).second)
1062 return eve::Result<std::vector<ArtifactId>>::failure(eve::Diagnostic::error(
1063 eve::DiagnosticCode::Conflict, "composite part identity conflicts", "artifact.children.id"));
1064 }
1065 }
1066 }
1067
1068 const auto checkDependencies = [&](ArtifactType type,
1069 const std::vector<ArtifactId> &dependencies) -> std::optional<eve::Diagnostic> {
1070 bool meshDependency = false;
1071 for (ArtifactId dependency : dependencies) {
1072 const auto found = available.find(dependency);
1073 if (found == available.end())
1075 "artifact dependency is not published or in batch",
1076 "artifact.dependencies");
1077 meshDependency = meshDependency || found->second == ArtifactType::MeshData;
1078 }
1079 if (type == ArtifactType::Collider && !meshDependency)
1081 "collider must depend on a mesh artifact", "artifact.dependencies");
1082 return std::nullopt;
1083 };
1084 for (const GeneratedArtifact &artifact : artifacts) {
1085 if (auto error = checkDependencies(artifact.type, artifact.dependencies))
1086 return eve::Result<std::vector<ArtifactId>>::failure(std::move(*error));
1087 if (artifact.type == ArtifactType::Composite)
1088 for (const ArtifactPart &part : std::get<CompositeArtifact>(artifact.payload).children)
1089 if (auto error = checkDependencies(part.type, part.dependencies))
1090 return eve::Result<std::vector<ArtifactId>>::failure(std::move(*error));
1091 }
1092
1093 try {
1094 artifacts_.reserve(artifacts_.size() + artifacts.size());
1095 std::size_t newParts = 0;
1096 for (const GeneratedArtifact &artifact : artifacts)
1097 if (artifact.type == ArtifactType::Composite)
1098 newParts += std::get<CompositeArtifact>(artifact.payload).children.size();
1099 partOwners_.reserve(partOwners_.size() + newParts);
1100 for (GeneratedArtifact &artifact : artifacts) {
1101 const ArtifactId owner = artifact.id;
1102 if (artifact.type == ArtifactType::Composite)
1103 for (const ArtifactPart &part : std::get<CompositeArtifact>(artifact.payload).children)
1104 partOwners_.emplace(part.id, owner);
1105 artifacts_.emplace(owner, std::move(artifact));
1106 }
1107 } catch (...) {
1108 for (ArtifactId id : ids) artifacts_.erase(id);
1109 for (auto owner = partOwners_.begin(); owner != partOwners_.end();) {
1110 if (std::find(ids.begin(), ids.end(), owner->second) != ids.end())
1111 owner = partOwners_.erase(owner);
1112 else
1113 ++owner;
1114 }
1116 eve::DiagnosticCode::Failed, "artifact store allocation failed; batch rolled back", "artifacts"));
1117 }
1118 return eve::Result<std::vector<ArtifactId>>::success(std::move(ids));
1119}
1120
1122 GeneratedArtifact artifact) {
1123 if (stageActive_)
1125 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "artifact store already has a pending stage"));
1126 std::vector<GeneratedArtifact> artifacts;
1127 try {
1128 artifacts.emplace_back(std::move(artifact));
1129 auto valid = validateBatchAgainstStore(*this, artifacts);
1130 if (!valid.ok())
1132 std::size_t newParts = 0;
1133 for (const auto &entry : artifacts)
1134 if (entry.type == ArtifactType::Composite)
1135 newParts += std::get<CompositeArtifact>(entry.payload).children.size();
1136 // Reserve while the store is still hidden. The no-throw commit only
1137 // transfers already-owned values into these reserved containers.
1138 artifacts_.reserve(artifacts_.size() + artifacts.size());
1139 partOwners_.reserve(partOwners_.size() + newParts);
1140 stageActive_ = true;
1142 std::make_unique<ArtifactStoreStage>(*this, std::move(artifacts)));
1143 } catch (...) {
1144 stageActive_ = false;
1146 eve::Diagnostic::error(eve::DiagnosticCode::Failed, "artifact store stage allocation failed"));
1147 }
1148}
1149
1150void ArtifactStore::commitStaged(std::vector<GeneratedArtifact> artifacts) noexcept {
1151 for (GeneratedArtifact &artifact : artifacts) {
1152 const ArtifactId owner = artifact.id;
1153 if (artifact.type == ArtifactType::Composite)
1154 for (const ArtifactPart &part : std::get<CompositeArtifact>(artifact.payload).children)
1155 partOwners_.emplace(part.id, owner);
1156 artifacts_.emplace(owner, std::move(artifact));
1157 }
1158 stageActive_ = false;
1159}
1160
1161void ArtifactStore::rollbackStaged() noexcept { stageActive_ = false; }
1162
1164 const auto found = artifacts_.find(id);
1165 return found == artifacts_.end() ? nullptr : &found->second;
1166}
1167
1169 const auto owner = partOwners_.find(id);
1170 if (owner == partOwners_.end()) return nullptr;
1171 const GeneratedArtifact *artifact = find(owner->second);
1172 if (!artifact || artifact->type != ArtifactType::Composite) return nullptr;
1173 const auto &children = std::get<CompositeArtifact>(artifact->payload).children;
1174 const auto found =
1175 std::find_if(children.begin(), children.end(), [id](const ArtifactPart &part) { return part.id == id; });
1176 return found == children.end() ? nullptr : &*found;
1177}
1178
1179std::optional<ArtifactType> ArtifactStore::typeOf(ArtifactId id) const noexcept {
1180 const auto artifact = artifacts_.find(id);
1181 if (artifact != artifacts_.end()) return artifact->second.type;
1182 const auto part = partOwners_.find(id);
1183 if (part != partOwners_.end()) {
1184 const auto owner = artifacts_.find(part->second);
1185 if (owner != artifacts_.end() && owner->second.type == ArtifactType::Composite) {
1186 const auto &children = std::get<CompositeArtifact>(owner->second.payload).children;
1187 const auto found = std::find_if(children.begin(), children.end(),
1188 [id](const ArtifactPart &value) { return value.id == id; });
1189 if (found != children.end()) return found->type;
1190 }
1191 }
1192 return std::nullopt;
1193}
1194
1195std::vector<ArtifactId> ArtifactStore::findByBuildKey(const BuildKey &key) const {
1196 std::vector<ArtifactId> result;
1197 for (const auto &entry : artifacts_) {
1198 if (entry.second.buildKey == key) result.push_back(entry.first);
1199 }
1200 std::sort(result.begin(), result.end(),
1201 [](const ArtifactId &lhs, const ArtifactId &rhs) { return lhs.format() < rhs.format(); });
1202 return result;
1203}
1204
1206 const auto found = artifacts_.find(id);
1207 if (found == artifacts_.end()) {
1209 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "artifact identity is not published", "artifact.id"));
1210 }
1211 if (found->second.type == ArtifactType::Composite)
1212 for (const ArtifactPart &part : std::get<CompositeArtifact>(found->second.payload).children)
1213 partOwners_.erase(part.id);
1214 artifacts_.erase(found);
1216}
1217
1218void ArtifactStore::clear() noexcept {
1219 partOwners_.clear();
1220 artifacts_.clear();
1221 stageActive_ = false;
1222}
1223
1224std::size_t ArtifactStore::partCount() const noexcept { return partOwners_.size(); }
1225
1227 try {
1228 std::vector<ArtifactId> ids;
1229 ids.reserve(artifacts_.size());
1230 for (const auto &entry : artifacts_) ids.push_back(entry.first);
1231 std::sort(ids.begin(), ids.end(), [](ArtifactId lhs, ArtifactId rhs) { return lhs.format() < rhs.format(); });
1232
1233 eve::Value::Array records;
1234 records.reserve(ids.size());
1235 for (ArtifactId id : ids) records.emplace_back(encodeArtifact(artifacts_.at(id)));
1237 state.emplace("provider", eve::Value("procgen.cpu-artifact-store"));
1238 state.emplace("version", eve::Value(std::int64_t(2)));
1239 state.emplace("unknownFields", eve::Value("ignore"));
1240 state.emplace("artifacts", eve::Value(std::move(records)));
1242 } catch (...) {
1244 eve::Diagnostic::error(eve::DiagnosticCode::Failed, "artifact store snapshot allocation failed"));
1245 }
1246}
1247
1249 if (stageActive_ || !artifacts_.empty())
1251 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "artifact store restore requires an empty store"));
1252 const auto *object = state.getIf<eve::Value::Object>();
1253 const auto *provider = object ? stateMember(*object, "provider") : nullptr;
1254 const auto *providerName = provider ? provider->getIf<std::string>() : nullptr;
1255 const auto *encodedVersion = object ? stateMember(*object, "version") : nullptr;
1256 const auto *version = encodedVersion ? encodedVersion->getIf<std::int64_t>() : nullptr;
1257 const auto *encodedArtifacts = object ? stateMember(*object, "artifacts") : nullptr;
1258 const auto *encodedList = encodedArtifacts ? encodedArtifacts->getIf<eve::Value::Array>() : nullptr;
1259 if (!object || !providerName || *providerName != "procgen.cpu-artifact-store" || !version || *version != 2 ||
1260 !encodedList)
1262 "artifact store requires dense snapshot version 2"));
1263
1264 std::vector<GeneratedArtifact> candidate;
1265 try {
1266 candidate.reserve(encodedList->size());
1267 for (const eve::Value &encoded : *encodedList) {
1268 GeneratedArtifact artifact;
1269 if (!decodeArtifact(encoded, artifact))
1271 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "invalid dense artifact store record"));
1272 candidate.push_back(std::move(artifact));
1273 }
1274 } catch (...) {
1276 eve::Diagnostic::error(eve::DiagnosticCode::Failed, "artifact store restore allocation failed"));
1277 }
1278 auto valid = validateBatchAgainstStore(*this, candidate);
1279 if (!valid.ok()) return valid;
1280 std::unordered_map<ArtifactId, GeneratedArtifact> restoredArtifacts;
1281 std::unordered_map<ArtifactId, ArtifactId> restoredParts;
1282 try {
1283 restoredArtifacts.reserve(candidate.size());
1284 std::size_t partCount = 0;
1285 for (const GeneratedArtifact &artifact : candidate)
1286 if (artifact.type == ArtifactType::Composite)
1287 partCount += std::get<CompositeArtifact>(artifact.payload).children.size();
1288 restoredParts.reserve(partCount);
1289 for (GeneratedArtifact &artifact : candidate) {
1290 const ArtifactId owner = artifact.id;
1291 if (artifact.type == ArtifactType::Composite)
1292 for (const ArtifactPart &part : std::get<CompositeArtifact>(artifact.payload).children)
1293 restoredParts.emplace(part.id, owner);
1294 restoredArtifacts.emplace(owner, std::move(artifact));
1295 }
1296 } catch (...) {
1298 eve::Diagnostic::error(eve::DiagnosticCode::Failed, "artifact store restore indexing allocation failed"));
1299 }
1300 artifacts_.swap(restoredArtifacts);
1301 partOwners_.swap(restoredParts);
1303}
1304
1305} // namespace eve::procgen
double z
double y
double x
Value::Object payload
std::map< std::string, std::vector< Key >, std::less<> > channels
std::string output
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
Owning, backend-neutral products published by procedural generation.
vk::UniqueImage image
float u
Definition Grass.cpp:233
std::uint32_t height
std::uint32_t width
std::string id
Poco::JSON::Object::Ptr result
bool valid
ScriptMotionSinkStore< ScriptMotionSink< MotionColorTraits > > colors
std::shared_ptr< OceanGpuSpectrum > owner
OceanMeshSettings mesh
std::string error
Definition Package.cpp:174
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::shared_ptr< const std::vector< glm::vec2 > > points
std::set< std::string > values
std::set< std::string > identities
Object::Ptr value
int detail
double number
bool found
std::string text
unsigned column
size_t end
std::string kind
Share string attribute map operations through the Windows Foundation DLL.
Json object
uint32_t seed
Definition TreeMesh.cpp:276
int children
Definition TreeMesh.cpp:432
float size
Definition TreeMesh.cpp:158
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
T takeValue() &&
Move the value out and remove it from this Result.
Definition Result.h:370
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
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
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
A prepared consumer mutation with a non-throwing visibility boundary.
Id128 public API.
Definition Identity.h:111
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:150
void rollback() noexcept override
Discard the prepared mutation; idempotent and non-throwing.
ArtifactStoreStage(ArtifactStore &owner, std::vector< GeneratedArtifact > artifacts)
void commit() noexcept override
Make the prepared mutation observable; the operation cannot fail.
In-memory owner and publisher for generated artifacts.
std::optional< ArtifactType > typeOf(ArtifactId id) const noexcept
Return the kind of a live identity or composite part.
std::size_t partCount() const noexcept
Return the number of indexed composite child products.
eve::Result< std::unique_ptr< eve::artifact::PreparedPublication > > stagePublish(GeneratedArtifact artifact)
Prepare one store mutation for a larger provider transaction.
const ArtifactPart * findPart(ArtifactId id) const noexcept
Look up a composite child part.
eve::Result< ArtifactId > publish(GeneratedArtifact artifact)
Validate and atomically publish one artifact and all composite parts.
std::vector< ArtifactId > findByBuildKey(const BuildKey &key) const
Find all identities with a matching deterministic build key.
void clear() noexcept
Remove all published artifacts.
const GeneratedArtifact * find(ArtifactId id) const noexcept
Look up a published artifact.
eve::Result< void > restoreState(const eve::Value &state)
Restore complete identity/build-key and typed payload state transactionally.
eve::Result< eve::Value > snapshotState() const
Export identity, build-key and complete typed dense payload state.
eve::Result< std::vector< ArtifactId > > publishBatch(std::vector< GeneratedArtifact > artifacts)
Validate and atomically publish a dependency-connected batch.
eve::Result< void > remove(ArtifactId id)
Remove one artifact; NotFound is returned when absent.
Stable key for deterministic-equivalent generation inputs.
static std::optional< BuildKey > fromCanonical(std::string_view canonical)
Construct a build key from canonical text.
Definition BuildKey.cpp:27
StateValue objects
Definition Snapshot.cpp:110
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
Result< std::vector< float > > decodeColors(const eve::Value::Object &object, std::size_t vertices)
eve::Value encodeMesh(const MeshBuild &mesh)
bool validMesh(const MeshBuild &mesh) noexcept
ArtifactType artifactType(const GeneratedArtifact::Payload &payload) noexcept
Return the variant kind for a payload.
const char * artifactTypeName(ArtifactType type) noexcept
Return the stable textual spelling of an artifact kind.
eve::Result< ArtifactPart > makeArtifactPart(std::string role, ArtifactId id, ArtifactType type, eve::SchemaVersion schemaVersion, BuildKey buildKey, Bounds bounds, std::vector< ArtifactId > dependencies, eve::Value::Object metadata, ArtifactLeafPayload payload)
Validate and construct a leaf part for a composite artifact.
MeshBuild MeshData
Existing dense CPU mesh type under the artifact vocabulary.
ArtifactType
Runtime payload kind; it is checked against the variant on publish.
eve::ArtifactId ArtifactId
Common strong UUID identity for one published procedural artifact.
std::variant< Grid2D, PointSet, MeshData, ImageData, Collider > ArtifactLeafPayload
Leaf payloads used by a CompositeArtifact.
eve::Result< GeneratedArtifact > makeArtifact(ArtifactId id, ArtifactType type, eve::SchemaVersion schemaVersion, BuildKey buildKey, Bounds bounds, std::vector< ArtifactId > dependencies, eve::Value::Object metadata, GeneratedArtifact::Payload payload)
Validate and construct one artifact record.
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
WidgetDesc grid(int columns, std::vector< WidgetDesc > children, std::string id)
Fixed-column grid; children are placed in source order.
Definition Widget.cpp:878
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
Result< bool > readBoolValue(const Value &value)
Read a Bool without coercing integers, strings or other kinds.
Definition Value.cpp:50
Result< int > readIntValue(const Value &value)
Read an Int64 value as a range-checked native int without numeric coercion.
Definition Value.cpp:41
Result< std::string > readStringMember(const Value::Object &object, std::string_view name)
Read a required string field, including an empty string, as an owning value.
Definition Value.cpp:25
Result< std::string > readNonEmptyStringMember(const Value::Object &object, std::string_view name)
Read a required nonempty string field as an independent owning value.
Definition Value.cpp:33
Result< std::int64_t > readInt64Value(const Value &value)
Read an Int64 without narrowing or numeric coercion.
Definition Value.cpp:57
One typed, role-named child product inside a composite artifact.
Axis-aligned bounds in the artifact's declared world coordinate space.
void include(float x, float y, float z) noexcept
Expand this box to include one point.
std::vector< float > vertices
std::vector< std::uint32_t > indices
bool isValid() const noexcept
Return whether the collider has complete triangle data.
A coherent set of products published from one deterministic build.
const ArtifactPart * find(std::string_view role) const noexcept
Find a child by its stable role.
Complete immutable-once-published artifact record.
std::variant< Grid2D, PointSet, MeshData, ImageData, Collider, CompositeArtifact > Payload
std::vector< std::uint8_t > pixels
bool isValid() const noexcept
Return whether dimensions and pixel storage describe an image.
glm::vec4 bounds