10using namespace snapshot_detail;
13Result<T> malformed(
const char*
message) {
16void anchors(
Object& o, b2Vec2
a, b2Vec2
b) {
17 o.emplace(
"ax",
Value(
a.x));
18 o.emplace(
"ay",
Value(
a.y));
19 o.emplace(
"bx",
Value(
b.x));
20 o.emplace(
"by",
Value(
b.y));
23 o.emplace(
"frequency",
Value(frequency));
24 o.emplace(
"damping",
Value(damping));
28 o.emplace(
"speed",
Value(speed));
33 o.emplace(
"limitEnabled",
Value(j.IsLimitEnabled()));
34 o.emplace(
"lower",
Value(j.GetLowerLimit()));
35 o.emplace(
"upper",
Value(j.GetUpperLimit()));
37Result<std::vector<float>>
parameters(
const Object& data, std::initializer_list<std::string_view> names) {
39 return malformed<std::vector<float>>(
"Joint parameters have unknown or missing fields");
41 for (
auto name : names) {
42 if (
name ==
"motorEnabled" ||
name ==
"limitEnabled") {
44 if (!
value)
return Result<std::vector<float>>::failure(
value.status());
48 if (!
value)
return Result<std::vector<float>>::failure(
value.status());
52 return Result<std::vector<float>>::success(std::move(
result));
54Result<int> positiveId(
const Object& o, std::string_view
name) {
57 if (
id.
value() <= 0 ||
id.
value() >= std::numeric_limits<int>::max())
58 return malformed<int>(
"Joint topology id is out of range");
61int bodyId(b2Body&
body) {
62 const auto* wrapper =
static_cast<const Body*
>(
body.GetUserData());
63 return wrapper ? wrapper->getId() : -1;
68 if (
static_cast<std::size_t
>(world.raw()->GetJointCount()) != world.joints_.size())
71 std::vector<Joint2D*> sorted(world.joints_.begin(), world.joints_.end());
72 std::sort(sorted.begin(), sorted.end(), [](
auto*
a,
auto*
b) { return a->getId() < b->getId(); });
74 for (
const auto* wrapper : sorted) {
75 auto&
raw = *wrapper->joint_;
77 switch (wrapper->kind_) {
79 const auto& j =
static_cast<const b2RevoluteJoint&
>(
raw);
80 anchors(data, j.GetLocalAnchorA(), j.GetLocalAnchorB());
81 data.emplace(
"referenceAngle",
Value(j.GetReferenceAngle()));
83 motor(data, j.IsMotorEnabled(), j.GetMotorSpeed(), j.GetMaxMotorTorque());
87 const auto& j =
static_cast<const b2PrismaticJoint&
>(
raw);
88 anchors(data, j.GetLocalAnchorA(), j.GetLocalAnchorB());
89 data.emplace(
"referenceAngle",
Value(j.GetReferenceAngle()));
90 data.emplace(
"axisX",
Value(j.GetLocalAxisA().x));
91 data.emplace(
"axisY",
Value(j.GetLocalAxisA().y));
93 motor(data, j.IsMotorEnabled(), j.GetMotorSpeed(), j.GetMaxMotorForce());
97 const auto& j =
static_cast<const b2DistanceJoint&
>(
raw);
98 anchors(data, j.GetLocalAnchorA(), j.GetLocalAnchorB());
99 data.emplace(
"length",
Value(j.GetLength()));
100 spring(data, j.GetFrequency(), j.GetDampingRatio());
104 const auto& j =
static_cast<const b2WheelJoint&
>(
raw);
105 anchors(data, j.GetLocalAnchorA(), j.GetLocalAnchorB());
106 data.emplace(
"axisX",
Value(j.GetLocalAxisA().x));
107 data.emplace(
"axisY",
Value(j.GetLocalAxisA().y));
108 spring(data, j.GetSpringFrequencyHz(), j.GetSpringDampingRatio());
109 motor(data, j.IsMotorEnabled(), j.GetMotorSpeed(), j.GetMaxMotorTorque());
113 const auto& j =
static_cast<const b2WeldJoint&
>(
raw);
114 anchors(data, j.GetLocalAnchorA(), j.GetLocalAnchorB());
115 data.emplace(
"referenceAngle",
Value(j.GetReferenceAngle()));
116 spring(data, j.GetFrequency(), j.GetDampingRatio());
120 const auto& j =
static_cast<const b2PulleyJoint&
>(
raw);
121 anchors(data, {wrapper->pulleyLocalA_.x, wrapper->pulleyLocalA_.y},
122 {wrapper->pulleyLocalB_.x, wrapper->pulleyLocalB_.y});
123 data.emplace(
"groundAx",
Value(j.GetGroundAnchorA().x));
124 data.emplace(
"groundAy",
Value(j.GetGroundAnchorA().y));
125 data.emplace(
"groundBx",
Value(j.GetGroundAnchorB().x));
126 data.emplace(
"groundBy",
Value(j.GetGroundAnchorB().y));
127 data.emplace(
"lengthA",
Value(j.GetLengthA()));
128 data.emplace(
"lengthB",
Value(j.GetLengthB()));
129 data.emplace(
"ratio",
Value(j.GetRatio()));
133 const auto& j =
static_cast<const b2MotorJoint&
>(
raw);
134 data.emplace(
"offsetX",
Value(j.GetLinearOffset().x));
135 data.emplace(
"offsetY",
Value(j.GetLinearOffset().y));
136 data.emplace(
"angle",
Value(j.GetAngularOffset()));
137 data.emplace(
"force",
Value(j.GetMaxForce()));
138 data.emplace(
"torque",
Value(j.GetMaxTorque()));
139 data.emplace(
"correction",
Value(j.GetCorrectionFactor()));
143 const auto& j =
static_cast<const b2GearJoint&
>(
raw);
145 for (
const auto*
source : sorted) {
149 if (
first < 0 ||
second < 0)
return malformed<Value>(
"Gear source is missing");
150 data.emplace(
"first",
Value(std::to_string(
first)));
151 data.emplace(
"second",
Value(std::to_string(
second)));
152 data.emplace(
"ratio",
Value(j.GetRatio()));
154 for (
float value : wrapper->gearReferencePoses_) poses.emplace_back(
value);
155 data.emplace(
"referencePoses",
Value(std::move(poses)));
160 {
"kind",
Value(std::to_string(
static_cast<int>(wrapper->kind_)))},
161 {
"bodyA",
Value(std::to_string(bodyId(*
raw.GetBodyA())))},
162 {
"bodyB",
Value(std::to_string(bodyId(*
raw.GetBodyB())))},
163 {
"collideConnected",
Value(
raw.GetCollideConnected())},
164 {
"data",
Value(std::move(data))}});
170 std::uint32_t firstHandleIndex)
try {
172 return malformed<void>(
"Restored joint handles exceed available identity space");
173 w.nextJointHandleIndex_ = firstHandleIndex;
180 std::vector<Record> records;
182 std::map<int, Body*> bodies;
183 std::map<int, Joint2D*> joints;
184 for (
auto*
body :
w.bodies_) bodies.emplace(
body->getId(),
body);
187 if (!o || !
hasExactFields(*o, {
"id",
"kind",
"bodyA",
"bodyB",
"collideConnected",
"data"}))
188 return malformed<void>(
"Joint record has unknown or missing fields");
189 auto id = positiveId(*o,
"id");
191 auto a = positiveId(*o,
"bodyA");
193 auto b = positiveId(*o,
"bodyB");
197 auto collide =
readBool(*o,
"collideConnected");
200 if (!data || !
ids.insert(
id.value()).second || !bodies.contains(
a.value()) || !bodies.contains(
b.value()) ||
202 return malformed<void>(
"Invalid joint kind, duplicated id or missing/distinct endpoint");
203 if (bodies.at(
a.value())->raw()->GetType() != b2_dynamicBody &&
204 bodies.at(
b.value())->raw()->GetType() != b2_dynamicBody)
205 return malformed<void>(
"Joint requires at least one dynamic endpoint");
207 {
id.value(),
a.value(),
b.value(),
static_cast<Joint2DKind>(
kind.value()), collide.value(), data});
210 std::sort(records.begin(), records.end(), [](
const Record&
a,
const Record&
b) {
211 if ((a.kind == Joint2DKind::Gear) != (b.kind == Joint2DKind::Gear)) return a.kind != Joint2DKind::Gear;
216 def.bodyB = bodies.at(
record.b)->raw();
217 def.collideConnected =
record.collide;
218 auto*
raw =
w.raw()->CreateJoint(&def);
219 auto owned = std::unique_ptr<Joint2D>(
223 w.joints_.insert(
owned.get());
224 w.restoredJoints2D_.push_back(std::move(
owned));
228 for (
const auto&
r : records) {
229 const auto& o = *
r.data;
232 auto parsed =
parameters(o, {
"offsetX",
"offsetY",
"angle",
"force",
"torque",
"correction"});
234 const auto&
p = parsed.value();
235 if (
p[3] < 0 ||
p[4] < 0 ||
p[5] < 0 ||
p[5] > 1)
return malformed<void>(
"Invalid motor parameters");
237 d.linearOffset.Set(
p[0],
p[1]);
238 d.angularOffset =
p[2];
241 d.correctionFactor =
p[5];
246 auto parsed =
parameters(o, {
"ax",
"ay",
"bx",
"by",
"referenceAngle",
"limitEnabled",
"lower",
"upper",
247 "motorEnabled",
"speed",
"maximum"});
249 const auto&
p = parsed.value();
250 if (
p[6] >
p[7] ||
p[10] < 0)
return malformed<void>(
"Invalid revolute limit/motor parameters");
251 b2RevoluteJointDef
d;
252 d.localAnchorA.Set(
p[0],
p[1]);
253 d.localAnchorB.Set(
p[2],
p[3]);
254 d.referenceAngle =
p[4];
255 d.enableLimit =
p[5] != 0;
258 d.enableMotor =
p[8] != 0;
260 d.maxMotorTorque =
p[10];
265 auto parsed =
parameters(o, {
"ax",
"ay",
"bx",
"by",
"referenceAngle",
"axisX",
"axisY",
"limitEnabled",
266 "lower",
"upper",
"motorEnabled",
"speed",
"maximum"});
268 const auto&
p = parsed.value();
269 if (
p[8] >
p[9] ||
p[12] < 0 || std::abs(std::hypot(
p[5],
p[6]) - 1.f) > 1e-5f)
270 return malformed<void>(
"Invalid prismatic axis/limit/motor parameters");
271 b2PrismaticJointDef
d;
272 d.localAnchorA.Set(
p[0],
p[1]);
273 d.localAnchorB.Set(
p[2],
p[3]);
274 d.referenceAngle =
p[4];
275 d.localAxisA.Set(
p[5],
p[6]);
276 d.enableLimit =
p[7] != 0;
277 d.lowerTranslation =
p[8];
278 d.upperTranslation =
p[9];
279 d.enableMotor =
p[10] != 0;
280 d.motorSpeed =
p[11];
281 d.maxMotorForce =
p[12];
286 auto parsed =
parameters(o, {
"ax",
"ay",
"bx",
"by",
"length",
"frequency",
"damping"});
288 const auto&
p = parsed.value();
289 if (
p[4] <= 0 ||
p[5] < 0 ||
p[6] < 0)
return malformed<void>(
"Invalid distance spring parameters");
290 b2DistanceJointDef
d;
291 d.localAnchorA.Set(
p[0],
p[1]);
292 d.localAnchorB.Set(
p[2],
p[3]);
294 d.frequencyHz =
p[5];
295 d.dampingRatio =
p[6];
300 auto parsed =
parameters(o, {
"ax",
"ay",
"bx",
"by",
"axisX",
"axisY",
"frequency",
"damping",
301 "motorEnabled",
"speed",
"maximum"});
303 const auto&
p = parsed.value();
304 if (
p[6] < 0 ||
p[7] < 0 ||
p[10] < 0 || std::abs(std::hypot(
p[4],
p[5]) - 1.f) > 1e-5f)
305 return malformed<void>(
"Invalid wheel axis/spring/motor parameters");
307 d.localAnchorA.Set(
p[0],
p[1]);
308 d.localAnchorB.Set(
p[2],
p[3]);
309 d.localAxisA.Set(
p[4],
p[5]);
310 d.frequencyHz =
p[6];
311 d.dampingRatio =
p[7];
312 d.enableMotor =
p[8] != 0;
314 d.maxMotorTorque =
p[10];
319 auto parsed =
parameters(o, {
"ax",
"ay",
"bx",
"by",
"referenceAngle",
"frequency",
"damping"});
321 const auto&
p = parsed.value();
322 if (
p[5] < 0 ||
p[6] < 0)
return malformed<void>(
"Invalid weld spring parameters");
324 d.localAnchorA.Set(
p[0],
p[1]);
325 d.localAnchorB.Set(
p[2],
p[3]);
326 d.referenceAngle =
p[4];
327 d.frequencyHz =
p[5];
328 d.dampingRatio =
p[6];
333 auto parsed =
parameters(o, {
"ax",
"ay",
"bx",
"by",
"groundAx",
"groundAy",
"groundBx",
"groundBy",
334 "lengthA",
"lengthB",
"ratio"});
336 const auto&
p = parsed.value();
337 if (
p[8] <= b2_linearSlop ||
p[9] <= b2_linearSlop ||
p[10] <= b2_epsilon ||
338 !std::isfinite(
p[8] +
p[10] *
p[9]))
339 return malformed<void>(
"Invalid pulley reference length or ratio");
341 d.localAnchorA.Set(
p[0],
p[1]);
342 d.localAnchorB.Set(
p[2],
p[3]);
343 d.groundAnchorA.Set(
p[4],
p[5]);
344 d.groundAnchorB.Set(
p[6],
p[7]);
349 j.pulleyLocalA_ = {
p[0],
p[1]};
350 j.pulleyLocalB_ = {
p[2],
p[3]};
354 if (!
hasExactFields(o, {
"first",
"second",
"ratio",
"referencePoses"}))
355 return malformed<void>(
"Invalid gear fields");
356 auto first = positiveId(o,
"first");
358 auto second = positiveId(o,
"second");
362 if (!joints.contains(
first.value()) || !joints.contains(
second.value()) ||
364 return malformed<void>(
"Missing gear sources or invalid gear ratio/collision policy");
365 auto*
a = joints.at(
first.value());
366 auto*
b = joints.at(
second.value());
370 if (!sourceKind(
a->kind_) || !sourceKind(
b->kind_) || bodyId(*
a->joint_->GetBodyB()) !=
r.a ||
371 bodyId(*
b->joint_->GetBodyB()) !=
r.b ||
a->joint_->GetBodyB()->GetType() != b2_dynamicBody ||
372 b->joint_->GetBodyB()->GetType() != b2_dynamicBody)
373 return malformed<void>(
"Invalid gear source kinds or endpoints");
375 if (!poses || poses->size() != 12)
376 return malformed<void>(
"Gear reference poses must contain four XY-angle triples");
377 std::array<float, 12>
reference{}, original{};
378 for (std::size_t i = 0; i <
reference.size(); ++i) {
383 const std::array<b2Body*, 4> endpoints{
a->joint_->GetBodyA(),
a->joint_->GetBodyB(),
384 b->joint_->GetBodyA(),
b->joint_->GetBodyB()};
385 for (std::size_t i = 0; i < endpoints.size(); ++i) {
386 original[3 * i] = endpoints[i]->GetPosition().x;
387 original[3 * i + 1] = endpoints[i]->GetPosition().y;
388 original[3 * i + 2] = endpoints[i]->GetAngle();
389 for (std::size_t j = 0; j < i; ++j)
390 if (endpoints[i] == endpoints[j] &&
393 return malformed<void>(
"Shared gear endpoint has inconsistent reference poses");
395 for (std::size_t i = 0; i < endpoints.size(); ++i)
397 auto coordinate = [](
Joint2D& j) {
399 ?
static_cast<b2RevoluteJoint*
>(j.joint_)->GetJointAngle()
400 :
static_cast<b2PrismaticJoint*
>(j.joint_)->GetJointTranslation();
402 if (!std::isfinite(coordinate(*
a) +
ratio.value() * coordinate(*
b)))
403 return malformed<void>(
"Gear reference constant overflows");
405 d.joint1 =
a->joint_;
406 d.joint2 =
b->joint_;
409 j.firstSource_ =
a->handle_;
410 j.secondSource_ =
b->handle_;
412 for (std::size_t i = 0; i < endpoints.size(); ++i)
413 endpoints[i]->SetTransform({original[3 * i], original[3 * i + 1]}, original[3 * i + 2]);
418 w.nextJointId_ =
ids.empty() ? 1 : *
ids.rbegin() + 1;
420}
catch (
const std::exception&
error) {
422 std::string(
"Planar joint preparation failed: ") +
error.what(),
423 "physics.world.restore.prepare"));
AuthorityStoreHandleRef reference
ScriptComponentRecord record
wgpu::PopErrorScopeStatus status
std::array< uint32_t, 9 > parameters
std::set< std::string > values
const AssetImportLimits & limits
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
static constexpr index_type invalidIndex
Reserved index value shared by all invalid handles.
The canonical owning dynamic value used by data-facing protocols.
std::map< std::string, Value > Object
std::vector< Value > Array
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Owning planar joint wrapper observing World-owned backend state. @ownership Caller/VM owns factory wr...
b2Joint * raw() const
Internal borrowed solver joint; valid only while this wrapper is valid.
Box2D world wrapper (2D physics) with pixel-space coordinates. Handles stepping, gravity,...
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Result< float > readFloat(const Value::Object &object, std::string_view name)
Reads a required finite number representable by float.
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...
bool hasExactFields(const Value::Object &object, std::initializer_list< std::string_view > expected)
Internal exact-field schema predicate.
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.
Optional physics backend for vehicle mobility and body attach.
Joint2DKind
Closed set of planar mechanical constraints. Gear couples two existing joints.
static Result< void > restoreJoints2D(World &candidate, const Value::Array &joints, std::uint32_t firstHandleIndex)
Rebuild validated joint definitions inside a detached candidate, allocating fresh runtime handles.
static Result< Value > captureJoints2D(const World &world)
Capture owning joint definitions; rejects unregistered backend joints.
static void adopt(World &live, World &prepared)