载入中...
搜索中...
未找到
SceneCapabilities.cpp
浏览该文件的文档.
1#include "common/Capability.h"
4#include "common/SceneQuery.h"
6#include "scene/Scene.h"
7#include "scene/SceneHost.h"
8#include "scene/SceneObject.h"
10
11#include <glm/gtx/matrix_decompose.hpp>
12#include <glm/gtx/quaternion.hpp>
13
14#include <cmath>
15#include <cstdint>
16#include <exception>
17#include <string>
18#include <unordered_map>
19#include <unordered_set>
20#include <utility>
21#include <vector>
22
23namespace eve::scene {
24namespace {
25struct PublicationScope {
26 bool& active;
27 explicit PublicationScope(bool& value) : active(value) { active = true; }
28 ~PublicationScope() { active = false; }
29};
30eve::Result<void> invokePreparedOwner(const std::function<eve::Result<void>()>& commit) {
31 try {
32 return commit();
33 } catch (const std::exception& error) {
35 } catch (...) {
37 eve::DiagnosticCode::CallbackFailure, "procedural scene owner commit threw an unknown exception"));
38 }
39}
40void notifyPublished(SceneHost& host, const std::string& action, const std::string& id, const std::string& parent,
41 std::vector<eve::Diagnostic>& warnings) {
42 try {
43 host.fireEvent(action, id, parent);
44 } catch (const std::exception& error) {
46 } catch (...) {
47 warnings.push_back(
49 "committed procedural scene notification threw an unknown exception", id));
50 }
51}
52bool hasConsistentAssetBinding(const eve::ProcgenInstanceDesc& instance) {
53 return !instance.assetBinding ||
54 (!instance.assetBinding->buildId.isNil() && instance.assetBinding->asset.format() == instance.asset &&
55 (instance.assetBinding->rootPose == eve::PrefabRootPose::Authored ||
57}
58
59template <class T>
60T* borrowSceneResult(eve::Result<T*> result) {
61 if (!result.ok()) return nullptr;
62 return std::move(result).takeValue();
63}
64
65SceneHost *hostByName(const std::string &name) {
66 if (name.empty()) return nullptr;
67 if (ecs::current()->getManager<SceneHost>() == nullptr) return nullptr;
68 auto view = ecs::View<SceneHost, SceneHost::Meta>();
69 for (auto it = view.begin(); it != view.end(); ++it) {
70 auto [meta] = *it;
71 if (meta->entity && meta->name == name) return meta->entity;
72 }
73 return nullptr;
74}
75
76SceneHost *hostAt(int index) {
77 if (index < 0 || ecs::current()->getManager<SceneHost>() == nullptr) return nullptr;
78 auto view = ecs::View<SceneHost, SceneHost::Meta>();
79 int i = 0;
80 for (auto it = view.begin(); it != view.end(); ++it, ++i) {
81 auto [meta] = *it;
82 if (i == index) return meta->entity;
83 }
84 return nullptr;
85}
86
87class SceneEntitySpatialProvider final : public eve::IEntitySpatialProvider {
88public:
89 eve::Result<eve::EntitySpatialPose> resolve(ecs::EntityHandle handle,
90 std::string_view bone) const override {
91 auto* object = dynamic_cast<SceneObject*>(ecs::try_get(handle));
92 if (!object)
93 return failure(eve::DiagnosticCode::NotFound, "entity is not owned by Scene", "entity");
94 if (!bone.empty())
96 "Scene root provider cannot resolve a bone or socket", "bone");
97 auto* host = hostByName(object->meta()->hostName);
98 if (!host) return failure(eve::DiagnosticCode::NotFound, "owning scene host is unavailable", "entity");
99 auto node = host->findById(object->meta()->nodeId);
102 glm::vec3 scale;
103 glm::quat rotation;
104 glm::vec3 translation;
105 glm::vec3 skew;
106 glm::vec4 perspective;
107 if (!glm::decompose(node.value()->world, scale, rotation, translation, skew, perspective))
108 return failure(eve::DiagnosticCode::Failed, "scene world transform could not be decomposed", "entity");
109 float yaw = 0.f, pitch = 0.f, roll = 0.f;
111 // rotationX/Y/Z keep meaning rotation about X/Y/Z, i.e. pitch/yaw/roll.
112 const glm::vec3 euler = glm::degrees(glm::vec3(pitch, yaw, roll));
113 return eve::Result<eve::EntitySpatialPose>::success({translation.x, translation.y, translation.z,
114 euler.x, euler.y, euler.z,
115 scale.x, scale.y, scale.z});
116 }
117
118private:
120 std::string path) {
122 eve::Diagnostic::error(code, std::move(message), std::move(path)));
123 }
124};
125
126SceneNodeInfo toInfo(SceneHost *host, const SceneNode &n) {
127 SceneNodeInfo info;
128 info.id = n.id;
129 info.name = n.name;
130 info.path = host->getPathById(n.id);
131 info.visible = n.visible;
132 info.x = n.x;
133 info.y = n.y;
134 info.z = n.z;
135 info.yaw = n.yaw;
136 info.pitch = n.pitch;
137 info.roll = n.roll;
138 info.sx = n.sx;
139 info.sy = n.sy;
140 info.sz = n.sz;
141 if (auto *p = host->getParentById(n.id)) info.parent = p->id;
142 for (int i = 0; i < host->getChildCountById(n.id); ++i) {
143 if (auto *c = host->getChildAtById(n.id, i)) info.children.push_back(c->id);
144 }
145 return info;
146}
147
148class SceneQueryImpl final : public eve::ISceneQuery {
149public:
150 SceneHost *host() const {
151 auto *s = eve::ModuleManager::getInstance<Scene>("Scene");
152 return s ? s->current() : nullptr;
153 }
154
155 std::string activeHost() const override {
156 auto *h = host();
157 return h ? h->getName() : std::string();
158 }
159
160 int hostCount() const override {
161 if (ecs::current()->getManager<SceneHost>() == nullptr) return 0;
162 auto view = ecs::View<SceneHost, SceneHost::Meta>();
163 int n = 0;
164 for (auto it = view.begin(); it != view.end(); ++it) ++n;
165 return n;
166 }
167
168 std::string hostNameAt(int index) const override {
169 auto *h = hostAt(index);
170 return h ? h->getName() : std::string();
171 }
172
173 int nodeCount() const override {
174 auto *h = host();
175 return h ? h->getNodeCount() : 0;
176 }
177
178 std::string rootId() const override {
179 auto *h = host();
180 auto *r = h ? h->getRoot() : nullptr;
181 return r ? r->id : std::string();
182 }
183
184 std::vector<SceneNodeInfo> nodes(int limit) const override {
185 return nodesOf(host() ? host()->getName() : std::string(), limit);
186 }
187
188 std::vector<SceneNodeInfo> nodesOf(const std::string &hostName, int limit) const override {
189 std::vector<SceneNodeInfo> out;
190 SceneHost *h = hostName.empty() ? host() : hostByName(hostName);
191 if (!h) return out;
192 h->walkDepthFirst([&](SceneHost *, int, SceneNode &n) {
193 if (static_cast<int>(out.size()) >= limit) return;
194 out.push_back(toInfo(h, n));
195 });
196 return out;
197 }
198
199 eve::Result<SceneNodeInfo> getNode(const std::string& id) const override {
200 auto *h = host();
201 if (!h) {
203 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "no active scene host", "host"));
204 }
205 return getNodeIn(h->getName(), id);
206 }
207
208 eve::Result<SceneNodeInfo> getNodeIn(const std::string& hostName, const std::string& id) const override {
209 SceneHost *h = hostName.empty() ? host() : hostByName(hostName);
210 if (!h) {
212 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "scene host not found", "host"));
213 }
214 SceneNode* n = borrowSceneResult(h->findById(id));
215 if (!n) {
217 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "scene node not found", "node"));
218 }
219 return eve::Result<SceneNodeInfo>::success(toInfo(h, *n));
220 }
221
222 eve::Result<void> setNodeTransform(const std::string& id, float x, float y, float z) override {
223 auto *h = host();
224 SceneNode *n = h ? borrowSceneResult(h->findById(id)) : nullptr;
225 if (!n) {
227 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "scene node not found", "node"));
228 }
229 n->x = x;
230 n->y = y;
231 n->z = z;
232 h->markTransformDirty();
234 }
235
236 eve::Result<void> setNodeVisible(const std::string& id, bool visible) override {
237 auto *h = host();
238 SceneNode *n = h ? borrowSceneResult(h->findById(id)) : nullptr;
239 if (!n) {
241 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "scene node not found", "node"));
242 }
243 n->visible = visible;
245 }
246
247 void syncTransforms() override { TransformSystem::updateAll(); }
248};
249
250class ProcgenSceneSinkImpl final : public eve::IProcgenSceneSink {
251public:
252 bool applyBatch(const std::string& batchId, const std::vector<eve::ProcgenInstanceDesc>& instances) override {
253 if (publicationActive_) return false;
254 if (batchId.empty()) return false;
255 for (const auto& instance : instances)
256 if (!hasConsistentAssetBinding(instance)) return false;
257 for (const auto& instance : instances)
258 if (!std::isfinite(instance.yaw) || !std::isfinite(instance.pitch) || !std::isfinite(instance.roll))
259 return false;
260 SceneHost* host = hostByName(hostName(batchId));
261 if (!host) host = borrowSceneResult(SceneHost::createHost(hostName(batchId)));
262 if (!host) return false;
263
264 NodeDesc root;
265 root.id = "pcg-root";
266 root.key = "pcg-root";
267 root.name = batchId;
268 root.tags = {"pcg", "pcg.batch"};
269 root.children.reserve(instances.size());
270 for (const auto& instance : instances) {
271 NodeDesc child;
272 child.id = instance.id;
273 child.key = instance.id;
274 child.name = instance.asset;
275 child.x = instance.x;
276 child.y = instance.y;
277 child.z = instance.z;
278 child.yaw = glm::radians(instance.yaw);
279 child.pitch = glm::radians(instance.pitch);
280 child.roll = glm::radians(instance.roll);
281 child.sx = instance.scaleX;
282 child.sy = instance.scaleY;
283 child.sz = instance.scaleZ;
284 child.tags = {"pcg", "pcg.instance"};
285 if (!instance.asset.empty()) child.tags.push_back("pcg.asset:" + instance.asset);
286 if (instance.assetBinding) {
287 child.tags.push_back("pcg.asset-build:" + instance.assetBinding->buildId.format());
288 child.tags.push_back(instance.assetBinding->rootPose == eve::PrefabRootPose::Authored
289 ? "pcg.asset-root-pose:authored"
290 : "pcg.asset-root-pose:placement");
291 }
292 root.children.push_back(std::move(child));
293 }
294 std::unordered_set<std::string> nextIds;
295 std::unordered_map<uint64_t, std::string> nextPointIds;
296 nextIds.reserve(instances.size());
297 nextPointIds.reserve(instances.size());
298 for (const auto& instance : instances) {
299 if (!nextIds.insert(instance.id).second) return false;
300 if (instance.sourcePointId != 0 && !nextPointIds.emplace(instance.sourcePointId, instance.id).second)
301 return false;
302 }
303 const auto previous = ids_.find(batchId);
304 const auto& previousIds = previous == ids_.end() ? emptyIds_ : previous->second;
305 Stats stats;
306 for (const auto& id : nextIds) {
307 if (previousIds.find(id) == previousIds.end()) ++stats.created;
308 else ++stats.reused;
309 }
310 for (const auto& id : previousIds) {
311 if (nextIds.find(id) == nextIds.end()) ++stats.removed;
312 }
313
314 host->setVisible(true);
315 host->setTreeReconcile(std::move(root));
317 counts_[batchId] = int(instances.size());
318 ids_[batchId] = std::move(nextIds);
319 instances_[batchId] = instances;
320 pointIds_[batchId] = std::move(nextPointIds);
321 revisions_[batchId] = revisions_[batchId] + 1;
322 stats_[batchId] = stats;
323 return true;
324 }
325
326 eve::Result<uint64_t> replaceBatch(const std::string& batchId, uint64_t targetRevision,
327 const std::vector<eve::ProcgenInstanceDesc>& instances) override {
328 const uint64_t currentRevision = batchRevision(batchId);
329 if (batchId.empty() || targetRevision == 0)
332 "procedural scene snapshot requires a batch id and non-zero target revision", "targetRevision"));
333 if (currentRevision >= targetRevision)
335 eve::DiagnosticCode::Conflict, "procedural scene snapshot revision is stale", "targetRevision"));
336 std::unordered_set<std::string> instanceIds;
337 std::unordered_set<uint64_t> pointIds;
338 instanceIds.reserve(instances.size());
339 pointIds.reserve(instances.size());
340 for (const auto& instance : instances) {
341 if (!hasConsistentAssetBinding(instance))
344 "procedural asset label conflicts with its typed binding", "asset"));
345 if (instance.id.empty() || instance.sourcePointId == 0 || !instanceIds.insert(instance.id).second ||
346 !pointIds.insert(instance.sourcePointId).second)
349 "procedural scene snapshot requires unique instance ids and source PointIds", "instances"));
350 }
351 if (!applyBatch(batchId, instances))
353 eve::DiagnosticCode::Failed, "procedural scene provider rejected snapshot commit", "batchId"));
354 revisions_[batchId] = targetRevision;
355 return eve::Result<uint64_t>::success(targetRevision);
356 }
357
358 eve::Result<uint64_t> replaceBatches(const std::vector<eve::ProcgenBatchSnapshot>& snapshots) override {
359 return replaceBatchesCoordinated(snapshots, [] { return eve::Result<void>::success(); });
360 }
361
362 eve::Result<uint64_t> replaceBatchesCoordinated(
363 const std::vector<eve::ProcgenBatchSnapshot>& snapshots,
364 const std::function<eve::Result<void>()>& commitPreparedOwner) override {
365 if (publicationActive_ || !commitPreparedOwner || ecs::current()->is_deferred())
368 "procedural scene publication requires a commit outside reentry or deferred iteration"));
369 PublicationScope publication(publicationActive_);
370 if (snapshots.empty())
373 "procedural scene transaction requires at least one snapshot", "snapshots"));
374
375 struct PreparedBatch {
376 const eve::ProcgenBatchSnapshot* snapshot = nullptr;
377 SceneHost* host = nullptr;
378 SceneHost::Tree tree;
379 std::unordered_set<std::string> ids;
380 std::unordered_map<uint64_t, std::string> pointIds;
381 std::vector<std::string> addedIds;
382 std::vector<std::string> reusedIds;
383 std::vector<std::string> removedIds;
384 Stats stats;
385 };
386 std::vector<PreparedBatch> prepared;
387 prepared.reserve(snapshots.size());
388 std::unordered_set<std::string> batchIds;
389 batchIds.reserve(snapshots.size());
390
391 for (const auto& snapshot : snapshots) {
392 if (snapshot.batchId.empty() || snapshot.targetRevision == 0)
395 "procedural scene transaction requires batch ids and non-zero revisions", "snapshots"));
396 if (!batchIds.insert(snapshot.batchId).second)
398 eve::DiagnosticCode::Conflict, "procedural scene transaction repeats a batch id", "snapshots"));
399 if (batchRevision(snapshot.batchId) >= snapshot.targetRevision)
402 "procedural scene transaction contains a stale revision", snapshot.batchId));
403
404 PreparedBatch batch;
405 batch.snapshot = &snapshot;
406 batch.ids.reserve(snapshot.instances.size());
407 batch.pointIds.reserve(snapshot.instances.size());
408 for (const auto& instance : snapshot.instances) {
409 if (!hasConsistentAssetBinding(instance))
412 "procedural asset label conflicts with its typed binding", "asset"));
413 if (!std::isfinite(instance.yaw) || !std::isfinite(instance.pitch) || !std::isfinite(instance.roll))
416 "procedural instance rotation must be finite", "rotation"));
417 if (instance.id.empty() || instance.sourcePointId == 0 || !batch.ids.insert(instance.id).second ||
418 !batch.pointIds.emplace(instance.sourcePointId, instance.id).second)
421 "procedural scene transaction requires unique instance ids and source PointIds",
422 snapshot.batchId));
423 }
424 const auto previous = ids_.find(snapshot.batchId);
425 const auto& previousIds = previous == ids_.end() ? emptyIds_ : previous->second;
426 for (const auto& id : batch.ids) {
427 if (previousIds.find(id) == previousIds.end()) {
428 ++batch.stats.created;
429 batch.addedIds.push_back(id);
430 } else {
431 ++batch.stats.reused;
432 batch.reusedIds.push_back(id);
433 }
434 }
435 for (const auto& id : previousIds) {
436 if (batch.ids.find(id) != batch.ids.end()) continue;
437 ++batch.stats.removed;
438 batch.removedIds.push_back(id);
439 }
440
441 batch.host = hostByName(hostName(snapshot.batchId));
442 NodeDesc root = makeRoot(snapshot.batchId, snapshot.instances);
443 auto tree = SceneHost::buildDetachedTree(batch.host ? &*batch.host->tree() : nullptr, std::move(root));
444 if (!tree) return eve::Result<uint64_t>::failure(tree.status());
445 batch.tree = std::move(tree).takeValue();
446 prepared.push_back(std::move(batch));
447 }
448
449 auto nextCounts = counts_;
450 auto nextIds = ids_;
451 auto nextInstances = instances_;
452 auto nextPointIds = pointIds_;
453 auto nextRevisions = revisions_;
454 auto nextStats = stats_;
455 for (const auto& batch : prepared) {
456 const auto& snapshot = *batch.snapshot;
457 nextCounts[snapshot.batchId] = int(snapshot.instances.size());
458 nextIds[snapshot.batchId] = batch.ids;
459 nextInstances[snapshot.batchId] = snapshot.instances;
460 nextPointIds[snapshot.batchId] = batch.pointIds;
461 nextRevisions[snapshot.batchId] = snapshot.targetRevision;
462 nextStats[snapshot.batchId] = batch.stats;
463 }
464
465 struct CandidateHosts {
466 std::vector<ecs::EntityHandle> handles;
467 bool committed = false;
468 ~CandidateHosts() {
469 if (!committed)
470 for (const auto& handle : handles)
471 if (auto* host = ecs::try_get(handle)) ecs::DestroyEntity(host);
472 }
473 } candidates;
474 candidates.handles.reserve(prepared.size());
475 std::vector<eve::Diagnostic> notificationWarnings;
476 std::size_t notificationCount = 0;
477 for (const auto& batch : prepared)
478 notificationCount += batch.removedIds.size() + batch.addedIds.size() + batch.reusedIds.size();
479 notificationWarnings.reserve(notificationCount);
480 for (auto& batch : prepared) {
481 if (batch.host) continue;
482 batch.host = borrowSceneResult(SceneHost::createHost(hostName(batch.snapshot->batchId)));
483 if (!batch.host)
485 eve::DiagnosticCode::Failed, "procedural scene transaction could not allocate all target hosts",
486 batch.snapshot->batchId));
487 candidates.handles.push_back(ecs::handle_of(batch.host));
488 batch.host->setVisible(false);
489 }
490
491 auto ownerCommit = invokePreparedOwner(commitPreparedOwner);
492 if (!ownerCommit.ok()) return eve::Result<uint64_t>::failure(ownerCommit.status());
493
494 for (auto& batch : prepared) {
495 *batch.host->tree() = std::move(batch.tree);
496 batch.host->setVisible(true);
497 }
498 counts_.swap(nextCounts);
499 ids_.swap(nextIds);
500 instances_.swap(nextInstances);
501 pointIds_.swap(nextPointIds);
502 revisions_.swap(nextRevisions);
503 stats_.swap(nextStats);
504 candidates.committed = true;
505 for (const auto& batch : prepared) TransformSystem::updateHost(batch.host);
506 for (const auto& batch : prepared) {
507 for (const auto& id : batch.removedIds)
508 notifyPublished(*batch.host, "node_removed", id, {}, notificationWarnings);
509 for (const auto& id : batch.addedIds)
510 notifyPublished(*batch.host, "node_added", id, "pcg-root", notificationWarnings);
511 for (const auto& id : batch.reusedIds)
512 notifyPublished(*batch.host, "node_changed", id, "pcg-root", notificationWarnings);
513 }
514 return eve::Result<uint64_t>::success(static_cast<uint64_t>(prepared.size()),
515 eve::Status(eve::StatusCode::Applied, std::move(notificationWarnings)));
516 }
517
518 eve::Result<uint64_t> applyDelta(const std::string& batchId, const eve::ProcgenInstanceDelta& delta) override {
519 if (publicationActive_)
521 eve::DiagnosticCode::PreconditionViolation, "procedural scene publication cannot be reentered"));
522 const auto current = revisions_.find(batchId);
523 if (batchId.empty() || current == revisions_.end())
525 eve::DiagnosticCode::NotFound, "procedural scene batch is not published", "batchId"));
526 auto target = eve::buildProcgenInstanceDeltaSnapshot(instances_.at(batchId), current->second, delta);
527 if (!target.ok()) return eve::Result<uint64_t>::failure(target.status());
528 return replaceBatch(batchId, delta.targetRevision, target.value());
529 }
530
531 uint64_t batchRevision(const std::string& batchId) const override {
532 const auto found = revisions_.find(batchId);
533 return found == revisions_.end() ? 0 : found->second;
534 }
535
536 bool removeBatch(const std::string& batchId) override {
537 if (publicationActive_) return false;
538 SceneHost* host = hostByName(hostName(batchId));
539 if (!host) return false;
540 NodeDesc root;
541 root.id = "pcg-root";
542 root.key = "pcg-root";
543 root.name = batchId;
544 root.tags = {"pcg", "pcg.batch"};
545 host->setTree(std::move(root));
546 host->setVisible(false);
547 Stats stats;
548 const auto ids = ids_.find(batchId);
549 if (ids != ids_.end()) stats.removed = int(ids->second.size());
550 stats_[batchId] = stats;
551 counts_.erase(batchId);
552 ids_.erase(batchId);
553 instances_.erase(batchId);
554 pointIds_.erase(batchId);
555 revisions_.erase(batchId);
556 return true;
557 }
558
559 eve::Result<uint64_t> removeBatches(const std::vector<std::string>& batchIds) override {
560 return removeBatchesCoordinated(batchIds, [] { return eve::Result<void>::success(); });
561 }
562
563 eve::Result<uint64_t> removeBatchesCoordinated(
564 const std::vector<std::string>& batchIds,
565 const std::function<eve::Result<void>()>& commitPreparedOwner) override {
566 if (publicationActive_)
568 eve::DiagnosticCode::PreconditionViolation, "procedural scene publication cannot be reentered"));
569 PublicationScope publication(publicationActive_);
570 if (batchIds.empty())
573 "procedural scene removal transaction requires at least one batch id", "batchIds"));
574 struct PreparedRemoval {
575 std::string batchId;
576 SceneHost* host = nullptr;
577 SceneHost::Tree tree;
578 std::vector<std::string> removedIds;
579 Stats stats;
580 };
581 std::vector<PreparedRemoval> prepared;
582 prepared.reserve(batchIds.size());
583 std::unordered_set<std::string> uniqueBatchIds;
584 uniqueBatchIds.reserve(batchIds.size());
585 for (const auto& batchId : batchIds) {
586 const auto ids = ids_.find(batchId);
587 if (batchId.empty() || !uniqueBatchIds.insert(batchId).second)
590 "procedural scene removal transaction requires unique non-empty batch ids", "batchIds"));
591 SceneHost* host = hostByName(hostName(batchId));
592 if (ids == ids_.end() || !host)
594 eve::DiagnosticCode::NotFound, "procedural scene removal transaction contains an unpublished batch",
595 batchId));
596 PreparedRemoval removal;
597 removal.batchId = batchId;
598 removal.host = host;
599 removal.removedIds.assign(ids->second.begin(), ids->second.end());
600 std::sort(removal.removedIds.begin(), removal.removedIds.end());
601 removal.stats.removed = int(ids->second.size());
602 auto tree = SceneHost::buildDetachedTree(&*host->tree(), makeRoot(batchId, {}));
603 if (!tree) return eve::Result<uint64_t>::failure(tree.status());
604 removal.tree = std::move(tree).takeValue();
605 prepared.push_back(std::move(removal));
606 }
607
608 auto nextCounts = counts_;
609 auto nextIds = ids_;
610 auto nextInstances = instances_;
611 auto nextPointIds = pointIds_;
612 auto nextRevisions = revisions_;
613 auto nextStats = stats_;
614 for (const auto& removal : prepared) {
615 nextCounts.erase(removal.batchId);
616 nextIds.erase(removal.batchId);
617 nextInstances.erase(removal.batchId);
618 nextPointIds.erase(removal.batchId);
619 nextRevisions.erase(removal.batchId);
620 nextStats[removal.batchId] = removal.stats;
621 }
622 if (!commitPreparedOwner)
624 eve::DiagnosticCode::InvalidArgument, "procedural scene removal transaction requires a commit",
625 "commitPreparedOwner"));
626 std::vector<eve::Diagnostic> notificationWarnings;
627 std::size_t notificationCount = 0;
628 for (const auto& removal : prepared) notificationCount += removal.removedIds.size();
629 notificationWarnings.reserve(notificationCount);
630 auto ownerCommit = invokePreparedOwner(commitPreparedOwner);
631 if (!ownerCommit.ok()) return eve::Result<uint64_t>::failure(ownerCommit.status());
632 for (auto& removal : prepared) {
633 *removal.host->tree() = std::move(removal.tree);
634 removal.host->setVisible(false);
635 }
636 counts_.swap(nextCounts);
637 ids_.swap(nextIds);
638 instances_.swap(nextInstances);
639 pointIds_.swap(nextPointIds);
640 revisions_.swap(nextRevisions);
641 stats_.swap(nextStats);
642 for (const auto& removal : prepared)
643 for (const auto& id : removal.removedIds)
644 notifyPublished(*removal.host, "node_removed", id, {}, notificationWarnings);
645 return eve::Result<uint64_t>::success(static_cast<uint64_t>(prepared.size()),
646 eve::Status(eve::StatusCode::Applied, std::move(notificationWarnings)));
647 }
648
649 int instanceCount(const std::string& batchId) const override {
650 const auto found = counts_.find(batchId);
651 return found == counts_.end() ? 0 : found->second;
652 }
653 int lastCreatedCount(const std::string& batchId) const override {
654 const auto found = stats_.find(batchId);
655 return found == stats_.end() ? 0 : found->second.created;
656 }
657 int lastReusedCount(const std::string& batchId) const override {
658 const auto found = stats_.find(batchId);
659 return found == stats_.end() ? 0 : found->second.reused;
660 }
661 int lastRemovedCount(const std::string& batchId) const override {
662 const auto found = stats_.find(batchId);
663 return found == stats_.end() ? 0 : found->second.removed;
664 }
665
666private:
667 bool publicationActive_ = false;
668 struct Stats {
669 int created = 0;
670 int reused = 0;
671 int removed = 0;
672 };
673 static NodeDesc makeRoot(const std::string& batchId, const std::vector<eve::ProcgenInstanceDesc>& instances) {
674 NodeDesc root;
675 root.id = "pcg-root";
676 root.key = "pcg-root";
677 root.name = batchId;
678 root.tags = {"pcg", "pcg.batch"};
679 root.children.reserve(instances.size());
680 for (const auto& instance : instances) {
681 NodeDesc child;
682 child.id = instance.id;
683 child.key = instance.id;
684 child.name = instance.asset;
685 child.x = instance.x;
686 child.y = instance.y;
687 child.z = instance.z;
688 child.yaw = glm::radians(instance.yaw);
689 child.pitch = glm::radians(instance.pitch);
690 child.roll = glm::radians(instance.roll);
691 child.sx = instance.scaleX;
692 child.sy = instance.scaleY;
693 child.sz = instance.scaleZ;
694 child.tags = {"pcg", "pcg.instance"};
695 if (!instance.asset.empty()) child.tags.push_back("pcg.asset:" + instance.asset);
696 if (instance.assetBinding) {
697 child.tags.push_back("pcg.asset-build:" + instance.assetBinding->buildId.format());
698 child.tags.push_back(instance.assetBinding->rootPose == eve::PrefabRootPose::Authored
699 ? "pcg.asset-root-pose:authored"
700 : "pcg.asset-root-pose:placement");
701 }
702 root.children.push_back(std::move(child));
703 }
704 return root;
705 }
706 static std::string hostName(const std::string& batchId) { return "__pcg/" + batchId; }
707 const std::unordered_set<std::string> emptyIds_;
708 std::unordered_map<std::string, int> counts_;
709 std::unordered_map<std::string, std::unordered_set<std::string>> ids_;
710 std::unordered_map<std::string, std::vector<eve::ProcgenInstanceDesc>> instances_;
711 std::unordered_map<std::string, std::unordered_map<uint64_t, std::string>> pointIds_;
712 std::unordered_map<std::string, uint64_t> revisions_;
713 std::unordered_map<std::string, Stats> stats_;
714};
715
716} // namespace
717
719 static SceneQueryImpl impl;
720 static ProcgenSceneSinkImpl procgenSink;
721 static SceneEntitySpatialProvider spatialProvider;
722 eve::cap::provide<eve::ISceneQuery>(&impl);
723 eve::cap::provide<eve::IProcgenSceneSink>(&procgenSink);
724 eve::cap::addListener<eve::IEntitySpatialProvider>(&spatialProvider);
725}
726
727} // namespace eve::scene
double z
double y
double x
LogicalId target
bool & active
int root
Definition AnimSmr.cpp:119
const std::string & s
float yaw
Definition BushMesh.cpp:37
void * impl
bool committed
glm::vec4 p[6]
std::string name
Definition ECS.cpp:154
Optional ECS-entity to world-pose capability.
std::string message
DiagnosticCode code
std::uint32_t instanceCount
glm::vec3 n
Definition Grass.cpp:63
double r
std::int32_t c
int h
const ColourScope * parent
std::array< float, 4 > rotation
std::array< float, 3 > scale
std::uint32_t bone
std::map< std::string, Node > nodes
std::string id
Poco::JSON::Object::Ptr result
Snapshot snapshot
OceanSprayView view
std::shared_ptr< const OceanSprayFrame > previous
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
PrimitiveHandle handle
Object::Ptr value
std::vector< EquipmentStat > stats
const RoadNode * node
bool found
int created
int removed
int reused
ScriptStructure out
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
double current
std::string string
bool visible
Json object
int limit
Definition TreeMesh.cpp:166
float size
Definition TreeMesh.cpp:158
UIHostHandle host
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Diagnostic warning(DiagnosticCode code, std::string message, std::string path={})
Construct a warning diagnostic.
One optional domain provider capable of resolving selected ECS entities.
Optional scene consumer for procedural instance batches.
Scene graph query/mutation surface (provided by the scene module).
Definition SceneQuery.h:31
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
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
static eve::Result< Tree > buildDetachedTree(const Tree *previous, NodeDesc root)
Builds a detached replacement tree without mutating a host or firing callbacks.
Definition NodeDesc.cpp:298
static eve::Result< SceneHost * > createHost(const std::string &name="")
Creates an ECS-owned scene host with an explicit Result contract.
static void updateHost(SceneHost *host)
Updates host.
static void updateAll()
Updates all.
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...
void registerSceneCapabilities()
Registers scene capabilities.
Result< VehiclePhysicsStatus > commit(physics::World &world, physics::ForceBatch &batch, std::shared_ptr< VehicleWheelRuntime > &runtime, std::vector< VehicleEntity::SuspensionState::WheelState > candidate, const SimulationStep &step)
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
void eulerYxzFromQuat(const glm::qua< T, glm::defaultp > &q, T &yaw, T &pitch, T &roll)
Quaternion overload of eulerYxzFromMatrix(); float and double both work.
Result< std::vector< ProcgenInstanceDesc > > buildProcgenInstanceDeltaSnapshot(const std::vector< ProcgenInstanceDesc > &current, uint64_t currentRevision, const ProcgenInstanceDelta &delta)
Build an owning target snapshot from one exact revision and identity delta; does not publish state.
One complete cell snapshot participating in an atomic multi-batch publication.
Identity-based, revision-checked mutation of one procedural scene batch.
Engine-neutral description of one procedural scene instance.
float pitch
Local X rotation in degrees, composed as yaw(Y), pitch(X), roll(Z); zero preserves legacy instances.
float roll
Local Z rotation in degrees; owned value retained by full snapshots and identity-based deltas.
float yaw
Local Y rotation in degrees; the scene provider converts all Euler angles to its native radians.
uint64_t sourcePointId
Stable source PointId; zero denotes a legacy instance without delta identity.
std::string asset
Compatibility asset label; when assetBinding exists, its typed identity is authoritative and must mat...
std::optional< ProcgenInstanceAssetBinding > assetBinding
Canonical asset link; asset remains its matching compatibility label when present.
glm::uvec4 info