载入中...
搜索中...
未找到
VehiclePhysics.cpp
浏览该文件的文档.
3
4#include "physics/Body.h"
5#include "physics/Body3D.h"
7#include "physics/Shape3D.h"
8#include "physics/World.h"
9#include "physics/World3D.h"
12
13#include <algorithm>
14#include <cmath>
15#include <cstdint>
16#include <memory>
17
18namespace eve::vehicle {
19
21public:
22 enum class Space : std::uint8_t { TwoD, ThreeD };
23 std::shared_ptr<VehicleWheelRuntime> wheelRuntime;
24
26 std::weak_ptr<const void> lifetime)
27 : link_(link), space_(Space::TwoD), world_(world), lifetime_(std::move(lifetime)) {}
28
30 std::weak_ptr<const void> lifetime)
31 : link_(link), space_(Space::ThreeD), world_(world), lifetime_(std::move(lifetime)) {}
32
34
35 [[nodiscard]] eve::physics::Body* resolve2D() const {
36 if (space_ != Space::TwoD) return nullptr;
37 auto lifetime = lifetime_.lock();
38 if (!lifetime) return nullptr;
39 auto* world = static_cast<eve::physics::World*>(world_);
40 if (!world) return nullptr;
41 auto resolved = link_.resolve(*world);
42 if (!resolved) {
43 resolved.ignore("vehicle physics link became stale");
44 return nullptr;
45 }
46 return std::move(resolved).takeValue();
47 }
48
49 [[nodiscard]] eve::physics::Body3D* resolve3D() const {
50 if (space_ != Space::ThreeD) return nullptr;
51 auto lifetime = lifetime_.lock();
52 if (!lifetime) return nullptr;
53 auto* world = static_cast<eve::physics::World3D*>(world_);
54 if (!world) return nullptr;
55 auto resolved = link_.resolve(*world);
56 if (!resolved) {
57 resolved.ignore("vehicle physics link became stale");
58 return nullptr;
59 }
60 return std::move(resolved).takeValue();
61 }
62
63 [[nodiscard]] bool isAttached() const { return resolve2D() != nullptr || resolve3D() != nullptr; }
64
65 void detach() noexcept {
66 wheelRuntime.reset();
67 if (auto* body = resolve2D()) body->destroy();
68 if (auto* body = resolve3D()) body->destroy();
69 link_ = {};
70 world_ = nullptr;
71 lifetime_.reset();
72 }
73
74private:
76 Space space_;
77 void* world_ = nullptr;
78 std::weak_ptr<const void> lifetime_;
79};
80
81namespace {
82
83constexpr float kPi = 3.14159265358979323846f;
84
85float normalizeDeg(float deg) {
86 deg = std::fmod(deg, 360.f);
87 if (deg < 0.f) deg += 360.f;
88 return deg;
89}
90
91
92void shipMove2D(VehicleEntity& v, eve::physics::Body* b, float dt) {
93 const VehicleDefinition* def = v.definition()->def;
94 if (def == nullptr) return;
95 auto in = v.input();
96 auto mo = v.motion();
97 mo->x = b->getX();
98 mo->y = b->getY();
99
100 const float speedFactor = std::clamp(std::fabs(mo->speed) / def->maxSpeed, 0.f, 1.f);
101 mo->heading = normalizeDeg(mo->heading + in->steer * def->turnRate * (0.35f + 0.65f * speedFactor) * dt);
102
103 float target = in->throttle * def->maxSpeed;
104 if (in->brake > 0.f || in->handbrake) target = 0.f;
105 const float dv = target - mo->speed;
106 const float maxDv = def->accel * dt;
107 mo->speed += std::clamp(dv, -maxDv, maxDv);
108
109 const float rad = mo->heading * kPi / 180.f;
110 b->setAngle(rad);
111 b->setLinearVelocity(std::cos(rad) * mo->speed, std::sin(rad) * mo->speed);
112}
113
114void shipMove3D(VehicleEntity& v, eve::physics::Body3D* b, float dt) {
115 const VehicleDefinition* def = v.definition()->def;
116 if (def == nullptr) return;
117 auto in = v.input();
118 auto mo = v.motion();
119 mo->x = b->getX();
120 mo->y = b->getZ();
121
122 const float speedFactor = std::clamp(std::fabs(mo->speed) / def->maxSpeed, 0.f, 1.f);
123 mo->heading = normalizeDeg(mo->heading + in->steer * def->turnRate * (0.35f + 0.65f * speedFactor) * dt);
124
125 float target = in->throttle * def->maxSpeed;
126 if (in->brake > 0.f || in->handbrake) target = 0.f;
127 const float dv = target - mo->speed;
128 const float maxDv = def->accel * dt;
129 mo->speed += std::clamp(dv, -maxDv, maxDv);
130
131 const float rad = mo->heading * kPi / 180.f;
132 b->setRotation(0.f, std::sin(rad * 0.5f), 0.f, std::cos(rad * 0.5f));
133 b->setLinearVelocity(std::sin(rad) * mo->speed, 0.f, std::cos(rad) * mo->speed);
134}
135
136class SuspensionMobility3D : public IVehicleMobility {
137public:
138 const char* name() const override { return "suspension"; }
139 void update(VehicleEntity& v, float dt) override {
141 if (IVehicleMobility* kinematic = VehicleSystem::findMobility("kinematic")) {
142 kinematic->update(v, dt);
143 }
144 }
145};
146
147} // namespace
148
150 if (v == nullptr || world == nullptr) return VehiclePhysicsStatus::Unavailable;
151 (void)detach(v);
152 const VehicleDefinition* def = v->definition()->def;
153 if (def == nullptr) return VehiclePhysicsStatus::Unavailable;
154 auto mo = v->motion();
155
156 eve::physics::Body* b = world->newBody("dynamic", mo->x, mo->y);
157 if (b == nullptr) return VehiclePhysicsStatus::Unavailable;
158 b->newCircleFixture(def->radius, 1.f, 0.6f, 0.f);
159 b->setAngle(mo->heading * kPi / 180.f);
161 if (!link) {
162 link.ignore("new vehicle body did not produce a valid physics link");
163 b->destroy();
165 }
166 v->physicsBody()->binding = std::make_shared<VehiclePhysicsBinding>(
167 std::move(link).takeValue(), world, world->lifetimeToken());
168 v->physicsBody()->space = "2d";
169 v->suspension()->wheels.clear();
171}
172
174 if (v == nullptr || world == nullptr) return VehiclePhysicsStatus::Unavailable;
175 (void)detach(v);
176 const VehicleDefinition* def = v->definition()->def;
177 if (def == nullptr) return VehiclePhysicsStatus::Unavailable;
178 auto mo = v->motion();
179
180 eve::physics::Body3D* b = world->newBody("dynamic", mo->x, heightY, mo->y);
181 if (b == nullptr) return VehiclePhysicsStatus::Unavailable;
182 eve::physics::Shape3D* shape = b->newBoxShape(def->radius, 0.35f, def->radius, 1.f, 0.8f, 0.f);
183 if (shape != nullptr) shape->setFilterBits(2, ~uint64_t{0});
184 const float rad = mo->heading * kPi / 180.f;
185 b->setRotation(0.f, std::sin(rad * 0.5f), 0.f, std::cos(rad * 0.5f));
186 b->setAwake(true);
187
189 if (!link) {
190 link.ignore("new vehicle body did not produce a valid physics link");
191 b->destroy();
193 }
194 v->physicsBody()->binding = std::make_shared<VehiclePhysicsBinding>(
195 std::move(link).takeValue(), world, world->lifetimeToken());
196 v->physicsBody()->space = "3d";
197 v->suspension()->wheels.assign(def->suspension.wheels.size(), {});
199}
200
202 if (v == nullptr) return VehiclePhysicsStatus::Unavailable;
203 auto pb = v->physicsBody();
204 const bool had = pb->binding != nullptr;
205 if (pb->binding) pb->binding->detach();
206 pb->binding.reset();
207 pb->space.clear();
209}
210
212 return v != nullptr && v->physicsBody()->binding && v->physicsBody()->binding->isAttached();
213}
214
216 const auto binding = v == nullptr ? nullptr : v->physicsBody()->binding;
217 if (auto* body = binding ? binding->resolve3D() : nullptr) return body->getY();
218 return 0.f;
219}
220
222 const auto binding = v.physicsBody()->binding;
223 if (eve::physics::Body* b = binding ? binding->resolve2D() : nullptr) {
224 if (const auto* definition = v.definition()->def; definition && definition->mobility == "ship") {
225 shipMove2D(v, b, dt);
227 }
228 auto synchronized = synchronizeWheelState(v);
229 if (!synchronized) return VehiclePhysicsStatus::Rejected;
231 auto mo = v.motion();
232 mo->x = b->getX();
233 mo->y = b->getY();
234 mo->heading = normalizeDeg(b->getAngle() * 180.f / kPi);
235 mo->speed =
236 std::cos(b->getAngle()) * b->getLinearVelocityX() + std::sin(b->getAngle()) * b->getLinearVelocityY();
237 auto duration = Duration::fromSeconds(double(dt));
239 auto nextTick = b->getWorld()->simulationTick().incremented();
240 if (!nextTick) return VehiclePhysicsStatus::Rejected;
241 auto submitted = submitWheelStep(v, {*nextTick, duration.value()});
242 return submitted ? submitted.value() : VehiclePhysicsStatus::Rejected;
243 }
244 if (eve::physics::Body3D* b = binding ? binding->resolve3D() : nullptr) {
245 if (const auto* definition = v.definition()->def; definition && definition->mobility == "ship") {
246 shipMove3D(v, b, dt);
248 }
249 auto synchronized = synchronizeWheelState(v);
250 if (!synchronized) return VehiclePhysicsStatus::Rejected;
252 const float qx = b->getRotX(), qy = b->getRotY(), qz = b->getRotZ(), qw = b->getRotW();
253 const float fx = 2 * (qx * qz + qw * qy), fy = 2 * (qy * qz - qw * qx), fz = 1 - 2 * (qx * qx + qy * qy);
254 auto mo = v.motion();
255 mo->x = b->getX();
256 mo->y = b->getZ();
257 mo->heading = normalizeDeg(std::atan2(fx, fz) * 180.f / kPi);
258 mo->speed = fx * b->getLinearVelocityX() + fy * b->getLinearVelocityY() + fz * b->getLinearVelocityZ();
259 auto duration = Duration::fromSeconds(double(dt));
261 auto nextTick = b->getWorld()->simulationTick().incremented();
262 if (!nextTick) return VehiclePhysicsStatus::Rejected;
263 auto submitted = submitWheelStep(v, {*nextTick, duration.value()});
264 return submitted ? submitted.value() : VehiclePhysicsStatus::Rejected;
265 }
267}
268
270 const auto binding = v.physicsBody()->binding;
271 if (!binding || !binding->isAttached())
273 if (auto* body = binding->resolve2D()) return tire_detail::submit2D(v, *body, binding->wheelRuntime, step);
274 if (auto* body = binding->resolve3D()) return tire_detail::submit3D(v, *body, binding->wheelRuntime, step);
276}
286
288 auto mo = v.motion();
289 const auto binding = v.physicsBody()->binding;
290 if (eve::physics::Body* b = binding ? binding->resolve2D() : nullptr) {
291 mo->x = b->getX();
292 mo->y = b->getY();
293 } else if (eve::physics::Body3D* b = binding ? binding->resolve3D() : nullptr) {
294 mo->x = b->getX();
295 mo->y = b->getZ();
296 }
297}
298
300 const auto binding = v.physicsBody()->binding;
301 if (eve::physics::Body* b = binding ? binding->resolve2D() : nullptr) {
302 b->setAngle(headingRad);
303 b->setLinearVelocity(std::cos(headingRad) * speed, std::sin(headingRad) * speed);
305 }
306 if (eve::physics::Body3D* b = binding ? binding->resolve3D() : nullptr) {
307 b->setRotation(0.f, std::sin(headingRad * 0.5f), 0.f, std::cos(headingRad * 0.5f));
308 b->setLinearVelocity(std::sin(headingRad) * speed, 0.f, std::cos(headingRad) * speed);
310 }
312}
313
315 static SuspensionMobility3D mobility;
317}
318
319} // namespace eve::vehicle
LogicalId target
float duration
std::string name
Definition ECS.cpp:154
ShaderImageInput shape
float v
std::weak_ptr< const void > lifetime
PhysicsJointLink link
MeleePoint3 b
Definition MeleeHit.cpp:41
double dt
eve::action::ActionVfxBinding binding
std::string body
Object::Ptr value
RoadNetwork resolved
float step
Definition TreeMesh.cpp:451
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
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
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
3D shape (box/sphere/capsule) attached to a Body3D with material settings. Created via Body3D::new*Sh...
Definition Shape3D.h:34
void setFilterBits(uint64_t categoryBits, uint64_t maskBits)
Collision filter bits used by world ray/query filters (Box3D b3Filter). categoryBits 声明本形状属于哪些类别;mask...
Definition Shape3D.cpp:613
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
载具实体:数据全部在组件里,行为在 VehicleSystem。
VehiclePhysicsBinding(eve::physics::PhysicsLink link, eve::physics::World *world, std::weak_ptr< const void > lifetime)
eve::physics::Body3D * resolve3D() const
eve::physics::Body * resolve2D() const
VehiclePhysicsBinding(eve::physics::PhysicsLink link, eve::physics::World3D *world, std::weak_ptr< const void > lifetime)
std::shared_ptr< VehicleWheelRuntime > wheelRuntime
static Result< VehiclePhysicsStatus > synchronizeWheelState(VehicleEntity &v)
Publish wheel candidates only after their physics step succeeds; no force submission.
static Result< VehiclePhysicsStatus > submitWheelStep(VehicleEntity &v, const SimulationStep &step)
Submit top-down 2D or ray-suspension 3D wheel forces for an exact positive fixed step; no solver adva...
static VehiclePhysicsStatus detach(VehicleEntity *v)
Destroy attached bodies if any.
static VehiclePhysicsStatus tryWheelMove(VehicleEntity &v, float dt)
Step wheel/ship mobility from an attached body.
static void registerBuiltinMobility()
Register suspension mobility when physics is in the build.
static void syncTrackFromBody(VehicleEntity &v)
Copy attached body pose into motion for tracked vehicles.
static VehiclePhysicsStatus attach2D(VehicleEntity *v, eve::physics::World *world)
Attach a 2D dynamic body when physics is in the build.
static VehiclePhysicsStatus tryTrackApply(VehicleEntity &v, float headingRad, float speed)
Apply tracked heading/speed to an attached body.
static bool isAttached(VehicleEntity *v)
Whether the entity has a live, resolvable physics body.
static VehiclePhysicsStatus attach3D(VehicleEntity *v, eve::physics::World3D *world, float heightY)
Attach a 3D dynamic body when physics is in the build.
static float height(VehicleEntity *v)
3D body height, or 0 when no 3D body is attached.
static IVehicleMobility * findMobility(const std::string &name)
按名字取移动模型;未注册返回 nullptr。
static void registerMobility(IVehicleMobility *mobility)
注册移动模型实现;同名替换。
Result< VehiclePhysicsStatus > synchronize(VehicleEntity &vehicle, std::shared_ptr< VehicleWheelRuntime > &runtime)
Result< VehiclePhysicsStatus > submit3D(VehicleEntity &vehicle, physics::Body3D &body, std::shared_ptr< VehicleWheelRuntime > &runtime, const SimulationStep &step)
Result< VehiclePhysicsStatus > submit2D(VehicleEntity &vehicle, physics::Body &body, std::shared_ptr< VehicleWheelRuntime > &runtime, const SimulationStep &step)
驾驶者接口与玩家控制状态。
VehiclePhysicsStatus
Outcome of an optional physics attach, detach, or mobility step.
@ Pending
Forces submitted; the world has not completed their step.
@ Unavailable
No physics module or no attached body.
@ Applied
Physics handled the request.
@ Cancelled
Restore or destruction cancelled a pending step.
@ Rejected
Compatibility projection of a structured failure; do not fall back to kinematic motion.
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
std::vector< SuspensionWheel > wheels
载具模板(registerVehiclesFromJson 注册,进程级注册表)。