11#include <glm/gtx/matrix_decompose.hpp>
12#include <glm/gtx/quaternion.hpp>
18#include <unordered_map>
19#include <unordered_set>
25struct PublicationScope {
28 ~PublicationScope() {
active =
false; }
33 }
catch (
const std::exception&
error) {
40void notifyPublished(SceneHost&
host,
const std::string& action,
const std::string&
id,
const std::string&
parent,
41 std::vector<eve::Diagnostic>& warnings) {
44 }
catch (
const std::exception&
error) {
49 "committed procedural scene notification threw an unknown exception",
id));
61 if (!
result.ok())
return nullptr;
62 return std::move(
result).takeValue();
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) {
71 if (meta->entity && meta->name ==
name)
return meta->entity;
76SceneHost *hostAt(
int index) {
77 if (
index < 0 || ecs::current()->getManager<SceneHost>() ==
nullptr)
return nullptr;
78 auto view = ecs::View<SceneHost, SceneHost::Meta>();
80 for (
auto it =
view.begin(); it !=
view.end(); ++it, ++i) {
82 if (i ==
index)
return meta->entity;
90 std::string_view
bone)
const override {
91 auto*
object =
dynamic_cast<SceneObject*
>(ecs::try_get(
handle));
96 "Scene root provider cannot resolve a bone or socket",
"bone");
97 auto*
host = hostByName(
object->meta()->hostName);
104 glm::vec3 translation;
106 glm::vec4 perspective;
107 if (!glm::decompose(
node.value()->world,
scale,
rotation, translation, skew, perspective))
112 const glm::vec3 euler = glm::degrees(glm::vec3(
pitch,
yaw,
roll));
114 euler.x, euler.y, euler.z,
126SceneNodeInfo toInfo(SceneHost *
host,
const SceneNode &
n) {
131 info.visible =
n.visible;
136 info.pitch =
n.pitch;
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);
150 SceneHost *
host()
const {
151 auto *
s = eve::ModuleManager::getInstance<Scene>(
"Scene");
152 return s ?
s->current() :
nullptr;
155 std::string activeHost()
const override {
157 return h ?
h->getName() : std::string();
160 int hostCount()
const override {
161 if (ecs::current()->getManager<SceneHost>() ==
nullptr)
return 0;
162 auto view = ecs::View<SceneHost, SceneHost::Meta>();
164 for (
auto it =
view.begin(); it !=
view.end(); ++it) ++
n;
168 std::string hostNameAt(
int index)
const override {
170 return h ?
h->getName() : std::string();
173 int nodeCount()
const override {
175 return h ?
h->getNodeCount() : 0;
178 std::string rootId()
const override {
180 auto *
r =
h ?
h->getRoot() :
nullptr;
181 return r ?
r->id : std::string();
184 std::vector<SceneNodeInfo>
nodes(
int limit)
const override {
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);
192 h->walkDepthFirst([&](SceneHost *,
int, SceneNode &
n) {
193 if (
static_cast<int>(
out.size()) >=
limit)
return;
194 out.push_back(toInfo(
h,
n));
205 return getNodeIn(
h->getName(),
id);
209 SceneHost *
h = hostName.empty() ?
host() : hostByName(hostName);
214 SceneNode*
n = borrowSceneResult(
h->findById(
id));
224 SceneNode *
n =
h ? borrowSceneResult(
h->findById(
id)) : nullptr;
232 h->markTransformDirty();
238 SceneNode *
n =
h ? borrowSceneResult(
h->findById(
id)) : nullptr;
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)
260 SceneHost*
host = hostByName(hostName(batchId));
262 if (!
host)
return false;
265 root.id =
"pcg-root";
266 root.key =
"pcg-root";
268 root.tags = {
"pcg",
"pcg.batch"};
269 root.children.reserve(instances.size());
270 for (
const auto& instance : instances) {
278 child.yaw = glm::radians(instance.
yaw);
280 child.roll = glm::radians(instance.
roll);
284 child.tags = {
"pcg",
"pcg.instance"};
285 if (!instance.
asset.empty())
child.tags.push_back(
"pcg.asset:" + instance.
asset);
287 child.tags.push_back(
"pcg.asset-build:" + instance.
assetBinding->buildId.format());
289 ?
"pcg.asset-root-pose:authored"
290 :
"pcg.asset-root-pose:placement");
292 root.children.push_back(std::move(child));
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;
303 const auto previous = ids_.find(batchId);
304 const auto& previousIds =
previous == ids_.end() ? emptyIds_ :
previous->second;
306 for (
const auto&
id : nextIds) {
307 if (previousIds.find(
id) == previousIds.end()) ++
stats.created;
310 for (
const auto&
id : previousIds) {
311 if (nextIds.find(
id) == nextIds.end()) ++
stats.removed;
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;
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)
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 ||
349 "procedural scene snapshot requires unique instance ids and source PointIds",
"instances"));
351 if (!applyBatch(batchId, instances))
354 revisions_[batchId] = targetRevision;
358 eve::Result<uint64_t> replaceBatches(
const std::vector<eve::ProcgenBatchSnapshot>& snapshots)
override {
363 const std::vector<eve::ProcgenBatchSnapshot>& snapshots,
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"));
375 struct PreparedBatch {
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;
386 std::vector<PreparedBatch> prepared;
387 prepared.reserve(snapshots.size());
388 std::unordered_set<std::string> batchIds;
389 batchIds.reserve(snapshots.size());
391 for (
const auto& snapshot : snapshots) {
395 "procedural scene transaction requires batch ids and non-zero revisions",
"snapshots"));
396 if (!batchIds.insert(
snapshot.batchId).second)
402 "procedural scene transaction contains a stale revision",
snapshot.batchId));
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 ||
421 "procedural scene transaction requires unique instance ids and source PointIds",
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);
431 ++batch.stats.reused;
432 batch.reusedIds.push_back(
id);
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);
441 batch.host = hostByName(hostName(
snapshot.batchId));
445 batch.tree = std::move(tree).takeValue();
446 prepared.push_back(std::move(batch));
449 auto nextCounts = counts_;
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;
458 nextIds[
snapshot.batchId] = batch.ids;
460 nextPointIds[
snapshot.batchId] = batch.pointIds;
462 nextStats[
snapshot.batchId] = batch.stats;
465 struct CandidateHosts {
466 std::vector<ecs::EntityHandle> handles;
470 for (
const auto&
handle : handles)
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;
486 batch.snapshot->batchId));
487 candidates.handles.push_back(ecs::handle_of(batch.host));
488 batch.host->setVisible(
false);
491 auto ownerCommit = invokePreparedOwner(commitPreparedOwner);
494 for (
auto& batch : prepared) {
495 *batch.host->tree() = std::move(batch.tree);
496 batch.host->setVisible(
true);
498 counts_.swap(nextCounts);
500 instances_.swap(nextInstances);
501 pointIds_.swap(nextPointIds);
502 revisions_.swap(nextRevisions);
503 stats_.swap(nextStats);
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);
519 if (publicationActive_)
522 const auto current = revisions_.find(batchId);
523 if (batchId.empty() ||
current == revisions_.end())
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;
536 bool removeBatch(
const std::string& batchId)
override {
537 if (publicationActive_)
return false;
538 SceneHost*
host = hostByName(hostName(batchId));
539 if (!
host)
return false;
541 root.id =
"pcg-root";
542 root.key =
"pcg-root";
544 root.tags = {
"pcg",
"pcg.batch"};
546 host->setVisible(
false);
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);
553 instances_.erase(batchId);
554 pointIds_.erase(batchId);
555 revisions_.erase(batchId);
564 const std::vector<std::string>& batchIds,
566 if (publicationActive_)
569 PublicationScope publication(publicationActive_);
570 if (batchIds.empty())
573 "procedural scene removal transaction requires at least one batch id",
"batchIds"));
574 struct PreparedRemoval {
576 SceneHost*
host =
nullptr;
577 SceneHost::Tree tree;
578 std::vector<std::string> removedIds;
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)
596 PreparedRemoval removal;
597 removal.batchId = batchId;
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());
604 removal.tree = std::move(tree).takeValue();
605 prepared.push_back(std::move(removal));
608 auto nextCounts = counts_;
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;
622 if (!commitPreparedOwner)
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);
632 for (
auto& removal : prepared) {
633 *removal.host->tree() = std::move(removal.tree);
634 removal.host->setVisible(
false);
636 counts_.swap(nextCounts);
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);
649 int instanceCount(
const std::string& batchId)
const override {
650 const auto found = counts_.find(batchId);
651 return found == counts_.end() ? 0 :
found->second;
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;
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;
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;
667 bool publicationActive_ =
false;
673 static NodeDesc makeRoot(
const std::string& batchId,
const std::vector<eve::ProcgenInstanceDesc>& instances) {
675 root.id =
"pcg-root";
676 root.key =
"pcg-root";
678 root.tags = {
"pcg",
"pcg.batch"};
679 root.children.reserve(instances.size());
680 for (
const auto& instance : instances) {
688 child.yaw = glm::radians(instance.
yaw);
690 child.roll = glm::radians(instance.
roll);
694 child.tags = {
"pcg",
"pcg.instance"};
695 if (!instance.
asset.empty())
child.tags.push_back(
"pcg.asset:" + instance.
asset);
697 child.tags.push_back(
"pcg.asset-build:" + instance.
assetBinding->buildId.format());
699 ?
"pcg.asset-root-pose:authored"
700 :
"pcg.asset-root-pose:placement");
702 root.children.push_back(std::move(child));
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_;
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);
Optional ECS-entity to world-pose capability.
std::uint32_t instanceCount
const ColourScope * parent
std::array< float, 4 > rotation
std::array< float, 3 > scale
std::shared_ptr< const OceanSprayFrame > previous
std::vector< EquipmentStat > stats
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
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).
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
Structured status and zero or more diagnostics for an operation.
static eve::Result< Tree > buildDetachedTree(const Tree *previous, NodeDesc root)
Builds a detached replacement tree without mutating a host or firing callbacks.
static eve::Result< SceneHost * > createHost(const std::string &name="")
Creates an ECS-owned scene host with an explicit Result contract.
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.
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 > ¤t, uint64_t currentRevision, const ProcgenInstanceDelta &delta)
Build an owning target snapshot from one exact revision and identity delta; does not publish state.
@ ReplaceTranslationRotation
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.