载入中...
搜索中...
未找到
WorldSnapshotCodec.cpp
浏览该文件的文档.
1#include "physics/World.h"
4
5#include "physics/Body.h"
6#include "physics/Body3D.h"
7#include "physics/Fixture.h"
8#include "physics/Joint3D.h"
9#include "physics/Shape3D.h"
10#include "physics/World3D.h"
12
13#include <Box2D/Box2D.h>
14#include <box3d/box3d.h>
15
16#include <algorithm>
17#include <charconv>
18#include <cmath>
19#include <cstdint>
20#include <exception>
21#include <initializer_list>
22#include <limits>
23#include <set>
24#include <string>
25#include <string_view>
26#include <utility>
27#include <vector>
28
31
34 const auto parsed = eve::LogicalId::parse(text);
35 if (!parsed)
37 eve::DiagnosticCode::InvariantViolation, "physics snapshot schema constant is invalid", "schema"));
39}
40
41eve::Result<void> checkEnvelope(const eve::SnapshotEnvelope& snapshot, std::string_view type, std::string_view schema) {
42 if (snapshot.type != type || snapshot.schema.format() != schema)
45 "snapshot type or schema does not belong to this physics world", "snapshot.type"));
47 if (snapshot.schemaVersion.value() != current && snapshot.schemaVersion.value() != current - 1 &&
48 !(type == kWorld3DType && snapshot.schemaVersion.value() == 1))
51 "physics world snapshot schema version is not supported", "snapshot.schemaVersion"));
53}
54
55
57 const eve::SnapshotEnvelope& snapshot) {
58 auto tick = readUint64(object, "tick");
60 auto revision = readUint64(object, "revision");
62 auto stepCount = readUint64(object, "stepCount");
63 if (!stepCount) return eve::Result<ObservationState>::failure(stepCount.status());
64 auto duration = readInt64(object, "simulatedDurationNs");
66 auto lastDelta = readFloat(object, "lastDeltaSeconds");
67 if (!lastDelta) return eve::Result<ObservationState>::failure(lastDelta.status());
68 if (duration.value() < 0 || revision.value() != stepCount.value() || tick.value() != snapshot.tick.value() ||
69 stepCount.value() != snapshot.revision.value()) {
71 eve::DiagnosticCode::Conflict, "physics snapshot payload progress disagrees with its envelope",
72 "payload.observation"));
73 }
74
76 result.value.stepCount = stepCount.value();
77 result.value.lastTick = eve::SimulationTick(tick.value());
78 result.value.simulatedDuration = eve::Duration::fromNanoseconds(duration.value());
79 result.value.simulatedSeconds = result.value.simulatedDuration.seconds();
80 result.value.lastDeltaSeconds = lastDelta.value();
81 auto valid = detail::validateSimulationObservation(result.value, "physics.snapshot.observation");
84}
85
86
87bool validBodyType(const std::string& type) { return type == "static" || type == "kinematic" || type == "dynamic"; }
88
90 const auto* object = value.getIf<eve::Value::Object>();
91 if (!object || !hasExactFields(*object, {"active", "angle", "awake", "bullet", "fixedRotation", "fixtures",
92 "dynamics", "id", "type", "vx", "vy", "angularVelocity", "x", "y"}))
95 "2D physics snapshot body has unknown or missing fields", "payload.bodies"));
97 auto id = readUint64(*object, "id");
98 if (!id || id.value() == 0 || id.value() >= static_cast<std::uint64_t>(std::numeric_limits<int>::max()))
100 eve::DiagnosticCode::ParseError, "2D physics snapshot body id is invalid", "payload.bodies.id"));
101 state.id = static_cast<int>(id.value());
102 auto type = readString(*object, "type");
103 if (!type || !validBodyType(type.value()))
105 eve::DiagnosticCode::InvalidArgument, "2D physics snapshot body type is invalid", "payload.bodies.type"));
106 state.type = std::move(type).takeValue();
107 auto x = readFloat(*object, "x");
108 if (!x) return eve::Result<Body2DState>::failure(x.status());
109 state.x = x.value();
110 auto y = readFloat(*object, "y");
111 if (!y) return eve::Result<Body2DState>::failure(y.status());
112 state.y = y.value();
113 auto angle = readFloat(*object, "angle");
114 if (!angle) return eve::Result<Body2DState>::failure(angle.status());
115 state.angle = angle.value();
116 auto vx = readFloat(*object, "vx");
117 if (!vx) return eve::Result<Body2DState>::failure(vx.status());
118 state.vx = vx.value();
119 auto vy = readFloat(*object, "vy");
120 if (!vy) return eve::Result<Body2DState>::failure(vy.status());
121 state.vy = vy.value();
122 auto angular = readFloat(*object, "angularVelocity");
124 state.angularVelocity = angular.value();
125 auto active = readBool(*object, "active");
126 if (!active) return eve::Result<Body2DState>::failure(active.status());
127 state.active = active.value();
128 auto bullet = readBool(*object, "bullet");
129 if (!bullet) return eve::Result<Body2DState>::failure(bullet.status());
130 state.bullet = bullet.value();
131 auto awake = readBool(*object, "awake");
132 if (!awake) return eve::Result<Body2DState>::failure(awake.status());
133 state.awake = awake.value();
134 auto fixed = readBool(*object, "fixedRotation");
135 if (!fixed) return eve::Result<Body2DState>::failure(fixed.status());
136 state.fixedRotation = fixed.value();
137 const eve::Value* fixtures = field(*object, "fixtures");
138 if (!fixtures || !fixtures->isArray())
140 "2D physics snapshot fixtures must be an array",
141 "payload.bodies.fixtures"));
142 state.fixtures = *fixtures;
143 const auto* dynamics = field(*object, "dynamics");
144 const auto* d = dynamics ? dynamics->getIf<Value::Object>() : nullptr;
145 if (!d || !hasExactFields(*d, {"linearDamping", "angularDamping", "gravityScale", "allowSleep"}))
147 Diagnostic::error(DiagnosticCode::ParseError, "Invalid planar body dynamics"));
148 auto linear = readFloat(*d, "linearDamping");
149 if (!linear) return Result<Body2DState>::failure(linear.status());
150 auto angularDamping = readFloat(*d, "angularDamping");
151 if (!angularDamping) return Result<Body2DState>::failure(angularDamping.status());
152 auto gravity = readFloat(*d, "gravityScale");
153 if (!gravity) return Result<Body2DState>::failure(gravity.status());
154 auto sleep = readBool(*d, "allowSleep");
155 if (!sleep) return Result<Body2DState>::failure(sleep.status());
156 if (linear.value() < 0 || angularDamping.value() < 0)
158 Diagnostic::error(DiagnosticCode::InvalidArgument, "Damping must be nonnegative"));
159 state.linearDamping = linear.value();
160 state.angularDamping = angularDamping.value();
161 state.gravityScale = gravity.value();
162 state.allowSleep = sleep.value();
163 return eve::Result<Body2DState>::success(std::move(state));
164}
165
167 const auto* object = value.getIf<eve::Value::Object>();
168 if (!object || !hasExactFields(*object, {"active", "awake", "bullet", "dynamics", "fixedRotation",
169 "id", "type", "x", "y", "z",
170 "qx", "qy", "qz", "qw", "vx",
171 "vy", "vz", "wx", "wy", "wz"}))
174 "3D physics snapshot body has unknown or missing fields", "payload.bodies"));
176 auto id = readUint64(*object, "id");
177 if (!id || id.value() == 0 || id.value() >= static_cast<std::uint64_t>(std::numeric_limits<int>::max()))
179 eve::DiagnosticCode::ParseError, "3D physics snapshot body id is invalid", "payload.bodies.id"));
180 state.id = static_cast<int>(id.value());
181 auto type = readString(*object, "type");
182 if (!type || !validBodyType(type.value()))
184 eve::DiagnosticCode::InvalidArgument, "3D physics snapshot body type is invalid", "payload.bodies.type"));
185 state.type = std::move(type).takeValue();
186#define EV_READ_BODY3D_FLOAT(name) \
187 do { \
188 auto value = readFloat(*object, #name); \
189 if (!value) return eve::Result<Body3DState>::failure(value.status()); \
190 state.name = value.value(); \
191 } while (false)
205#undef EV_READ_BODY3D_FLOAT
206 const double quaternionLengthSquared =
207 static_cast<double>(state.qx) * state.qx + static_cast<double>(state.qy) * state.qy +
208 static_cast<double>(state.qz) * state.qz + static_cast<double>(state.qw) * state.qw;
209 if (!std::isfinite(quaternionLengthSquared) || std::abs(quaternionLengthSquared - 1.0) > 1e-4)
212 "3D physics snapshot rotation must be normalized", "payload.bodies.rotation"));
213#define EV_READ_BODY3D_BOOL(name) \
214 do { \
215 auto value = readBool(*object, #name); \
216 if (!value) return eve::Result<Body3DState>::failure(value.status()); \
217 state.name = value.value(); \
218 } while (false)
223#undef EV_READ_BODY3D_BOOL
224 const auto* dynamics = field(*object, "dynamics")->getIf<Value::Object>();
225 if (!dynamics ||
226 !hasExactFields(*dynamics, {"linearDamping", "angularDamping", "gravityScale", "sleepThreshold", "allowSleep"}))
228 Diagnostic::error(DiagnosticCode::ParseError, "Invalid 3D body dynamics fields"));
229 for (auto [name, target] : {std::pair{"linearDamping", &state.linearDamping},
230 {"angularDamping", &state.angularDamping},
231 {"gravityScale", &state.gravityScale},
232 {"sleepThreshold", &state.sleepThreshold}}) {
233 auto parsed = readFloat(*dynamics, name);
234 if (!parsed) return Result<Body3DState>::failure(parsed.status());
235 *target = parsed.value();
236 }
237 auto allowSleep = readBool(*dynamics, "allowSleep");
238 if (!allowSleep) return Result<Body3DState>::failure(allowSleep.status());
239 state.allowSleep = allowSleep.value();
240 if (state.linearDamping < 0 || state.angularDamping < 0 || state.sleepThreshold < 0)
242 Diagnostic::error(DiagnosticCode::InvalidArgument, "3D damping and sleep threshold must be nonnegative"));
243 return eve::Result<Body3DState>::success(std::move(state));
244}
245
248 object.emplace("active", eve::Value(body.isActive()));
249 object.emplace("dynamics", Value(Value::Object{{"linearDamping", Value(body.raw()->GetLinearDamping())},
250 {"angularDamping", Value(body.raw()->GetAngularDamping())},
251 {"gravityScale", Value(body.raw()->GetGravityScale())},
252 {"allowSleep", Value(body.raw()->IsSleepingAllowed())}}));
253 object.emplace("angle", eve::Value(body.getAngle()));
254 object.emplace("awake", eve::Value(body.isAwake()));
255 object.emplace("bullet", eve::Value(body.isBullet()));
256 object.emplace("fixedRotation", eve::Value(body.isFixedRotation()));
257 object.emplace("id", eve::Value(std::to_string(body.getId())));
258 object.emplace("type", eve::Value(body.getType()));
259 object.emplace("vx", eve::Value(body.getLinearVelocityX()));
260 object.emplace("vy", eve::Value(body.getLinearVelocityY()));
261 object.emplace("angularVelocity", eve::Value(body.getAngularVelocity()));
262 object.emplace("x", eve::Value(body.getX()));
263 object.emplace("y", eve::Value(body.getY()));
264 return eve::Value(std::move(object));
265}
266
269 object.emplace("dynamics",
271 {"linearDamping", Value(b3Body_GetLinearDamping(eve::physics::box3d::Access::bodyId(body)))},
272 {"angularDamping", Value(b3Body_GetAngularDamping(eve::physics::box3d::Access::bodyId(body)))},
273 {"gravityScale", Value(b3Body_GetGravityScale(eve::physics::box3d::Access::bodyId(body)))},
274 {"sleepThreshold", Value(b3Body_GetSleepThreshold(eve::physics::box3d::Access::bodyId(body)))},
275 {"allowSleep", Value(b3Body_IsSleepEnabled(eve::physics::box3d::Access::bodyId(body)))}}));
276 object.emplace("active", eve::Value(body.isActive()));
277 object.emplace("awake", eve::Value(body.isAwake()));
278 object.emplace("bullet", eve::Value(body.isBullet()));
279 object.emplace("fixedRotation", eve::Value(body.isFixedRotation()));
280 object.emplace("id", eve::Value(std::to_string(body.getId())));
281 object.emplace("type", eve::Value(body.getType()));
282 object.emplace("x", eve::Value(body.getX()));
283 object.emplace("y", eve::Value(body.getY()));
284 object.emplace("z", eve::Value(body.getZ()));
285 object.emplace("qx", eve::Value(body.getRotX()));
286 object.emplace("qy", eve::Value(body.getRotY()));
287 object.emplace("qz", eve::Value(body.getRotZ()));
288 object.emplace("qw", eve::Value(body.getRotW()));
289 object.emplace("vx", eve::Value(body.getLinearVelocityX()));
290 object.emplace("vy", eve::Value(body.getLinearVelocityY()));
291 object.emplace("vz", eve::Value(body.getLinearVelocityZ()));
292 object.emplace("wx", eve::Value(body.getAngularVelocityX()));
293 object.emplace("wy", eve::Value(body.getAngularVelocityY()));
294 object.emplace("wz", eve::Value(body.getAngularVelocityZ()));
295 return eve::Value(std::move(object));
296}
297
300 const b2Body* rawBody = body.raw();
301 for (const b2Fixture* fixture = rawBody ? rawBody->GetFixtureList() : nullptr; fixture;
302 fixture = fixture->GetNext()) {
304 const b2Shape* shape = fixture->GetShape();
305 object.emplace("type", eve::Value(std::to_string(static_cast<int>(shape->GetType()))));
306 object.emplace("radius", eve::Value(shape->m_radius));
307 object.emplace("material", fixtureMaterialValue(*fixture));
309 switch (shape->GetType()) {
310 case b2Shape::e_circle: {
311 const auto* circle = static_cast<const b2CircleShape*>(shape);
312 geometry.emplace_back(circle->m_p.x);
313 geometry.emplace_back(circle->m_p.y);
314 break;
315 }
316 case b2Shape::e_polygon: {
317 const auto* polygon = static_cast<const b2PolygonShape*>(shape);
318 for (int index = 0; index < polygon->m_count; ++index) {
319 geometry.emplace_back(polygon->m_vertices[index].x);
320 geometry.emplace_back(polygon->m_vertices[index].y);
321 }
322 break;
323 }
324 case b2Shape::e_chain: {
325 const auto* chain = static_cast<const b2ChainShape*>(shape);
326 for (int index = 0; index < chain->m_count; ++index) {
327 geometry.emplace_back(chain->m_vertices[index].x);
328 geometry.emplace_back(chain->m_vertices[index].y);
329 }
330 geometry.emplace_back(chain->m_hasPrevVertex);
331 geometry.emplace_back(chain->m_hasNextVertex);
332 break;
333 }
334 case b2Shape::e_edge: {
335 const auto* edge = static_cast<const b2EdgeShape*>(shape);
336 geometry.emplace_back(edge->m_vertex1.x);
337 geometry.emplace_back(edge->m_vertex1.y);
338 geometry.emplace_back(edge->m_vertex2.x);
339 geometry.emplace_back(edge->m_vertex2.y);
340 break;
341 }
342 default: break;
343 }
344 object.emplace("geometry", eve::Value(std::move(geometry)));
345 fixtures.emplace_back(std::move(object));
346 }
347 return eve::Value(std::move(fixtures));
348}
349
350eve::Value shapesTopologyValue(const std::vector<Shape3D*>& shapes) {
351 std::vector<Shape3D*> sorted = shapes;
352 std::sort(sorted.begin(), sorted.end(),
353 [](const Shape3D* left, const Shape3D* right) { return left->getId() < right->getId(); });
355 for (const Shape3D* shape : sorted)
356 if (shape && shape->isValid()) values.push_back(WorldSnapshotAccess::shapeSource(*shape));
357 return eve::Value(std::move(values));
358}
359
360eve::Value jointsTopologyValue(const std::vector<Joint3D*>& joints) {
361 std::vector<Joint3D*> sorted = joints;
362 std::sort(sorted.begin(), sorted.end(),
363 [](const Joint3D* left, const Joint3D* right) { return left->getId() < right->getId(); });
365 for (const Joint3D* joint : sorted) {
366 if (!joint || !joint->isValid()) continue;
368 object.emplace("id", eve::Value(std::to_string(joint->getId())));
369 object.emplace("kind", eve::Value(joint->getKind()));
370 object.emplace("bodyAId", eve::Value(std::to_string(joint->getBodyAId())));
371 object.emplace("bodyBId", eve::Value(std::to_string(joint->getBodyBId())));
372 const b3Transform frameA = b3Joint_GetLocalFrameA(eve::physics::box3d::Access::jointId(*joint));
373 const b3Transform frameB = b3Joint_GetLocalFrameB(eve::physics::box3d::Access::jointId(*joint));
374 eve::Value::Array frames;
375 for (float component : {static_cast<float>(frameA.p.x), static_cast<float>(frameA.p.y),
376 static_cast<float>(frameA.p.z), frameA.q.v.x, frameA.q.v.y, frameA.q.v.z, frameA.q.s,
377 static_cast<float>(frameB.p.x), static_cast<float>(frameB.p.y),
378 static_cast<float>(frameB.p.z), frameB.q.v.x, frameB.q.v.y, frameB.q.v.z, frameB.q.s})
379 frames.emplace_back(component);
380 object.emplace("localFrames", eve::Value(std::move(frames)));
381 object.emplace("parameters", captureJoint3DParameters(box3d::Access::jointId(*joint)));
382 values.emplace_back(std::move(object));
383 }
384 return eve::Value(std::move(values));
385}
386
389 object.emplace("tick", eve::Value(std::to_string(tick.value())));
390 object.emplace("revision", eve::Value(std::to_string(observation.stepCount)));
391 object.emplace("stepCount", eve::Value(std::to_string(observation.stepCount)));
392 object.emplace("simulatedDurationNs", eve::Value(std::to_string(observation.simulatedDuration.nanoseconds())));
393 object.emplace("lastDeltaSeconds", eve::Value(observation.lastDeltaSeconds));
394 return object;
395}
396
397eve::Value make2DPayload(const World& world, const std::vector<Body*>& bodies) {
398 const auto observation = world.simulationObservation();
399 eve::Value::Object object = observationFields(observation, world.simulationTick());
400 object.emplace("gravityX", eve::Value(world.getGravityX()));
401 object.emplace("gravityY", eve::Value(world.getGravityY()));
402 object.emplace("meter", eve::Value(world.getMeter()));
403 object.emplace("allowSleep", Value(world.raw()->GetAllowSleeping()));
404 std::vector<Body*> sortedBodies = bodies;
405 std::sort(sortedBodies.begin(), sortedBodies.end(),
406 [](const Body* left, const Body* right) { return left->getId() < right->getId(); });
408 values.reserve(sortedBodies.size());
409 for (const Body* body : sortedBodies)
410 if (body && body->isValid()) {
412 value.getIf<eve::Value::Object>()->emplace("fixtures", fixtureTopologyValue(*body));
413 values.push_back(std::move(value));
414 }
415 object.emplace("bodies", eve::Value(std::move(values)));
416 return eve::Value(std::move(object));
417}
418
419eve::Value make3DPayload(const World3D& world, const std::vector<Body3D*>& bodies, const std::vector<Shape3D*>& shapes,
420 const std::vector<Joint3D*>& joints) {
421 const auto observation = world.simulationObservation();
422 eve::Value::Object object = observationFields(observation, world.simulationTick());
423 object.emplace("gravityX", eve::Value(world.getGravityX()));
424 object.emplace("gravityY", eve::Value(world.getGravityY()));
425 object.emplace("gravityZ", eve::Value(world.getGravityZ()));
426 object.emplace("allowSleep", Value(b3World_IsSleepingEnabled(eve::physics::box3d::Access::worldId(world))));
427 std::vector<Body3D*> sortedBodies = bodies;
428 std::sort(sortedBodies.begin(), sortedBodies.end(),
429 [](const Body3D* left, const Body3D* right) { return left->getId() < right->getId(); });
431 values.reserve(sortedBodies.size());
432 for (const Body3D* body : sortedBodies)
433 if (body && body->isValid()) values.push_back(bodyValue(*body));
434 object.emplace("bodies", eve::Value(std::move(values)));
435 object.emplace("shapes", shapesTopologyValue(shapes));
436 object.emplace("joints", jointsTopologyValue(joints));
437 return eve::Value(std::move(object));
438}
439
441 const eve::Value* value = field(object, "bodies");
442 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
443 if (!array)
445 eve::DiagnosticCode::ParseError, "physics snapshot bodies must be an array", "payload.bodies"));
446 std::vector<Body2DState> result;
447 result.reserve(array->size());
448 for (const eve::Value& entry : *array) {
449 auto body = parseBody2D(entry);
450 if (!body) return eve::Result<std::vector<Body2DState>>::failure(body.status());
451 result.push_back(std::move(body).takeValue());
452 }
453 return eve::Result<std::vector<Body2DState>>::success(std::move(result));
454}
455
457 const eve::Value* value = field(object, "bodies");
458 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
459 if (!array)
461 eve::DiagnosticCode::ParseError, "physics snapshot bodies must be an array", "payload.bodies"));
462 std::vector<Body3DState> result;
463 result.reserve(array->size());
464 for (const eve::Value& entry : *array) {
465 auto body = parseBody3D(entry);
466 if (!body) return eve::Result<std::vector<Body3DState>>::failure(body.status());
467 result.push_back(std::move(body).takeValue());
468 }
469 return eve::Result<std::vector<Body3DState>>::success(std::move(result));
470}
471
472eve::Result<std::unique_ptr<World>> prepareWorld2D(const std::vector<Body2DState>& states, float gravityX,
473 float gravityY, float meter,
474 const SimulationObservation& observation,
476 try {
477 auto prepared = std::make_unique<World>(gravityX, gravityY, false, meter, instanceId);
478 int maxId = 0;
479 for (const Body2DState& state : states) {
480 Body* body = prepared->newBody(state.type, state.x, state.y);
481 WorldSnapshotAccess::ownPreparedBody(*prepared, std::unique_ptr<Body>(body));
483 maxId = std::max(maxId, state.id);
484 const auto* fixtures = state.fixtures.getIf<eve::Value::Array>();
485 for (auto it = fixtures->rbegin(); it != fixtures->rend(); ++it) {
486 const auto* fixture = it->getIf<eve::Value::Object>();
487 if (!fixture || !hasExactFields(*fixture, {"geometry", "radius", "type", "material"}))
488 return eve::Result<std::unique_ptr<World>>::failure(
490 "2D fixture has unknown or missing fields", "payload.bodies.fixtures"));
491 auto type = readInt64(*fixture, "type");
492 if (!type) return Result<std::unique_ptr<World>>::failure(type.status());
493 auto radius = readFloat(*fixture, "radius");
494 if (!radius) return Result<std::unique_ptr<World>>::failure(radius.status());
495 const eve::Value* geometryValue = field(*fixture, "geometry");
496 const auto* geometry = geometryValue ? geometryValue->getIf<eve::Value::Array>() : nullptr;
497 if (!geometry)
498 return eve::Result<std::unique_ptr<World>>::failure(
499 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "2D fixture geometry is malformed",
500 "payload.bodies.fixtures.geometry"));
501 std::vector<float> values;
502 values.reserve(geometry->size());
503 for (const eve::Value& component : *geometry) {
504 if (!component.isNumeric()) {
505 if (component.isBool()) continue;
507 eve::DiagnosticCode::ParseError, "2D fixture coordinate must be numeric",
508 "payload.bodies.fixtures.geometry"));
509 }
510 values.push_back(
511 static_cast<float>(component.isDouble() ? component.asDouble() : component.asInt()) * meter);
512 }
513 Fixture* created = nullptr;
514 if (type.value() == b2Shape::e_circle && values.size() == 2)
515 created = body->newCircleFixture(radius.value() * meter);
516 else if (type.value() == b2Shape::e_polygon && values.size() >= 6)
517 created = body->newPolygonFixture(values);
518 else if (type.value() == b2Shape::e_chain && values.size() >= 4) {
519 const bool loop = geometry->size() >= 2 && (*geometry)[geometry->size() - 2].isBool() &&
520 (*geometry)[geometry->size() - 2].asBool() && geometry->back().isBool() &&
521 geometry->back().asBool();
522 // Box2D stores the closing vertex explicitly; the body factory closes loops itself.
523 if (loop && values.size() >= 8 && values[0] == values[values.size() - 2] &&
524 values[1] == values.back())
525 values.resize(values.size() - 2);
526 created = body->newChainFixture(values, loop);
527 }
528 if (!created)
530 eve::DiagnosticCode::Unsupported, "2D fixture shape cannot be reconstructed",
531 "payload.bodies.fixtures.type"));
532 WorldSnapshotAccess::ownPreparedFixture(*prepared, std::unique_ptr<Fixture>(created));
533 auto material = restoreFixtureMaterial(*created, *field(*fixture, "material"));
534 if (!material) return Result<std::unique_ptr<World>>::failure(material.status());
535 }
536 body->raw()->SetLinearDamping(state.linearDamping);
537 body->raw()->SetAngularDamping(state.angularDamping);
538 body->raw()->SetGravityScale(state.gravityScale);
539 body->raw()->SetSleepingAllowed(state.allowSleep);
540 body->setFixedRotation(state.fixedRotation);
541 body->setBullet(state.bullet);
542 body->setActive(state.active);
543 body->setAngle(state.angle);
544 body->setLinearVelocity(state.vx, state.vy);
545 body->setAngularVelocity(state.angularVelocity);
546 body->setAwake(state.awake);
547 }
548 auto restored = WorldSnapshotAccess::finishPrepared(*prepared, maxId + 1, observation);
549 if (!restored) return eve::Result<std::unique_ptr<World>>::failure(restored.status());
550 return eve::Result<std::unique_ptr<World>>::success(std::move(prepared));
551 } catch (const std::exception& error) {
553 eve::DiagnosticCode::Failed, std::string("2D topology preparation failed: ") + error.what(),
554 "physics.world.restore.prepare"));
555 }
556}
557
559 const eve::Value* value = field(object, name);
560 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
561 if (!array)
563 eve::DiagnosticCode::ParseError, "snapshot field must be an array", std::string(name)));
564 std::vector<float> result;
565 result.reserve(array->size());
566 for (const eve::Value& item : *array) {
567 if (!item.isNumeric())
568 return eve::Result<std::vector<float>>::failure(eve::Diagnostic::error(
569 eve::DiagnosticCode::ParseError, "snapshot array item must be numeric", std::string(name)));
570 const double number = item.isDouble() ? item.asDouble() : item.asInt();
571 if (!std::isfinite(number) || std::abs(number) > std::numeric_limits<float>::max())
572 return Result<std::vector<float>>::failure(Diagnostic::error(
573 DiagnosticCode::InvalidArgument, "Snapshot number exceeds finite float range", std::string(name)));
574 result.push_back(static_cast<float>(number));
575 }
576 return eve::Result<std::vector<float>>::success(std::move(result));
577}
578
580 const eve::Value* value = field(object, name);
581 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
582 if (!array)
584 eve::DiagnosticCode::ParseError, "snapshot field must be an array", std::string(name)));
585 std::vector<std::int32_t> result;
586 for (const eve::Value& item : *array) {
587 if (!item.isString())
588 return eve::Result<std::vector<std::int32_t>>::failure(eve::Diagnostic::error(
589 eve::DiagnosticCode::ParseError, "snapshot integer array item must be a string", std::string(name)));
590 std::int64_t parsed = 0;
591 const std::string& text = item.asString();
592 const auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), parsed);
593 if (ec != std::errc{} || end != text.data() + text.size() || parsed < INT32_MIN || parsed > INT32_MAX)
595 eve::DiagnosticCode::ParseError, "snapshot integer array item is invalid", std::string(name)));
596 result.push_back(static_cast<std::int32_t>(parsed));
597 }
598 return eve::Result<std::vector<std::int32_t>>::success(std::move(result));
599}
600
601eve::Result<std::unique_ptr<World3D>> prepareWorld3D(const std::vector<Body3DState>& states,
602 const eve::Value::Array& shapes, const eve::Value::Array& joints,
603 float gravityX, float gravityY, float gravityZ,
604 const SimulationObservation& observation,
605 eve::PersistentId instanceId, bool legacyParameters,
606 bool allowSleep) {
607 try {
608 auto prepared = WorldSnapshotAccess::makeDetachedWorld3D(gravityX, gravityY, gravityZ, instanceId, allowSleep);
609 std::unordered_map<int, Body3D*> bodyById;
610 int maxBodyId = 0;
611 for (const Body3DState& state : states) {
612 Body3D* body = prepared->newBody(state.type, state.x, state.y, state.z);
613 WorldSnapshotAccess::ownPreparedBody(*prepared, std::unique_ptr<Body3D>(body));
615 bodyById.emplace(state.id, body);
616 maxBodyId = std::max(maxBodyId, state.id);
617 body->setFixedRotation(state.fixedRotation);
618 body->setBullet(state.bullet);
619 body->setActive(state.active);
620 body->setRotation(state.qx, state.qy, state.qz, state.qw);
621 }
622 std::vector<std::pair<Shape3D*, float>> densities;
623 int maxShapeId = 0;
624 std::set<int> shapeIds;
625 for (const eve::Value& value : shapes) {
626 const auto* object = value.getIf<eve::Value::Object>();
627 if (!object)
629 eve::DiagnosticCode::ParseError, "3D shape must be an object", "payload.shapes"));
630 const std::initializer_list<std::string_view> sourceFields{"bodyId",
631 "id",
632 "kind",
633 "a",
634 "b",
635 "c",
636 "hullVertices",
637 "hullMaxVertices",
638 "meshVertices",
639 "meshIndices",
640 "meshWeldVertices",
641 "meshWeldTolerance",
642 "meshIdentifyEdges",
643 "meshUseMedianSplit",
644 "meshMaterialIndices",
645 "heightValues",
646 "heightCountX",
647 "heightCountZ",
648 "heightCellSizeX",
649 "heightCellSizeZ",
650 "heightGlobalMin",
651 "heightGlobalMax",
652 "heightClockwise"};
653 if (object->size() != sourceFields.size() + (legacyParameters ? 0 : 2))
655 DiagnosticCode::ParseError, "Shape has unknown or missing fields", "payload.shapes"));
656 for (auto name : sourceFields)
657 if (!field(*object, name))
658 return Result<std::unique_ptr<World3D>>::failure(Diagnostic::error(
659 DiagnosticCode::ParseError, "Shape source field is missing", std::string(name)));
660 auto bodyId = readInt64(*object, "bodyId");
661 if (!bodyId) return Result<std::unique_ptr<World3D>>::failure(bodyId.status());
662 auto id = readInt64(*object, "id");
663 if (!id) return Result<std::unique_ptr<World3D>>::failure(id.status());
664 auto kind = readString(*object, "kind");
665 if (!kind) return Result<std::unique_ptr<World3D>>::failure(kind.status());
666 auto a = readFloat(*object, "a");
667 if (!a) return Result<std::unique_ptr<World3D>>::failure(a.status());
668 auto b = readFloat(*object, "b");
669 if (!b) return Result<std::unique_ptr<World3D>>::failure(b.status());
670 auto c = readFloat(*object, "c");
671 if (!c) return Result<std::unique_ptr<World3D>>::failure(c.status());
672 if (bodyId.value() <= 0 || bodyId.value() >= std::numeric_limits<int>::max() || !id || id.value() <= 0 ||
673 id.value() >= std::numeric_limits<int>::max() ||
674 !shapeIds.insert(static_cast<int>(id.value())).second || !kind || !a || !b || !c ||
675 !bodyById.contains(static_cast<int>(bodyId.value())))
677 eve::DiagnosticCode::Conflict, "3D shape references invalid identity or source", "payload.shapes"));
678 Body3D* body = bodyById.at(static_cast<int>(bodyId.value()));
679 Shape3D* shape = nullptr;
680 if (kind.value() == "box")
681 shape = body->newBoxShape(a.value() * 2.f, b.value() * 2.f, c.value() * 2.f);
682 else if (kind.value() == "sphere")
683 shape = body->newSphereShape(a.value());
684 else if (kind.value() == "capsule")
685 shape = body->newCapsuleShape(a.value() * 2.f, b.value());
686 else if (kind.value() == "convexHull") {
687 auto vertices = readFloatArray(*object, "hullVertices");
688 if (!vertices) return Result<std::unique_ptr<World3D>>::failure(vertices.status());
689 auto maxVertices = readInt64(*object, "hullMaxVertices");
690 if (!maxVertices) return Result<std::unique_ptr<World3D>>::failure(maxVertices.status());
691 if (!vertices || !maxVertices)
693 eve::DiagnosticCode::ParseError, "convex hull source is invalid", "payload.shapes"));
694 shape = body->newConvexHullShape(vertices.value(), static_cast<int>(maxVertices.value()));
695 } else if (kind.value() == "triangleMesh") {
696 auto vertices = readFloatArray(*object, "meshVertices");
697 if (!vertices) return Result<std::unique_ptr<World3D>>::failure(vertices.status());
698 auto indices = readIntArray(*object, "meshIndices");
699 if (!indices) return Result<std::unique_ptr<World3D>>::failure(indices.status());
700 auto weld = readBool(*object, "meshWeldVertices");
701 if (!weld) return Result<std::unique_ptr<World3D>>::failure(weld.status());
702 auto tolerance = readFloat(*object, "meshWeldTolerance");
703 if (!tolerance) return Result<std::unique_ptr<World3D>>::failure(tolerance.status());
704 auto edges = readBool(*object, "meshIdentifyEdges");
705 if (!edges) return Result<std::unique_ptr<World3D>>::failure(edges.status());
706 auto median = readBool(*object, "meshUseMedianSplit");
707 if (!median) return Result<std::unique_ptr<World3D>>::failure(median.status());
708 if (!vertices || !indices || !weld || !tolerance || !edges || !median)
710 eve::DiagnosticCode::ParseError, "mesh source is invalid", "payload.shapes"));
711 shape = body->newTriangleMeshShape(vertices.value(), indices.value(), weld.value(), tolerance.value(),
712 edges.value(), median.value());
713 } else if (kind.value() == "heightField") {
714 auto heights = readFloatArray(*object, "heightValues");
715 if (!heights) return Result<std::unique_ptr<World3D>>::failure(heights.status());
716 auto cx = readInt64(*object, "heightCountX");
717 if (!cx) return Result<std::unique_ptr<World3D>>::failure(cx.status());
718 auto cz = readInt64(*object, "heightCountZ");
719 if (!cz) return Result<std::unique_ptr<World3D>>::failure(cz.status());
720 auto sx = readFloat(*object, "heightCellSizeX");
721 if (!sx) return Result<std::unique_ptr<World3D>>::failure(sx.status());
722 auto sz = readFloat(*object, "heightCellSizeZ");
723 if (!sz) return Result<std::unique_ptr<World3D>>::failure(sz.status());
724 auto mn = readFloat(*object, "heightGlobalMin");
725 if (!mn) return Result<std::unique_ptr<World3D>>::failure(mn.status());
726 auto mx = readFloat(*object, "heightGlobalMax");
727 if (!mx) return Result<std::unique_ptr<World3D>>::failure(mx.status());
728 auto clockwise = readBool(*object, "heightClockwise");
729 if (!clockwise) return Result<std::unique_ptr<World3D>>::failure(clockwise.status());
730 if (!heights || !cx || !cz || !sx || !sz || !mn || !mx || !clockwise)
732 eve::DiagnosticCode::ParseError, "height field source is invalid", "payload.shapes"));
733 shape =
734 body->newHeightFieldShape(static_cast<int>(cx.value()), static_cast<int>(cz.value()), sx.value(),
735 sz.value(), heights.value(), mn.value(), mx.value(), clockwise.value());
736 }
737 if (!shape)
739 eve::DiagnosticCode::Unsupported, "3D shape kind cannot be reconstructed", "payload.shapes.kind"));
740 WorldSnapshotAccess::ownPreparedShape(*prepared, std::unique_ptr<Shape3D>(shape));
741 WorldSnapshotAccess::setShapeId(*shape, static_cast<int>(id.value()));
742 if (legacyParameters) {
743 if (object->contains("localTransform"))
744 return Result<std::unique_ptr<World3D>>::failure(
745 Diagnostic::error(DiagnosticCode::ParseError, "Legacy shape has unexpected local transform"));
746 } else {
747 auto transform = readFloatArray(*object, "localTransform");
748 if (!transform) return Result<std::unique_ptr<World3D>>::failure(transform.status());
749 const auto& t = transform.value();
750 if (t.size() != 7 || !b3IsNormalizedQuat({{t[3], t[4], t[5]}, t[6]}))
752 DiagnosticCode::InvalidArgument, "Shape transform requires a position and unit quaternion"));
753 shape->setLocalTransform(t[0], t[1], t[2], t[3], t[4], t[5], t[6]);
755 if (!contact) return Result<std::unique_ptr<World3D>>::failure(contact.status());
756 densities.emplace_back(shape, contact.value());
757 }
758 maxShapeId = std::max(maxShapeId, static_cast<int>(id.value()));
759 }
760 for (auto [shape, density] : densities)
761 b3Shape_SetDensity(eve::physics::box3d::Access::shapeId(*shape), density, false);
762 auto mass = WorldSnapshotAccess::finishShapeMass(*prepared);
763 if (!mass) return Result<std::unique_ptr<World3D>>::failure(mass.status());
764 int maxJointId = 0;
765 std::set<int> jointIds;
766 for (const eve::Value& value : joints) {
767 const auto* object = value.getIf<eve::Value::Object>();
768 if (!object ||
769 !(legacyParameters
770 ? hasExactFields(*object, {"bodyAId", "bodyBId", "id", "kind", "localFrames"})
771 : hasExactFields(*object, {"bodyAId", "bodyBId", "id", "kind", "localFrames", "parameters"})))
772 return eve::Result<std::unique_ptr<World3D>>::failure(eve::Diagnostic::error(
773 eve::DiagnosticCode::ParseError, "3D joint has unknown or missing fields", "payload.joints"));
774 auto bodyAId = readInt64(*object, "bodyAId");
775 if (!bodyAId) return eve::Result<std::unique_ptr<World3D>>::failure(bodyAId.status());
776 auto bodyBId = readInt64(*object, "bodyBId");
777 if (!bodyBId) return eve::Result<std::unique_ptr<World3D>>::failure(bodyBId.status());
778 auto id = readInt64(*object, "id");
779 if (!id) return eve::Result<std::unique_ptr<World3D>>::failure(id.status());
780 auto kind = readString(*object, "kind");
781 if (!kind) return eve::Result<std::unique_ptr<World3D>>::failure(kind.status());
782 auto frames = readFloatArray(*object, "localFrames");
783 if (!frames) return eve::Result<std::unique_ptr<World3D>>::failure(frames.status());
784 if (id.value() <= 0 || id.value() >= std::numeric_limits<int>::max() || bodyAId.value() <= 0 ||
785 bodyAId.value() >= std::numeric_limits<int>::max() || bodyBId.value() <= 0 ||
786 bodyBId.value() >= std::numeric_limits<int>::max() || bodyAId.value() == bodyBId.value() ||
787 !jointIds.insert(static_cast<int>(id.value())).second || frames.value().size() != 14 ||
788 !bodyById.contains(static_cast<int>(bodyAId.value())) ||
789 !bodyById.contains(static_cast<int>(bodyBId.value())))
791 eve::DiagnosticCode::Conflict, "3D joint references invalid bodies or frames", "payload.joints"));
792 Body3D* aBody = bodyById.at(static_cast<int>(bodyAId.value()));
793 Body3D* bBody = bodyById.at(static_cast<int>(bodyBId.value()));
794 const auto& f = frames.value();
795 const b3Pos anchorA =
796 b3Body_GetWorldPoint(eve::physics::box3d::Access::bodyId(*aBody), b3Pos{f[0], f[1], f[2]});
797 const b3Pos anchorB =
798 b3Body_GetWorldPoint(eve::physics::box3d::Access::bodyId(*bBody), b3Pos{f[7], f[8], f[9]});
799 const b3Quat qa{{f[3], f[4], f[5]}, f[6]};
800 const b3Quat qb{{f[10], f[11], f[12]}, f[13]};
801 if (!b3IsNormalizedQuat(qa) || !b3IsNormalizedQuat(qb))
804 "Joint frame rotation must be normalized", "payload.joints.localFrames"));
805 Joint3D* joint = nullptr;
806 if (kind.value() == "distance") {
807 const b3Vec3 d = anchorB - anchorA;
808 const float length = std::sqrt(b3Dot(d, d));
809 joint = prepared->newDistanceJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z, anchorB.x, anchorB.y,
810 anchorB.z, length);
811 } else if (kind.value() == "revolute") {
812 const b3Vec3 axis = b3Body_GetWorldVector(eve::physics::box3d::Access::bodyId(*aBody),
813 b3RotateVector(qa, b3Vec3_axisZ));
814 joint =
815 prepared->newRevoluteJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z, axis.x, axis.y, axis.z);
816 } else if (kind.value() == "prismatic") {
817 const b3Vec3 axis = b3Body_GetWorldVector(eve::physics::box3d::Access::bodyId(*aBody),
818 b3RotateVector(qa, b3Vec3_axisX));
819 joint =
820 prepared->newPrismaticJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z, axis.x, axis.y, axis.z);
821 } else if (kind.value() == "spherical") {
822 const b3Vec3 axis = b3Body_GetWorldVector(eve::physics::box3d::Access::bodyId(*aBody),
823 b3RotateVector(qa, b3Vec3_axisZ));
824 joint =
825 prepared->newSphericalJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z, axis.x, axis.y, axis.z);
826 } else if (kind.value() == "wheel") {
827 const b3Vec3 suspension = b3Body_GetWorldVector(eve::physics::box3d::Access::bodyId(*aBody),
828 b3RotateVector(qa, b3Vec3_axisX));
829 const b3Vec3 wheel = b3Body_GetWorldVector(eve::physics::box3d::Access::bodyId(*bBody),
830 b3RotateVector(qb, b3Vec3_axisZ));
831 joint = prepared->newWheelJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z, suspension.x,
832 suspension.y, suspension.z, wheel.x, wheel.y, wheel.z);
833 } else if (kind.value() == "weld") {
834 joint = prepared->newWeldJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z);
835 } else if (kind.value() == "motor") {
836 joint = prepared->newMotorJoint(aBody, bBody);
837 } else if (kind.value() == "parallel") {
838 const b3Vec3 axis =
839 b3Body_GetWorldVector(box3d::Access::bodyId(*aBody), b3RotateVector(qa, b3Vec3_axisZ));
840 joint = prepared->newParallelJoint(aBody, bBody, axis.x, axis.y, axis.z);
841 } else if (kind.value() == "filter") {
842 joint = prepared->newFilterJoint(aBody, bBody);
843 }
844 if (!joint)
846 eve::DiagnosticCode::Unsupported, "3D joint kind cannot be reconstructed", "payload.joints.kind"));
847 WorldSnapshotAccess::ownPreparedJoint(*prepared, std::unique_ptr<Joint3D>(joint));
848 b3Joint_SetLocalFrameA(eve::physics::box3d::Access::jointId(*joint),
849 b3Transform{b3Pos{f[0], f[1], f[2]}, qa});
850 b3Joint_SetLocalFrameB(eve::physics::box3d::Access::jointId(*joint),
851 b3Transform{b3Pos{f[7], f[8], f[9]}, qb});
852 if (!legacyParameters) {
853 auto parameters =
854 restoreJoint3DParameters(box3d::Access::jointId(*joint), *field(*object, "parameters"));
855 if (!parameters) return eve::Result<std::unique_ptr<World3D>>::failure(parameters.status());
856 }
857 WorldSnapshotAccess::setJointId(*joint, static_cast<int>(id.value()));
858 maxJointId = std::max(maxJointId, static_cast<int>(id.value()));
859 }
860 for (const auto& state : states) {
861 auto* body = bodyById.at(state.id);
862 b3Body_SetLinearDamping(eve::physics::box3d::Access::bodyId(*body), state.linearDamping);
863 b3Body_SetAngularDamping(eve::physics::box3d::Access::bodyId(*body), state.angularDamping);
864 b3Body_SetGravityScale(eve::physics::box3d::Access::bodyId(*body), state.gravityScale);
865 b3Body_SetSleepThreshold(eve::physics::box3d::Access::bodyId(*body), state.sleepThreshold);
866 b3Body_EnableSleep(eve::physics::box3d::Access::bodyId(*body), state.allowSleep);
867 body->setLinearVelocity(state.vx, state.vy, state.vz);
868 body->setAngularVelocity(state.wx, state.wy, state.wz);
869 body->setAwake(state.awake);
870 }
871 auto restored =
872 WorldSnapshotAccess::finishPrepared(*prepared, maxBodyId + 1, maxShapeId + 1, maxJointId + 1, observation);
873 if (!restored) return eve::Result<std::unique_ptr<World3D>>::failure(restored.status());
874 return eve::Result<std::unique_ptr<World3D>>::success(std::move(prepared));
875 } catch (const std::exception& error) {
877 eve::DiagnosticCode::Failed, std::string("3D topology preparation failed: ") + error.what(),
878 "physics.world3d.restore.prepare"));
879 }
880}
881
882} // namespace eve::physics::snapshot_detail
double z
double y
double x
LogicalId target
bool & active
float duration
std::uint64_t revision
float cx
Definition CardTypes.cpp:36
bool awake
b3Vec3 angular
std::string name
Definition ECS.cpp:154
int instanceId
ScriptForceVector gravity
float linear
float density
ShaderImageInput shape
wgpu::PopErrorScopeStatus status
std::vector< std::uint32_t > indices
HexVec3 left
HexVec3 right
std::int32_t c
JointPoint2D anchorB
float length
JointPoint2D axis
JointPoint2D anchorA
std::vector< Edge > edges
Poco::JSON::Object::Ptr result
Snapshot snapshot
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
std::string error
Definition Package.cpp:174
std::array< uint32_t, 16 > material
std::array< uint32_t, 9 > parameters
float f
#define EV_READ_BODY3D_BOOL(name)
eve::Value fixtures
#define EV_READ_BODY3D_FLOAT(name)
bool fixedRotation
std::set< std::string > values
std::string body
Object::Ptr value
float d
float t
double number
int created
std::string geometry
std::string text
size_t end
std::string kind
double current
Backend-neutral, observable fixed-step contract for physics domains.
SimulationTick tick
std::array< double, 2 > vertices[3]
Json object
uint32_t index
Contact contact
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
constexpr std::int64_t nanoseconds() const noexcept
Return the exact signed nanosecond representation.
Definition Time.h:69
static constexpr Duration fromNanoseconds(std::int64_t nanoseconds) noexcept
Construct an exact duration from nanoseconds.
Definition Time.h:55
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
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
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
bool isArray() const noexcept
Return true when this value is an array.
Definition Value.h:108
std::vector< Value > Array
Definition Value.h:33
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
Id128 public API.
Definition Identity.h:111
Backend-neutral 3D rigid body in meter-space coordinates (+Y up by convention). Owned by a World3D; c...
Definition Body3D.h:31
2D rigid body (Box2D) in pixel-space coordinates. Owned by a World; create shapes with newRectangleFi...
Definition Body.h:21
2D fixture: a shape attached to a Body with material + filter settings. Also carries a string tag use...
Definition Fixture.h:18
Script-facing joint owned by a World3D. Legacy scalar/void methods adapt the checked backend contract...
Definition Joint3D.h:27
3D shape (box/sphere/capsule) attached to a Body3D with material settings. Created via Body3D::new*Sh...
Definition Shape3D.h:34
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
Box2D world wrapper (2D physics) with pixel-space coordinates. Handles stepping, gravity,...
Definition World.h:44
Result< float > readFloat(const Value::Object &object, std::string_view name)
Reads a required finite number representable by float.
eve::Result< std::unique_ptr< World3D > > prepareWorld3D(const std::vector< Body3DState > &states, const eve::Value::Array &shapes, const eve::Value::Array &joints, float gravityX, float gravityY, float gravityZ, const SimulationObservation &observation, eve::PersistentId instanceId, bool legacyParameters, bool allowSleep)
constexpr std::uint64_t kSnapshotVersion
Result< void > restoreFixtureMaterial(Fixture &fixture, const Value &value)
Validate material fields before applying them to a detached fixture.
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...
eve::Value shapesTopologyValue(const std::vector< Shape3D * > &shapes)
eve::Value make2DPayload(const World &world, const std::vector< Body * > &bodies)
eve::Value jointsTopologyValue(const std::vector< Joint3D * > &joints)
eve::Value::Object observationFields(const SimulationObservation &observation, eve::SimulationTick tick)
bool hasExactFields(const Value::Object &object, std::initializer_list< std::string_view > expected)
Internal exact-field schema predicate.
eve::Value fixtureTopologyValue(const Body &body)
Result< void > restoreJoint3DParameters(b3JointId id, const Value &value)
Validate the complete parameter object before updating a live candidate joint; no retained references...
constexpr std::string_view kWorld3DType
Result< std::uint64_t > readUint64(const Value::Object &object, std::string_view name)
Reads a required unsigned decimal integer string.
eve::Value make3DPayload(const World3D &world, const std::vector< Body3D * > &bodies, const std::vector< Shape3D * > &shapes, const std::vector< Joint3D * > &joints)
constexpr std::string_view kWorld2DType
Result< std::int64_t > readInt64(const Value::Object &object, std::string_view name)
Reads a required signed decimal integer string.
Result< bool > readBool(const Value::Object &object, std::string_view name)
Reads a required boolean.
eve::Result< std::vector< float > > readFloatArray(const eve::Value::Object &object, std::string_view name)
Read a finite float array, rejecting missing or malformed elements.
eve::Result< std::vector< std::int32_t > > readIntArray(const eve::Value::Object &object, std::string_view name)
eve::Result< Body2DState > parseBody2D(const eve::Value &value)
eve::Result< eve::LogicalId > snapshotSchema(std::string_view text)
Value captureJoint3DParameters(b3JointId id)
Capture solver-owned parameters on the physics owner thread into an owning value.
eve::Result< std::unique_ptr< World > > prepareWorld2D(const std::vector< Body2DState > &states, float gravityX, float gravityY, float meter, const SimulationObservation &observation, eve::PersistentId instanceId)
eve::Result< std::vector< Body2DState > > parseBodies2D(const eve::Value::Object &object)
eve::Result< void > checkEnvelope(const eve::SnapshotEnvelope &snapshot, std::string_view type, std::string_view schema)
eve::Result< std::vector< Body3DState > > parseBodies3D(const eve::Value::Object &object)
constexpr std::uint64_t kSnapshot2DVersion
eve::Result< Body3DState > parseBody3D(const eve::Value &value)
Value fixtureMaterialValue(const b2Fixture &fixture)
Owning material/filter projection from a synchronous backend observation.
eve::Value bodyValue(const Body &body)
bool validBodyType(const std::string &type)
Result< std::string > readString(const Value::Object &object, std::string_view name)
Reads a required owning string.
eve::Result< ObservationState > parseObservation(const eve::Value::Object &object, const eve::SnapshotEnvelope &snapshot)
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
Observable backend progress shared by CPU and accelerator providers.
eve::Duration simulatedDuration
Accumulated logical simulation time, never wall-clock time.
float lastDeltaSeconds
Duration consumed by the most recently completed step.
std::uint64_t stepCount
Number of completed steps since backend creation.
static void setJointId(Joint3D &joint, int id)
static std::unique_ptr< World3D > makeDetachedWorld3D(float gx, float gy, float gz, eve::PersistentId instanceId, bool allowSleep)
static void setShapeId(Shape3D &shape, int id)
static Result< void > finishShapeMass(World3D &world)
Preflight candidate mass/inertia arithmetic before applying backend mass updates.
static void ownPreparedFixture(World &world, std::unique_ptr< Fixture > fixture)
Candidate owns a fixture wrapper after registering it with its backend.
static eve::Result< void > finishPrepared(World &world, int nextId, const SimulationObservation &observation)
static eve::Value shapeSource(const Shape3D &shape)
static Result< float > restoreShapeContact(Shape3D &shape, const Value::Object &source)
Restore validated candidate contact state; return density for deferred mass preparation.
static void ownPreparedShape(World3D &world, std::unique_ptr< Shape3D > shape)
Transfer one reconstructed shape wrapper to its candidate world.
static void ownPreparedJoint(World3D &world, std::unique_ptr< Joint3D > joint)
Transfer one reconstructed joint wrapper to its candidate world.
static void ownPreparedBody(World &world, std::unique_ptr< Body > body)
Candidate owns newly reconstructed wrappers so rollback releases all allocations.
static void setBodyId(Body &body, int id)
static b3BodyId bodyId(const Body3D &body)
Borrows the native identifier synchronously; facade must belong to a Box3D world.
static b3WorldId worldId(const World3D &world)
Internal checked Box3D world ID; fails for another backend.
static b3ShapeId shapeId(const Shape3D &shape)
Borrows a Box3D shape identifier for a synchronous native operation.
static b3JointId jointId(const Joint3D &joint)
Internal checked Box3D joint ID; fails for another backend.