7#include <Box2D/Box2D.h>
18bool finite(JointPoint2D
p) {
return std::isfinite(
p.x) && std::isfinite(
p.y); }
19b2Vec2 vec(JointPoint2D
p) {
return {
p.x,
p.y}; }
20JointPoint2D
point(b2Vec2
p) {
return {
p.x,
p.y}; }
21bool valid(
const Joint2DSettings&
s) {
23 std::isfinite(
s.length) &&
s.length > 0 && std::isfinite(
s.ratio) &&
s.ratio > 0 &&
24 std::isfinite(
s.springHertz) &&
s.springHertz >= 0 && std::isfinite(
s.dampingRatio) &&
s.dampingRatio >= 0;
28 : id_(world.nextJointId_++), world_(&world), joint_(&joint), kind_(
kind), handle_(
handle) {
29 joint_->SetUserData(
this);
30 world.joints_.insert(
this);
31 world.jointHandles_[
handle] =
this;
33Joint2D::~Joint2D() { release(); }
34bool Joint2D::isValid() const noexcept {
return world_ !=
nullptr && joint_ !=
nullptr; }
35void Joint2D::invalidate() noexcept {
36 if (world_) world_->forgetJoint(
this);
39 handle_ = PhysicsJointHandle::invalid();
41void Joint2D::release() {
42 if (!isValid())
return;
44 EV_ASSERT(!world_->raw()->IsLocked(),
"Destroy Joint2D outside solver callbacks");
45 const auto handle = handle_;
47 for (
auto* candidate : world_->joints_)
48 if (candidate != this && (candidate->firstSource_ ==
handle || candidate->secondSource_ ==
handle))
50 for (
auto* dependent :
dependents) dependent->release();
51 world_->joints_.erase(
this);
52 world_->raw()->DestroyJoint(joint_);
56 if (isValid() && world_->raw()->IsLocked())
57 return failure<void>(DiagnosticCode::PreconditionViolation,
"World is stepping");
62 using R = std::unique_ptr<Joint2D>;
63 if (!
w.isValid() || !
a.isValid() || !
b.isValid() ||
a.getWorld() != &
w ||
b.getWorld() != &
w || &
a == &
b ||
65 return failure<R>(DiagnosticCode::InvalidArgument,
66 "Live distinct same-world bodies and finite valid settings required");
67 if (
w.raw()->IsLocked())
return failure<R>(DiagnosticCode::PreconditionViolation,
"World is stepping");
68 if (
a.raw()->GetType() != b2_dynamicBody &&
b.raw()->GetType() != b2_dynamicBody)
69 return failure<R>(DiagnosticCode::InvalidArgument,
"At least one endpoint must be dynamic");
70 if (
w.nextJointHandleIndex_ == PhysicsJointHandle::invalidIndex ||
71 w.nextJointId_ == std::numeric_limits<int>::max())
72 return failure<R>(DiagnosticCode::Failed,
"Joint handle space exhausted");
73 b2Vec2
axis = vec(
s.axis);
74 const float axisLength =
axis.Length();
75 if ((
s.kind == Joint2DKind::Prismatic ||
s.kind == Joint2DKind::Wheel) &&
76 (!std::isfinite(axisLength) || axisLength < 1e-6f))
77 return failure<R>(DiagnosticCode::InvalidArgument,
"Joint axis must be nonzero");
78 if (axisLength > 0)
axis *= 1 / axisLength;
79 b2Joint*
raw =
nullptr;
81 case Joint2DKind::Revolute: {
83 d.Initialize(
a.raw(),
b.raw(), vec(
s.anchorA));
84 d.collideConnected =
s.collideConnected;
85 raw =
w.raw()->CreateJoint(&
d);
88 case Joint2DKind::Prismatic: {
89 b2PrismaticJointDef
d;
90 d.Initialize(
a.raw(),
b.raw(), vec(
s.anchorA),
axis);
91 d.collideConnected =
s.collideConnected;
92 raw =
w.raw()->CreateJoint(&
d);
95 case Joint2DKind::Distance: {
97 d.Initialize(
a.raw(),
b.raw(), vec(
s.anchorA), vec(
s.anchorB));
99 d.frequencyHz =
s.springHertz;
100 d.dampingRatio =
s.dampingRatio;
101 d.collideConnected =
s.collideConnected;
102 raw =
w.raw()->CreateJoint(&
d);
105 case Joint2DKind::Pulley: {
106 const float la = (vec(
s.anchorA) - vec(
s.groundA)).Length();
107 const float lb = (vec(
s.anchorB) - vec(
s.groundB)).Length();
108 if (
s.ratio <= b2_epsilon || !std::isfinite(la) || !std::isfinite(lb) || la <= b2_linearSlop ||
109 lb <= b2_linearSlop || !std::isfinite(la +
s.ratio * lb))
110 return failure<R>(DiagnosticCode::InvalidArgument,
"Pulley segments must have positive finite lengths");
112 d.Initialize(
a.raw(),
b.raw(), vec(
s.groundA), vec(
s.groundB), vec(
s.anchorA), vec(
s.anchorB),
s.ratio);
113 d.collideConnected =
s.collideConnected;
114 raw =
w.raw()->CreateJoint(&
d);
117 case Joint2DKind::Wheel: {
119 d.Initialize(
a.raw(),
b.raw(), vec(
s.anchorA),
axis);
120 d.frequencyHz =
s.springHertz;
121 d.dampingRatio =
s.dampingRatio;
122 d.collideConnected =
s.collideConnected;
123 raw =
w.raw()->CreateJoint(&
d);
126 case Joint2DKind::Weld: {
128 d.Initialize(
a.raw(),
b.raw(), vec(
s.anchorA));
129 d.frequencyHz =
s.springHertz;
130 d.dampingRatio =
s.dampingRatio;
131 d.collideConnected =
s.collideConnected;
132 raw =
w.raw()->CreateJoint(&
d);
135 case Joint2DKind::Motor: {
137 d.Initialize(
a.raw(),
b.raw());
138 d.collideConnected =
s.collideConnected;
139 raw =
w.raw()->CreateJoint(&
d);
142 default:
return failure<R>(DiagnosticCode::Unsupported,
"Use createGear for coupled constraints");
146 if (
s.kind == Joint2DKind::Pulley) {
147 owned->pulleyLocalA_ =
point(
a.raw()->GetLocalPoint(vec(
s.anchorA)));
148 owned->pulleyLocalB_ =
point(
b.raw()->GetLocalPoint(vec(
s.anchorB)));
150 w.joints_.insert(
owned.get());
154 using R = std::unique_ptr<Joint2D>;
155 auto supported = [](
Joint2DKind k) {
return k == Joint2DKind::Revolute || k == Joint2DKind::Prismatic; };
156 if (!
w.isValid() || !
a.isValid() || !
b.isValid() ||
a.world_ != &
w ||
b.world_ != &
w || &
a == &
b ||
157 !supported(
a.kind_) || !supported(
b.kind_) || !std::isfinite(
ratio) ||
ratio == 0)
158 return failure<R>(DiagnosticCode::InvalidArgument,
159 "Two distinct same-world revolute/prismatic joints and nonzero ratio required");
160 if (
w.raw()->IsLocked())
return failure<R>(DiagnosticCode::PreconditionViolation,
"World is stepping");
161 if (
w.nextJointHandleIndex_ == PhysicsJointHandle::invalidIndex ||
162 w.nextJointId_ == std::numeric_limits<int>::max())
163 return failure<R>(DiagnosticCode::Failed,
"Joint handle space exhausted");
164 if (
a.joint_->GetBodyB() ==
b.joint_->GetBodyB() ||
a.joint_->GetBodyB()->GetType() != b2_dynamicBody ||
165 b.joint_->GetBodyB()->GetType() != b2_dynamicBody)
166 return failure<R>(DiagnosticCode::InvalidArgument,
"Gear body-B endpoints must be distinct dynamic bodies");
168 return source.kind_ == Joint2DKind::Revolute
169 ?
static_cast<const b2RevoluteJoint*
>(
source.joint_)->GetJointAngle()
170 :
static_cast<const b2PrismaticJoint*
>(
source.joint_)->GetJointTranslation();
172 if (!std::isfinite(coordinate(
a) +
ratio * coordinate(
b)))
173 return failure<R>(DiagnosticCode::InvalidArgument,
"Gear reference constant must be finite");
175 d.bodyA =
a.joint_->GetBodyB();
176 d.bodyB =
b.joint_->GetBodyB();
180 auto*
raw =
w.raw()->CreateJoint(&
d);
183 owned->firstSource_ =
a.handle_;
184 owned->secondSource_ =
b.handle_;
185 const std::array<b2Body*, 4> endpoints{
a.joint_->GetBodyA(),
a.joint_->GetBodyB(),
b.joint_->GetBodyA(),
186 b.joint_->GetBodyB()};
187 for (std::size_t i = 0; i < endpoints.size(); ++i) {
188 owned->gearReferencePoses_[3 * i] = endpoints[i]->GetPosition().x;
189 owned->gearReferencePoses_[3 * i + 1] = endpoints[i]->GetPosition().y;
190 owned->gearReferencePoses_[3 * i + 2] = endpoints[i]->GetAngle();
192 w.joints_.insert(
owned.get());
196 if (!isValid())
return failure<void>(DiagnosticCode::StaleHandle,
"Joint is dead");
197 if (world_->raw()->IsLocked())
return failure<void>(DiagnosticCode::PreconditionViolation,
"World is stepping");
198 if (!std::isfinite(speed) || !std::isfinite(maximumForce) || maximumForce < 0)
199 return failure<void>(DiagnosticCode::InvalidArgument,
"Finite speed and nonnegative maximum force required");
201 case Joint2DKind::Revolute: {
202 auto& j = *
static_cast<b2RevoluteJoint*
>(joint_);
203 j.SetMotorSpeed(speed);
204 j.SetMaxMotorTorque(maximumForce);
208 case Joint2DKind::Prismatic: {
209 auto& j = *
static_cast<b2PrismaticJoint*
>(joint_);
210 j.SetMotorSpeed(speed);
211 j.SetMaxMotorForce(maximumForce);
215 case Joint2DKind::Wheel: {
216 auto& j = *
static_cast<b2WheelJoint*
>(joint_);
217 j.SetMotorSpeed(speed);
218 j.SetMaxMotorTorque(maximumForce);
222 default:
return failure<void>(DiagnosticCode::Unsupported,
"Joint kind has no motor");
227 if (!isValid())
return failure<void>(DiagnosticCode::StaleHandle,
"Joint is dead");
228 if (world_->raw()->IsLocked())
return failure<void>(DiagnosticCode::PreconditionViolation,
"World is stepping");
229 if (!std::isfinite(lower) || !std::isfinite(upper) || lower > upper)
230 return failure<void>(DiagnosticCode::InvalidArgument,
"Finite ordered limits required");
232 case Joint2DKind::Revolute: {
233 auto& j = *
static_cast<b2RevoluteJoint*
>(joint_);
234 j.SetLimits(lower, upper);
238 case Joint2DKind::Prismatic: {
239 auto& j = *
static_cast<b2PrismaticJoint*
>(joint_);
240 j.SetLimits(lower, upper);
244 default:
return failure<void>(DiagnosticCode::Unsupported,
"Joint kind has no limits");
249 if (!isValid())
return failure<Joint2DState>(DiagnosticCode::StaleHandle,
"Joint is dead");
250 if (!std::isfinite(
dt) ||
dt <= 0 || !std::isfinite(1 /
dt))
251 return failure<Joint2DState>(DiagnosticCode::InvalidArgument,
"Positive finite sampling duration required");
254 out.anchorA =
point(joint_->GetAnchorA());
255 out.anchorB =
point(joint_->GetAnchorB());
256 out.reactionForce =
point(joint_->GetReactionForce(1 /
dt));
257 out.reactionTorque = joint_->GetReactionTorque(1 /
dt);
259 case Joint2DKind::Revolute:
out.coordinate =
static_cast<b2RevoluteJoint*
>(joint_)->GetJointAngle();
break;
260 case Joint2DKind::Prismatic:
261 out.coordinate =
static_cast<b2PrismaticJoint*
>(joint_)->GetJointTranslation();
263 case Joint2DKind::Distance:
out.coordinate = (joint_->GetAnchorB() - joint_->GetAnchorA()).Length();
break;
264 case Joint2DKind::Pulley: {
265 auto& j = *
static_cast<b2PulleyJoint*
>(joint_);
266 out.coordinate = j.GetCurrentLengthA();
267 out.secondaryCoordinate = j.GetCurrentLengthB();
270 case Joint2DKind::Gear:
out.coordinate =
static_cast<b2GearJoint*
>(joint_)->GetRatio();
break;
271 case Joint2DKind::Wheel:
out.coordinate =
static_cast<b2WheelJoint*
>(joint_)->GetJointTranslation();
break;
272 case Joint2DKind::Weld:
273 case Joint2DKind::Motor:
break;
278void World::releaseBodyJoints2D(
Body&
body) {
279 std::vector<Joint2D*> attached;
280 for (
auto* joint : joints_)
281 if (joint->joint_->GetBodyA() ==
body.
raw() || joint->joint_->GetBodyB() ==
body.
raw())
282 attached.push_back(joint);
283 for (
auto* joint : attached) joint->release();
285void World::invalidateJoints2D() noexcept {
287 for (
auto* joint :
retiring) joint->invalidate();
289 restoredJoints2D_.clear();
292 for (
auto* joint : joints_)
297 if (!joint.
isValid())
return failure<PhysicsJointLink>(DiagnosticCode::StaleHandle,
"Joint is dead");
301 if (
owner.isValid() &&
owner.runtimeHandle() == world && joint.isValid()) {
302 for (
auto* candidate :
owner.joints_)
306 Diagnostic::error(DiagnosticCode::StaleHandle,
"Planar joint link is stale or has a foreign world"));
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
std::vector< JobImpl * > dependents
std::shared_ptr< OceanGpuSpectrum > owner
Typed composition link from a gameplay entity to a physics body.
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 failure(Status status)
Construct a failed result from a structured status.
2D rigid body (Box2D) in pixel-space coordinates. Owned by a World; create shapes with newRectangleFi...
Owning planar joint wrapper observing World-owned backend state. @ownership Caller/VM owns factory wr...
bool isValid() const noexcept
True until wrapper release or a body/world/source-joint is destroyed.
Joint2D(const Joint2D &)=delete
Box2D world wrapper (2D physics) with pixel-space coordinates. Handles stepping, gravity,...
PhysicsWorldHandle runtimeHandle() const noexcept
Process-local identity used by PhysicsLink; invalid after destruction.
Optional physics backend for vehicle mobility and body attach.
Joint2DKind
Closed set of planar mechanical constraints. Gear couples two existing joints.
eve::RuntimeHandle< PhysicsJointHandleTag > PhysicsJointHandle
Generation-qualified runtime identity for a physics joint.
DiagnosticCode
Stable machine-readable diagnostic codes.
Validated-at-creation joint parameters; all lengths are meters, angles radians.
Owning solver observation. Coordinate is angle/radians or translation/meters by kind.