载入中...
搜索中...
未找到
GeometryCollectionInstance.cpp
浏览该文件的文档.
2
3#include "physics/Body3D.h"
4#include "physics/Joint3D.h"
5#include "physics/World3D.h"
8
9#include <algorithm>
10#include <cmath>
11#include <queue>
12#include <utility>
13
14namespace eve::physics {
15namespace {
16
17constexpr float kSleepSpeed = 0.05f;
18
19void setBoneBodyType(Body3D& body, BoneRuntimeState state) {
20 switch (state) {
23 body.setType("static");
24 break;
26 body.setType("dynamic");
27 body.setAwake(true);
28 break;
29 }
30}
31
32} // namespace
33
35 float originZ)
36 : worldHandle_(worldHandle), originX_(originX), originY_(originY), originZ_(originZ) {}
37
38GeometryCollectionInstance::~GeometryCollectionInstance() { releaseBodies(); }
39
41 World3D& world, const GeometryCollectionAsset& asset, float originX, float originY, float originZ) {
42 return createInternal(world, asset, {}, originX, originY, originZ);
43}
44std::shared_ptr<const FractureGeometry> GeometryCollectionInstance::fragmentGeometry() const noexcept {
45 return geometry_;
46}
47eve::Result<std::unique_ptr<GeometryCollectionInstance>> GeometryCollectionInstance::createFractured(
48 World3D& world, const GeometryCollectionAsset& asset, const FractureGeometry& geometry, float x, float y, float z) {
49 auto valid = geometry.validate();
51 if (geometry.fragments.size() != asset.bones.size())
53 eve::DiagnosticCode::InvalidArgument, "fragment count does not match bones", "geometry"));
54 for (std::size_t i = 0; i < geometry.fragments.size(); ++i) {
55 const auto& b = asset.bones[i];
56 const auto& f = geometry.fragments[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)
62 eve::DiagnosticCode::InvalidArgument, "fragment vertices exceed declared bounds", "geometry"));
63 }
64 return createInternal(world, asset, std::make_shared<const FractureGeometry>(geometry), x, y, z);
65}
66eve::Result<std::unique_ptr<GeometryCollectionInstance>> GeometryCollectionInstance::createInternal(
67 World3D& world, const GeometryCollectionAsset& asset, std::shared_ptr<const FractureGeometry> geometry,
68 float originX, float originY, float originZ) {
69 auto valid = asset.validate();
71 if (!std::isfinite(originX) || !std::isfinite(originY) || !std::isfinite(originZ))
73 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "instance origin must be finite", "origin"));
74 if (!world.isValid())
76 eve::DiagnosticCode::StaleHandle, "geometry-collection create requires a live World3D", "world"));
77
78 auto instance = std::unique_ptr<GeometryCollectionInstance>(
79 new GeometryCollectionInstance(world.runtimeHandle(), originX, originY, originZ));
80 instance->geometry_ = std::move(geometry);
81 instance->bones_.reserve(asset.bones.size());
82 instance->edges_.reserve(asset.edges.size());
83
84 std::vector<Body3D*> createdBodies;
85 createdBodies.reserve(asset.bones.size());
86 auto rollback = [&]() {
87 for (Body3D* body : createdBodies) {
88 if (body && body->isValid()) body->destroy();
89 }
90 createdBodies.clear();
91 instance->bones_.clear();
92 };
93
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;
98 // Intact Attached bones stay static so connection-graph topology (not
99 // independent dynamic bodies) keeps the collection from falling apart
100 // before any edge breaks. Detach sync promotes free islands to dynamic.
101 Body3D* body = world.newBody("static", x, y, z);
102 if (!body || !body->isValid()) {
103 rollback();
105 eve::DiagnosticCode::Failed, "geometry-collection failed to create a bone body", "body"));
106 }
107 try {
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);
112 } else {
113 body->newBoxShape(boneDef.halfExtentX * 2.f, boneDef.halfExtentY * 2.f, boneDef.halfExtentZ * 2.f,
114 boneDef.density, boneDef.friction, boneDef.restitution);
115 }
116 } catch (const std::exception& error) {
117 body->destroy();
118 rollback();
120 eve::Diagnostic::error(eve::DiagnosticCode::Failed, error.what(), "fragmentCollider"));
121 }
122 auto link = PhysicsLink::fromBody(*body);
123 if (!link) {
124 rollback();
125 if (body->isValid()) body->destroy();
127 }
128 BoneRuntime bone;
129 bone.state = BoneRuntimeState::Attached;
130 bone.anchored = boneDef.anchoredDefault;
131 bone.link = link.value();
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);
139 }
140
141 for (const auto& edgeDef : asset.edges) {
142 EdgeRuntime edge;
143 edge.boneA = edgeDef.boneA;
144 edge.boneB = edgeDef.boneB;
145 edge.strainThreshold = edgeDef.strainThreshold;
146 instance->edges_.push_back(edge);
147 }
148
149 if (instance->geometry_) {
150 auto constraints = instance->stageConstraints(instance->edges_);
151 if (!constraints) {
152 rollback();
153 return eve::Result<std::unique_ptr<GeometryCollectionInstance>>::failure(constraints.status());
154 }
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();
159 }
160 return eve::Result<std::unique_ptr<GeometryCollectionInstance>>::success(std::move(instance));
161}
162
163bool GeometryCollectionInstance::hasLiveWorld() const noexcept { return resolveWorld() != nullptr; }
164
165World3D* GeometryCollectionInstance::resolveWorld() const noexcept {
166 World3D* world = World3D::findWorld(worldHandle_);
167 if (!world || !world->isValid()) return nullptr;
168 return world;
169}
170
171eve::Result<Body3D*> GeometryCollectionInstance::resolveBoneBody(int boneIndex) const {
172 if (boneIndex < 0 || boneIndex >= static_cast<int>(bones_.size()))
174 eve::DiagnosticCode::InvalidArgument, "geometry-collection bone index is out of range", "bone"));
175 World3D* world = resolveWorld();
176 if (!world)
178 eve::DiagnosticCode::StaleHandle, "geometry-collection world is gone", "world"));
179 return bones_[static_cast<std::size_t>(boneIndex)].link.resolve(*world);
180}
181
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;
191}
192
193eve::Result<FieldApplicationReceipt> GeometryCollectionInstance::applyField(const DestructionField& field) {
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))
197 eve::DiagnosticCode::InvalidArgument, "destruction field parameters must be finite", "field"));
198 if (field.kind == DestructionFieldKind::Impulse &&
199 (!std::isfinite(field.dirX) || !std::isfinite(field.dirY) || !std::isfinite(field.dirZ)))
201 eve::DiagnosticCode::InvalidArgument, "impulse field direction must be finite", "field"));
202 World3D* world = resolveWorld();
203 if (!world) {
204 orphanedPhysics_ = true;
206 eve::DiagnosticCode::StaleHandle, "geometry-collection world is gone", "world"));
207 }
208
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;
215 Body3D* body = bodyResult.value();
216 const float weight = falloffAt(field, body->getX(), body->getY(), body->getZ());
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_;
225 ++receipt.bonesAffected;
226 needGraphSync = true;
227 break;
228 }
229 case DestructionFieldKind::Impulse: {
230 // Anchored foundations and still-Attached graph members stay put.
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);
234 if (len <= 1e-6f) {
235 dx = 0.f;
236 dy = 1.f;
237 dz = 0.f;
238 } else {
239 dx /= len;
240 dy /= len;
241 dz /= len;
242 }
243 const float impulse = field.magnitude * weight;
244 const bool wasSleeping = bones_[i].state == BoneRuntimeState::Sleeping;
245 body->setType("dynamic");
246 body->applyLinearImpulse(dx * impulse, dy * impulse, dz * impulse);
247 bones_[i].state = BoneRuntimeState::Detached;
248 if (wasSleeping) ++sleepBatchRevision_;
249 ++receipt.bonesAffected;
250 break;
251 }
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) {
260 ++receipt.sleepsDeferred;
261 break;
262 }
263 body->setType("static");
264 if (bones_[i].state != BoneRuntimeState::Sleeping) ++sleepBatchRevision_;
265 bones_[i].state = BoneRuntimeState::Sleeping;
266 ++receipt.bonesAffected;
267 ++sleepsThisCall;
268 break;
269 }
270 case DestructionFieldKind::Strain:
271 break;
272 }
273 }
274 if (needGraphSync) syncBoneActivationFromGraph();
275
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()))
281 continue;
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;
291 ++receipt.edgesAffected;
292 }
293 }
295}
296
297void GeometryCollectionInstance::breakEdge(int edgeIndex, std::uint64_t tick, DestructionStepReceipt& receipt) {
298 auto& edge = edges_[static_cast<std::size_t>(edgeIndex)];
299 if (edge.broken) return;
300 edge.broken = true;
301 if (static_cast<std::size_t>(edgeIndex) < ownedJoints_.size())
302 ownedJoints_[static_cast<std::size_t>(edgeIndex)].reset();
303 edge.joint = PhysicsJointHandle::invalid();
304 ++receipt.edgesBroken;
305
306 BoneDetachEvent event;
307 event.boneA = edge.boneA;
308 event.boneB = edge.boneB;
309 event.tick = static_cast<std::int64_t>(tick);
310 detachEvents_.push_back(event);
311
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) {
317 ClusterBreakEvent clusterEvent;
318 clusterEvent.clusterA = clusterA;
319 clusterEvent.clusterB = clusterB;
320 clusterEvent.boneA = edge.boneA;
321 clusterEvent.boneB = edge.boneB;
322 clusterEvent.tick = static_cast<std::int64_t>(tick);
323 clusterBreakEvents_.push_back(clusterEvent);
324 ++receipt.clusterBreaks;
325 }
326 }
327}
328
329void GeometryCollectionInstance::syncBoneActivationFromGraph() {
330 const int boneCount = static_cast<int>(bones_.size());
331 if (boneCount == 0) return;
332
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;
337 adjacency[static_cast<std::size_t>(edge.boneA)].push_back(edge.boneB);
338 adjacency[static_cast<std::size_t>(edge.boneB)].push_back(edge.boneA);
339 }
340
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;
348 queue.push(i);
349 component[static_cast<std::size_t>(i)] = componentCount;
350 while (!queue.empty()) {
351 const int cur = queue.front();
352 queue.pop();
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;
356 queue.push(next);
357 }
358 }
359 ++componentCount;
360 }
361
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;
366 }
367
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; // Sleep is sticky until Impulse/Anchor
372 const bool stayAttached =
373 bone.anchored ||
374 componentHasAnchor[static_cast<std::size_t>(component[static_cast<std::size_t>(i)])] ||
375 (!anyAnchored && componentCount == 1);
376 const BoneRuntimeState desired =
377 stayAttached ? BoneRuntimeState::Attached : BoneRuntimeState::Detached;
378 if (bone.state == desired) {
379 // Ensure Attached bones remain static even if a prior path made them dynamic.
380 if (desired == BoneRuntimeState::Attached && world) {
381 auto body = bone.link.resolve(*world);
382 if (body) setBoneBodyType(*body.value(), desired);
383 }
384 continue;
385 }
386 bone.state = desired;
387 if (!world) continue;
388 auto body = bone.link.resolve(*world);
389 if (body) setBoneBodyType(*body.value(), desired);
390 }
391}
392
393eve::Result<DestructionStepReceipt> GeometryCollectionInstance::step(SimulationStep step) {
395 if (step.delta.nanoseconds() < 0)
397 eve::DiagnosticCode::InvalidArgument, "geometry-collection step delta must be non-negative", "step"));
398 const std::uint64_t tick = step.tick.value();
399 if (lastTick_ != 0 && tick <= lastTick_)
401 eve::DiagnosticCode::InvalidArgument, "geometry-collection step tick must advance", "step"));
402 World3D* world = resolveWorld();
403 if (!world) {
404 orphanedPhysics_ = true;
406 eve::DiagnosticCode::StaleHandle, "geometry-collection world is gone", "world"));
407 }
408 orphanedPhysics_ = false;
409 detachEvents_.clear();
410 clusterBreakEvents_.clear();
411
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));
418 }
419 std::sort(toBreak.begin(), toBreak.end());
420 toBreak.erase(std::unique(toBreak.begin(), toBreak.end()), toBreak.end());
421
422 const int budget =
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);
430 ++receipt.edgesDeferred;
431 continue;
432 }
433 breakEdge(edgeIndex, tick, receipt);
434 ++brokenThisStep;
435 }
436 if (receipt.edgesBroken > 0) syncBoneActivationFromGraph();
437 lastTick_ = tick;
439}
440
441BoneRuntimeState GeometryCollectionInstance::boneState(int boneIndex) const {
442 if (boneIndex < 0 || boneIndex >= static_cast<int>(bones_.size())) return BoneRuntimeState::Attached;
443 return bones_[static_cast<std::size_t>(boneIndex)].state;
444}
445
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;
449}
450
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;
454}
455
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;
459}
460
461BoneDetachEvent GeometryCollectionInstance::detachEventAt(int index) const {
462 if (index < 0 || index >= static_cast<int>(detachEvents_.size())) return {};
463 return detachEvents_[static_cast<std::size_t>(index)];
464}
465
466ClusterBreakEvent GeometryCollectionInstance::clusterBreakEventAt(int index) const {
467 if (index < 0 || index >= static_cast<int>(clusterBreakEvents_.size())) return {};
468 return clusterBreakEvents_[static_cast<std::size_t>(index)];
469}
470
471eve::Result<PhysicsLink> GeometryCollectionInstance::boneLink(int boneIndex) const {
472 if (boneIndex < 0 || boneIndex >= static_cast<int>(bones_.size()))
474 eve::DiagnosticCode::InvalidArgument, "geometry-collection bone index is out of range", "bone"));
475 World3D* world = resolveWorld();
476 if (!world)
478 eve::DiagnosticCode::StaleHandle, "geometry-collection world is gone", "world"));
479 auto body = bones_[static_cast<std::size_t>(boneIndex)].link.resolve(*world);
480 if (!body) return eve::Result<PhysicsLink>::failure(body.status());
481 return eve::Result<PhysicsLink>::success(bones_[static_cast<std::size_t>(boneIndex)].link);
482}
483
484eve::Result<BonePresentation> GeometryCollectionInstance::bonePresentation(int boneIndex) const {
485 if (boneIndex < 0 || boneIndex >= static_cast<int>(bones_.size()))
487 eve::DiagnosticCode::InvalidArgument, "geometry-collection bone index is out of range", "bone"));
488 World3D* world = resolveWorld();
489 if (!world)
491 eve::DiagnosticCode::StaleHandle, "geometry-collection world is gone", "world"));
492 const auto& bone = bones_[static_cast<std::size_t>(boneIndex)];
493 auto body = bone.link.resolve(*world);
494 if (!body) return eve::Result<BonePresentation>::failure(body.status());
496 presentation.state = bone.state;
497 presentation.halfExtentX = bone.halfExtentX;
498 presentation.halfExtentY = bone.halfExtentY;
499 presentation.halfExtentZ = bone.halfExtentZ;
500 presentation.worldX = body.value()->getX();
501 presentation.worldY = body.value()->getY();
502 presentation.worldZ = body.value()->getZ();
503 presentation.rotX = body.value()->getRotX();
504 presentation.rotY = body.value()->getRotY();
505 presentation.rotZ = body.value()->getRotZ();
506 presentation.rotW = body.value()->getRotW();
507 presentation.clusterId = bone.clusterId;
508 presentation.fractureLevel = bone.fractureLevel;
510}
511
512eve::Result<GeometryCollectionInstanceSnapshot> GeometryCollectionInstance::captureSnapshot() const {
514 snapshot.originX = originX_;
515 snapshot.originY = originY_;
516 snapshot.originZ = originZ_;
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);
523 boneSnap.anchored = bone.anchored;
524 boneSnap.clusterId = bone.clusterId;
525 boneSnap.fractureLevel = bone.fractureLevel;
526 boneSnap.halfExtentX = bone.halfExtentX;
527 boneSnap.halfExtentY = bone.halfExtentY;
528 boneSnap.halfExtentZ = bone.halfExtentZ;
529 snapshot.bones.push_back(boneSnap);
530 }
531 snapshot.edges.reserve(edges_.size());
532 for (const auto& edge : edges_) {
534 edgeSnap.boneA = edge.boneA;
535 edgeSnap.boneB = edge.boneB;
536 edgeSnap.strainThreshold = edge.strainThreshold;
537 edgeSnap.accumulatedStrain = edge.accumulatedStrain;
538 edgeSnap.broken = edge.broken;
539 snapshot.edges.push_back(edgeSnap);
540 }
541 auto valid = snapshot.validate();
544}
545
546eve::Result<void> GeometryCollectionInstance::restoreSnapshot(const GeometryCollectionInstanceSnapshot& snapshot) {
547 auto valid = snapshot.validate();
548 if (!valid) return eve::Result<void>::failure(valid.status());
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();
554 if (!world) {
555 orphanedPhysics_ = true;
557 eve::DiagnosticCode::StaleHandle, "geometry-collection world is gone", "world"));
558 }
559
560 // Stage + resolve every body before mutating World3D so failures leave both
561 // the instance topology and body types unchanged.
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"));
573 stagedBones[i].state = static_cast<BoneRuntimeState>(src.state);
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);
581 if (!body) return eve::Result<void>::failure(body.status());
582 bodies[i] = body.value();
583 }
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)
588 eve::DiagnosticCode::InvalidArgument, "instance-snapshot edge topology mismatch", "edges"));
589 stagedEdges[i].strainThreshold = src.strainThreshold;
590 stagedEdges[i].accumulatedStrain = src.accumulatedStrain;
591 stagedEdges[i].broken = src.broken;
592 }
593
594 if (geometry_) {
595 auto stagedJoints = stageConstraints(stagedEdges);
596 if (!stagedJoints) return eve::Result<void>::failure(stagedJoints.status());
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();
601 }
602 for (std::size_t i = 0; i < stagedBones.size(); ++i) {
603 Body3D* body = bodies[i];
604 switch (stagedBones[i].state) {
605 case BoneRuntimeState::Attached:
606 body->setType(stagedBones[i].anchored ? "static" : "dynamic");
607 break;
608 case BoneRuntimeState::Detached:
609 body->setType("dynamic");
610 body->setAwake(true);
611 break;
612 case BoneRuntimeState::Sleeping:
613 body->setType("static");
614 break;
615 }
616 }
617
618 bones_ = std::move(stagedBones);
619 edges_ = std::move(stagedEdges);
620 originX_ = snapshot.originX;
621 originY_ = snapshot.originY;
622 originZ_ = snapshot.originZ;
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;
630}
631
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();
636 bone.link = {};
637 }
638}
639
640void GeometryCollectionInstance::releaseBodies() {
641 releaseConstraints();
642 if (World3D* world = resolveWorld()) {
643 destroyOwnedBodies(*world);
644 } else {
645 for (auto& bone : bones_) bone.link = {};
646 orphanedPhysics_ = true;
647 }
648}
649
650} // namespace eve::physics
double z
double y
double x
float v
PhysicsJointLink link
std::vector< Bone > bones
std::uint32_t bone
std::vector< Edge > edges
std::map< std::string, std::vector< size_t > > adjacency
Snapshot snapshot
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
glm::dvec3 dx
glm::dvec3 dz
std::string error
Definition Package.cpp:174
float f
std::unique_ptr< DeformMeshPresentation > presentation
std::string body
std::string geometry
float dy
Definition Shadow.cpp:151
SimulationTick tick
float step
Definition TreeMesh.cpp:451
double weight
uint32_t index
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.
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
Backend-neutral 3D rigid body in meter-space coordinates (+Y up by convention). Owned by a World3D; c...
Definition Body3D.h:31
void setType(const std::string &bodyType)
"static" | "kinematic" | "dynamic".
Definition Body3D.cpp:383
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...
Definition World3D.h:47
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
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.
Definition Time.h:158
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.