载入中...
搜索中...
未找到
VehicleTires2D.cpp
浏览该文件的文档.
1// eve-hot-path
2#include <Box2D/Box2D.h>
3#include <algorithm>
4#include <cmath>
5#include <optional>
6#include "physics/Body.h"
7#include "physics/World.h"
11
12namespace eve::vehicle {
13namespace tire_detail {
14namespace {
15Result<VehiclePhysicsStatus> reject(std::string message) {
18}
19bool positive(double x) { return std::isfinite(x) && x > 0; }
20bool nonnegative(double x) { return std::isfinite(x) && x >= 0; }
21} // namespace
23 std::shared_ptr<VehicleWheelRuntime>& runtime, const SimulationStep& step) {
24 using namespace physics;
25 auto pending = submissionState(runtime, step);
27 const auto* definition = vehicle.definition()->def;
28 auto* world = body.getWorld();
29 if (!definition || !world || !body.isValid()) return reject("Vehicle definition or planar body is unavailable");
30 const auto& config = definition->suspension;
31 const double dt = step.delta.seconds(), meter = world->getMeter(), mass = body.getMass();
32 const auto input = *vehicle.input();
33 if (!positive(dt) || dt > .05 || !positive(meter) || !positive(mass) || !nonnegative(definition->maxSpeed) ||
34 !nonnegative(definition->accel) || !nonnegative(config.supportAcceleration2D) ||
35 !nonnegative(config.driveForce) || !nonnegative(config.brakeTorque) || !nonnegative(config.maxSteerAngle) ||
36 config.maxSteerAngle > 1.4 || !std::isfinite(input.throttle) || !std::isfinite(input.steer) ||
37 !std::isfinite(input.brake))
38 return reject("Invalid vehicle tire input, units or fixed duration");
39 auto wheels = config.wheels;
40 if (wheels.empty()) {
41 if (!positive(definition->radius)) return reject("Default wheel layout requires a positive chassis radius");
42 SuspensionWheel front, rear;
43 front.x = static_cast<float>(definition->radius / meter * .7);
44 rear.x = -front.x;
45 front.radius = rear.radius = static_cast<float>(std::clamp(definition->radius / meter * .5, .05, .5));
46 rear.steer = false;
47 wheels = {front, rear};
48 }
49 std::vector<VehicleEntity::SuspensionState::WheelState> candidate(wheels.size());
50 const auto& previous = vehicle.suspension()->wheels;
51 if (previous.size() == wheels.size()) candidate = previous;
52 const double wheelCount = static_cast<double>(wheels.size());
53 std::vector<ForceLoad> loads;
54 loads.reserve(wheels.size());
55 auto link = PhysicsLink::fromBody(body);
56 if (!link) return Result<VehiclePhysicsStatus>::failure(link.status());
57 auto* raw = body.raw();
58 const auto localCenter = raw->GetLocalCenter();
59 const double inertia = raw->GetInertia() - mass * b2Dot(localCenter, localCenter);
60 const double inverseInertia = raw->IsFixedRotation() ? 0 : (inertia > 0 ? 1 / inertia : 0);
61 const auto center = raw->GetWorldCenter();
62 const std::size_t driven =
63 std::count_if(wheels.begin(), wheels.end(), [](const auto& wheel) { return wheel.drive; });
64 for (std::size_t i = 0; i < wheels.size(); ++i) {
65 const auto& wheel = wheels[i];
66 if (!std::isfinite(wheel.x) || !std::isfinite(wheel.y) || wheel.z != 0 || !positive(wheel.radius))
67 return reject("2D tire mounts require finite XY meters, zero Z and positive radius");
68 const auto point = raw->GetWorldPoint({wheel.x, wheel.y});
69 const double steer = wheel.steer ? std::clamp(double(input.steer), -1.0, 1.0) * config.maxSteerAngle : 0;
70 const auto forward = raw->GetWorldVector({float(std::cos(steer)), float(std::sin(steer))});
71 const b2Vec2 lateral{-forward.y, forward.x};
72 const auto velocity = raw->GetLinearVelocityFromWorldPoint(point);
73 const auto lever = point - center;
74 const double a = b2Cross(lever, forward), b = b2Cross(lever, lateral);
75 const double crossMass = std::abs(a * b * inverseInertia);
76 auto tireModel = model(config, wheel.radius);
77 TireInput sampleInput;
78 sampleInput.longitudinalVelocity = b2Dot(velocity, forward);
79 sampleInput.lateralVelocity = b2Dot(velocity, lateral);
80 sampleInput.angularVelocity = candidate[i].angularVelocity;
81 sampleInput.normalLoad = mass * config.supportAcceleration2D / wheelCount;
82 driveInputs(sampleInput, config, input, wheel, driven, definition->maxSpeed / meter,
83 std::min(double(config.driveForce), mass * definition->accel / meter));
84 // A diagonal majorant bounds cross-axis and all-wheel chassis response (Cauchy-Schwarz).
85 // It adds implicit damping, rather than pretending off-center contacts have diagonal inverse mass.
86 sampleInput.longitudinalInverseMass = wheelCount * (1 / mass + a * a * inverseInertia + crossMass);
87 sampleInput.lateralInverseMass = wheelCount * (1 / mass + b * b * inverseInertia + crossMass);
88 auto sampled = ForceModels::tire(tireModel, sampleInput, dt);
89 if (!sampled) return Result<VehiclePhysicsStatus>::failure(sampled.status());
90 const auto& value = sampled.value();
91 auto& state = candidate[i];
92 state.angularVelocity = value.angularVelocity;
93 state.longitudinalForce = value.longitudinalForce;
94 state.lateralForce = value.lateralForce;
95 state.slipRatio = value.slipRatio;
96 state.slipAngle = value.slipAngle;
97 state.normalLoad = sampleInput.normalLoad;
98 state.grounded = sampleInput.normalLoad > 0;
99 const ForceVector force{forward.x * value.longitudinalForce + lateral.x * value.lateralForce,
100 forward.y * value.longitudinalForce + lateral.y * value.lateralForce, 0};
101 loads.push_back({link.value(), force, {point.x, point.y, 0}, {}});
102 }
103 auto batch = ForceBatch::prepare(*world, loads);
104 if (!batch) return Result<VehiclePhysicsStatus>::failure(batch.status());
105 return commit(*world, batch.value(), runtime, std::move(candidate), step);
106}
107} // namespace tire_detail
108} // namespace eve::vehicle
double x
double lateral
std::vector< QuestEvent > pending
b3Matrix3 inverseInertia
double raw
EvpackChunkInput input
Definition Evpack.cpp:170
ForceVector force
float inertia
std::string message
PhysicsJointLink link
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
glm::dvec2 center
glm::dvec3 velocity
double dt
std::shared_ptr< const OceanSprayFrame > previous
std::string body
Object::Ptr value
glm::mat4 model
float step
Definition TreeMesh.cpp:451
V forward
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
载具实体:数据全部在组件里,行为在 VehicleSystem。
Result< VehiclePhysicsStatus > submissionState(const std::shared_ptr< VehicleWheelRuntime > &runtime, const SimulationStep &step)
Result< VehiclePhysicsStatus > commit(physics::World &world, physics::ForceBatch &batch, std::shared_ptr< VehicleWheelRuntime > &runtime, std::vector< VehicleEntity::SuspensionState::WheelState > candidate, const SimulationStep &step)
void driveInputs(physics::TireInput &target, const SuspensionConfig &config, const VehicleEntity::Input &input, const SuspensionWheel &wheel, std::size_t driven, double maximumSpeed, double traction)
Result< VehiclePhysicsStatus > submit2D(VehicleEntity &vehicle, physics::Body &body, std::shared_ptr< VehicleWheelRuntime > &runtime, const SimulationStep &step)
驾驶者接口与玩家控制状态。
@ Unavailable
No physics module or no attached body.
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Wheel mount for 3D ray suspension or 2D top-down tire contact.
float x
Local mount in meters: 3D uses +Y up; top-down 2D uses XY with z = 0.