载入中...
搜索中...
未找到
WorldJoints2D.cpp
浏览该文件的文档.
1#include "physics/World.h"
2
3#include "physics/Body.h"
4#include "physics/Joint2D.h"
6#include "common/Exception.h"
7
8#include <Box2D/Box2D.h>
9
10#include <cmath>
11
12namespace eve::physics {
13namespace {
14
15void requireFiniteParams(const float *values, int count, const char *operation) {
16 for (int i = 0; i < count; ++i) {
17 if (!std::isfinite(values[i]))
18 throw eve::Exception("%s: parameters must be finite", operation);
19 }
20}
21
22void requireDistinctBodies(World *world, Body *bodyA, Body *bodyB, const char *operation) {
23 if (!world || !world->isValid() || !bodyA || !bodyB || !bodyA->isValid() || !bodyB->isValid() ||
24 bodyA->getWorld() != world || bodyB->getWorld() != world || bodyA == bodyB)
25 throw eve::Exception("%s: bodies must be distinct and belong to this world", operation);
26}
27
28b2Vec2 normalizedAxisPixels(float x, float y, const char *operation) {
29 const float length = std::sqrt(x * x + y * y);
30 if (length <= 1e-8f) throw eve::Exception("%s: axis length must be > 0", operation);
31 return b2Vec2(x / length, y / length);
32}
33
34} // namespace
35
37 if (!joint) return;
38 joints_.erase(joint);
39 if (joint->runtimeHandle().isValid()) jointHandles_.erase(joint->runtimeHandle());
40 for (auto it = jointHandles_.begin(); it != jointHandles_.end();) {
41 if (it->second == joint)
42 it = jointHandles_.erase(it);
43 else
44 ++it;
45 }
46}
47
49 if (!mechanism) return;
50 mechanisms_.erase(mechanism);
51}
52
53int World::nextJointId() { return nextJointId_++; }
54
55int World::nextMechanismId() { return nextMechanismId_++; }
56
58 if (nextJointHandleIndex_ == PhysicsJointHandle::invalidIndex)
59 throw eve::Exception("World.newJoint: process-local joint handle space exhausted");
60 return PhysicsJointHandle(nextJointHandleIndex_++, 1u);
61}
62
64 if (!isValid() || handle.isInvalid()) return nullptr;
65 const auto found = jointHandles_.find(handle);
66 if (found == jointHandles_.end() || !found->second || !found->second->isValid()) return nullptr;
67 return found->second;
68}
69
70namespace {
71Joint2D *createLegacy(World &world, Body *a, Body *b, Joint2DSettings settings) {
72 requireDistinctBodies(&world, a, b, "World.newJoint");
73 auto result = Joint2D::create(world, *a, *b, settings);
74 if (!result) throw eve::Exception("%s", result.status().describe().c_str());
75 return std::move(result).takeValue().release();
76}
77} // namespace
78Joint2D *World::newDistanceJoint(Body *a, Body *b, float ax, float ay, float bx, float by, float length, bool collide) {
81 s.anchorA = {toMeters(ax), toMeters(ay)};
82 s.anchorB = {toMeters(bx), toMeters(by)};
83 s.length = toMeters(length);
84 s.collideConnected = collide;
85 return createLegacy(*this, a, b, s);
86}
87Joint2D *World::newRevoluteJoint(Body *a, Body *b, float x, float y, bool collide) {
90 s.anchorA = {toMeters(x), toMeters(y)};
91 s.collideConnected = collide;
92 return createLegacy(*this, a, b, s);
93}
94Joint2D *World::newPrismaticJoint(Body *a, Body *b, float x, float y, float ax, float ay, bool collide) {
97 s.anchorA = {toMeters(x), toMeters(y)};
98 s.axis = {ax, ay};
99 s.collideConnected = collide;
100 return createLegacy(*this, a, b, s);
101}
102Joint2D *World::newWeldJoint(Body *a, Body *b, float x, float y, bool collide) {
105 s.anchorA = {toMeters(x), toMeters(y)};
106 s.collideConnected = collide;
107 return createLegacy(*this, a, b, s);
108}
109Joint2D *World::newWheelJoint(Body *a, Body *b, float x, float y, float ax, float ay, bool collide) {
112 s.anchorA = {toMeters(x), toMeters(y)};
113 s.axis = {ax, ay};
114 s.collideConnected = collide;
115 return createLegacy(*this, a, b, s);
116}
120 s.collideConnected = collide;
121 return createLegacy(*this, a, b, s);
122}
124 if (!first || !second) throw eve::Exception("World.newGearJoint: live source joints required");
125 auto result = Joint2D::createGear(*this, *first, *second, ratio);
126 if (!result) throw eve::Exception("%s", result.status().describe().c_str());
127 return std::move(result).takeValue().release();
128}
129
130Mechanism2D *World::newShaft(Body *support, Body *rotor, float anchorX, float anchorY,
131 bool collideConnected) {
132 requireDistinctBodies(this, support, rotor, "World.newShaft");
133 Joint2D *drive = newRevoluteJoint(support, rotor, anchorX, anchorY, collideConnected);
134 auto *mechanism =
135 new Mechanism2D(this, Mechanism2D::Kind::Shaft, nextMechanismId(), drive, nullptr, nullptr,
136 nullptr, 1, 0.f);
137 mechanisms_.insert(mechanism);
138 return mechanism;
139}
140
141Mechanism2D *World::newRatchet(Body *frame, Body *wheel, float anchorX, float anchorY, int direction,
142 float engagementTorque, bool collideConnected) {
143 requireDistinctBodies(this, frame, wheel, "World.newRatchet");
144 if (direction != 1 && direction != -1)
145 throw eve::Exception("World.newRatchet: direction must be +1 or -1");
146 if (!std::isfinite(engagementTorque) || engagementTorque < 0.f)
147 throw eve::Exception("World.newRatchet: engagementTorque must be finite and >= 0");
148 Joint2D *drive = newRevoluteJoint(frame, wheel, anchorX, anchorY, collideConnected);
149 auto *mechanism =
150 new Mechanism2D(this, Mechanism2D::Kind::Ratchet, nextMechanismId(), drive, nullptr,
151 nullptr, nullptr, direction, engagementTorque);
152 mechanisms_.insert(mechanism);
153 return mechanism;
154}
155
157 float crankAnchorX, float crankAnchorY, float crankPinX,
158 float crankPinY, float sliderPinX, float sliderPinY,
159 float slideAxisX, float slideAxisY, bool collideConnected) {
160 requireDistinctBodies(this, frame, crank, "World.newCrankSlider");
161 requireDistinctBodies(this, crank, rod, "World.newCrankSlider");
162 requireDistinctBodies(this, rod, slider, "World.newCrankSlider");
163 requireDistinctBodies(this, frame, slider, "World.newCrankSlider");
164 if (frame == rod || crank == slider)
165 throw eve::Exception("World.newCrankSlider: bodies must form a four-bar chain");
166 const float values[] = {crankAnchorX, crankAnchorY, crankPinX, crankPinY, sliderPinX,
167 sliderPinY, slideAxisX, slideAxisY};
168 requireFiniteParams(values, 8, "World.newCrankSlider");
169 (void)normalizedAxisPixels(slideAxisX, slideAxisY, "World.newCrankSlider");
170
171 Joint2D *drive = newRevoluteJoint(frame, crank, crankAnchorX, crankAnchorY, collideConnected);
172 Joint2D *crankPin = newRevoluteJoint(crank, rod, crankPinX, crankPinY, collideConnected);
173 Joint2D *sliderPin = newRevoluteJoint(rod, slider, sliderPinX, sliderPinY, collideConnected);
174 Joint2D *prismatic =
175 newPrismaticJoint(frame, slider, sliderPinX, sliderPinY, slideAxisX, slideAxisY,
177 auto *mechanism =
178 new Mechanism2D(this, Mechanism2D::Kind::CrankSlider, nextMechanismId(), drive, crankPin,
179 sliderPin, prismatic, 1, 0.f);
180 mechanisms_.insert(mechanism);
181 return mechanism;
182}
183
184} // namespace eve::physics
double y
double x
ActionParameterOperation operation
const std::string & s
std::int32_t second
std::int32_t first
float ratio
bool collideConnected
float length
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanWakeSettings settings
ssq::Object frame
PrimitiveHandle handle
std::set< std::string > values
RoadLaneDirection direction
bool found
int count
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
constexpr bool isValid() const noexcept
Returns whether both coordinates are usable handle values.
static constexpr index_type invalidIndex
Reserved index value shared by all invalid handles.
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
static Result< std::unique_ptr< Joint2D > > create(World &world, Body &a, Body &b, const Joint2DSettings &settings)
Create a constraint; rejects invalid input, foreign/dead bodies, Gear kind and locked worlds atomical...
Definition Joint2D.cpp:61
PhysicsJointHandle runtimeHandle() const noexcept
Process-local generation handle; invalid after destruction, never serialized.
Definition Joint2D.h:182
static Result< std::unique_ptr< Joint2D > > createGear(World &world, Joint2D &first, Joint2D &second, float ratio)
Couple two revolute/prismatic joints in the same world with coordinate1 + ratio*coordinate2 constant.
Definition Joint2D.cpp:153
Composed 2D mechanical assembly owned by a World.
Definition Mechanism2D.h:25
Box2D world wrapper (2D physics) with pixel-space coordinates. Handles stepping, gravity,...
Definition World.h:44
void forgetMechanism(Mechanism2D *mechanism)
Internal: removes a mechanism wrapper from ownership bookkeeping.
Joint2D * newDistanceJoint(Body *bodyA, Body *bodyB, float anchorAX, float anchorAY, float anchorBX, float anchorBY, float lengthPixels, bool collideConnected=false)
Connects two pixel-space anchors with a distance constraint.
Joint2D * newWheelJoint(Body *bodyA, Body *bodyB, float anchorX, float anchorY, float axisX, float axisY, bool collideConnected=false)
Creates a wheel joint with a pixel-space suspension axis.
Joint2D * newWeldJoint(Body *bodyA, Body *bodyB, float anchorX, float anchorY, bool collideConnected=false)
Welds two bodies at a shared pixel-space anchor.
Joint2D * findJoint(PhysicsJointHandle handle) const
Resolves a live joint handle; returns null when stale or foreign.
void forgetJoint(Joint2D *joint)
Internal: removes a joint wrapper from ownership bookkeeping.
Joint2D * newPrismaticJoint(Body *bodyA, Body *bodyB, float anchorX, float anchorY, float axisX, float axisY, bool collideConnected=false)
Creates a prismatic slider along a pixel-space axis.
Joint2D * newRevoluteJoint(Body *bodyA, Body *bodyB, float anchorX, float anchorY, bool collideConnected=false)
Creates a revolute hinge at a shared pixel-space anchor.
int nextMechanismId()
Internal: next stable mechanism id.
Mechanism2D * newCrankSlider(Body *frame, Body *crank, Body *rod, Body *slider, float crankAnchorX, float crankAnchorY, float crankPinX, float crankPinY, float sliderPinX, float sliderPinY, float slideAxisX, float slideAxisY, bool collideConnected=false)
Builds a planar crank-slider from frame, crank, connecting rod and slider bodies.
int nextJointId()
Internal: next stable joint id.
friend class Mechanism2D
Definition World.h:463
Joint2D * newGearJoint(Joint2D *joint1, Joint2D *joint2, float ratio)
Creates a gear joint that couples two revolute or prismatic joints.
Mechanism2D * newRatchet(Body *frame, Body *wheel, float anchorX, float anchorY, int direction, float engagementTorque, bool collideConnected=false)
Builds a one-way ratchet around a revolute hinge.
PhysicsJointHandle nextJointRuntimeHandle()
Internal: next generation-qualified joint handle.
bool isValid() const
True while the underlying Box2D world is alive.
Definition World.h:332
float toMeters(float pixels) const
Converts a pixel-space length to meters.
Definition World.cpp:467
Joint2D * newMotorJoint(Body *bodyA, Body *bodyB, bool collideConnected=false)
Creates a motor joint that drives relative pose between bodies.
Mechanism2D * newShaft(Body *support, Body *rotor, float anchorX, float anchorY, bool collideConnected=false)
Builds a shaft (support↔rotor revolute) with optional drive motor helpers.
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
eve::RuntimeHandle< PhysicsJointHandleTag > PhysicsJointHandle
Generation-qualified runtime identity for a physics joint.
Validated-at-creation joint parameters; all lengths are meters, angles radians.
Definition Joint2D.h:30