载入中...
搜索中...
未找到
Coupling3DSnapshot.cpp
浏览该文件的文档.
1#include <cmath>
2#include <map>
6
7namespace eve::physics {
8namespace {
9using namespace snapshot_detail;
10Result<void> invalidCoupling(const char* message) {
12}
13Result<double> number(const Value::Object& object, const char* name) {
14 const auto* value = field(object, name);
15 if (!value || !value->isNumeric())
17 Diagnostic::error(DiagnosticCode::ParseError, "Transmission field must be numeric", name));
18 const double n = value->isDouble() ? value->asDouble() : value->asInt();
19 if (!std::isfinite(n))
21 Diagnostic::error(DiagnosticCode::InvalidArgument, "Transmission field must be finite", name));
23}
24Value point(CouplingPoint3D p) { return Value(Value::Array{Value(p.x), Value(p.y), Value(p.z)}); }
25Result<CouplingPoint3D> readPoint(const Value::Object& o, const char* name) {
26 auto a = readFloatArray(o, name);
27 if (!a) return Result<CouplingPoint3D>::failure(a.status());
28 if (a.value().size() != 3)
30 Diagnostic::error(DiagnosticCode::ParseError, "Transmission point needs three components", name));
31 return Result<CouplingPoint3D>::success({a.value()[0], a.value()[1], a.value()[2]});
32}
33} // namespace
35 Value::Array records;
36 for (auto [id, coupling] : world.couplings3D_) {
37 const auto& d = *coupling->data_;
38 auto row = d.row();
39 if (!row) return Result<Value>::failure(row.status());
40 const auto& limits = d.limits();
41 Value::Object object{{"id", Value(std::to_string(id))},
42 {"kind", Value(d.gear ? "gear" : "pulley")},
43 {"enabled", Value(d.enabled)},
44 {"impulse", Value(d.lastImpulse)},
45 {"saturated", Value(d.saturated)},
46 {"limits", Value(Value::Array{Value(limits.positionCorrection),
47 Value(limits.maxCorrectionSpeed), Value(limits.maxForce)})}};
48 if (d.gear) {
49 for (int i = 0; i < 2; ++i) {
50 auto* source = world.findJoint(d.sources[i]);
51 if (!source)
53 Diagnostic::error(DiagnosticCode::StaleHandle, "Missing gear source"));
54 object.emplace(i == 0 ? "sourceA" : "sourceB", Value(std::to_string(source->getId())));
55 }
56 object.emplace("ratio", Value(d.gearSettings.ratio));
57 object.emplace("reference", Value(d.reference));
58 object.emplace("coordinateA", Value(row.value().coordinate[0]));
59 object.emplace("coordinateB", Value(row.value().coordinate[1]));
60 } else {
61 for (int i = 0; i < 2; ++i) {
62 auto* body = world.findBody(d.bodies[i]);
63 if (!body)
65 Diagnostic::error(DiagnosticCode::StaleHandle, "Missing pulley body"));
66 object.emplace(i == 0 ? "sourceA" : "sourceB", Value(std::to_string(body->getId())));
67 }
68 const auto& p = d.pulleySettings;
69 object.emplace("ratio", Value(p.ratio));
70 object.emplace("length", Value(p.length));
71 object.emplace("tensionOnly", Value(p.tensionOnly));
72 object.emplace("localAnchorA", point(p.localAnchorA));
73 object.emplace("localAnchorB", point(p.localAnchorB));
74 object.emplace("groundA", point(p.groundA));
75 object.emplace("groundB", point(p.groundB));
76 }
77 records.emplace_back(std::move(object));
78 }
79 return Result<Value>::success(Value(std::move(records)));
80}
82 using namespace snapshot_detail;
83 try {
84 std::map<int, const Value::Object*> ordered;
85 for (const auto& value : values) {
86 const auto* o = value.getIf<Value::Object>();
87 if (!o) return invalidCoupling("Transmission must be an object");
88 auto id = readInt64(*o, "id");
89 if (!id) return Result<void>::failure(id.status());
90 if (id.value() <= 0 || id.value() >= std::numeric_limits<int>::max() ||
91 !ordered.emplace(static_cast<int>(id.value()), o).second)
92 return invalidCoupling("Invalid or duplicate transmission id");
93 }
94 std::map<int, Joint3D*> joints;
95 for (auto* joint : world.joints_) joints.emplace(joint->getId(), joint);
96 for (auto [id, o] : ordered) {
97 auto kind = readString(*o, "kind");
98 if (!kind) return Result<void>::failure(kind.status());
99 const bool gear = kind.value() == "gear";
100 if (!gear && kind.value() != "pulley") return invalidCoupling("Unknown transmission kind");
101 if (!(gear ? hasExactFields(*o, {"id", "kind", "enabled", "impulse", "saturated", "limits", "sourceA",
102 "sourceB", "ratio", "reference", "coordinateA", "coordinateB"})
103 : hasExactFields(*o, {"id", "kind", "enabled", "impulse", "saturated", "limits", "sourceA",
104 "sourceB", "ratio", "length", "tensionOnly", "localAnchorA",
105 "localAnchorB", "groundA", "groundB"})))
106 return invalidCoupling("Unknown or missing transmission fields");
107 auto sourceA = readInt64(*o, "sourceA");
108 if (!sourceA) return Result<void>::failure(sourceA.status());
109 auto sourceB = readInt64(*o, "sourceB");
110 if (!sourceB) return Result<void>::failure(sourceB.status());
111 if (sourceA.value() <= 0 || sourceA.value() >= std::numeric_limits<int>::max() || sourceB.value() <= 0 ||
112 sourceB.value() >= std::numeric_limits<int>::max())
113 return invalidCoupling("Source id out of range");
114 auto enabled = readBool(*o, "enabled");
115 if (!enabled) return Result<void>::failure(enabled.status());
116 auto saturated = readBool(*o, "saturated");
117 if (!saturated) return Result<void>::failure(saturated.status());
118 auto impulse = number(*o, "impulse");
119 if (!impulse) return Result<void>::failure(impulse.status());
120 auto ratio = readFloat(*o, "ratio");
121 if (!ratio) return Result<void>::failure(ratio.status());
122 auto limits = readFloatArray(*o, "limits");
123 if (!limits) return Result<void>::failure(limits.status());
124 if (limits.value().size() != 3) return invalidCoupling("Transmission limits need three values");
125 CouplingLimits3D policy{limits.value()[0], limits.value()[1], limits.value()[2]};
126 world.nextCoupling3DId_ = id;
127 std::unique_ptr<Coupling3D> owned;
128 if (gear) {
129 auto reference = number(*o, "reference");
130 if (!reference) return Result<void>::failure(reference.status());
131 auto a = number(*o, "coordinateA");
132 if (!a) return Result<void>::failure(a.status());
133 auto b = number(*o, "coordinateB");
134 if (!b) return Result<void>::failure(b.status());
135 auto first = joints.find(static_cast<int>(sourceA.value())),
136 second = joints.find(static_cast<int>(sourceB.value()));
137 if (first == joints.end() || second == joints.end()) return invalidCoupling("Missing gear source");
138 auto created = Coupling3D::createGear(world, *first->second, *second->second, {ratio.value(), policy});
139 if (!created) return Result<void>::failure(created.status());
140 owned = std::move(created).takeValue();
141 owned->data_->reference = reference.value();
142 owned->data_->coordinate = {a.value(), b.value()};
143 } else {
144 auto length = readFloat(*o, "length");
145 if (!length) return Result<void>::failure(length.status());
146 auto tension = readBool(*o, "tensionOnly");
147 if (!tension) return Result<void>::failure(tension.status());
148 auto la = readPoint(*o, "localAnchorA");
149 if (!la) return Result<void>::failure(la.status());
150 auto lb = readPoint(*o, "localAnchorB");
151 if (!lb) return Result<void>::failure(lb.status());
152 auto ga = readPoint(*o, "groundA");
153 if (!ga) return Result<void>::failure(ga.status());
154 auto gb = readPoint(*o, "groundB");
155 if (!gb) return Result<void>::failure(gb.status());
156 auto* first = world.findBodyById(static_cast<int>(sourceA.value()));
157 auto* second = world.findBodyById(static_cast<int>(sourceB.value()));
158 if (!first || !second) return invalidCoupling("Missing pulley body");
160 {la.value(), lb.value(), ga.value(), gb.value(), ratio.value(),
161 length.value(), tension.value(), policy});
162 if (!created) return Result<void>::failure(created.status());
163 owned = std::move(created).takeValue();
164 }
165 owned->data_->enabled = enabled.value();
166 owned->data_->lastImpulse = impulse.value();
167 owned->data_->saturated = saturated.value();
168 auto row = owned->data_->row();
169 if (!row) return Result<void>::failure(row.status());
170 world.restoredCouplings3D_.push_back(std::move(owned));
171 }
172 return Result<void>::success();
173 } catch (const std::exception& e) {
175 DiagnosticCode::Failed, std::string("Transmission preparation failed: ") + e.what(), "payload.couplings"));
176 }
177}
178} // namespace eve::physics
ActiveSource owned
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
glm::vec4 p[6]
std::string name
Definition ECS.cpp:154
std::string message
wgpu::PopErrorScopeStatus status
glm::vec3 n
Definition Grass.cpp:63
std::int32_t second
std::int32_t first
float ratio
float length
bool ordered
std::string id
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::set< std::string > values
std::string body
Object::Ptr value
float d
std::vector< Gear > gear
double number
int created
std::string_view source
std::string kind
const AssetImportLimits & limits
std::array< double, 3 > impulse
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 success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
static Result< std::unique_ptr< Coupling3D > > createGear(World3D &world, Joint3D &first, Joint3D &second, const GearCoupling3DSettings &settings)
Couple two live same-world revolute/prismatic joints with finite nonzero signed ratio.
static Result< std::unique_ptr< Coupling3D > > createPulley(World3D &world, Body3D &a, Body3D &b, const PulleyCoupling3DSettings &settings)
Connect distinct same-world bodies to fixed guides with positive lengths and ratio.
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Result< float > readFloat(const Value::Object &object, std::string_view name)
Reads a required finite number representable by float.
const Value * field(const Value::Object &object, std::string_view name)
Borrow an optional field only during the current synchronous codec call. @ownership Object owns the r...
bool hasExactFields(const Value::Object &object, std::initializer_list< std::string_view > expected)
Internal exact-field schema predicate.
Result< std::int64_t > readInt64(const Value::Object &object, std::string_view name)
Reads a required signed decimal integer string.
Result< bool > readBool(const Value::Object &object, std::string_view name)
Reads a required boolean.
eve::Result< std::vector< float > > readFloatArray(const eve::Value::Object &object, std::string_view name)
Read a finite float array, rejecting missing or malformed elements.
Result< std::string > readString(const Value::Object &object, std::string_view name)
Reads a required owning string.
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
bool enabled
Stabilization and force limits for an ideal mechanical transmission.
Definition Coupling3D.h:16
static Result< void > restoreCouplings3D(World3D &world, const Value::Array &values)
Rebuild transmissions after candidate handles and native joints are ready.
static Result< Value > captureCouplings3D(const World3D &world)
Capture transmissions with stable source ids and current unwrapped phase.