载入中...
搜索中...
未找到
Joint2D.cpp
浏览该文件的文档.
2#include "common/Assert.h"
3#include "physics/Body.h"
5#include "physics/World.h"
6
7#include <Box2D/Box2D.h>
8#include <cmath>
9#include <limits>
10#include <vector>
11
12namespace eve::physics {
13namespace {
14template <class T>
15Result<T> failure(DiagnosticCode code, const char* message) {
16 return Result<T>::failure(Diagnostic::error(code, message, "physics.joint2d"));
17}
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) {
22 return finite(s.anchorA) && finite(s.anchorB) && finite(s.axis) && finite(s.groundA) && finite(s.groundB) &&
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;
25}
26} // namespace
27Joint2D::Joint2D(World& world, b2Joint& joint, Joint2DKind kind, PhysicsJointHandle handle)
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;
32}
33Joint2D::~Joint2D() { release(); }
34bool Joint2D::isValid() const noexcept { return world_ != nullptr && joint_ != nullptr; }
35void Joint2D::invalidate() noexcept {
36 if (world_) world_->forgetJoint(this);
37 world_ = nullptr;
38 joint_ = nullptr;
39 handle_ = PhysicsJointHandle::invalid();
40}
41void Joint2D::release() {
42 if (!isValid()) return;
43 // Public lifetime contract forbids wrapper destruction from solver callbacks.
44 EV_ASSERT(!world_->raw()->IsLocked(), "Destroy Joint2D outside solver callbacks");
45 const auto handle = handle_;
46 std::vector<Joint2D*> dependents;
47 for (auto* candidate : world_->joints_)
48 if (candidate != this && (candidate->firstSource_ == handle || candidate->secondSource_ == handle))
49 dependents.push_back(candidate);
50 for (auto* dependent : dependents) dependent->release();
51 world_->joints_.erase(this);
52 world_->raw()->DestroyJoint(joint_);
53 invalidate();
54}
55Result<void> Joint2D::destroyChecked() {
56 if (isValid() && world_->raw()->IsLocked())
57 return failure<void>(DiagnosticCode::PreconditionViolation, "World is stepping");
58 release();
59 return Result<void>::success();
60}
62 using R = std::unique_ptr<Joint2D>;
63 if (!w.isValid() || !a.isValid() || !b.isValid() || a.getWorld() != &w || b.getWorld() != &w || &a == &b ||
64 !valid(s))
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;
80 switch (s.kind) {
81 case Joint2DKind::Revolute: {
82 b2RevoluteJointDef d;
83 d.Initialize(a.raw(), b.raw(), vec(s.anchorA));
84 d.collideConnected = s.collideConnected;
85 raw = w.raw()->CreateJoint(&d);
86 break;
87 }
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);
93 break;
94 }
95 case Joint2DKind::Distance: {
96 b2DistanceJointDef d;
97 d.Initialize(a.raw(), b.raw(), vec(s.anchorA), vec(s.anchorB));
98 d.length = s.length;
99 d.frequencyHz = s.springHertz;
100 d.dampingRatio = s.dampingRatio;
101 d.collideConnected = s.collideConnected;
102 raw = w.raw()->CreateJoint(&d);
103 break;
104 }
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");
111 b2PulleyJointDef d;
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);
115 break;
116 }
117 case Joint2DKind::Wheel: {
118 b2WheelJointDef d;
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);
124 break;
125 }
126 case Joint2DKind::Weld: {
127 b2WeldJointDef d;
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);
133 break;
134 }
135 case Joint2DKind::Motor: {
136 b2MotorJointDef d;
137 d.Initialize(a.raw(), b.raw());
138 d.collideConnected = s.collideConnected;
139 raw = w.raw()->CreateJoint(&d);
140 break;
141 }
142 default: return failure<R>(DiagnosticCode::Unsupported, "Use createGear for coupled constraints");
143 }
144 const PhysicsJointHandle handle(w.nextJointHandleIndex_++, 1u);
145 R owned(new Joint2D(w, *raw, s.kind, handle));
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)));
149 }
150 w.joints_.insert(owned.get());
151 return Result<R>::success(std::move(owned));
152}
153Result<std::unique_ptr<Joint2D>> Joint2D::createGear(World& w, Joint2D& a, Joint2D& b, float ratio) {
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");
167 auto coordinate = [](const Joint2D& source) {
168 return source.kind_ == Joint2DKind::Revolute
169 ? static_cast<const b2RevoluteJoint*>(source.joint_)->GetJointAngle()
170 : static_cast<const b2PrismaticJoint*>(source.joint_)->GetJointTranslation();
171 };
172 if (!std::isfinite(coordinate(a) + ratio * coordinate(b)))
173 return failure<R>(DiagnosticCode::InvalidArgument, "Gear reference constant must be finite");
174 b2GearJointDef d;
175 d.bodyA = a.joint_->GetBodyB();
176 d.bodyB = b.joint_->GetBodyB();
177 d.joint1 = a.joint_;
178 d.joint2 = b.joint_;
179 d.ratio = ratio;
180 auto* raw = w.raw()->CreateJoint(&d);
181 const PhysicsJointHandle handle(w.nextJointHandleIndex_++, 1u);
182 R owned(new Joint2D(w, *raw, Joint2DKind::Gear, handle));
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();
191 }
192 w.joints_.insert(owned.get());
193 return Result<R>::success(std::move(owned));
194}
195Result<void> Joint2D::setMotor(bool enabled, float speed, float maximumForce) {
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");
200 switch (kind_) {
201 case Joint2DKind::Revolute: {
202 auto& j = *static_cast<b2RevoluteJoint*>(joint_);
203 j.SetMotorSpeed(speed);
204 j.SetMaxMotorTorque(maximumForce);
205 j.EnableMotor(enabled);
206 break;
207 }
208 case Joint2DKind::Prismatic: {
209 auto& j = *static_cast<b2PrismaticJoint*>(joint_);
210 j.SetMotorSpeed(speed);
211 j.SetMaxMotorForce(maximumForce);
212 j.EnableMotor(enabled);
213 break;
214 }
215 case Joint2DKind::Wheel: {
216 auto& j = *static_cast<b2WheelJoint*>(joint_);
217 j.SetMotorSpeed(speed);
218 j.SetMaxMotorTorque(maximumForce);
219 j.EnableMotor(enabled);
220 break;
221 }
222 default: return failure<void>(DiagnosticCode::Unsupported, "Joint kind has no motor");
223 }
224 return Result<void>::success();
225}
226Result<void> Joint2D::setLimits(bool enabled, float lower, float upper) {
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");
231 switch (kind_) {
232 case Joint2DKind::Revolute: {
233 auto& j = *static_cast<b2RevoluteJoint*>(joint_);
234 j.SetLimits(lower, upper);
235 j.EnableLimit(enabled);
236 break;
237 }
238 case Joint2DKind::Prismatic: {
239 auto& j = *static_cast<b2PrismaticJoint*>(joint_);
240 j.SetLimits(lower, upper);
241 j.EnableLimit(enabled);
242 break;
243 }
244 default: return failure<void>(DiagnosticCode::Unsupported, "Joint kind has no limits");
245 }
246 return Result<void>::success();
247}
248Result<Joint2DState> Joint2D::sample(float dt) const {
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");
253 out.kind = kind_;
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);
258 switch (kind_) {
259 case Joint2DKind::Revolute: out.coordinate = static_cast<b2RevoluteJoint*>(joint_)->GetJointAngle(); break;
260 case Joint2DKind::Prismatic:
261 out.coordinate = static_cast<b2PrismaticJoint*>(joint_)->GetJointTranslation();
262 break;
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();
268 break;
269 }
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;
274 }
276}
277
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();
284}
285void World::invalidateJoints2D() noexcept {
286 const auto retiring = joints_;
287 for (auto* joint : retiring) joint->invalidate();
288 joints_.clear();
289 restoredJoints2D_.clear();
290}
291ResultRef<Joint2D> World::resolveJoint2D(int id) const {
292 for (auto* joint : joints_)
293 if (joint->getId() == id) return ResultRef<Joint2D>::success(std::ref(*joint));
294 return ResultRef<Joint2D>::failure(Diagnostic::error(DiagnosticCode::StaleHandle, "Planar joint id is absent"));
295}
296Result<PhysicsJointLink> PhysicsJointLink::fromJoint(const Joint2D& joint) {
297 if (!joint.isValid()) return failure<PhysicsJointLink>(DiagnosticCode::StaleHandle, "Joint is dead");
298 return Result<PhysicsJointLink>::success({joint.world_->runtimeHandle(), joint.handle_});
299}
300ResultRef<Joint2D> PhysicsJointLink::resolve(World& owner) const {
301 if (owner.isValid() && owner.runtimeHandle() == world && joint.isValid()) {
302 for (auto* candidate : owner.joints_)
303 if (candidate->runtimeHandle() == joint) return ResultRef<Joint2D>::success(std::ref(*candidate));
304 }
306 Diagnostic::error(DiagnosticCode::StaleHandle, "Planar joint link is stale or has a foreign world"));
307}
308
309} // namespace eve::physics
float w
Definition AnimClip.cpp:738
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
ActiveSource owned
const std::string & s
glm::vec4 p[6]
double raw
std::string message
DiagnosticCode code
eve::Observer retiring
std::vector< JobImpl * > dependents
float ratio
JointPoint2D axis
std::string id
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::shared_ptr< OceanGpuSpectrum > owner
double dt
bool finite
PrimitiveHandle handle
std::string body
float d
ScriptStructure out
std::string_view source
std::string kind
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
2D rigid body (Box2D) in pixel-space coordinates. Owned by a World; create shapes with newRectangleFi...
Definition Body.h:21
Owning planar joint wrapper observing World-owned backend state. @ownership Caller/VM owns factory wr...
Definition Joint2D.h:58
bool isValid() const noexcept
True until wrapper release or a body/world/source-joint is destroyed.
Definition Joint2D.cpp:34
Joint2D(const Joint2D &)=delete
Box2D world wrapper (2D physics) with pixel-space coordinates. Handles stepping, gravity,...
Definition World.h:44
PhysicsWorldHandle runtimeHandle() const noexcept
Process-local identity used by PhysicsLink; invalid after destruction.
Definition World.h:128
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
Joint2DKind
Closed set of planar mechanical constraints. Gear couples two existing joints.
Definition Joint2D.h:16
eve::RuntimeHandle< PhysicsJointHandleTag > PhysicsJointHandle
Generation-qualified runtime identity for a physics joint.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
bool enabled
Validated-at-creation joint parameters; all lengths are meters, angles radians.
Definition Joint2D.h:30
Owning solver observation. Coordinate is angle/radians or translation/meters by kind.
Definition Joint2D.h:41