载入中...
搜索中...
未找到
Rope.cpp
浏览该文件的文档.
1#include "physics/rope/Rope.h"
2
3#include "common/Exception.h"
4#include "common/Json.h"
10
11#include <simplesquirrel/simplesquirrel.hpp>
12
13#include <cstdint>
14#include <functional>
15#include <memory>
16#include <optional>
17#include <utility>
18
19namespace eve::physics {
20namespace {
21
22constexpr auto kRopeCreateSchemaId = "physics:rope3d-create";
23
25 std::optional<double> minimum = {}, std::optional<double> maximum = {},
26 std::string defaultJson = {}) {
28 field.name = std::move(name);
29 field.type = type;
30 field.required = required;
31 field.minimum = minimum;
32 field.maximum = maximum;
33 field.defaultJson = std::move(defaultJson);
34 return field;
35}
36
37eve::schema::SchemaDefinition ropeCreateSchema() {
40 schema.id = kRopeCreateSchemaId;
41 schema.version = 1;
42 schema.title = "3D Rope Creation Parameters";
43 schema.description = "Validated construction and initial solver settings for Rope3D.";
44 schema.additionalProperties = false;
45 schema.fields = {
46 ropeField("particleCount", ValueType::Integer, true, 2, 100000),
47 ropeField("startX", ValueType::Number, true),
48 ropeField("startY", ValueType::Number, true),
49 ropeField("startZ", ValueType::Number, true),
50 ropeField("endX", ValueType::Number, true),
51 ropeField("endY", ValueType::Number, true),
52 ropeField("endZ", ValueType::Number, true),
53 ropeField("gravityX", ValueType::Number, false, {}, {}, "0"),
54 ropeField("gravityY", ValueType::Number, false, {}, {}, "-9.81"),
55 ropeField("gravityZ", ValueType::Number, false, {}, {}, "0"),
56 ropeField("stretchCompliance", ValueType::Number, false, 0, {}, "0"),
57 ropeField("distanceConstraintsEnabled", ValueType::Boolean, false, {}, {}, "true"),
58 ropeField("bendCompliance", ValueType::Number, false, 0, {}, "0.002"),
59 ropeField("bendConstraintsEnabled", ValueType::Boolean, false, {}, {}, "true"),
60 ropeField("maxBending", ValueType::Number, false, 0, 0.5, "0.025"),
61 ropeField("plasticYield", ValueType::Number, false, 0, 0.5, "0"),
62 ropeField("plasticCreep", ValueType::Number, false, 0, {}, "0"),
63 ropeField("maxCompression", ValueType::Number, false, 0, 1, "0"),
64 ropeField("damping", ValueType::Number, false, 0, 1, "0.01"),
65 ropeField("particleMass", ValueType::Number, false, 0.000001, {}, "0.1"),
66 ropeField("radius", ValueType::Number, false, 0.000001, {}, "0.04"),
67 ropeField("collisionFriction", ValueType::Number, false, 0, 1, "0"),
68 ropeField("collisionRestitution", ValueType::Number, false, 0, 1, "0"),
69 ropeField("continuousCollision", ValueType::Boolean, false, {}, {}, "true"),
70 ropeField("selfCollision", ValueType::Boolean, false, {}, {}, "true"),
71 ropeField("pinStart", ValueType::Boolean, false, {}, {}, "false"),
72 ropeField("pinEnd", ValueType::Boolean, false, {}, {}, "false"),
73 ropeField("tearingEnabled", ValueType::Boolean, false, {}, {}, "false"),
74 ropeField("tearResistance", ValueType::Number, false, 0.000001, {}, "1000"),
75 ropeField("maxTearsPerStep", ValueType::Integer, false, 1, 1000, "1"),
76 };
77 return schema;
78}
79
80eve::Result<void> ensureRopeCreateSchema() {
81 if (eve::schema::SchemaRegistry::resolve(kRopeCreateSchemaId, 1)) return eve::Result<void>::success();
82 auto registration = eve::schema::SchemaRegistry::registerVersioned(ropeCreateSchema());
83 if (!registration.ok()) return eve::Result<void>::failure(registration.status());
85}
86
87bool ropeChangeOrThrow(eve::Result<RopeTopologyChange> result, const char* operation) {
88 if (result.ok()) return result.value() == RopeTopologyChange::Changed;
89 const auto* diagnostic = result.status().primaryDiagnostic();
90 throw Exception("Rope3D.%s: %s", operation, diagnostic ? diagnostic->message().c_str() : "operation failed");
91}
92
93bool ropeColliderChangeOrThrow(eve::Result<RopeColliderChange> result, const char* operation) {
94 if (result.ok()) return result.value() == RopeColliderChange::Changed;
95 const auto* diagnostic = result.status().primaryDiagnostic();
96 throw Exception("Rope3D.%s: %s", operation, diagnostic ? diagnostic->message().c_str() : "operation failed");
97}
98
99std::int64_t ropeColliderIdOrThrow(eve::Result<RopeColliderId> result, const char* operation) {
100 if (result.ok()) return static_cast<std::int64_t>(result.value().value);
101 const auto* diagnostic = result.status().primaryDiagnostic();
102 throw Exception("Rope3D.%s: %s", operation, diagnostic ? diagnostic->message().c_str() : "operation failed");
103}
104
105} // namespace
106
108
109Rope3D* Rope::newRope3D(int count, float sx, float sy, float sz, float ex, float ey, float ez) {
110 return new Rope3D(count, sx, sy, sz, ex, ey, ez);
111}
112
113eve::Result<void> Rope::registerRope3DCreateSchema() { return ensureRopeCreateSchema(); }
114
116 auto registered = registerRope3DCreateSchema();
117 if (!registered.ok()) return eve::Result<Rope3D*>::failure(registered.status());
118 const auto errors = eve::schema::SchemaRegistry::validate(kRopeCreateSchemaId, 1, json);
119 if (!errors.empty())
121 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, errors.front().message, errors.front().path,
122 eve::DiagnosticDetails{{"schemaId", kRopeCreateSchemaId}, {"schemaVersion", "1"}},
123 "physics.rope3d.create-schema"));
124 std::string parseError;
125 auto document = eve::json::Document::parse(json, &parseError);
126 if (!document.valid())
129 eve::DiagnosticDetails{{"schemaId", kRopeCreateSchemaId}, {"schemaVersion", "1"}},
130 "physics.rope3d.create-schema"));
131 const auto root = document.root();
132 try {
133 auto rope = std::make_unique<Rope3D>(root.getInt("particleCount"), root.getFloat("startX"),
134 root.getFloat("startY"), root.getFloat("startZ"), root.getFloat("endX"),
135 root.getFloat("endY"), root.getFloat("endZ"));
136 rope->setGravity(root.getFloat("gravityX", 0.f), root.getFloat("gravityY", -9.81f),
137 root.getFloat("gravityZ", 0.f));
138 rope->setStretchCompliance(root.getFloat("stretchCompliance", 0.f));
139 rope->setDistanceConstraintsEnabled(root.getBool("distanceConstraintsEnabled", true));
140 rope->setBendCompliance(root.getFloat("bendCompliance", 0.002f));
141 rope->setBendConstraintsEnabled(root.getBool("bendConstraintsEnabled", true));
142 rope->setMaxBending(root.getFloat("maxBending", 0.025f));
143 rope->setPlasticity(root.getFloat("plasticYield", 0.f), root.getFloat("plasticCreep", 0.f));
144 rope->setMaxCompression(root.getFloat("maxCompression", 0.f));
145 rope->setDamping(root.getFloat("damping", 0.01f));
146 rope->setParticleMass(root.getFloat("particleMass", 0.1f));
147 rope->setRadius(root.getFloat("radius", 0.04f));
148 rope->setCollisionFriction(root.getFloat("collisionFriction", 0.f));
149 rope->setCollisionRestitution(root.getFloat("collisionRestitution", 0.f));
150 rope->setContinuousCollision(root.getBool("continuousCollision", true));
151 rope->setSelfCollision(root.getBool("selfCollision", true));
152 if (root.getBool("pinStart", false)) {
153 auto pinned = rope->pin(0);
154 if (!pinned.ok()) return eve::Result<Rope3D*>::failure(pinned.status());
155 }
156 if (root.getBool("pinEnd", false)) {
157 auto pinned = rope->pin(rope->getParticleCount() - 1);
158 if (!pinned.ok()) return eve::Result<Rope3D*>::failure(pinned.status());
159 }
160 if (root.getBool("tearingEnabled", false))
161 rope->setTearing(root.getFloat("tearResistance", 1000.f), root.getInt("maxTearsPerStep", 1));
163 } catch (const std::exception& exception) {
166 eve::DiagnosticDetails{{"schemaId", kRopeCreateSchemaId}, {"schemaVersion", "1"}},
167 "physics.rope3d.create-schema"));
168 }
169}
170
171Rope3D* Rope::newRope3DFromJsonScript(const std::string& json) {
172 auto created = newRope3DFromJson(json);
173 if (created.ok()) return created.value();
174 const auto* diagnostic = created.status().primaryDiagnostic();
175 throw Exception("Rope.newRope3DFromJson: %s", diagnostic ? diagnostic->message().c_str() : "creation failed");
176}
177
178void Rope::expose(ssq::Table& table) {
179 auto cls = table.addClass(name, Rope::create, false);
180 expose(cls);
181 auto rope = table.addClass<Rope3D>("Rope3D", std::function<Rope3D*()>([]() -> Rope3D* { return nullptr; }), true);
182 rope.addFunc("captureBake",
183 [vm = table.getHandle()](Rope3D* self, const ssq::Object& recordingObject, float seconds) {
184 return eve::physics::bake_detail::appendCapturedDeform(vm, *self, recordingObject, seconds);
185 });
186 rope.addFunc("update", &Rope3D::update);
187 rope.addFunc("setGravity", &Rope3D::setGravity);
188 rope.addFunc("getGravityX", &Rope3D::getGravityX);
189 rope.addFunc("getGravityY", &Rope3D::getGravityY);
190 rope.addFunc("getGravityZ", &Rope3D::getGravityZ);
191 rope.addFunc("setStretchCompliance", &Rope3D::setStretchCompliance);
192 rope.addFunc("setDistanceConstraintsEnabled", &Rope3D::setDistanceConstraintsEnabled);
193 rope.addFunc("getDistanceConstraintsEnabled", [](Rope3D* self) { return self->getDistanceConstraintsEnabled(); });
194 rope.addFunc("setBendCompliance", &Rope3D::setBendCompliance);
195 rope.addFunc("setBendConstraintsEnabled", &Rope3D::setBendConstraintsEnabled);
196 rope.addFunc("getBendConstraintsEnabled", [](Rope3D* self) { return self->getBendConstraintsEnabled(); });
197 rope.addFunc("setMaxBending", &Rope3D::setMaxBending);
198 rope.addFunc("getMaxBending", [](Rope3D* self) { return self->getMaxBending(); });
199 rope.addFunc("setPlasticity", &Rope3D::setPlasticity);
200 rope.addFunc("getPlasticYield", [](Rope3D* self) { return self->getPlasticYield(); });
201 rope.addFunc("getPlasticCreep", [](Rope3D* self) { return self->getPlasticCreep(); });
202 rope.addFunc("getBendPlasticity", &Rope3D::getBendPlasticity);
203 rope.addFunc("setMaxCompression", &Rope3D::setMaxCompression);
204 rope.addFunc("setDamping", &Rope3D::setDamping);
205 rope.addFunc("getDamping", &Rope3D::getDamping);
206 rope.addFunc("setParticleMass", &Rope3D::setParticleMass);
207 rope.addFunc("getParticleMass", &Rope3D::getParticleMass);
208 rope.addFunc("setRadius", &Rope3D::setRadius);
209 rope.addFunc("getRadius", &Rope3D::getRadius);
210 rope.addFunc("setCollisionFriction", &Rope3D::setCollisionFriction);
211 rope.addFunc("getCollisionFriction", [](Rope3D* self) { return self->getCollisionFriction(); });
212 rope.addFunc("setCollisionRestitution", &Rope3D::setCollisionRestitution);
213 rope.addFunc("getCollisionRestitution", [](Rope3D* self) { return self->getCollisionRestitution(); });
214 rope.addFunc("setContinuousCollision", &Rope3D::setContinuousCollision);
215 rope.addFunc("getContinuousCollision", [](Rope3D* self) { return self->getContinuousCollision(); });
216 rope.addFunc("setCollideWorld", &Rope3D::setCollideWorld);
217 rope.addFunc("getCollideWorld", [](Rope3D* self) { return self->getCollideWorld(); });
218 rope.addFunc("setCollideSdf", &Rope3D::setCollideSdf);
219 rope.addFunc("getCollideSdf", [](Rope3D* self) { return self->getCollideSdf(); });
220 rope.addFunc("clearColliders", &Rope3D::clearColliders);
221 rope.addFunc("setSelfCollision", &Rope3D::setSelfCollision);
222 rope.addFunc("getSelfCollision", &Rope3D::getSelfCollision);
223 rope.addFunc("setBounds", &Rope3D::setBounds);
224 rope.addFunc("clearBounds", &Rope3D::clearBounds);
225 rope.addFunc("isAttached", &Rope3D::isAttached);
226 rope.addFunc("applyForce", &Rope3D::applyForce);
227 rope.addFunc("getRestLength", &Rope3D::getRestLength);
228 rope.addFunc("calculateLength", &Rope3D::calculateLength);
229 rope.addFunc("isElementActive", &Rope3D::isElementActive);
230 rope.addFunc("getElementForce", &Rope3D::getElementForce);
231 rope.addFunc("getTopologyRevision", [](Rope3D* self) { return self->getTopologyRevision(); });
232 rope.addFunc("getLastTornElementCount", [](Rope3D* self) { return self->getLastTornElementCount(); });
233 rope.addFunc("getLastTornElement", &Rope3D::getLastTornElement);
234 rope.addFunc("setTearing", &Rope3D::setTearing);
235 rope.addFunc("disableTearing", &Rope3D::disableTearing);
236 rope.addFunc("getParticleCount", &Rope3D::getParticleCount);
237 rope.addFunc("getParticleX", &Rope3D::getParticleX);
238 rope.addFunc("getParticleY", &Rope3D::getParticleY);
239 rope.addFunc("getParticleZ", &Rope3D::getParticleZ);
240 rope.addFunc("getSampleX", &Rope3D::getSampleX);
241 rope.addFunc("getSampleY", &Rope3D::getSampleY);
242 rope.addFunc("getSampleZ", &Rope3D::getSampleZ);
243 rope.addFunc("getSampleTangentX", &Rope3D::getSampleTangentX);
244 rope.addFunc("getSampleTangentY", &Rope3D::getSampleTangentY);
245 rope.addFunc("getSampleTangentZ", &Rope3D::getSampleTangentZ);
246 rope.addFunc("addSphereCollider", [](Rope3D* self, float x, float y, float z, float radius) {
247 return ropeColliderIdOrThrow(self->addSphereCollider(x, y, z, radius), "addSphereCollider");
248 });
249 rope.addFunc("addPlaneCollider", [](Rope3D* self, float x, float y, float z, float nx, float ny, float nz) {
250 return ropeColliderIdOrThrow(self->addPlaneCollider(x, y, z, nx, ny, nz), "addPlaneCollider");
251 });
252 rope.addFunc("moveSphereCollider", [](Rope3D* self, std::int64_t id, float x, float y, float z) {
253 return ropeColliderChangeOrThrow(
254 self->moveSphereCollider(RopeColliderId{static_cast<std::uint64_t>(id)}, x, y, z), "moveSphereCollider");
255 });
256 rope.addFunc("removeCollider", [](Rope3D* self, std::int64_t id) {
257 return ropeColliderChangeOrThrow(self->removeCollider(RopeColliderId{static_cast<std::uint64_t>(id)}),
258 "removeCollider");
259 });
260 rope.addFunc("pin", [](Rope3D* self, int index) { return ropeChangeOrThrow(self->pin(index), "pin"); });
261 rope.addFunc("attach", [](Rope3D* self, int index, float x, float y, float z) {
262 return ropeChangeOrThrow(self->attach(index, x, y, z), "attach");
263 });
264 rope.addFunc("moveAttachment", [](Rope3D* self, int index, float x, float y, float z) {
265 return ropeChangeOrThrow(self->moveAttachment(index, x, y, z), "moveAttachment");
266 });
267 rope.addFunc("detach", [](Rope3D* self, int index) { return ropeChangeOrThrow(self->detach(index), "detach"); });
268 rope.addFunc("cut", [](Rope3D* self, int index) { return ropeChangeOrThrow(self->cut(index), "cut"); });
269 rope.addFunc("repair", [](Rope3D* self, int index) { return ropeChangeOrThrow(self->repair(index), "repair"); });
270 rope.addFunc("setRestLength", [](Rope3D* self, float length) {
271 return ropeChangeOrThrow(self->setRestLength(length), "setRestLength");
272 });
273 rope.addFunc("changeLength", [](Rope3D* self, float length, float spacing, bool fromEnd) {
274 return ropeChangeOrThrow(self->changeLength(length, spacing, fromEnd), "changeLength");
275 });
276}
277
278void Rope::expose(ssq::Class& cls) {
279 cls.addFunc("getName", &Rope::getName);
280 cls.addFunc("newRope3D", [vm = cls.getHandle()](Rope* self, int count, float sx, float sy, float sz, float ex,
281 float ey, float ez) {
282 auto owned = script::makeOwnedSquirrelInstance(
283 vm, std::unique_ptr<Rope3D>(self->newRope3D(count, sx, sy, sz, ex, ey, ez)));
284 if (!owned) throw Exception("Rope.newRope3D: failed to publish owned script instance");
285 return std::move(owned).takeValue();
286 });
287 cls.addFunc("newRope3DFromJson", [vm = cls.getHandle()](Rope* self, const std::string& json) {
288 auto owned =
289 script::makeOwnedSquirrelInstance(vm, std::unique_ptr<Rope3D>(self->newRope3DFromJsonScript(json)));
290 if (!owned) throw Exception("Rope.newRope3DFromJson: failed to publish owned script instance");
291 return std::move(owned).takeValue();
292 });
293}
294
295} // namespace eve::physics
double z
double y
double x
ActionParameterOperation operation
int root
Definition AnimSmr.cpp:119
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
float maximum[3]
float minimum[3]
eve::ResourcePin pinned
float length
bool required
Poco::JSON::Object::Ptr result
double radius
Definition MeleeHit.cpp:42
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
int created
int count
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
int spacing
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
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
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
Type type() const noexcept
Return the active value kind.
Definition Value.h:94
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
Renderer-independent particle rope with XPBD stretch and bend constraints.
Definition Rope3D.h:38
Optional physics satellite that owns rope construction, schema, and script bindings.
Definition Rope.h:15
eve::Result< void > registerRope3DCreateSchema()
Registers physics:rope3d-create@1 for tools and editors.
Definition Rope.cpp:113
Rope3D * newRope3D(int particleCount, float startX, float startY, float startZ, float endX, float endY, float endZ)
Creates a straight renderer-independent rope.
Definition Rope.cpp:109
eve::Result< Rope3D * > newRope3DFromJson(const std::string &json)
Validates a versioned creation document and transfers the new rope to the caller.
Definition Rope.cpp:115
static eve::Result< SchemaRegistrationStatus > registerVersioned(const SchemaDefinition &definition)
Registers a new exact (id, version) entry without replacing it.
static std::vector< ValidationError > validate(const std::string &schemaId, const std::string &json)
Validates JSON text against the highest registered schema version.
static const SchemaDefinition * resolve(const std::string &schemaId, int schemaVersion)
Resolves one exact (schemaId, schemaVersion) pair, or nullptr.
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...
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
ValueType
JSON-compatible value kinds understood by a schema field.
Definition SchemaTypes.h:16
std::vector< DiagnosticDetail > DiagnosticDetails
Owning collection of diagnostic details with stable insertion order.
Definition Diagnostic.h:88
Metadata and validation constraints for one object member.
Definition SchemaTypes.h:77
Versioned runtime schema for a JSON object.
Definition SchemaTypes.h:93
std::vector< FieldDefinition > fields
Definition SchemaTypes.h:99