载入中...
搜索中...
未找到
Coupling3DStep.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cmath>
3#include <numbers>
4#include <unordered_map>
5#include <vector>
6#include "physics/Body3D.h"
7#include "physics/World3D.h"
10
11namespace eve::physics {
12namespace {
13Result<void> rejected(const char* message) {
15 Diagnostic::error(DiagnosticCode::InvalidArgument, message, "physics.coupling3d.step"));
16}
17struct PhaseGuard {
18 bool& active;
19 explicit PhaseGuard(bool& value) : active(value) { active = true; }
20 ~PhaseGuard() { active = false; }
21};
22struct Velocity {
23 b3BodyId body;
25 b3Matrix3 inverseInertia;
27 bool dynamic, awake, changed = false;
28};
29bool same(b3Vec3 a, b3Vec3 b) { return a.x == b.x && a.y == b.y && a.z == b.z; }
30struct VelocityTransaction {
31 std::vector<Velocity> values;
32 bool applied = false, committed = false;
33 void apply() {
34 applied = true;
35 for (auto& v : values)
36 if (v.dynamic && (!same(v.linear, v.originalLinear) || !same(v.angular, v.originalAngular))) {
37 v.changed = true;
38 b3Body_SetAwake(v.body, true);
39 b3Body_SetLinearVelocity(v.body, v.linear);
40 b3Body_SetAngularVelocity(v.body, v.angular);
41 }
42 }
43 ~VelocityTransaction() {
44 if (!applied || committed) return;
45 for (const auto& v : values)
46 if (v.changed && b3Body_IsValid(v.body)) {
47 b3Body_SetLinearVelocity(v.body, v.originalLinear);
48 b3Body_SetAngularVelocity(v.body, v.originalAngular);
49 b3Body_SetAwake(v.body, v.awake);
50 }
51 }
52};
53} // namespace
54Result<void> World3D::stepCoupledBackend(const SimulationStep& step, const SimulationSettings& settings) {
55 PhaseGuard phase(couplingStepActive_);
56 const double dt = step.delta.seconds();
57 if (couplings3D_.empty() || dt == 0) return simulation_->step(step, settings);
58 struct Prepared {
59 Coupling3D* owner;
60 coupling_detail::Row row;
61 std::array<std::size_t, 4> index{};
62 double response = 0, impulse = 0, maximum = 0, bias = 0;
63 bool tensionOnly = false;
64 };
65 std::vector<Prepared> rows;
66 VelocityTransaction transaction;
67 std::unordered_map<PhysicsBodyHandle, std::size_t> indices;
68 rows.reserve(couplings3D_.size());
69 for (auto [id, coupling] : couplings3D_) {
70 auto& data = *coupling->data_;
71 auto result = data.row();
72 if (!result) return Result<void>::failure(result.status());
73 Prepared p;
74 p.owner = coupling;
75 p.row = std::move(result).takeValue();
76 p.maximum = data.limits().maxForce * dt;
77 p.tensionOnly = !data.gear && data.pulleySettings.tensionOnly;
78 const double gain = p.tensionOnly && p.row.error < 0 ? 1.0 : data.limits().positionCorrection;
79 p.bias = std::clamp(gain * p.row.error / dt, -static_cast<double>(data.limits().maxCorrectionSpeed),
80 static_cast<double>(data.limits().maxCorrectionSpeed));
81 for (int i = 0; i < p.row.count; ++i) {
82 const auto& term = p.row.terms[i];
83 auto found = indices.find(term.body);
84 if (found == indices.end()) {
85 auto* body = findBody(term.body);
86 if (!body || !body->isValid()) return rejected("Coupling body became stale during preparation");
88 const auto linear = b3Body_GetLinearVelocity(raw), angular = b3Body_GetAngularVelocity(raw);
89 const auto inertia = b3Body_GetWorldInverseRotationalInertia(raw);
90 const float mass = b3Body_GetInverseMass(raw);
91 if (!b3IsValidVec3(linear) || !b3IsValidVec3(angular) || !std::isfinite(mass) || mass < 0 ||
92 !b3IsValidVec3(inertia.cx) || !b3IsValidVec3(inertia.cy) || !b3IsValidVec3(inertia.cz))
93 return rejected("Non-finite coupling body state");
94 const auto index = transaction.values.size();
95 transaction.values.push_back({raw, linear, angular, linear, angular, inertia, mass,
96 b3Body_GetType(raw) == b3_dynamicBody, b3Body_IsAwake(raw)});
97 found = indices.emplace(term.body, index).first;
98 }
99 p.index[i] = found->second;
100 const auto& v = transaction.values[found->second];
101 if (v.dynamic)
102 p.response += v.inverseMass * b3Dot(term.linear, term.linear) +
103 b3Dot(term.angular, b3MulMV(v.inverseInertia, term.angular));
104 }
105 if (p.row.active && (!std::isfinite(p.response) || p.response <= 0))
106 return rejected("Coupling has no finite movable degree of freedom");
107 rows.push_back(std::move(p));
108 }
109 // Project all transmissions together. Shared endpoints accumulate one Jacobian before effective-mass evaluation.
110 for (int iteration = 0; iteration < settings.velocityIterations; ++iteration)
111 for (auto& p : rows) {
112 if (!p.row.active) continue;
113 double speed = 0;
114 for (int i = 0; i < p.row.count; ++i) {
115 const auto& v = transaction.values[p.index[i]];
116 const auto& t = p.row.terms[i];
117 speed += b3Dot(t.linear, v.linear) + b3Dot(t.angular, v.angular);
118 }
119 const double next =
120 std::clamp(p.impulse - (speed + p.bias) / p.response, -p.maximum, p.tensionOnly ? 0.0 : p.maximum);
121 const float impulse = static_cast<float>(next - p.impulse);
122 if (!std::isfinite(impulse)) return rejected("Coupling impulse overflow");
123 p.impulse = next;
124 for (int i = 0; i < p.row.count; ++i) {
125 auto& v = transaction.values[p.index[i]];
126 const auto& t = p.row.terms[i];
127 if (!v.dynamic) continue;
128 v.linear = b3Add(v.linear, b3MulSV(impulse * v.inverseMass, t.linear));
129 v.angular = b3Add(v.angular, b3MulMV(v.inverseInertia, b3MulSV(impulse, t.angular)));
130 if (!b3IsValidVec3(v.linear) || !b3IsValidVec3(v.angular))
131 return rejected("Coupling velocity overflow");
132 }
133 }
134 for (const auto& p : rows) {
135 const auto& d = *p.owner->data_;
136 if (!d.gear) continue;
137 for (int i = 0; i < 2; ++i)
138 if (d.revolute[i]) {
139 const auto& a = transaction.values[indices.at(d.bodies[2 * i])];
140 const auto& b = transaction.values[indices.at(d.bodies[2 * i + 1])];
141 if (b3Length(b3Sub(b.angular, a.angular)) * dt >= std::numbers::pi)
142 return rejected("Revolute coupling requires less than pi radians of relative rotation per step");
143 }
144 }
145 transaction.apply();
146 auto result = simulation_->step(step, settings);
147 if (!result) return result;
148 transaction.committed = true;
149 for (const auto& p : rows) {
150 auto& d = *p.owner->data_;
151 d.previous = p.row.wrapped;
152 d.coordinate = p.row.coordinate;
153 d.lastImpulse = p.impulse;
154 d.saturated = p.row.active && std::abs(p.impulse) >= p.maximum;
155 }
156 return result;
157}
158} // namespace eve::physics
bool & active
bool changed
bool committed
b3Matrix3 inverseInertia
b3Vec3 originalLinear
bool awake
b3Vec3 angular
bool dynamic
b3Vec3 originalAngular
bool applied
float inverseMass
glm::vec4 p[6]
double raw
int rows
float inertia
float linear
std::string message
float maximum[3]
std::vector< std::uint32_t > indices
float v
std::string response
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanWakeSettings settings
std::shared_ptr< OceanGpuSpectrum > owner
double dt
std::set< std::string > values
std::string body
Object::Ptr value
float d
float t
bool found
float bias
Definition Shadow.cpp:149
float phase
float step
Definition TreeMesh.cpp:451
uint32_t index
std::array< double, 3 > impulse
double gain
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Body3D * findBody(PhysicsBodyHandle handle) const
Borrows a live body; null for stale/foreign handles. Never delete lookup results.
Definition World3D.cpp:431
Result< T > rejected(RuleId rule, std::string message, eve::DiagnosticCode code=eve::DiagnosticCode::PreconditionViolation)
Construct a Rejected result for invalid editing input or preconditions.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
eve::SimulationStep SimulationStep
Compatibility alias for the common injected simulation step.
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
Definition Widget.cpp:870
static b3BodyId bodyId(const Body3D &body)
Borrows the native identifier synchronously; facade must belong to a Box3D world.