17constexpr float kSleepSpeed = 0.05f;
23 body.setType(
"static");
26 body.setType(
"dynamic");
36 : worldHandle_(worldHandle), originX_(originX), originY_(originY), originZ_(originZ) {}
38GeometryCollectionInstance::~GeometryCollectionInstance() { releaseBodies(); }
42 return createInternal(world, asset, {}, originX, originY, originZ);
44std::shared_ptr<const FractureGeometry> GeometryCollectionInstance::fragmentGeometry() const noexcept {
54 for (std::size_t i = 0; i <
geometry.fragments.size(); ++i) {
55 const auto&
b = asset.
bones[i];
57 for (std::size_t
v = 0;
v <
f.positions.size();
v += 3)
58 if (std::abs(
f.positions[
v]) >
b.halfExtentX + 1e-5f ||
59 std::abs(
f.positions[
v + 1]) >
b.halfExtentY + 1e-5f ||
60 std::abs(
f.positions[
v + 2]) >
b.halfExtentZ + 1e-5f)
64 return createInternal(world, asset, std::make_shared<const FractureGeometry>(
geometry),
x,
y,
z);
68 float originX,
float originY,
float originZ) {
71 if (!std::isfinite(originX) || !std::isfinite(originY) || !std::isfinite(originZ))
78 auto instance = std::unique_ptr<GeometryCollectionInstance>(
80 instance->geometry_ = std::move(
geometry);
81 instance->bones_.reserve(asset.
bones.size());
82 instance->edges_.reserve(asset.
edges.size());
84 std::vector<Body3D*> createdBodies;
85 createdBodies.reserve(asset.
bones.size());
86 auto rollback = [&]() {
90 createdBodies.clear();
91 instance->bones_.clear();
94 for (
const auto& boneDef : asset.
bones) {
95 const float x = originX + boneDef.localX;
96 const float y = originY + boneDef.localY;
97 const float z = originZ + boneDef.localZ;
101 Body3D*
body = world.newBody(
"static",
x,
y,
z);
108 if (instance->geometry_) {
109 const auto& fragment = instance->geometry_->fragments[instance->bones_.size()];
110 body->newConvexHullShape(fragment.positions, 254, boneDef.density, boneDef.friction,
111 boneDef.restitution);
113 body->newBoxShape(boneDef.halfExtentX * 2.f, boneDef.halfExtentY * 2.f, boneDef.halfExtentZ * 2.f,
114 boneDef.density, boneDef.friction, boneDef.restitution);
116 }
catch (
const std::exception&
error) {
122 auto link = PhysicsLink::fromBody(*
body);
125 if (
body->isValid())
body->destroy();
129 bone.state = BoneRuntimeState::Attached;
130 bone.anchored = boneDef.anchoredDefault;
132 bone.halfExtentX = boneDef.halfExtentX;
133 bone.halfExtentY = boneDef.halfExtentY;
134 bone.halfExtentZ = boneDef.halfExtentZ;
135 bone.clusterId = boneDef.clusterId;
136 bone.fractureLevel = boneDef.fractureLevel;
137 instance->bones_.push_back(
bone);
138 createdBodies.push_back(
body);
141 for (
const auto& edgeDef : asset.
edges) {
143 edge.boneA = edgeDef.boneA;
144 edge.boneB = edgeDef.boneB;
145 edge.strainThreshold = edgeDef.strainThreshold;
146 instance->edges_.push_back(
edge);
149 if (instance->geometry_) {
150 auto constraints = instance->stageConstraints(instance->edges_);
155 instance->ownedJoints_ = std::move(constraints).takeValue();
156 for (std::size_t i = 0; i < instance->edges_.size(); ++i)
157 instance->edges_[i].joint =
158 instance->ownedJoints_[i] ? instance->ownedJoints_[i]->runtimeHandle() : PhysicsJointHandle::invalid();
163bool GeometryCollectionInstance::hasLiveWorld() const noexcept {
return resolveWorld() !=
nullptr; }
165World3D* GeometryCollectionInstance::resolveWorld() const noexcept {
166 World3D* world = World3D::findWorld(worldHandle_);
167 if (!world || !world->isValid())
return nullptr;
172 if (boneIndex < 0 || boneIndex >=
static_cast<int>(bones_.size()))
175 World3D* world = resolveWorld();
179 return bones_[
static_cast<std::size_t
>(boneIndex)].
link.resolve(*world);
182float GeometryCollectionInstance::falloffAt(
const DestructionField& field,
float x,
float y,
float z)
const {
183 const float dx =
x - field.centerX;
184 const float dy =
y - field.centerY;
185 const float dz =
z - field.centerZ;
186 const float dist = std::sqrt(
dx *
dx +
dy *
dy +
dz *
dz);
187 if (!(field.radius > 0.f) || !std::isfinite(field.radius))
return 0.f;
188 if (dist > field.radius)
return 0.f;
189 if (field.falloff == DestructionFieldFalloff::None)
return 1.f;
190 return 1.f - dist / field.radius;
194 if (!std::isfinite(field.centerX) || !std::isfinite(field.centerY) || !std::isfinite(field.centerZ) ||
195 !std::isfinite(field.radius) || field.radius < 0.f || !std::isfinite(field.magnitude))
198 if (field.kind == DestructionFieldKind::Impulse &&
199 (!std::isfinite(field.dirX) || !std::isfinite(field.dirY) || !std::isfinite(field.dirZ)))
202 World3D* world = resolveWorld();
204 orphanedPhysics_ =
true;
210 int sleepsThisCall = 0;
211 bool needGraphSync =
false;
212 for (std::size_t i = 0; i < bones_.size(); ++i) {
213 auto bodyResult = bones_[i].link.resolve(*world);
214 if (!bodyResult)
continue;
217 if (
weight <= 0.f)
continue;
218 switch (field.kind) {
219 case DestructionFieldKind::Anchor: {
220 const bool wasSleeping = bones_[i].state == BoneRuntimeState::Sleeping;
221 bones_[i].anchored =
true;
222 bones_[i].state = BoneRuntimeState::Attached;
223 body->setType(
"static");
224 if (wasSleeping) ++sleepBatchRevision_;
226 needGraphSync =
true;
229 case DestructionFieldKind::Impulse: {
231 if (bones_[i].anchored || bones_[i].
state == BoneRuntimeState::Attached)
break;
232 float dx = field.dirX,
dy = field.dirY,
dz = field.dirZ;
233 const float len = std::sqrt(
dx *
dx +
dy *
dy +
dz *
dz);
244 const bool wasSleeping = bones_[i].state == BoneRuntimeState::Sleeping;
245 body->setType(
"dynamic");
247 bones_[i].state = BoneRuntimeState::Detached;
248 if (wasSleeping) ++sleepBatchRevision_;
252 case DestructionFieldKind::Sleep: {
253 if (bones_[i].
state != BoneRuntimeState::Detached)
break;
254 const float vx =
body->getLinearVelocityX();
255 const float vy =
body->getLinearVelocityY();
256 const float vz =
body->getLinearVelocityZ();
257 const float speed = std::sqrt(
vx *
vx +
vy *
vy +
vz *
vz);
258 if (speed > kSleepSpeed)
break;
259 if (budget_.maxSleepsPerStep > 0 && sleepsThisCall >= budget_.maxSleepsPerStep) {
263 body->setType(
"static");
264 if (bones_[i].
state != BoneRuntimeState::Sleeping) ++sleepBatchRevision_;
265 bones_[i].state = BoneRuntimeState::Sleeping;
270 case DestructionFieldKind::Strain:
274 if (needGraphSync) syncBoneActivationFromGraph();
276 if (field.kind == DestructionFieldKind::Strain) {
277 for (
auto&
edge : edges_) {
278 if (
edge.broken)
continue;
279 if (
edge.boneA < 0 ||
edge.boneB < 0 ||
edge.boneA >=
static_cast<int>(bones_.size()) ||
280 edge.boneB >=
static_cast<int>(bones_.size()))
282 auto bodyA = bones_[
static_cast<std::size_t
>(
edge.boneA)].
link.resolve(*world);
283 auto bodyB = bones_[
static_cast<std::size_t
>(
edge.boneB)].
link.resolve(*world);
284 if (!bodyA || !bodyB)
continue;
285 const float midX = 0.5f * (bodyA.value()->getX() + bodyB.value()->getX());
286 const float midY = 0.5f * (bodyA.value()->getY() + bodyB.value()->getY());
287 const float midZ = 0.5f * (bodyA.value()->getZ() + bodyB.value()->getZ());
288 const float weight = falloffAt(field, midX, midY, midZ);
289 if (
weight <= 0.f)
continue;
290 edge.accumulatedStrain += field.magnitude *
weight;
298 auto&
edge = edges_[
static_cast<std::size_t
>(edgeIndex)];
299 if (
edge.broken)
return;
301 if (
static_cast<std::size_t
>(edgeIndex) < ownedJoints_.size())
302 ownedJoints_[
static_cast<std::size_t
>(edgeIndex)].reset();
303 edge.joint = PhysicsJointHandle::invalid();
308 event.boneB =
edge.boneB;
309 event.tick =
static_cast<std::int64_t
>(
tick);
310 detachEvents_.push_back(event);
312 if (
edge.boneA >= 0 &&
edge.boneB >= 0 &&
edge.boneA <
static_cast<int>(bones_.size()) &&
313 edge.boneB <
static_cast<int>(bones_.size())) {
314 const int clusterA = bones_[
static_cast<std::size_t
>(
edge.boneA)].
clusterId;
315 const int clusterB = bones_[
static_cast<std::size_t
>(
edge.boneB)].
clusterId;
316 if (clusterA != clusterB) {
322 clusterEvent.
tick =
static_cast<std::int64_t
>(
tick);
323 clusterBreakEvents_.push_back(clusterEvent);
329void GeometryCollectionInstance::syncBoneActivationFromGraph() {
330 const int boneCount =
static_cast<int>(bones_.size());
331 if (boneCount == 0)
return;
333 std::vector<std::vector<int>>
adjacency(
static_cast<std::size_t
>(boneCount));
334 for (
const auto&
edge : edges_) {
335 if (
edge.broken)
continue;
336 if (
edge.boneA < 0 ||
edge.boneB < 0 ||
edge.boneA >= boneCount ||
edge.boneB >= boneCount)
continue;
341 std::vector<int> component(
static_cast<std::size_t
>(boneCount), -1);
342 int componentCount = 0;
343 bool anyAnchored =
false;
344 for (
int i = 0; i < boneCount; ++i) {
345 if (bones_[
static_cast<std::size_t
>(i)].anchored) anyAnchored =
true;
346 if (component[
static_cast<std::size_t
>(i)] >= 0)
continue;
347 std::queue<int> queue;
349 component[
static_cast<std::size_t
>(i)] = componentCount;
350 while (!queue.empty()) {
351 const int cur = queue.front();
353 for (
int next :
adjacency[static_cast<
std::size_t>(cur)]) {
354 if (component[
static_cast<std::size_t
>(next)] >= 0)
continue;
355 component[
static_cast<std::size_t
>(
next)] = componentCount;
362 std::vector<bool> componentHasAnchor(
static_cast<std::size_t
>(componentCount),
false);
363 for (
int i = 0; i < boneCount; ++i) {
364 if (bones_[
static_cast<std::size_t
>(i)].anchored)
365 componentHasAnchor[
static_cast<std::size_t
>(component[
static_cast<std::size_t
>(i)])] =
true;
368 World3D* world = resolveWorld();
369 for (
int i = 0; i < boneCount; ++i) {
370 auto&
bone = bones_[
static_cast<std::size_t
>(i)];
371 if (
bone.state == BoneRuntimeState::Sleeping)
continue;
372 const bool stayAttached =
374 componentHasAnchor[
static_cast<std::size_t
>(component[
static_cast<std::size_t
>(i)])] ||
375 (!anyAnchored && componentCount == 1);
377 stayAttached ? BoneRuntimeState::Attached : BoneRuntimeState::Detached;
378 if (
bone.state == desired) {
380 if (desired == BoneRuntimeState::Attached && world) {
381 auto body =
bone.link.resolve(*world);
382 if (
body) setBoneBodyType(*
body.value(), desired);
386 bone.state = desired;
387 if (!world)
continue;
388 auto body =
bone.link.resolve(*world);
389 if (
body) setBoneBodyType(*
body.value(), desired);
395 if (
step.delta.nanoseconds() < 0)
398 const std::uint64_t
tick =
step.tick.value();
399 if (lastTick_ != 0 &&
tick <= lastTick_)
402 World3D* world = resolveWorld();
404 orphanedPhysics_ =
true;
408 orphanedPhysics_ =
false;
409 detachEvents_.clear();
410 clusterBreakEvents_.clear();
412 std::vector<int> toBreak = pendingEdgeBreaks_;
413 pendingEdgeBreaks_.clear();
414 for (std::size_t i = 0; i < edges_.size(); ++i) {
415 const auto&
edge = edges_[i];
416 if (
edge.broken)
continue;
417 if (
edge.accumulatedStrain >=
edge.strainThreshold) toBreak.push_back(
static_cast<int>(i));
419 std::sort(toBreak.begin(), toBreak.end());
420 toBreak.erase(std::unique(toBreak.begin(), toBreak.end()), toBreak.end());
423 budget_.maxEdgeBreaksPerStep > 0 ? budget_.maxEdgeBreaksPerStep :
static_cast<int>(toBreak.size());
424 int brokenThisStep = 0;
425 for (
int edgeIndex : toBreak) {
426 if (edgeIndex < 0 || edgeIndex >=
static_cast<int>(edges_.size()))
continue;
427 if (edges_[
static_cast<std::size_t
>(edgeIndex)].broken)
continue;
428 if (brokenThisStep >= budget) {
429 pendingEdgeBreaks_.push_back(edgeIndex);
433 breakEdge(edgeIndex,
tick, receipt);
436 if (receipt.
edgesBroken > 0) syncBoneActivationFromGraph();
442 if (boneIndex < 0 || boneIndex >=
static_cast<int>(bones_.size()))
return BoneRuntimeState::Attached;
443 return bones_[
static_cast<std::size_t
>(boneIndex)].
state;
446int GeometryCollectionInstance::boneClusterId(
int boneIndex)
const {
447 if (boneIndex < 0 || boneIndex >=
static_cast<int>(bones_.size()))
return -1;
448 return bones_[
static_cast<std::size_t
>(boneIndex)].
clusterId;
451float GeometryCollectionInstance::edgeStrain(
int edgeIndex)
const {
452 if (edgeIndex < 0 || edgeIndex >=
static_cast<int>(edges_.size()))
return 0.f;
453 return edges_[
static_cast<std::size_t
>(edgeIndex)].accumulatedStrain;
456bool GeometryCollectionInstance::isEdgeBroken(
int edgeIndex)
const {
457 if (edgeIndex < 0 || edgeIndex >=
static_cast<int>(edges_.size()))
return false;
458 return edges_[
static_cast<std::size_t
>(edgeIndex)].broken;
462 if (index < 0 || index >=
static_cast<int>(detachEvents_.size()))
return {};
463 return detachEvents_[
static_cast<std::size_t
>(
index)];
467 if (index < 0 || index >=
static_cast<int>(clusterBreakEvents_.size()))
return {};
468 return clusterBreakEvents_[
static_cast<std::size_t
>(
index)];
472 if (boneIndex < 0 || boneIndex >=
static_cast<int>(bones_.size()))
475 World3D* world = resolveWorld();
479 auto body = bones_[
static_cast<std::size_t
>(boneIndex)].
link.resolve(*world);
485 if (boneIndex < 0 || boneIndex >=
static_cast<int>(bones_.size()))
488 World3D* world = resolveWorld();
492 const auto&
bone = bones_[
static_cast<std::size_t
>(boneIndex)];
493 auto body =
bone.link.resolve(*world);
517 snapshot.lastTick =
static_cast<std::int64_t
>(lastTick_);
518 snapshot.sleepBatchRevision = sleepBatchRevision_;
519 snapshot.bones.reserve(bones_.size());
520 for (
const auto&
bone : bones_) {
522 boneSnap.
state =
static_cast<std::uint8_t
>(
bone.state);
531 snapshot.edges.reserve(edges_.size());
532 for (
const auto&
edge : edges_) {
549 if (
snapshot.bones.size() != bones_.size() ||
snapshot.edges.size() != edges_.size())
552 "instance-snapshot bone/edge counts must match the live instance",
"snapshot"));
553 World3D* world = resolveWorld();
555 orphanedPhysics_ =
true;
562 std::vector<BoneRuntime> stagedBones = bones_;
563 std::vector<EdgeRuntime> stagedEdges = edges_;
564 std::vector<Body3D*> bodies(
snapshot.bones.size(),
nullptr);
565 for (std::size_t i = 0; i <
snapshot.bones.size(); ++i) {
566 const auto& src =
snapshot.bones[i];
567 if (geometry_ && (src.halfExtentX != bones_[i].halfExtentX || src.halfExtentY != bones_[i].halfExtentY ||
568 src.halfExtentZ != bones_[i].halfExtentZ || src.clusterId != bones_[i].clusterId ||
569 src.fractureLevel != bones_[i].fractureLevel))
572 "snapshot cannot replace immutable fragment metadata",
"snapshot"));
574 stagedBones[i].anchored = src.anchored;
575 stagedBones[i].clusterId = src.clusterId;
576 stagedBones[i].fractureLevel = src.fractureLevel;
577 stagedBones[i].halfExtentX = src.halfExtentX;
578 stagedBones[i].halfExtentY = src.halfExtentY;
579 stagedBones[i].halfExtentZ = src.halfExtentZ;
580 auto body = stagedBones[i].link.resolve(*world);
582 bodies[i] =
body.value();
584 for (std::size_t i = 0; i <
snapshot.edges.size(); ++i) {
585 const auto& src =
snapshot.edges[i];
586 if (src.boneA != stagedEdges[i].boneA || src.boneB != stagedEdges[i].boneB)
589 stagedEdges[i].strainThreshold = src.strainThreshold;
590 stagedEdges[i].accumulatedStrain = src.accumulatedStrain;
591 stagedEdges[i].broken = src.broken;
595 auto stagedJoints = stageConstraints(stagedEdges);
597 releaseConstraints();
598 ownedJoints_ = std::move(stagedJoints).takeValue();
599 for (std::size_t i = 0; i < stagedEdges.size(); ++i)
600 stagedEdges[i].joint = ownedJoints_[i] ? ownedJoints_[i]->runtimeHandle() : PhysicsJointHandle::invalid();
602 for (std::size_t i = 0; i < stagedBones.size(); ++i) {
604 switch (stagedBones[i].
state) {
605 case BoneRuntimeState::Attached:
606 body->
setType(stagedBones[i].anchored ?
"static" :
"dynamic");
608 case BoneRuntimeState::Detached:
609 body->setType(
"dynamic");
610 body->setAwake(
true);
612 case BoneRuntimeState::Sleeping:
613 body->setType(
"static");
618 bones_ = std::move(stagedBones);
619 edges_ = std::move(stagedEdges);
623 lastTick_ =
static_cast<std::uint64_t
>(
snapshot.lastTick);
624 sleepBatchRevision_ =
snapshot.sleepBatchRevision;
625 detachEvents_.clear();
626 clusterBreakEvents_.clear();
627 pendingEdgeBreaks_.clear();
628 orphanedPhysics_ =
false;
632void GeometryCollectionInstance::destroyOwnedBodies(
World3D& world) {
633 for (
auto&
bone : bones_) {
634 auto body =
bone.link.resolve(world);
635 if (
body &&
body.value() &&
body.value()->isValid())
body.value()->destroy();
640void GeometryCollectionInstance::releaseBodies() {
641 releaseConstraints();
642 if (
World3D* world = resolveWorld()) {
643 destroyOwnedBodies(*world);
645 for (
auto&
bone : bones_)
bone.link = {};
646 orphanedPhysics_ =
true;
std::vector< Bone > bones
std::unique_ptr< DeformMeshPresentation > presentation
std::array< double, 3 > impulse
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.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
Backend-neutral 3D rigid body in meter-space coordinates (+Y up by convention). Owned by a World3D; c...
void setType(const std::string &bodyType)
"static" | "kinematic" | "dynamic".
Runtime owner of bone state, connection strain, and PhysicsLink bindings.
GeometryCollectionInstance(const GeometryCollectionInstance &)=delete
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Optional physics backend for vehicle mobility and body attach.
BoneRuntimeState
Runtime lifecycle for one bone inside a geometry-collection instance.
eve::RuntimeHandle< PhysicsWorldHandleTag > PhysicsWorldHandle
Generation-qualified runtime identity for a physics world.
One deterministic fixed-step emitted by SimulationClock.
One ordered detach event emitted during step.
Presentation snapshot for one bone (world pose + proxy extents).
Emitted when a broken edge separates two different cook clusters.
One volumetric influence applied to a geometry-collection instance.
Observable outcome of one checked step.
Observable receipt for one checked field application.
int sleepsDeferred
Sleep conversions skipped because of the per-step sleep budget.
Owning, typed mesh payload shared immutably by simulation, clip and renderer. @thread Read-only shari...
Immutable cooked/authored geometry-collection asset.
std::vector< GeometryCollectionEdge > edges
std::vector< GeometryCollectionBone > bones
eve::Result< void > validate() const
Validate bone/edge topology and numeric ranges.
Persistent runtime snapshot for one geometry-collection instance.