载入中...
搜索中...
未找到
Destruction.cpp
浏览该文件的文档.
3
4#include "common/Exception.h"
5#include "common/Json.h"
6#include "common/Value.h"
7#include "physics/World3D.h"
8
9#include <simplesquirrel/simplesquirrel.hpp>
10
11#include <functional>
12#include <utility>
13
14namespace eve::physics {
15
17
23
25 auto parsed = eve::Value::fromJson(json);
26 if (!parsed) return eve::Result<GeometryCollectionAsset>::failure(parsed.status());
27 return GeometryCollectionAsset::fromValue(parsed.value());
28}
29
33
37
39 World3D* world, const GeometryCollectionAsset& asset, float originX, float originY, float originZ) {
40 if (!world)
42 eve::DiagnosticCode::InvalidArgument, "geometry-collection create requires a World3D", "world"));
43 return GeometryCollectionInstance::create(*world, asset, originX, originY, originZ);
44}
45
47 auto created = makeWeldedBoxesFixture(strainThreshold);
48 if (!created.ok()) {
49 const auto* diagnostic = created.status().primaryDiagnostic();
50 throw Exception("Destruction.newWeldedBoxesFixture: %s",
51 diagnostic ? diagnostic->message().c_str() : "creation failed");
52 }
53 return new GeometryCollectionAsset(std::move(created.value()));
54}
55
57 auto created = makeClusterPillarFixture(interClusterStrain);
58 if (!created.ok()) {
59 const auto* diagnostic = created.status().primaryDiagnostic();
60 throw Exception("Destruction.newClusterPillarFixture: %s",
61 diagnostic ? diagnostic->message().c_str() : "creation failed");
62 }
63 return new GeometryCollectionAsset(std::move(created.value()));
64}
65
67 auto decoded = assetFromJson(json);
68 if (!decoded.ok()) {
69 const auto* diagnostic = decoded.status().primaryDiagnostic();
70 throw Exception("Destruction.assetFromJson: %s",
71 diagnostic ? diagnostic->message().c_str() : "decode failed");
72 }
73 return new GeometryCollectionAsset(std::move(decoded.value()));
74}
75
77 float originX, float originY, float originZ) {
78 if (!asset) throw Exception("Destruction.createInstance: asset is null");
79 auto created = createInstance(world, *asset, originX, originY, originZ);
80 if (!created.ok()) {
81 const auto* diagnostic = created.status().primaryDiagnostic();
82 throw Exception("Destruction.createInstance: %s",
83 diagnostic ? diagnostic->message().c_str() : "creation failed");
84 }
85 return created.value().release();
86}
87
88namespace {
89
90DestructionField makeStrainField(float x, float y, float z, float radius, float magnitude) {
94 field.centerX = x;
95 field.centerY = y;
96 field.centerZ = z;
97 field.radius = radius;
98 field.magnitude = magnitude;
99 return field;
100}
101
102DestructionField makeAnchorField(float x, float y, float z, float radius) {
103 DestructionField field;
106 field.centerX = x;
107 field.centerY = y;
108 field.centerZ = z;
109 field.radius = radius;
110 field.magnitude = 1.f;
111 return field;
112}
113
114DestructionField makeSleepField(float x, float y, float z, float radius) {
115 DestructionField field;
118 field.centerX = x;
119 field.centerY = y;
120 field.centerZ = z;
121 field.radius = radius;
122 field.magnitude = 1.f;
123 return field;
124}
125
126DestructionField makeImpulseField(float x, float y, float z, float radius, float magnitude, float dirX, float dirY,
127 float dirZ) {
128 DestructionField field;
131 field.centerX = x;
132 field.centerY = y;
133 field.centerZ = z;
134 field.radius = radius;
135 field.magnitude = magnitude;
136 field.dirX = dirX;
137 field.dirY = dirY;
138 field.dirZ = dirZ;
139 return field;
140}
141
142void applyStrainFieldScript(GeometryCollectionInstance* self, float x, float y, float z, float radius,
143 float magnitude) {
144 if (!self) throw Exception("GeometryCollectionInstance.applyStrainField: null");
145 auto result = self->applyField(makeStrainField(x, y, z, radius, magnitude));
146 if (!result.ok()) {
147 const auto* diagnostic = result.status().primaryDiagnostic();
148 throw Exception("GeometryCollectionInstance.applyStrainField: %s",
149 diagnostic ? diagnostic->message().c_str() : "failed");
150 }
151}
152
153void applyAnchorFieldScript(GeometryCollectionInstance* self, float x, float y, float z, float radius) {
154 if (!self) throw Exception("GeometryCollectionInstance.applyAnchorField: null");
155 auto result = self->applyField(makeAnchorField(x, y, z, radius));
156 if (!result.ok()) {
157 const auto* diagnostic = result.status().primaryDiagnostic();
158 throw Exception("GeometryCollectionInstance.applyAnchorField: %s",
159 diagnostic ? diagnostic->message().c_str() : "failed");
160 }
161}
162
163void applySleepFieldScript(GeometryCollectionInstance* self, float x, float y, float z, float radius) {
164 if (!self) throw Exception("GeometryCollectionInstance.applySleepField: null");
165 auto result = self->applyField(makeSleepField(x, y, z, radius));
166 if (!result.ok()) {
167 const auto* diagnostic = result.status().primaryDiagnostic();
168 throw Exception("GeometryCollectionInstance.applySleepField: %s",
169 diagnostic ? diagnostic->message().c_str() : "failed");
170 }
171}
172
173void applyImpulseFieldScript(GeometryCollectionInstance* self, float x, float y, float z, float radius,
174 float magnitude, float dirX, float dirY, float dirZ) {
175 if (!self) throw Exception("GeometryCollectionInstance.applyImpulseField: null");
176 auto result = self->applyField(makeImpulseField(x, y, z, radius, magnitude, dirX, dirY, dirZ));
177 if (!result.ok()) {
178 const auto* diagnostic = result.status().primaryDiagnostic();
179 throw Exception("GeometryCollectionInstance.applyImpulseField: %s",
180 diagnostic ? diagnostic->message().c_str() : "failed");
181 }
182}
183
184void stepScript(GeometryCollectionInstance* self, int tick, float dtSeconds) {
185 if (!self) throw Exception("GeometryCollectionInstance.step: null");
186 auto delta = eve::Duration::fromSeconds(dtSeconds);
187 if (!delta.ok()) throw Exception("GeometryCollectionInstance.step: invalid dt");
188 eve::SimulationStep step{eve::SimulationTick{static_cast<std::uint64_t>(tick)}, delta.value()};
189 auto result = self->step(step);
190 if (!result.ok()) {
191 const auto* diagnostic = result.status().primaryDiagnostic();
192 throw Exception("GeometryCollectionInstance.step: %s",
193 diagnostic ? diagnostic->message().c_str() : "failed");
194 }
195}
196
197int boneStateScript(GeometryCollectionInstance* self, int boneIndex) {
198 if (!self) throw Exception("GeometryCollectionInstance.boneState: null");
199 return static_cast<int>(self->boneState(boneIndex));
200}
201
202void setStepBudgetScript(GeometryCollectionInstance* self, int maxEdgeBreaks, int maxSleeps) {
203 if (!self) throw Exception("GeometryCollectionInstance.setStepBudget: null");
204 if (maxEdgeBreaks < 0 || maxSleeps < 0)
205 throw Exception("GeometryCollectionInstance.setStepBudget: budgets must be non-negative");
206 DestructionStepBudget budget;
207 budget.maxEdgeBreaksPerStep = maxEdgeBreaks;
208 budget.maxSleepsPerStep = maxSleeps;
209 self->setStepBudget(budget);
210}
211
212std::string captureSnapshotJsonScript(GeometryCollectionInstance* self) {
213 if (!self) throw Exception("GeometryCollectionInstance.captureSnapshotJson: null");
214 auto snapshot = self->captureSnapshot();
215 if (!snapshot.ok()) {
216 const auto* diagnostic = snapshot.status().primaryDiagnostic();
217 throw Exception("GeometryCollectionInstance.captureSnapshotJson: %s",
218 diagnostic ? diagnostic->message().c_str() : "failed");
219 }
220 auto encoded = snapshot.value().toValue();
221 if (!encoded.ok()) {
222 const auto* diagnostic = encoded.status().primaryDiagnostic();
223 throw Exception("GeometryCollectionInstance.captureSnapshotJson: %s",
224 diagnostic ? diagnostic->message().c_str() : "encode failed");
225 }
226 auto json = encoded.value().toJson();
227 if (!json.ok()) {
228 const auto* diagnostic = json.status().primaryDiagnostic();
229 throw Exception("GeometryCollectionInstance.captureSnapshotJson: %s",
230 diagnostic ? diagnostic->message().c_str() : "json failed");
231 }
232 return json.value();
233}
234
235void restoreSnapshotJsonScript(GeometryCollectionInstance* self, const std::string& json) {
236 if (!self) throw Exception("GeometryCollectionInstance.restoreSnapshotJson: null");
237 auto parsed = eve::Value::fromJson(json);
238 if (!parsed.ok()) {
239 const auto* diagnostic = parsed.status().primaryDiagnostic();
240 throw Exception("GeometryCollectionInstance.restoreSnapshotJson: %s",
241 diagnostic ? diagnostic->message().c_str() : "parse failed");
242 }
244 if (!snapshot.ok()) {
245 const auto* diagnostic = snapshot.status().primaryDiagnostic();
246 throw Exception("GeometryCollectionInstance.restoreSnapshotJson: %s",
247 diagnostic ? diagnostic->message().c_str() : "decode failed");
248 }
249 auto restored = self->restoreSnapshot(snapshot.value());
250 if (!restored.ok()) {
251 const auto* diagnostic = restored.status().primaryDiagnostic();
252 throw Exception("GeometryCollectionInstance.restoreSnapshotJson: %s",
253 diagnostic ? diagnostic->message().c_str() : "restore failed");
254 }
255}
256
257} // namespace
258
259void Destruction::expose(ssq::Table& table) {
261 auto cls = table.addClass(name, Destruction::create, false);
262 expose(cls);
263
264 auto asset = table.addClass<GeometryCollectionAsset>(
265 "GeometryCollectionAsset", std::function<GeometryCollectionAsset*()>([]() -> GeometryCollectionAsset* {
266 return nullptr;
267 }),
268 true);
269 (void)asset;
270
271 auto instance = table.addClass<GeometryCollectionInstance>(
272 "GeometryCollectionInstance",
273 std::function<GeometryCollectionInstance*()>([]() -> GeometryCollectionInstance* { return nullptr; }), true);
274 instance.addFunc("applyStrainField", applyStrainFieldScript);
275 instance.addFunc("applyAnchorField", applyAnchorFieldScript);
276 instance.addFunc("applySleepField", applySleepFieldScript);
277 instance.addFunc("applyImpulseField", applyImpulseFieldScript);
278 instance.addFunc("step", stepScript);
279 instance.addFunc("setStepBudget", setStepBudgetScript);
280 instance.addFunc("boneCount", [](GeometryCollectionInstance* self) { return self->boneCount(); });
281 instance.addFunc("edgeCount", [](GeometryCollectionInstance* self) { return self->edgeCount(); });
282 instance.addFunc("boneState", boneStateScript);
283 instance.addFunc("boneClusterId", [](GeometryCollectionInstance* self, int boneIndex) {
284 return self->boneClusterId(boneIndex);
285 });
286 instance.addFunc("edgeStrain", [](GeometryCollectionInstance* self, int edgeIndex) {
287 return self->edgeStrain(edgeIndex);
288 });
289 instance.addFunc("isEdgeBroken", [](GeometryCollectionInstance* self, int edgeIndex) {
290 return self->isEdgeBroken(edgeIndex);
291 });
292 instance.addFunc("detachEventCount", [](GeometryCollectionInstance* self) {
293 return self->detachEventCount();
294 });
295 instance.addFunc("clusterBreakEventCount", [](GeometryCollectionInstance* self) {
296 return self->clusterBreakEventCount();
297 });
298 instance.addFunc("pendingEdgeBreakCount", [](GeometryCollectionInstance* self) {
299 return self->pendingEdgeBreakCount();
300 });
301 instance.addFunc("hasLiveWorld", [](GeometryCollectionInstance* self) { return self->hasLiveWorld(); });
302 instance.addFunc("sleepBatchRevision", [](GeometryCollectionInstance* self) {
303 return static_cast<int>(self->sleepBatchRevision());
304 });
305 instance.addFunc("captureSnapshotJson", captureSnapshotJsonScript);
306 instance.addFunc("restoreSnapshotJson", restoreSnapshotJsonScript);
307 instance.addFunc("releaseBodies", [](GeometryCollectionInstance* self) { self->releaseBodies(); });
308}
309
310void Destruction::expose(ssq::Class& cls) {
311 cls.addFunc("registerGeometryCollectionSchema", [](Destruction* self) {
312 auto result = self->registerGeometryCollectionSchema();
313 if (!result.ok()) {
314 const auto* diagnostic = result.status().primaryDiagnostic();
315 throw Exception("Destruction.registerGeometryCollectionSchema: %s",
316 diagnostic ? diagnostic->message().c_str() : "failed");
317 }
318 });
319 cls.addFunc("newWeldedBoxesFixture", &Destruction::newWeldedBoxesFixtureScript);
320 cls.addFunc("newClusterPillarFixture", &Destruction::newClusterPillarFixtureScript);
321 cls.addFunc("assetFromJson", &Destruction::assetFromJsonScript);
322 cls.addFunc("createInstance", &Destruction::createInstanceScript);
323}
324
325} // namespace eve::physics
double z
double y
double x
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
Poco::JSON::Object::Ptr result
Snapshot snapshot
double radius
Definition MeleeHit.cpp:42
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
int created
SimulationTick tick
float step
Definition TreeMesh.cpp:451
Owning, renderer-independent dynamic values.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
Type kind() const noexcept
Compatibility spelling for the former dialogue data tree.
Definition Value.h:96
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
Optional physics satellite for Chaos-style geometry-collection destruction.
Definition Destruction.h:22
GeometryCollectionInstance * createInstanceScript(World3D *world, GeometryCollectionAsset *asset, float originX, float originY, float originZ)
Script facade: create instance or throw; VM owns the pointer.
GeometryCollectionAsset * newClusterPillarFixtureScript(float interClusterStrain)
Script facade: cluster pillar fixture or throw.
eve::Result< GeometryCollectionAsset > makeWeldedBoxesFixture(float strainThreshold=1.f)
Build the two-box welded fixture used by demos and tests.
GeometryCollectionAsset * assetFromJsonScript(const std::string &json)
Script facade: decode asset JSON or throw; VM owns the pointer.
eve::Result< std::unique_ptr< GeometryCollectionInstance > > createInstance(World3D *world, const GeometryCollectionAsset &asset, float originX, float originY, float originZ)
Instantiate a collection against a live World3D. @ownership Caller owns the returned instance.
GeometryCollectionAsset * newWeldedBoxesFixtureScript(float strainThreshold)
Script facade: welded boxes fixture or throw.
eve::Result< GeometryCollectionAsset > makeClusterPillarFixture(float interClusterStrain=0.8f)
Build the two-cluster anchored pillar fixture used by demos.
eve::Result< void > registerGeometryCollectionSchema()
Registers asset physics:geometry-collection@2 and instance snapshot physics:geometry-collection-insta...
eve::Result< GeometryCollectionAsset > assetFromJson(const std::string &json)
Decode a versioned asset document.
Runtime owner of bone state, connection strain, and PhysicsLink bindings.
static eve::Result< std::unique_ptr< GeometryCollectionInstance > > create(World3D &world, const GeometryCollectionAsset &asset, float originX, float originY, float originZ)
Create bodies for every bone and bind PhysicsLinks.
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
const Value * field(const Value::Object &object, std::string_view name)
Borrow an optional field only during the current synchronous codec call. @ownership Object owns the r...
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
EVENGINE_API_DOMAINS void exposeCollapseAnimation(ssq::Table &table)
Register owning animation and sampled pose script types in the destruction VM module.
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
One volumetric influence applied to a geometry-collection instance.
Immutable cooked/authored geometry-collection asset.
static eve::Result< void > ensureSchemaRegistered()
Idempotently register version 2 in the process schema registry.
static eve::Result< GeometryCollectionAsset > fromValue(const eve::Value &value)
Decode and validate version 2, or migrate version 1 (cluster fields = 0).
static eve::Result< GeometryCollectionAsset > makeWeldedBoxesFixture(float strainThreshold=1.f)
Build a two-box welded fixture used by tests and the smoke example.
static eve::Result< GeometryCollectionAsset > makeClusterPillarFixture(float interClusterStrain=0.8f)
Build a 2×3 anchored pillar with two cook clusters for demos.
static eve::Result< void > ensureSchemaRegistered()
Idempotently register version 1 in the process schema registry.
static eve::Result< GeometryCollectionInstanceSnapshot > fromValue(const eve::Value &value)
Decode and validate version 1 transactionally.