载入中...
搜索中...
未找到
Cloth3D.cpp
浏览该文件的文档.
2#include <glm/mat4x4.hpp>
5
6#include "common/Exception.h"
7#include "graphics/Canvas.h"
8#include "graphics/Graphics.h"
9#include "graphics/Mesh.h"
10#include "physics/Body3D.h"
11#include "physics/World3D.h"
12
13#include <algorithm>
14#include <array>
15#include <cmath>
16#include <exception>
17#include <limits>
18#include <utility>
19
20namespace eve::physics {
21
22// Color lives in eve::graphics (see graphics/Canvas.h); keep the unqualified form.
25
26namespace {
27constexpr float kPi = 3.14159265358979323846f;
28
29int64_t pairKey(int lo, int hi) { return (int64_t(lo) << 32) | int64_t(hi); }
30
31// Minimal 3D vector helpers for the triangle-level self-collision pass.
32struct V3 {
33 float x = 0.f, y = 0.f, z = 0.f;
34};
35
36V3 sub(const V3& a, const V3& b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
37V3 add(const V3& a, const V3& b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
38V3 mul(float s, const V3& a) { return {s * a.x, s * a.y, s * a.z}; }
39V3 fma(const V3& a, float s, const V3& b) { return {a.x * s + b.x, a.y * s + b.y, a.z * s + b.z}; }
40float dot(const V3& a, const V3& b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
41V3 cross(const V3& a, const V3& b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
42float vlen(const V3& a) { return std::sqrt(dot(a, a)); }
43V3 vnorm(const V3& a) {
44 const float l = vlen(a);
45 return l > 1e-8f ? mul(1.f / l, a) : V3{0.f, 1.f, 0.f};
46}
47
48// Rotate vector v around the given unit axis by angle (right-hand rule).
49V3 rotateAround(const V3& v, const V3& axis, float angle) {
50 const float c = std::cos(angle);
51 const float sn = std::sin(angle);
52 const V3 cv = cross(axis, v);
53 const float d = dot(axis, v);
54 return add(add(mul(c, v), mul(sn, cv)), mul(d * (1.f - c), axis));
55}
56
57// Signed angle from a to b around the unit axis u (positive = CCW along +u).
58float signedAngle(const V3& a, const V3& b, const V3& u) { return std::atan2(dot(cross(a, b), u), dot(a, b)); }
59
60// Closest point on segment [a,b] to point p (Ericson, RTCD ch. 5).
61V3 closestPointSegment(const V3& a, const V3& b, const V3& p) {
62 const V3 ab = sub(b, a);
63 const float len2 = dot(ab, ab);
64 if (len2 < 1e-12f) return a;
65 const float t = std::clamp(dot(sub(p, a), ab) / len2, 0.f, 1.f);
66 return fma(ab, t, a);
67}
68
69// Closest point on triangle (a,b,c) to point p (Ericson, RTCD ch. 5).
70V3 closestPointTriangle(const V3& a, const V3& b, const V3& c, const V3& p) {
71 const V3 ab = sub(b, a);
72 const V3 ac = sub(c, a);
73 const V3 ap = sub(p, a);
74 const float d1 = dot(ab, ap);
75 const float d2 = dot(ac, ap);
76 if (d1 <= 0.f && d2 <= 0.f) return a;
77
78 const V3 bp = sub(p, b);
79 const float d3 = dot(ab, bp);
80 const float d4 = dot(ac, bp);
81 if (d3 >= 0.f && d4 <= d3) return b;
82
83 const float vc = d1 * d4 - d3 * d2;
84 if (vc <= 0.f && d1 >= 0.f && d3 <= 0.f) {
85 const float t = d1 / (d1 - d3);
86 return fma(ab, t, a);
87 }
88
89 const V3 cp = sub(p, c);
90 const float d5 = dot(ab, cp);
91 const float d6 = dot(ac, cp);
92 if (d6 >= 0.f && d5 <= d6) return c;
93
94 const float vb = d5 * d2 - d1 * d6;
95 if (vb <= 0.f && d2 >= 0.f && d6 <= 0.f) {
96 const float t = d2 / (d2 - d6);
97 return fma(ac, t, a);
98 }
99
100 const float va = d3 * d6 - d5 * d4;
101 if (va <= 0.f && (d4 - d3) >= 0.f && (d5 - d6) >= 0.f) {
102 const float t = (d4 - d3) / ((d4 - d3) + (d5 - d6));
103 return fma(sub(c, b), t, b);
104 }
105
106 const float denom = 1.f / (va + vb + vc);
107 const float v = vb * denom;
108 const float w = vc * denom;
109 return add(fma(ab, v, a), mul(w, ac));
110}
111
112// Closest points between segments (p1,p2) and (q1,q2); returns distance.
113float closestPointSegments(const V3& p1, const V3& p2, const V3& q1, const V3& q2, V3& cp1, V3& cp2) {
114 const V3 d1 = sub(p2, p1);
115 const V3 d2 = sub(q2, q1);
116 const V3 r = sub(p1, q1);
117 const float a = dot(d1, d1);
118 const float e = dot(d2, d2);
119 const float f = dot(d2, r);
120 float s = 0.f;
121 float t = 0.f;
122 if (a <= 1e-12f && e <= 1e-12f) {
123 s = t = 0.f;
124 } else if (a <= 1e-12f) {
125 s = 0.f;
126 t = std::clamp(f / e, 0.f, 1.f);
127 } else {
128 const float c = dot(d1, r);
129 if (e <= 1e-12f) {
130 t = 0.f;
131 s = std::clamp(-c / a, 0.f, 1.f);
132 } else {
133 const float b = dot(d1, d2);
134 const float denom = a * e - b * b;
135 s = denom > 1e-12f ? std::clamp((b * f - c * e) / denom, 0.f, 1.f) : 0.f;
136 t = (b * s + f) / e;
137 if (t < 0.f) {
138 t = 0.f;
139 s = std::clamp(-c / a, 0.f, 1.f);
140 } else if (t > 1.f) {
141 t = 1.f;
142 s = std::clamp((b - c) / a, 0.f, 1.f);
143 }
144 }
145 }
146 cp1 = fma(d1, s, p1);
147 cp2 = fma(d2, t, q1);
148 return vlen(sub(cp1, cp2));
149}
150
151bool pointInTriangle(const V3& p, const V3& a, const V3& b, const V3& c) {
152 const V3 n = cross(sub(b, a), sub(c, a));
153 const V3 pa = cross(sub(b, a), sub(p, a));
154 const V3 pb = cross(sub(c, b), sub(p, b));
155 const V3 pc = cross(sub(a, c), sub(p, c));
156 return dot(pa, n) >= -1e-8f && dot(pb, n) >= -1e-8f && dot(pc, n) >= -1e-8f;
157}
158
159// Closest distance between two triangles plus the indices of the vertices
160// forming the closest feature on each side (1, 2 or 3 vertices).
161float triangleDistance(const V3* A, const V3* B, int featA[3], int featB[3], int& countA, int& countB, V3& cpA,
162 V3& cpB) {
163 float best = std::numeric_limits<float>::max();
164 countA = countB = 0;
165 for (int i = 0; i < 3; ++i) {
166 const V3 cp = closestPointTriangle(B[0], B[1], B[2], A[i]);
167 const float d = vlen(sub(A[i], cp));
168 if (d < best) {
169 best = d;
170 cpA = A[i];
171 cpB = cp;
172 featA[0] = i;
173 featB[0] = 0;
174 featB[1] = 1;
175 featB[2] = 2;
176 countA = 1;
177 countB = 3;
178 }
179 }
180 for (int j = 0; j < 3; ++j) {
181 const V3 cp = closestPointTriangle(A[0], A[1], A[2], B[j]);
182 const float d = vlen(sub(B[j], cp));
183 if (d < best) {
184 best = d;
185 cpA = cp;
186 cpB = B[j];
187 featA[0] = 0;
188 featA[1] = 1;
189 featA[2] = 2;
190 featB[0] = j;
191 countA = 3;
192 countB = 1;
193 }
194 }
195 const int aEdges[3][2] = {{0, 1}, {1, 2}, {2, 0}};
196 const int bEdges[3][2] = {{0, 1}, {1, 2}, {2, 0}};
197 for (const auto& ea : aEdges) {
198 for (const auto& eb : bEdges) {
199 V3 cp1;
200 V3 cp2;
201 const float d = closestPointSegments(A[ea[0]], A[ea[1]], B[eb[0]], B[eb[1]], cp1, cp2);
202 if (d < best) {
203 best = d;
204 cpA = cp1;
205 cpB = cp2;
206 featA[0] = ea[0];
207 featA[1] = ea[1];
208 featB[0] = eb[0];
209 featB[1] = eb[1];
210 countA = 2;
211 countB = 2;
212 }
213 }
214 }
215 return best;
216}
217} // namespace
218
219Cloth3D::Cloth3D(int cols, int rows, float spacing, float originX, float originY, float originZ)
220 : cols_(cols), rows_(rows), spacing_(spacing), originX_(originX), originY_(originY), originZ_(originZ) {
221 auto model = ClothModel::grid(cols, rows, spacing, originX, originY, originZ);
222 if (!model)
223 throw Exception("%s", model.error() ? model.error()->message().c_str() : "Cloth3D grid model creation failed");
224 initializeFromModel(model.value());
225}
226
227Cloth3D::Cloth3D(const ClothModel& model) { initializeFromModel(model); }
228
230
231void Cloth3D::destroy() { destroyed_ = true; }
232
234 particles_ = restParticles_;
235 grabIndex_ = -1;
236 forceX_ = forceY_ = forceZ_ = 0.f;
237 interactStrength_ = 0.f;
238}
239
240void Cloth3D::rebuildLinks() {
241 links_.clear();
242 auto add = [&](int a, int b) {
243 if (a < 0 || b < 0 || a >= getParticleCount() || b >= getParticleCount()) return;
244 Link link;
245 link.a = a;
246 link.b = b;
247 const Particle& pa = particles_[static_cast<size_t>(a)];
248 const Particle& pb = particles_[static_cast<size_t>(b)];
249 const float dx = pb.x - pa.x;
250 const float dy = pb.y - pa.y;
251 const float dz = pb.z - pa.z;
252 link.rest = std::sqrt(dx * dx + dy * dy + dz * dz);
253 if (link.rest > 1e-4f) links_.push_back(link);
254 };
255
256 for (int r = 0; r < rows_; ++r) {
257 for (int c = 0; c < cols_; ++c) {
258 const int i = r * cols_ + c;
259 // Structural
260 if (c + 1 < cols_) add(i, i + 1);
261 if (r + 1 < rows_) add(i, i + cols_);
262 // Shear
263 if (c + 1 < cols_ && r + 1 < rows_) add(i, i + cols_ + 1);
264 if (c > 0 && r + 1 < rows_) add(i, i + cols_ - 1);
265 // Bend (every other)
266 if (c + 2 < cols_) add(i, i + 2);
267 if (r + 2 < rows_) add(i, i + cols_ * 2);
268 }
269 }
270 buildLinkKeys();
271}
272
273void Cloth3D::buildLinkKeys() {
274 linkKeys_.clear();
275 for (const Link& link : links_) {
276 const int lo = std::min(link.a, link.b);
277 const int hi = std::max(link.a, link.b);
278 linkKeys_.insert(pairKey(lo, hi));
279 }
280}
281
282bool Cloth3D::areLinked(int a, int b) const {
283 if (a == b) return true;
284 const int lo = std::min(a, b);
285 const int hi = std::max(a, b);
286 return linkKeys_.find(pairKey(lo, hi)) != linkKeys_.end();
287}
288
289void Cloth3D::rebuildTriangles() {
290 triangles_.clear();
291 foldPairs_.clear();
292
293 // Two triangles per quad, wound so the +Y side is the front face.
294 std::unordered_map<int64_t, std::vector<int>> edgeTris;
295 auto addTri = [&](int a, int b, int c, std::unordered_map<int64_t, std::vector<int>>& map) {
296 Tri tri;
297 tri.v[0] = a;
298 tri.v[1] = b;
299 tri.v[2] = c;
300 const int idx = static_cast<int>(triangles_.size());
301 const int edges[3][2] = {{a, b}, {b, c}, {c, a}};
302 for (const auto& e : edges) {
303 map[pairKey(std::min(e[0], e[1]), std::max(e[0], e[1]))].push_back(idx);
304 }
305 triangles_.push_back(tri);
306 };
307
308 for (int r = 0; r + 1 < rows_; ++r) {
309 for (int c = 0; c + 1 < cols_; ++c) {
310 const int a = r * cols_ + c;
311 const int b = r * cols_ + c + 1;
312 const int cc = (r + 1) * cols_ + c + 1;
313 const int d = (r + 1) * cols_ + c;
314 addTri(a, d, b, edgeTris);
315 addTri(d, cc, b, edgeTris);
316 }
317 }
318
319 for (const auto& entry : edgeTris) {
320 if (entry.second.size() != 2) continue;
321 const Tri& t0 = triangles_[static_cast<size_t>(entry.second[0])];
322 const Tri& t1 = triangles_[static_cast<size_t>(entry.second[1])];
323 const int e0 = int(entry.first >> 32);
324 const int e1 = static_cast<int>(static_cast<uint32_t>(entry.first));
325 // Shared edge endpoints e0/e1; opposite vertices are the third of each tri.
326 int k = -1;
327 for (int v : t0.v) {
328 if (v != e0 && v != e1) {
329 k = v;
330 break;
331 }
332 }
333 int l = -1;
334 for (int v : t1.v) {
335 if (v != e0 && v != e1) {
336 l = v;
337 break;
338 }
339 }
340 if (k < 0 || l < 0) continue;
341 FoldPair pair;
342 pair.a = e0;
343 pair.b = e1;
344 pair.k = k;
345 pair.l = l;
346 foldPairs_.push_back(pair);
347 }
348}
349
350bool Cloth3D::validIndex(int index) const { return index >= 0 && index < getParticleCount(); }
351
352void Cloth3D::setGravity(float gx, float gy, float gz) {
353 gravityX_ = gx;
354 gravityY_ = gy;
355 gravityZ_ = gz;
356}
357
358void Cloth3D::setStiffness(float stiffness) { stiffness_ = std::clamp(stiffness, 0.f, 1.f); }
359
360void Cloth3D::setStretchCompliance(float compliance) {
361 stretchCompliance_ = std::isfinite(compliance) ? std::max(0.f, compliance) : 0.f;
362}
363
364void Cloth3D::setShearCompliance(float compliance) {
365 shearCompliance_ = std::isfinite(compliance) ? std::max(0.f, compliance) : 0.f;
366}
367
368void Cloth3D::setBendCompliance(float compliance) {
369 bendCompliance_ = std::isfinite(compliance) ? std::max(0.f, compliance) : 0.f;
370}
371
372void Cloth3D::setIterations(int iterations) { iterations_ = std::max(1, iterations); }
373
374void Cloth3D::setDamping(float damping) { damping_ = std::clamp(damping, 0.f, 1.f); }
375
376void Cloth3D::setParticleSize(float size) { particleSize_ = std::max(0.01f, size); }
377
378void Cloth3D::setParticleMass(float mass) { particleMass_ = std::max(1e-4f, mass); }
379
380void Cloth3D::initializeFromModel(const ClothModel& model) {
381 cols_ = model.gridCols();
382 rows_ = model.gridRows();
383 spacing_ = model.gridSpacing();
384 if (!model.particles().empty()) {
385 originX_ = model.particles().front().x;
386 originY_ = model.particles().front().y;
387 originZ_ = model.particles().front().z;
388 }
389 particles_.clear();
390 particles_.reserve(model.particles().size());
391 for (const ClothModelParticle& source : model.particles()) {
392 Particle particle;
393 particle.x = particle.px = source.x;
394 particle.y = particle.py = source.y;
395 particle.z = particle.pz = source.z;
396 particle.inverseMass = source.inverseMass;
397 particle.pinned = source.inverseMass == 0.f;
398 particles_.push_back(particle);
399 }
400 restParticles_ = particles_;
401
402 links_.clear();
403 links_.reserve(model.distanceConstraints().size());
404 for (const ClothModelDistanceConstraint& source : model.distanceConstraints())
405 links_.push_back({source.a, source.b, source.restLength, source.kind, 0.f});
406
407 triangles_.clear();
408 triangles_.reserve(model.triangles().size());
409 for (const ClothModelTriangle& source : model.triangles())
410 triangles_.push_back({{source.vertices[0], source.vertices[1], source.vertices[2]}});
411
412 foldPairs_.clear();
413 foldPairs_.reserve(model.foldConstraints().size());
414 for (const ClothModelFoldConstraint& source : model.foldConstraints())
415 foldPairs_.push_back({source.a, source.b, source.oppositeA, source.oppositeB});
416 tethers_.clear();
417 tethers_.reserve(model.tetherConstraints().size());
418 for (const ClothModelTetherConstraint& source : model.tetherConstraints())
419 tethers_.push_back({source.particle, source.anchor, source.maxLength, 0.f});
420 restVolume_ = model.restVolume();
421 buildLinkKeys();
422}
423
424void Cloth3D::setWindVelocity(float vx, float vy, float vz) {
425 windVelocityX_ = vx;
426 windVelocityY_ = vy;
427 windVelocityZ_ = vz;
428}
429
430float Cloth3D::getWindVelocityX() const { return windVelocityX_; }
431
432float Cloth3D::getWindVelocityY() const { return windVelocityY_; }
433
434float Cloth3D::getWindVelocityZ() const { return windVelocityZ_; }
435
436void Cloth3D::setAerodynamics(float airDensity, float dragCoefficient, float liftCoefficient) {
437 airDensity_ = std::max(0.f, airDensity);
438 dragCoefficient_ = std::max(0.f, dragCoefficient);
439 liftCoefficient_ = std::max(0.f, liftCoefficient);
440}
441
442float Cloth3D::getAirDensity() const { return airDensity_; }
443
444float Cloth3D::getDragCoefficient() const { return dragCoefficient_; }
445
446float Cloth3D::getLiftCoefficient() const { return liftCoefficient_; }
447
448void Cloth3D::setSelfCollision(bool on) { selfCollision_ = on; }
449
450void Cloth3D::setFoldStiffness(float k) { foldStiffness_ = std::clamp(k, 0.f, 1.f); }
451
452void Cloth3D::setMaxFoldAngle(float degrees) { maxFoldAngle_ = std::clamp(degrees, 0.f, 180.f) * kPi / 180.f; }
453
454void Cloth3D::setBounds(float x, float y, float z, float w, float h, float d) {
455 if (w <= 0.f || h <= 0.f || d <= 0.f) {
456 clearBounds();
457 return;
458 }
459 hasBounds_ = true;
460 boundX_ = x;
461 boundY_ = y;
462 boundZ_ = z;
463 boundW_ = w;
464 boundH_ = h;
465 boundD_ = d;
466}
467
468void Cloth3D::clearBounds() { hasBounds_ = false; }
469
471 collisionFriction_ = std::isfinite(friction) ? std::clamp(friction, 0.f, 1.f) : 0.f;
472 collisionRestitution_ = std::isfinite(restitution) ? std::clamp(restitution, 0.f, 1.f) : 0.f;
473}
474
475void Cloth3D::setCollisionFilter(uint64_t categoryBits, uint64_t maskBits) {
476 collisionCategoryBits_ = categoryBits;
477 collisionMaskBits_ = maskBits;
478}
479
481 if (!validIndex(index)) throw Exception("Cloth3D.pin: index out of range");
482 Particle& particle = particles_[static_cast<size_t>(index)];
483 particle.pinned = true;
484 particle.inverseMass = 0.f;
485}
486
488 if (!validIndex(index)) throw Exception("Cloth3D.unpin: index out of range");
489 Particle& particle = particles_[static_cast<size_t>(index)];
490 particle.pinned = false;
491 particle.inverseMass = 1.f;
492}
493
495 for (int c = 0; c < cols_; ++c) pin(c);
496}
497
498bool Cloth3D::isPinned(int index) const {
499 if (!validIndex(index)) return false;
500 return particles_[static_cast<size_t>(index)].pinned;
501}
502
504 if (!validIndex(index)) throw Exception("Cloth3D.setParticleInverseMass: index out of range");
505 Particle& particle = particles_[static_cast<size_t>(index)];
506 particle.inverseMass = std::isfinite(inverseMass) ? std::max(0.f, inverseMass) : 0.f;
507 particle.pinned = particle.inverseMass == 0.f;
508}
509
511 return validIndex(index) ? particles_[static_cast<size_t>(index)].inverseMass : 0.f;
512}
513
514int Cloth3D::grabAt(float x, float y, float z, float radius) {
515 grabIndex_ = -1;
516 float best = radius * radius;
517 for (int i = 0; i < getParticleCount(); ++i) {
518 const Particle& p = particles_[static_cast<size_t>(i)];
519 if (p.pinned) continue;
520 const float dx = p.x - x;
521 const float dy = p.y - y;
522 const float dz = p.z - z;
523 const float d2 = dx * dx + dy * dy + dz * dz;
524 if (d2 <= best) {
525 best = d2;
526 grabIndex_ = i;
527 }
528 }
529 if (grabIndex_ >= 0) moveGrab(x, y, z);
530 return grabIndex_;
531}
532
533void Cloth3D::moveGrab(float x, float y, float z) {
534 grabX_ = x;
535 grabY_ = y;
536 grabZ_ = z;
537 if (!validIndex(grabIndex_)) return;
538 Particle& p = particles_[static_cast<size_t>(grabIndex_)];
539 p.x = x;
540 p.y = y;
541 p.z = z;
542 p.px = x;
543 p.py = y;
544 p.pz = z;
545}
546
547void Cloth3D::releaseGrab() { grabIndex_ = -1; }
548
549void Cloth3D::applyForce(float fx, float fy, float fz) {
550 forceX_ += fx;
551 forceY_ += fy;
552 forceZ_ += fz;
553}
554
555void Cloth3D::interactAt(float x, float y, float z, float radius, float strength) {
556 interactX_ = x;
557 interactY_ = y;
558 interactZ_ = z;
559 interactRadius_ = std::max(0.f, radius);
560 interactStrength_ = strength;
561}
562
563void Cloth3D::setCollideWorld(World3D* world) { world_ = world; }
564
565void Cloth3D::setColor(float r, float g, float b, float a) {
566 colorR_ = r;
567 colorG_ = g;
568 colorB_ = b;
569 colorA_ = a;
570}
571
572float Cloth3D::getParticleX(int index) const {
573 if (!validIndex(index)) return 0.f;
574 return particles_[static_cast<size_t>(index)].x;
575}
576
577float Cloth3D::getParticleY(int index) const {
578 if (!validIndex(index)) return 0.f;
579 return particles_[static_cast<size_t>(index)].y;
580}
581
582float Cloth3D::getParticleZ(int index) const {
583 if (!validIndex(index)) return 0.f;
584 return particles_[static_cast<size_t>(index)].z;
585}
586
587void Cloth3D::setParticlePosition(int index, float x, float y, float z) {
588 if (!validIndex(index)) throw Exception("Cloth3D.setParticlePosition: index out of range");
589 Particle& p = particles_[static_cast<size_t>(index)];
590 p.x = p.px = x;
591 p.y = p.py = y;
592 p.z = p.pz = z;
593}
594
595int64_t Cloth3D::cellKey(int cx, int cy, int cz) const {
596 // 21 bits per axis keeps the packed key inside a signed 64-bit int.
597 return int64_t(uint32_t(cx) & 0x1fffffu) | (int64_t(uint32_t(cy) & 0x1fffffu) << 21) |
598 (int64_t(uint32_t(cz) & 0x1fffffu) << 42);
599}
600
601void Cloth3D::rebuildHash() {
602 hash_.clear();
603 const float cell = std::max(1e-3f, particleSize_ * 2.f);
604 const float inv = 1.f / cell;
605 for (int i = 0; i < getParticleCount(); ++i) {
606 const Particle& p = particles_[static_cast<size_t>(i)];
607 const int cx = int(std::floor(p.x * inv));
608 const int cy = int(std::floor(p.y * inv));
609 const int cz = int(std::floor(p.z * inv));
610 hash_[cellKey(cx, cy, cz)].push_back(i);
611 }
612}
613
614void Cloth3D::integrate(float dt) {
615 if (dt <= 0.f) return;
616 const float ax = gravityX_ + forceX_;
617 const float ay = gravityY_ + forceY_;
618 const float az = gravityZ_ + forceZ_;
619 const float damp = 1.f - damping_;
620 const bool hasInteract = interactRadius_ > 0.f && interactStrength_ != 0.f;
621
622 std::vector<float> aerodynamicAcceleration;
623 if (airDensity_ > 0.f && (dragCoefficient_ > 0.f || liftCoefficient_ > 0.f)) {
624 aerodynamicAcceleration.assign(particles_.size() * 3, 0.f);
625 accumulateAerodynamicAcceleration(dt, aerodynamicAcceleration);
626 }
627
628 for (size_t particleIndex = 0; particleIndex < particles_.size(); ++particleIndex) {
629 Particle& p = particles_[particleIndex];
630 if (p.pinned) {
631 p.px = p.x;
632 p.py = p.y;
633 p.pz = p.z;
634 continue;
635 }
636 const float vx = (p.x - p.px) * damp;
637 const float vy = (p.y - p.py) * damp;
638 const float vz = (p.z - p.pz) * damp;
639 p.px = p.x;
640 p.py = p.y;
641 p.pz = p.z;
642 const float aeroX = aerodynamicAcceleration.empty() ? 0.f : aerodynamicAcceleration[particleIndex * 3];
643 const float aeroY = aerodynamicAcceleration.empty() ? 0.f : aerodynamicAcceleration[particleIndex * 3 + 1];
644 const float aeroZ = aerodynamicAcceleration.empty() ? 0.f : aerodynamicAcceleration[particleIndex * 3 + 2];
645 p.x += vx + (ax + aeroX) * dt * dt;
646 p.y += vy + (ay + aeroY) * dt * dt;
647 p.z += vz + (az + aeroZ) * dt * dt;
648 if (hasInteract) {
649 const float dx = interactX_ - p.x;
650 const float dy = interactY_ - p.y;
651 const float dz = interactZ_ - p.z;
652 const float r2 = dx * dx + dy * dy + dz * dz;
653 const float R2 = interactRadius_ * interactRadius_;
654 if (r2 < R2 && r2 > 1e-6f) {
655 const float r = std::sqrt(r2);
656 const float w = 1.f - r / interactRadius_;
657 const float a = interactStrength_ * w * dt * dt;
658 p.x += (dx / r) * a;
659 p.y += (dy / r) * a;
660 p.z += (dz / r) * a;
661 }
662 }
663 constexpr float maxSpeed = 9.f; // m/s
664 const float maxDisp = maxSpeed * dt;
665 const float dvx = p.x - p.px;
666 const float dvy = p.y - p.py;
667 const float dvz = p.z - p.pz;
668 const float v2 = dvx * dvx + dvy * dvy + dvz * dvz;
669 if (v2 > maxDisp * maxDisp) {
670 const float s = maxDisp / std::sqrt(v2);
671 p.px = p.x - dvx * s;
672 p.py = p.y - dvy * s;
673 p.pz = p.z - dvz * s;
674 }
675 }
676}
677
678void Cloth3D::accumulateAerodynamicAcceleration(float dt, std::vector<float>& accelerations) const {
679 const float invDt = dt > 1e-6f ? 1.f / dt : 0.f;
680 const float invMass = 1.f / particleMass_;
681 for (const Tri& tri : triangles_) {
682 const Particle& a = particles_[static_cast<size_t>(tri.v[0])];
683 const Particle& b = particles_[static_cast<size_t>(tri.v[1])];
684 const Particle& c = particles_[static_cast<size_t>(tri.v[2])];
685
686 const V3 ab{b.x - a.x, b.y - a.y, b.z - a.z};
687 const V3 ac{c.x - a.x, c.y - a.y, c.z - a.z};
688 const V3 areaNormal = cross(ab, ac);
689 const float twiceArea = vlen(areaNormal);
690 if (twiceArea < 1e-8f) continue;
691 V3 normal = mul(1.f / twiceArea, areaNormal);
692
693 const V3 clothVelocity{((a.x - a.px) + (b.x - b.px) + (c.x - c.px)) * (invDt / 3.f),
694 ((a.y - a.py) + (b.y - b.py) + (c.y - c.py)) * (invDt / 3.f),
695 ((a.z - a.pz) + (b.z - b.pz) + (c.z - c.pz)) * (invDt / 3.f)};
696 const V3 relativeWind{windVelocityX_ - clothVelocity.x, windVelocityY_ - clothVelocity.y,
697 windVelocityZ_ - clothVelocity.z};
698 const float speed = vlen(relativeWind);
699 if (speed < 1e-5f) continue;
700 const V3 windDirection = mul(1.f / speed, relativeWind);
701 float incidence = dot(normal, windDirection);
702 if (incidence < 0.f) {
703 normal = mul(-1.f, normal);
704 incidence = -incidence;
705 }
706 if (incidence < 1e-5f) continue;
707
708 const float dynamicPressureArea = 0.5f * airDensity_ * speed * speed * (twiceArea * 0.5f);
709 const V3 drag = mul(dragCoefficient_ * incidence * dynamicPressureArea, windDirection);
710 V3 liftDirection = sub(normal, mul(incidence, windDirection));
711 const float liftLength = vlen(liftDirection);
712 if (liftLength > 1e-6f)
713 liftDirection = mul(1.f / liftLength, liftDirection);
714 else
715 liftDirection = V3{0.f, 0.f, 0.f};
716 const V3 lift = mul(liftCoefficient_ * incidence * dynamicPressureArea, liftDirection);
717 const V3 acceleration = mul(invMass / 3.f, add(drag, lift));
718
719 for (int vertex : tri.v) {
720 if (particles_[static_cast<size_t>(vertex)].pinned) continue;
721 accelerations[static_cast<size_t>(vertex) * 3] += acceleration.x;
722 accelerations[static_cast<size_t>(vertex) * 3 + 1] += acceleration.y;
723 accelerations[static_cast<size_t>(vertex) * 3 + 2] += acceleration.z;
724 }
725 }
726}
727
728void Cloth3D::solveConstraints(float dt) {
729 for (Link& link : links_) link.lambda = 0.f;
730 for (Tether& tether : tethers_) tether.lambda = 0.f;
731 for (SkinConstraint& skin : skinConstraints_) skin.lambda = 0.f;
732 for (Attachment& attachment : attachments_) attachment.lambda = 0.f;
733 volumeLambda_ = 0.f;
734 const float invDtSquared = dt > 1e-8f ? 1.f / (dt * dt) : 0.f;
735 for (int iter = 0; iter < iterations_; ++iter) {
736 for (Link& link : links_) {
737 Particle& a = particles_[static_cast<size_t>(link.a)];
738 Particle& b = particles_[static_cast<size_t>(link.b)];
739 if (a.pinned && b.pinned) continue;
740 float dx = b.x - a.x;
741 float dy = b.y - a.y;
742 float dz = b.z - a.z;
743 const float dist = std::sqrt(dx * dx + dy * dy + dz * dz);
744 if (dist < 1e-5f) continue;
745 float compliance = stretchCompliance_;
747 compliance = shearCompliance_;
748 else if (link.kind == ClothConstraintKind::Bend)
749 compliance = bendCompliance_;
750 if (compliance > 0.f) {
751 const float weightA = a.pinned ? 0.f : a.inverseMass;
752 const float weightB = b.pinned ? 0.f : b.inverseMass;
753 const float alpha = compliance * invDtSquared;
754 const float deltaLambda = (-(dist - link.rest) - alpha * link.lambda) / (weightA + weightB + alpha);
755 link.lambda += deltaLambda;
756 const float nx = dx / dist;
757 const float ny = dy / dist;
758 const float nz = dz / dist;
759 a.x -= weightA * nx * deltaLambda;
760 a.y -= weightA * ny * deltaLambda;
761 a.z -= weightA * nz * deltaLambda;
762 b.x += weightB * nx * deltaLambda;
763 b.y += weightB * ny * deltaLambda;
764 b.z += weightB * nz * deltaLambda;
765 continue;
766 }
767 const float diff = (dist - link.rest) / dist * stiffness_;
768 if (a.pinned) {
769 b.x -= dx * diff;
770 b.y -= dy * diff;
771 b.z -= dz * diff;
772 } else if (b.pinned) {
773 a.x += dx * diff;
774 a.y += dy * diff;
775 a.z += dz * diff;
776 } else {
777 const float half = diff * 0.5f;
778 a.x += dx * half;
779 a.y += dy * half;
780 a.z += dz * half;
781 b.x -= dx * half;
782 b.y -= dy * half;
783 b.z -= dz * half;
784 }
785 }
786 solveTetherConstraints(dt);
787 solveVolumeConstraint(dt);
788 solveSkinConstraints(dt);
789 solveAttachments(dt);
790 if (validIndex(grabIndex_)) {
791 Particle& g = particles_[static_cast<size_t>(grabIndex_)];
792 g.x = grabX_;
793 g.y = grabY_;
794 g.z = grabZ_;
795 g.px = grabX_;
796 g.py = grabY_;
797 g.pz = grabZ_;
798 }
799 }
800}
801
802void Cloth3D::solveFoldConstraint() {
803 if (foldStiffness_ <= 0.f || maxFoldAngle_ >= kPi || foldPairs_.empty()) return;
804 // Fold pairs share edge (a,b) with opposite vertices k (tri 1) and l (tri 2).
805 // For a flat sheet the in-plane directions m1,m2 point to opposite sides
806 // (theta = pi); folding brings them toward the same side (theta -> 0). When
807 // theta drops below pi - maxFoldAngle, rotate both triangles rigidly around
808 // the shared edge to reopen the fold to the limit.
809 const float thetaMin = kPi - maxFoldAngle_;
810 const float s = foldStiffness_;
811 for (const FoldPair& pair : foldPairs_) {
812 Particle& pa = particles_[static_cast<size_t>(pair.a)];
813 Particle& pb = particles_[static_cast<size_t>(pair.b)];
814 Particle& pk = particles_[static_cast<size_t>(pair.k)];
815 Particle& pl = particles_[static_cast<size_t>(pair.l)];
816 if (pa.pinned && pb.pinned && pk.pinned && pl.pinned) continue;
817
818 const V3 paV{pa.x, pa.y, pa.z};
819 const V3 pbV{pb.x, pb.y, pb.z};
820 V3 pkV{pk.x, pk.y, pk.z};
821 V3 plV{pl.x, pl.y, pl.z};
822
823 const V3 u = vnorm(sub(pbV, paV));
824 const V3 vk = sub(pkV, paV);
825 const V3 vl = sub(plV, paV);
826 const V3 h1 = sub(vk, mul(dot(vk, u), u));
827 const V3 h2 = sub(vl, mul(dot(vl, u), u));
828 const float b1 = vlen(h1);
829 const float b2 = vlen(h2);
830 if (b1 < 1e-6f || b2 < 1e-6f) continue;
831 const V3 m1 = mul(1.f / b1, h1);
832 const V3 m2 = mul(1.f / b2, h2);
833 const float theta = std::acos(std::clamp(dot(m1, m2), -1.f, 1.f));
834 if (theta >= thetaMin) continue;
835
836 // Reopen the fold along its own path: a pure fold moves m1/m2 from
837 // opposite (flat, theta = pi) toward the same side (theta -> 0) with a
838 // fixed rotation sign; rotate both triangles back by delta/2 each.
839 const float phi = signedAngle(m1, m2, u);
840 const float sign = phi >= 0.f ? 1.f : -1.f;
841 const float delta = thetaMin - theta;
842 const float a1 = -sign * delta * 0.5f * s;
843 const float a2 = sign * delta * 0.5f * s;
844 if (!pk.pinned) {
845 pkV = add(paV, rotateAround(vk, u, a1 * s));
846 pk.x = pkV.x;
847 pk.y = pkV.y;
848 pk.z = pkV.z;
849 }
850 if (!pl.pinned) {
851 plV = add(paV, rotateAround(vl, u, a2 * s));
852 pl.x = plV.x;
853 pl.y = plV.y;
854 pl.z = plV.z;
855 }
856 }
857}
858
859void Cloth3D::solveSelfCollision() {
860 if (!selfCollision_ || getParticleCount() == 0) return;
861 const float minDist = particleSize_ * 2.f;
862 if (minDist <= 0.f) return;
863 rebuildHash();
864 const float cell = std::max(1e-3f, minDist);
865 const float inv = 1.f / cell;
866 for (int i = 0; i < getParticleCount(); ++i) {
867 Particle& pi = particles_[static_cast<size_t>(i)];
868 const int cx = int(std::floor(pi.x * inv));
869 const int cy = int(std::floor(pi.y * inv));
870 const int cz = int(std::floor(pi.z * inv));
871 for (int oz = -1; oz <= 1; ++oz) {
872 for (int oy = -1; oy <= 1; ++oy) {
873 for (int ox = -1; ox <= 1; ++ox) {
874 auto it = hash_.find(cellKey(cx + ox, cy + oy, cz + oz));
875 if (it == hash_.end()) continue;
876 for (int j : it->second) {
877 if (j <= i) continue;
878 if (areLinked(i, j)) continue;
879 Particle& pj = particles_[static_cast<size_t>(j)];
880 float dx = pj.x - pi.x;
881 float dy = pj.y - pi.y;
882 float dz = pj.z - pi.z;
883 const float d2 = dx * dx + dy * dy + dz * dz;
884 if (d2 >= minDist * minDist || d2 < 1e-8f) continue;
885 if (pi.pinned && pj.pinned) continue;
886 const float d = std::sqrt(d2);
887 const float corr = std::min(0.5f, (minDist - d) / d);
888 float wa = 0.5f;
889 float wb = 0.5f;
890 if (pi.pinned && !pj.pinned) {
891 wa = 0.f;
892 wb = 1.f;
893 } else if (pj.pinned && !pi.pinned) {
894 wa = 1.f;
895 wb = 0.f;
896 }
897 pi.x -= dx * corr * wa;
898 pi.y -= dy * corr * wa;
899 pi.z -= dz * corr * wa;
900 pj.x += dx * corr * wb;
901 pj.y += dy * corr * wb;
902 pj.z += dz * corr * wb;
903 }
904 }
905 }
906 }
907 }
908}
909
910void Cloth3D::solveSelfCollisionTriangles() {
911 if (!selfCollision_ || triangles_.size() < 2) return;
912 const float thickness = std::max(1e-3f, particleSize_ * 2.f);
913 const int triCount = static_cast<int>(triangles_.size());
914
915 std::vector<V3> pos(particles_.size());
916 for (size_t i = 0; i < particles_.size(); ++i) {
917 pos[i] = {particles_[i].x, particles_[i].y, particles_[i].z};
918 }
919
920 const float cell = thickness;
921 const float inv = 1.f / cell;
922 std::unordered_map<int64_t, std::vector<int>> triHash;
923 auto triCellKey = [](int cx, int cy, int cz) -> int64_t {
924 return int64_t(uint32_t(cx) & 0x1fffffu) | (int64_t(uint32_t(cy) & 0x1fffffu) << 21) |
925 (int64_t(uint32_t(cz) & 0x1fffffu) << 42);
926 };
927 const auto insertTri = [&](int ti) {
928 const Tri& tri = triangles_[static_cast<size_t>(ti)];
929 V3 mn = pos[static_cast<size_t>(tri.v[0])];
930 V3 mx = mn;
931 for (int k = 1; k < 3; ++k) {
932 const V3& p = pos[static_cast<size_t>(tri.v[k])];
933 mn.x = std::min(mn.x, p.x);
934 mn.y = std::min(mn.y, p.y);
935 mn.z = std::min(mn.z, p.z);
936 mx.x = std::max(mx.x, p.x);
937 mx.y = std::max(mx.y, p.y);
938 mx.z = std::max(mx.z, p.z);
939 }
940 const V3 pad{thickness, thickness, thickness};
941 mn = sub(mn, pad);
942 mx = add(mx, pad);
943 const int x0 = int(std::floor(mn.x * inv));
944 const int y0 = int(std::floor(mn.y * inv));
945 const int z0 = int(std::floor(mn.z * inv));
946 const int x1 = int(std::floor(mx.x * inv));
947 const int y1 = int(std::floor(mx.y * inv));
948 const int z1 = int(std::floor(mx.z * inv));
949 for (int cz = z0; cz <= z1; ++cz)
950 for (int cy = y0; cy <= y1; ++cy)
951 for (int cx = x0; cx <= x1; ++cx) triHash[triCellKey(cx, cy, cz)].push_back(ti);
952 };
953 for (int ti = 0; ti < triCount; ++ti) insertTri(ti);
954
955 const auto sharesVertex = [&](const Tri& a, const Tri& b) {
956 for (int i = 0; i < 3; ++i)
957 for (int j = 0; j < 3; ++j)
958 if (a.v[i] == b.v[j]) return true;
959 return false;
960 };
961
962 std::unordered_set<int64_t> processed;
963 std::vector<int> cells;
964 int featA[3];
965 int featB[3];
966
967 for (int i = 0; i < triCount; ++i) {
968 const Tri& triI = triangles_[static_cast<size_t>(i)];
969 const V3& pa0 = pos[static_cast<size_t>(triI.v[0])];
970 V3 mn = pa0;
971 V3 mx = mn;
972 for (int k = 1; k < 3; ++k) {
973 const V3& p = pos[static_cast<size_t>(triI.v[k])];
974 mn.x = std::min(mn.x, p.x);
975 mn.y = std::min(mn.y, p.y);
976 mn.z = std::min(mn.z, p.z);
977 mx.x = std::max(mx.x, p.x);
978 mx.y = std::max(mx.y, p.y);
979 mx.z = std::max(mx.z, p.z);
980 }
981 const V3 pad{thickness, thickness, thickness};
982 mn = sub(mn, pad);
983 mx = add(mx, pad);
984 const int x0 = int(std::floor(mn.x * inv));
985 const int y0 = int(std::floor(mn.y * inv));
986 const int z0 = int(std::floor(mn.z * inv));
987 const int x1 = int(std::floor(mx.x * inv));
988 const int y1 = int(std::floor(mx.y * inv));
989 const int z1 = int(std::floor(mx.z * inv));
990 cells.clear();
991 for (int cz = z0; cz <= z1; ++cz)
992 for (int cy = y0; cy <= y1; ++cy)
993 for (int cx = x0; cx <= x1; ++cx) {
994 auto it = triHash.find(triCellKey(cx, cy, cz));
995 if (it != triHash.end()) cells.insert(cells.end(), it->second.begin(), it->second.end());
996 }
997 for (int j : cells) {
998 if (j <= i) continue;
999 const int64_t key = pairKey(i, j);
1000 if (!processed.insert(key).second) continue;
1001 const Tri& triJ = triangles_[static_cast<size_t>(j)];
1002 if (sharesVertex(triI, triJ)) continue;
1003
1004 const V3 A[3] = {pos[static_cast<size_t>(triI.v[0])], pos[static_cast<size_t>(triI.v[1])],
1005 pos[static_cast<size_t>(triI.v[2])]};
1006 const V3 B[3] = {pos[static_cast<size_t>(triJ.v[0])], pos[static_cast<size_t>(triJ.v[1])],
1007 pos[static_cast<size_t>(triJ.v[2])]};
1008 V3 cpA;
1009 V3 cpB;
1010 int countA = 0;
1011 int countB = 0;
1012 const float d = triangleDistance(A, B, featA, featB, countA, countB, cpA, cpB);
1013 if (d >= thickness) continue;
1014
1015 V3 n = vnorm(sub(cpB, cpA));
1016 if (vlen(sub(cpB, cpA)) < 1e-6f) {
1017 n = vnorm(cross(sub(B[1], B[0]), sub(B[2], B[0])));
1018 }
1019 const float corr = (thickness - d) * stiffness_;
1020 if (corr <= 0.f) continue;
1021
1022 const auto freeCount = [&](const int* feat, int count) {
1023 int free = 0;
1024 for (int k = 0; k < count; ++k)
1025 if (!particles_[static_cast<size_t>(feat[k])].pinned) ++free;
1026 return free;
1027 };
1028 const int freeA = freeCount(featA, countA);
1029 const int freeB = freeCount(featB, countB);
1030 if (freeA == 0 && freeB == 0) continue;
1031 const float wA = freeA > 0 ? (freeB > 0 ? 0.5f : 1.f) : 0.f;
1032 const float wB = freeB > 0 ? (freeA > 0 ? 0.5f : 1.f) : 0.f;
1033 const auto pushFeature = [&](const int* feat, int count, const V3& dir) {
1034 for (int k = 0; k < count; ++k) {
1035 Particle& pv = particles_[static_cast<size_t>(feat[k])];
1036 if (pv.pinned) continue;
1037 pv.x += dir.x;
1038 pv.y += dir.y;
1039 pv.z += dir.z;
1040 }
1041 };
1042 if (freeA > 0) {
1043 const V3 dir = mul(-corr * wA / float(freeA), n);
1044 pushFeature(featA, countA, dir);
1045 }
1046 if (freeB > 0) {
1047 const V3 dir = mul(corr * wB / float(freeB), n);
1048 pushFeature(featB, countB, dir);
1049 }
1050 }
1051 }
1052
1053 // Vertex-through-face: push any vertex that has crossed into the prism of a
1054 // non-adjacent triangle back out along the face normal.
1055 for (int i = 0; i < triCount; ++i) {
1056 const Tri& triI = triangles_[static_cast<size_t>(i)];
1057 const V3 A[3] = {pos[static_cast<size_t>(triI.v[0])], pos[static_cast<size_t>(triI.v[1])],
1058 pos[static_cast<size_t>(triI.v[2])]};
1059 const V3 nI = vnorm(cross(sub(A[1], A[0]), sub(A[2], A[0])));
1060 for (int j = i + 1; j < triCount; ++j) {
1061 const Tri& triJ = triangles_[static_cast<size_t>(j)];
1062 if (sharesVertex(triI, triJ)) continue;
1063 const V3 B[3] = {pos[static_cast<size_t>(triJ.v[0])], pos[static_cast<size_t>(triJ.v[1])],
1064 pos[static_cast<size_t>(triJ.v[2])]};
1065 const V3 nJ = vnorm(cross(sub(B[1], B[0]), sub(B[2], B[0])));
1066 // Vertices of tri i against the face of tri j.
1067 for (int k = 0; k < 3; ++k) {
1068 Particle& pv = particles_[static_cast<size_t>(triI.v[k])];
1069 if (pv.pinned) continue;
1070 const V3 va = A[k];
1071 const float d = dot(sub(va, B[0]), nJ);
1072 if (std::fabs(d) >= thickness) continue;
1073 const V3 q = add(va, mul(-d, nJ));
1074 if (!pointInTriangle(q, B[0], B[1], B[2])) continue;
1075 const float push = (thickness - std::fabs(d)) * stiffness_ * 0.5f;
1076 const V3 dir = mul(d >= 0.f ? push : -push, nJ);
1077 pv.x += dir.x;
1078 pv.y += dir.y;
1079 pv.z += dir.z;
1080 }
1081 // Vertices of tri j against the face of tri i.
1082 for (int k = 0; k < 3; ++k) {
1083 Particle& pv = particles_[static_cast<size_t>(triJ.v[k])];
1084 if (pv.pinned) continue;
1085 const V3 vb = B[k];
1086 const float d = dot(sub(vb, A[0]), nI);
1087 if (std::fabs(d) >= thickness) continue;
1088 const V3 q = add(vb, mul(-d, nI));
1089 if (!pointInTriangle(q, A[0], A[1], A[2])) continue;
1090 const float push = (thickness - std::fabs(d)) * stiffness_ * 0.5f;
1091 const V3 dir = mul(d >= 0.f ? push : -push, nI);
1092 pv.x += dir.x;
1093 pv.y += dir.y;
1094 pv.z += dir.z;
1095 }
1096 }
1097 }
1098}
1099
1100void Cloth3D::collideWorld(float dt) {
1101 if (!world_ || !world_->isValid() || particleSize_ <= 0.f) return;
1102 const float invDt = dt > 1e-6f ? 1.f / dt : 0.f;
1103 ClothContact3D contact;
1104 for (int i = 0; i < getParticleCount(); ++i) {
1105 Particle& p = particles_[static_cast<size_t>(i)];
1106 if (p.pinned) continue;
1107 if (world_->pointProbeFiltered(p.x, p.y, p.z, particleSize_, &contact, collisionCategoryBits_,
1108 collisionMaskBits_) != ClothProbeStatus::Hit ||
1109 !contact.hit)
1110 continue;
1111 const float vpx = (p.x - p.px) * invDt;
1112 const float vpy = (p.y - p.py) * invDt;
1113 const float vpz = (p.z - p.pz) * invDt;
1114 p.x += contact.nx * contact.depth;
1115 p.y += contact.ny * contact.depth;
1116 p.z += contact.nz * contact.depth;
1117
1118 float vbx = 0.f;
1119 float vby = 0.f;
1120 float vbz = 0.f;
1121 float bodyMass = 0.f;
1122 const bool dynamic = contact.body != nullptr && contact.body->getType() == "dynamic";
1123 if (dynamic) {
1124 vbx = contact.body->getLinearVelocityX();
1125 vby = contact.body->getLinearVelocityY();
1126 vbz = contact.body->getLinearVelocityZ();
1127 bodyMass = contact.body->getMass();
1128 }
1129 const float vn = (vpx - vbx) * contact.nx + (vpy - vby) * contact.ny + (vpz - vbz) * contact.nz;
1130 if (vn < 0.f) {
1131 const float restitution = std::max(collisionRestitution_, contact.restitution);
1132 const float friction = std::clamp(std::sqrt(collisionFriction_ * std::max(0.f, contact.friction)), 0.f, 1.f);
1133 const float relativeX = vpx - vbx;
1134 const float relativeY = vpy - vby;
1135 const float relativeZ = vpz - vbz;
1136 const float tangentX = relativeX - vn * contact.nx;
1137 const float tangentY = relativeY - vn * contact.ny;
1138 const float tangentZ = relativeZ - vn * contact.nz;
1139 const float nextNormal = -vn * restitution;
1140 const float nextVx = vbx + tangentX * (1.f - friction) + contact.nx * nextNormal;
1141 const float nextVy = vby + tangentY * (1.f - friction) + contact.ny * nextNormal;
1142 const float nextVz = vbz + tangentZ * (1.f - friction) + contact.nz * nextNormal;
1143 p.px = p.x - nextVx * dt;
1144 p.py = p.y - nextVy * dt;
1145 p.pz = p.z - nextVz * dt;
1146 const float m = particleMass_;
1147 const float reduced = bodyMass > 0.f ? (m * bodyMass) / (m + bodyMass) : m;
1148 float j = -(1.f + restitution) * vn * reduced;
1149 const float maxKick = 9.f; // m/s
1150 j = std::min(j, maxKick * m);
1151 const float kick = (j / m) * dt;
1152 p.x += contact.nx * kick;
1153 p.y += contact.ny * kick;
1154 p.z += contact.nz * kick;
1155 if (dynamic && bodyMass > 0.f) {
1156 contact.body->applyLinearImpulse(-contact.nx * j, -contact.ny * j, -contact.nz * j);
1157 }
1158 }
1159 }
1160}
1161
1162void Cloth3D::collideBounds() {
1163 if (!hasBounds_) return;
1164 const float minX = boundX_;
1165 const float minY = boundY_;
1166 const float minZ = boundZ_;
1167 const float maxX = boundX_ + boundW_;
1168 const float maxY = boundY_ + boundH_;
1169 const float maxZ = boundZ_ + boundD_;
1170 const float bounce = collisionRestitution_;
1171
1172 for (Particle& p : particles_) {
1173 if (p.pinned) continue;
1174 if (p.x < minX) {
1175 const float vx = p.x - p.px;
1176 p.x = minX;
1177 p.px = p.x + vx * bounce;
1178 } else if (p.x > maxX) {
1179 const float vx = p.x - p.px;
1180 p.x = maxX;
1181 p.px = p.x + vx * bounce;
1182 }
1183 if (p.y < minY) {
1184 const float vy = p.y - p.py;
1185 p.y = minY;
1186 p.py = p.y + vy * bounce;
1187 } else if (p.y > maxY) {
1188 const float vy = p.y - p.py;
1189 p.y = maxY;
1190 p.py = p.y + vy * bounce;
1191 }
1192 if (p.z < minZ) {
1193 const float vz = p.z - p.pz;
1194 p.z = minZ;
1195 p.pz = p.z + vz * bounce;
1196 } else if (p.z > maxZ) {
1197 const float vz = p.z - p.pz;
1198 p.z = maxZ;
1199 p.pz = p.z + vz * bounce;
1200 }
1201 }
1202}
1203
1204void Cloth3D::update(float dt) {
1205 if (destroyed_) return;
1206 if (dt < 0.f) dt = 0.f;
1207 if (dt > 0.05f) dt = 0.05f;
1208
1209 updateSubsteps(dt, 2);
1210}
1211
1212void Cloth3D::updateSubsteps(float dt, int substeps) {
1213 if (destroyed_ || substeps < 1) return;
1214
1215 const float h = dt / float(substeps);
1216 for (int s = 0; s < substeps; ++s) {
1217 integrate(h);
1218 applyAutomaticTearing();
1219 solveConstraints(h);
1220 solveFoldConstraint();
1221 solveSelfCollision();
1222 solveSelfCollisionTriangles();
1223 collideWorld(h);
1224 collideBounds();
1225 if (grabIndex_ >= 0) {
1226 Particle& p = particles_[static_cast<size_t>(grabIndex_)];
1227 p.px = p.x;
1228 p.py = p.y;
1229 p.pz = p.z;
1230 }
1231 }
1232 forceX_ = 0.f;
1233 forceY_ = 0.f;
1234 forceZ_ = 0.f;
1235 interactStrength_ = 0.f;
1236}
1237
1239 if (destroyed_)
1241 eve::DiagnosticCode::PreconditionViolation, "Cannot step a destroyed cloth", "physics.cloth3d.step"));
1242 auto valid = detail::validateSimulationStep(stepValue, settings, observation_);
1243 if (!valid) return valid;
1244 auto next = detail::advanceSimulationObservation(observation_, stepValue);
1245 if (!next) return eve::Result<void>::failure(next.status());
1246 try {
1247 updateSubsteps(static_cast<float>(stepValue.delta.seconds()), settings.subStepCount);
1248 } catch (const std::exception& error) {
1250 eve::DiagnosticCode::Failed, std::string("Cloth3D step failed: ") + error.what(), "physics.cloth3d.step"));
1251 } catch (...) {
1253 eve::DiagnosticCode::Failed, "Cloth3D step failed with an unknown exception", "physics.cloth3d.step"));
1254 }
1255 observation_ = std::move(next).takeValue();
1257}
1258
1260 auto valid = detail::validateSimulationObservation(observation, "physics.cloth3d.restoreObservation");
1261 if (!valid) return valid;
1262 if (destroyed_)
1264 "Cannot restore a destroyed cloth",
1265 "physics.cloth3d.restoreObservation"));
1266 observation_ = observation;
1268}
1269
1271 if (!gfx || destroyed_ || getParticleCount() < 3 || triangles_.empty()) return;
1272
1273 // Double-sided mesh: front vertices carry the face normals, back vertices
1274 // duplicate positions with flipped normals and reversed winding.
1275 const int gridVertices = getParticleCount();
1276 const int vertexCount = gridVertices * 2;
1277 const int indexCount = static_cast<int>(triangles_.size()) * 6;
1278
1279 std::vector<float> pos(static_cast<size_t>(vertexCount) * 3);
1280 std::vector<float> nrm(static_cast<size_t>(vertexCount) * 3, 0.f);
1281 std::vector<float> uv(static_cast<size_t>(vertexCount) * 2);
1282 for (int index = 0; index < gridVertices; ++index) {
1283 const size_t i = static_cast<size_t>(index);
1284 const Particle& p = particles_[i];
1285 const float u = cols_ > 1 ? float(index % cols_) / float(cols_ - 1) : p.x;
1286 const float v = rows_ > 1 ? float(index / cols_) / float(rows_ - 1) : p.z;
1287 for (int side = 0; side < 2; ++side) {
1288 const size_t vi = i + static_cast<size_t>(side) * gridVertices;
1289 pos[vi * 3 + 0] = p.x;
1290 pos[vi * 3 + 1] = p.y;
1291 pos[vi * 3 + 2] = p.z;
1292 uv[vi * 2 + 0] = u;
1293 uv[vi * 2 + 1] = v;
1294 }
1295 }
1296
1297 // Accumulate face normals.
1298 for (const Tri& tri : triangles_) {
1299 const float* pa = &pos[static_cast<size_t>(tri.v[0]) * 3];
1300 const float* pb = &pos[static_cast<size_t>(tri.v[1]) * 3];
1301 const float* pc = &pos[static_cast<size_t>(tri.v[2]) * 3];
1302 float e1x = pb[0] - pa[0], e1y = pb[1] - pa[1], e1z = pb[2] - pa[2];
1303 float e2x = pc[0] - pa[0], e2y = pc[1] - pa[1], e2z = pc[2] - pa[2];
1304 float nx = e1y * e2z - e1z * e2y;
1305 float ny = e1z * e2x - e1x * e2z;
1306 float nz = e1x * e2y - e1y * e2x;
1307 const float len = std::sqrt(nx * nx + ny * ny + nz * nz);
1308 if (len > 1e-8f) {
1309 nx /= len;
1310 ny /= len;
1311 nz /= len;
1312 } else {
1313 nx = 0.f;
1314 ny = 1.f;
1315 nz = 0.f;
1316 }
1317 for (int v : tri.v) {
1318 nrm[static_cast<size_t>(v) * 3 + 0] += nx;
1319 nrm[static_cast<size_t>(v) * 3 + 1] += ny;
1320 nrm[static_cast<size_t>(v) * 3 + 2] += nz;
1321 nrm[(static_cast<size_t>(v) + gridVertices) * 3 + 0] -= nx;
1322 nrm[(static_cast<size_t>(v) + gridVertices) * 3 + 1] -= ny;
1323 nrm[(static_cast<size_t>(v) + gridVertices) * 3 + 2] -= nz;
1324 }
1325 }
1326 for (int i = 0; i < gridVertices; ++i) {
1327 const float nx = nrm[static_cast<size_t>(i) * 3 + 0];
1328 const float ny = nrm[static_cast<size_t>(i) * 3 + 1];
1329 const float nz = nrm[static_cast<size_t>(i) * 3 + 2];
1330 const float len = std::sqrt(nx * nx + ny * ny + nz * nz);
1331 for (int side = 0; side < 2; ++side) {
1332 const size_t vi = static_cast<size_t>(i) + static_cast<size_t>(side) * gridVertices;
1333 const float sign = side == 0 ? 1.f : -1.f;
1334 if (len > 1e-8f) {
1335 nrm[vi * 3 + 0] = sign * nx / len;
1336 nrm[vi * 3 + 1] = sign * ny / len;
1337 nrm[vi * 3 + 2] = sign * nz / len;
1338 } else {
1339 nrm[vi * 3 + 1] = sign;
1340 }
1341 }
1342 }
1343
1344 if (!mesh_ || meshVertexCount_ != vertexCount || meshIndexCount_ != indexCount) {
1345 std::vector<uint32_t> indices(static_cast<size_t>(indexCount));
1346 int out = 0;
1347 for (const Tri& triangle : triangles_) {
1348 for (int corner = 0; corner < 3; ++corner) {
1349 indices[static_cast<size_t>(out + corner)] = static_cast<uint32_t>(triangle.v[corner]);
1350 indices[static_cast<size_t>(out + 3 + corner)] =
1351 static_cast<uint32_t>(triangle.v[2 - corner] + gridVertices);
1352 }
1353 out += 6;
1354 }
1355 mesh_ = gfx->newMeshFromArrays(pos.data(), nrm.data(), uv.data(), vertexCount, indices.data(), indexCount);
1356 meshVertexCount_ = vertexCount;
1357 meshIndexCount_ = indexCount;
1358 } else {
1359 gfx->updateMeshVertices(mesh_, pos.data(), nrm.data(), uv.data(), vertexCount, nullptr, 0);
1360 }
1361
1362 if (mesh_) {
1363 gfx->drawMesh(mesh_, glm::mat4(1.f), nullptr, Color(colorR_, colorG_, colorB_, colorA_));
1364 }
1365}
1366
1367// Multi-sheet coupling reuses the same triangle feature queries as self-contact.
1368LayeredCloth3D::LayeredCloth3D(int count, int cols, int rows, float spacing, float gap, float x, float y, float z) {
1369 if (count < 1 || count > 32 || !std::isfinite(gap) || gap <= 0.f || !std::isfinite(x) || !std::isfinite(y) ||
1370 !std::isfinite(z) || !std::isfinite(spacing) || !std::isfinite(y + float(count - 1) * gap))
1371 throw Exception("LayeredCloth3D: invalid count, gap or coordinates");
1372 for (int i = 0; i < count; ++i) {
1373 auto cloth = std::make_unique<Cloth3D>(cols, rows, spacing, x, y + float(i) * gap, z);
1374 cloth->setParticleSize(std::min(spacing * 0.2f, gap * 0.4f));
1375 cloth->setStretchCompliance(1e-7f);
1376 cloth->setBendCompliance(1e-4f * float(i + 1));
1377 cloth->setParticleMass(0.08f + 0.04f * float(i));
1378 cloth->setAerodynamics(1.225f, 0.6f, 0.05f);
1379 const float t = count > 1 ? float(i) / float(count - 1) : 0.f;
1380 cloth->setColor(0.2f + t * 0.7f, 0.65f - t * 0.3f, 0.9f - t * 0.65f, 1.f);
1381 layers_.push_back(std::move(cloth));
1382 }
1383}
1384
1385LayeredCloth3D::LayeredCloth3D(std::span<const ClothModel> models) {
1386 if (models.empty()) throw Exception("LayeredCloth3D: models cannot be empty");
1387 for (const auto& model : models) layers_.push_back(std::make_unique<Cloth3D>(model));
1388}
1391 if (index < 0 || index >= getLayerCount()) throw Exception("LayeredCloth3D: invalid layer index");
1392 return *layers_[static_cast<size_t>(index)];
1393}
1394int LayeredCloth3D::getLayerCount() const { return static_cast<int>(layers_.size()); }
1395void LayeredCloth3D::setSolver(int substeps, int passes) {
1396 if (substeps < 1 || substeps > 32 || passes < 1 || passes > 16)
1397 throw Exception("LayeredCloth3D: invalid solver budget");
1398 substeps_ = substeps;
1399 passes_ = passes;
1400}
1401void LayeredCloth3D::setInterCollision(bool enabled) { interCollision_ = enabled; }
1402bool LayeredCloth3D::getInterCollision() const { return interCollision_; }
1403int LayeredCloth3D::getContactCount() const { return contacts_; }
1404void LayeredCloth3D::setWindVelocity(float x, float y, float z) {
1405 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z)) throw Exception("LayeredCloth3D: invalid wind");
1406 for (auto& cloth : layers_) cloth->setWindVelocity(x, y, z);
1407}
1409 for (auto& cloth : layers_) cloth->reset();
1410 contacts_ = 0;
1411}
1413 for (auto& cloth : layers_) cloth->draw(gfx);
1414}
1416 if (!std::isfinite(dt) || dt < 0.f || dt > 0.05f)
1417 throw Exception("LayeredCloth3D: dt must be finite and in [0,0.05]");
1418 for (const auto& cloth : layers_)
1419 if (cloth->destroyed_) throw Exception("LayeredCloth3D: layer was destroyed");
1420 contacts_ = 0;
1421 if (dt == 0.f) return;
1422 const float h = dt / float(substeps_);
1423 for (int step = 0; step < substeps_; ++step) {
1424 for (auto& c : layers_) {
1425 c->integrate(h);
1426 c->applyAutomaticTearing();
1427 }
1428 for (int pass = 0; pass < passes_; ++pass) {
1429 for (auto& c : layers_) {
1430 c->solveConstraints(h);
1431 c->solveFoldConstraint();
1432 c->solveSelfCollision();
1433 c->solveSelfCollisionTriangles();
1434 c->collideWorld(h);
1435 c->collideBounds();
1436 }
1437 if (interCollision_)
1438 for (size_t a = 0; a < layers_.size(); ++a)
1439 for (size_t b = a + 1; b < layers_.size(); ++b) solveContacts(*layers_[a], *layers_[b]);
1440 }
1441 for (auto& c : layers_)
1442 if (c->grabIndex_ >= 0) {
1443 auto& p = c->particles_[static_cast<size_t>(c->grabIndex_)];
1444 p.px = p.x;
1445 p.py = p.y;
1446 p.pz = p.z;
1447 }
1448 }
1449 for (auto& c : layers_) {
1450 c->forceX_ = c->forceY_ = c->forceZ_ = 0.f;
1451 c->interactStrength_ = 0.f;
1452 }
1453}
1454
1455void LayeredCloth3D::solveContacts(Cloth3D& a, Cloth3D& b) {
1456 if (!(a.collisionCategoryBits_ & b.collisionMaskBits_) || !(b.collisionCategoryBits_ & a.collisionMaskBits_))
1457 return;
1458 const float thickness = a.particleSize_ + b.particleSize_;
1459 // Sweep on X; Y/Z AABB rejection precedes the full vertex/edge/face query.
1460 struct Bounds {
1461 float lo[3], hi[3];
1462 size_t triangle;
1463 };
1464 auto bounds = [](const Cloth3D& cloth) {
1465 std::vector<Bounds> result;
1466 result.reserve(cloth.triangles_.size());
1467 for (size_t i = 0; i < cloth.triangles_.size(); ++i) {
1468 Bounds box{{INFINITY, INFINITY, INFINITY}, {-INFINITY, -INFINITY, -INFINITY}, i};
1469 for (int index : cloth.triangles_[i].v) {
1470 const auto& p = cloth.particles_[static_cast<size_t>(index)];
1471 const float xyz[3] = {p.x, p.y, p.z};
1472 for (int k = 0; k < 3; ++k) {
1473 box.lo[k] = std::min(box.lo[k], xyz[k]);
1474 box.hi[k] = std::max(box.hi[k], xyz[k]);
1475 }
1476 }
1477 result.push_back(box);
1478 }
1479 std::stable_sort(result.begin(), result.end(),
1480 [](const Bounds& x, const Bounds& y) { return x.lo[0] < y.lo[0]; });
1481 return result;
1482 };
1483 const auto boxesA = bounds(a), boxesB = bounds(b);
1484 // Candidate bounds are a snapshot of this pass. New contacts introduced by
1485 // projection are picked up by the next coupling pass/substep.
1486 for (const auto& ba : boxesA)
1487 for (const auto& bb : boxesB) {
1488 if (bb.lo[0] > ba.hi[0] + thickness) break;
1489 if (bb.hi[0] < ba.lo[0] - thickness || bb.lo[1] > ba.hi[1] + thickness || bb.hi[1] < ba.lo[1] - thickness ||
1490 bb.lo[2] > ba.hi[2] + thickness || bb.hi[2] < ba.lo[2] - thickness)
1491 continue;
1492 const auto& ta = a.triangles_[ba.triangle];
1493 const auto& tb = b.triangles_[bb.triangle];
1494 V3 pa[3], pb[3];
1495 for (int i = 0; i < 3; ++i) {
1496 const auto& p = a.particles_[static_cast<size_t>(ta.v[i])];
1497 const auto& q = b.particles_[static_cast<size_t>(tb.v[i])];
1498 pa[i] = {p.x, p.y, p.z};
1499 pb[i] = {q.x, q.y, q.z};
1500 }
1501 V3 ca, cb;
1502 int fa[3], fb[3], na = 0, nb = 0;
1503 const float distance = triangleDistance(pa, pb, fa, fb, na, nb, ca, cb);
1504 if (distance >= thickness) continue;
1505 // Recover barycentric contact gradients for all three feature types.
1506 auto weights = [](const V3* p, const int* feature, int count, V3 cp) {
1507 std::array<float, 3> w{};
1508 if (count == 1)
1509 w[static_cast<size_t>(feature[0])] = 1.f;
1510 else if (count == 2) {
1511 const V3 edge = sub(p[feature[1]], p[feature[0]]);
1512 const float t =
1513 std::clamp(dot(sub(cp, p[feature[0]]), edge) / std::max(dot(edge, edge), 1e-12f), 0.f, 1.f);
1514 w[static_cast<size_t>(feature[0])] = 1.f - t;
1515 w[static_cast<size_t>(feature[1])] = t;
1516 } else {
1517 const V3 u = sub(p[1], p[0]), v = sub(p[2], p[0]), q = sub(cp, p[0]);
1518 const float uu = dot(u, u), uv = dot(u, v), vv = dot(v, v);
1519 const float det = uu * vv - uv * uv;
1520 if (det <= 1e-12f) {
1521 w[0] = 1.f;
1522 return w;
1523 }
1524 w[1] = std::clamp((vv * dot(q, u) - uv * dot(q, v)) / det, 0.f, 1.f);
1525 w[2] = std::clamp((uu * dot(q, v) - uv * dot(q, u)) / det, 0.f, 1.f - w[1]);
1526 w[0] = 1.f - w[1] - w[2];
1527 }
1528 return w;
1529 };
1530 const auto wa = weights(pa, fa, na, ca), wb = weights(pb, fb, nb, cb);
1531 V3 previousA{}, previousB{};
1532 float denominator = 0.f;
1533 for (int i = 0; i < 3; ++i) {
1534 const auto& p = a.particles_[static_cast<size_t>(ta.v[i])];
1535 const auto& q = b.particles_[static_cast<size_t>(tb.v[i])];
1536 previousA = add(previousA, mul(wa[i], {p.px, p.py, p.pz}));
1537 previousB = add(previousB, mul(wb[i], {q.px, q.py, q.pz}));
1538 denominator += (p.pinned || ta.v[i] == a.grabIndex_ ? 0.f : p.inverseMass) * wa[i] * wa[i];
1539 denominator += (q.pinned || tb.v[i] == b.grabIndex_ ? 0.f : q.inverseMass) * wb[i] * wb[i];
1540 }
1541 if (denominator <= 1e-12f) continue;
1542 V3 normal = distance > 1e-7f ? mul(1.f / distance, sub(ca, cb)) : vnorm(sub(previousA, previousB));
1543 const float lambda = (thickness - distance) / denominator;
1544 const V3 relative = sub(sub(ca, previousA), sub(cb, previousB));
1545 const V3 tangent = sub(relative, mul(dot(relative, normal), normal));
1546 const float length = vlen(tangent);
1547 const float friction = std::sqrt(a.collisionFriction_ * b.collisionFriction_);
1548 const V3 frictionDelta =
1549 mul(std::min(1.f, friction * (thickness - distance) / std::max(length, 1e-8f)) / denominator, tangent);
1550 for (int i = 0; i < 3; ++i) {
1551 auto project = [&](Cloth3D& c, int index, float weight, float sign) {
1552 auto& p = c.particles_[static_cast<size_t>(index)];
1553 if (p.pinned || index == c.grabIndex_) return;
1554 const float scale = sign * p.inverseMass * weight;
1555 p.x += normal.x * lambda * scale;
1556 p.y += normal.y * lambda * scale;
1557 p.z += normal.z * lambda * scale;
1558 p.px += frictionDelta.x * scale;
1559 p.py += frictionDelta.y * scale;
1560 p.pz += frictionDelta.z * scale;
1561 };
1562 project(a, ta.v[i], wa[i], 1.f);
1563 project(b, tb.v[i], wb[i], -1.f);
1564 }
1565 ++contacts_;
1566 }
1567}
1568
1569} // namespace eve::physics
double z
double y
double m[16]
double x
float w
Definition AnimClip.cpp:738
Vec3 relative
Definition AnimSmr.cpp:164
const std::string & s
float gap
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
float degrees
Definition CardTypes.cpp:38
float uv
bool dynamic
float inverseMass
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
int rows
int cols
int triangle
Definition FluidSdf.cpp:554
float strength
float friction
ScriptForceVector acceleration
std::uint32_t vertexCount
std::uint32_t indexCount
tensor::Graph g
Definition GpuGraph.cpp:7
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
std::uint32_t ab
double r
std::uint32_t ac
std::vector< std::uint32_t > indices
HexDirection windDirection
float v
std::int32_t second
std::int32_t c
eve::ResourcePin pinned
int h
float length
JointPoint2D axis
PhysicsJointLink link
std::array< float, 3 > scale
float thickness
std::vector< Edge > edges
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
std::vector< TriangleRef > triangles
float tb
Texture * normal
float ta
OceanWakeSettings settings
glm::dvec3 dx
glm::dvec3 dz
double dt
glm::dvec3 tangentZ
glm::dvec3 tangentX
std::string error
Definition Package.cpp:174
int idx
float f
std::vector< BakedParticleSample > particles
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
float d
float t
glm::mat4 model
ScriptStructure out
std::string_view source
float dy
Definition Shadow.cpp:151
double restitution
int count
Cell cell
std::map< Cell, int > best
float weights[3]
int spacing
int iterations
Definition TreeMesh.cpp:448
float step
Definition TreeMesh.cpp:451
float size
Definition TreeMesh.cpp:158
V3 dir
Definition TreeMesh.cpp:151
double weight
uint32_t index
std::vector< double > phi
double oy
double ox
Contact contact
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
double seconds() const noexcept
Return this duration as seconds for legacy/presentation APIs.
Definition Time.cpp:29
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
virtual void drawMesh(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint)=0
Draw one mesh with model matrix. Requires begin3DFrame() (or an open swapchain pass).
virtual bool updateMeshVertices(Mesh *mesh, const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
In-place update of a mesh's vertex/index data (CPU -> host-visible VBO). Only call when content chang...
virtual Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh from packed CPU arrays. Owned by Graphics. posXYZ required (vertexCount*3)....
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
Interactive 3D cloth — Verlet particles + distance constraints. Meter space, +Y up,...
Definition Cloth3D.h:32
void clearBounds()
Clears bounds.
Definition Cloth3D.cpp:468
float getWindVelocityZ() const
Return configured air velocity along Z in m/s.
Definition Cloth3D.cpp:434
void setGravity(float gx, float gy, float gz)
Sets the gravity.
Definition Cloth3D.cpp:352
void setCollisionMaterial(float friction, float restitution)
Configure cloth contact friction and restitution in [0,1].
Definition Cloth3D.cpp:470
void pin(int index)
Definition Cloth3D.cpp:480
~Cloth3D()
Cloth 3 d.
Definition Cloth3D.cpp:229
void setParticleInverseMass(int index, float inverseMass)
Set per-particle inverse mass; zero makes the particle kinematic/pinned.
Definition Cloth3D.cpp:503
void interactAt(float x, float y, float z, float radius, float strength)
Pointer-field interaction like Fluid2D::interactAt (3D): positive strength attracts,...
Definition Cloth3D.cpp:555
Cloth3D(int cols, int rows, float spacing, float originX, float originY, float originZ)
Cloth 3 d.
Definition Cloth3D.cpp:219
void destroy()
Destroys .
Definition Cloth3D.cpp:231
void setShearCompliance(float compliance)
Set XPBD shear compliance in m/N; zero preserves legacy PBD.
Definition Cloth3D.cpp:364
float getDragCoefficient() const
Return the aerodynamic drag coefficient.
Definition Cloth3D.cpp:444
void moveGrab(float x, float y, float z)
Moves grab.
Definition Cloth3D.cpp:533
void setCollideWorld(World3D *world)
Attach a World3D so free particles collide with its non-sensor shapes in meter space....
Definition Cloth3D.cpp:563
void draw(graphics::Graphics *gfx)
Draw the cloth as a triangle mesh (requires an open 3D frame).
Definition Cloth3D.cpp:1270
float getLiftCoefficient() const
Return the aerodynamic lift coefficient.
Definition Cloth3D.cpp:446
void setWindVelocity(float vx, float vy, float vz)
Set world-space air velocity used by the aerodynamic model (m/s).
Definition Cloth3D.cpp:424
void setStretchCompliance(float compliance)
Set XPBD stretch compliance in m/N; zero preserves legacy PBD.
Definition Cloth3D.cpp:360
void setSelfCollision(bool on)
Enable proximity-based self-collision between non-adjacent particles and triangles (default true)....
Definition Cloth3D.cpp:448
int grabAt(float x, float y, float z, float radius=0.3f)
Grab nearest free particle within radius (meters). Returns particle index, or -1 if none.
Definition Cloth3D.cpp:514
bool isPinned(int index) const
True when pinned.
Definition Cloth3D.cpp:498
void pinTopRow()
Pin top row.
Definition Cloth3D.cpp:494
void setColor(float r, float g, float b, float a=1.f)
Sets the color.
Definition Cloth3D.cpp:565
void setStiffness(float stiffness)
Constraint relaxation strength in [0,1] (default 0.85).
Definition Cloth3D.cpp:358
eve::Result< void > step(const eve::SimulationStep &step, const SimulationSettings &settings) override
Advances cloth with the shared ticked backend contract.
Definition Cloth3D.cpp:1238
void setCollisionFilter(uint64_t categoryBits, uint64_t maskBits)
Configure symmetric category/mask filtering for World3D contacts.
Definition Cloth3D.cpp:475
float getParticleX(int index) const
Definition Cloth3D.cpp:572
void setBendCompliance(float compliance)
Set XPBD distance-bend compliance in m/N; zero preserves legacy PBD.
Definition Cloth3D.cpp:368
void unpin(int index)
Unpin.
Definition Cloth3D.cpp:487
eve::Result< void > restoreObservation(const SimulationObservation &observation) override
Restores tick/progress metadata after an owner-level restore.
Definition Cloth3D.cpp:1259
void setBounds(float x, float y, float z, float w, float h, float d)
Axis-aligned box (origin + extents, meters); particles bounce inside.
Definition Cloth3D.cpp:454
void reset()
Restore the flat grid pose (top row pinned) and clear transient state.
Definition Cloth3D.cpp:233
void releaseGrab()
Release grab.
Definition Cloth3D.cpp:547
SimulationObservation observation() const noexcept override
Returns completed tick/time observables.
Definition Cloth3D.h:69
void setParticleSize(float size)
Particle radius in meters (default 0.1): self-collision separation, draw scale and rigid-body collisi...
Definition Cloth3D.cpp:376
void setIterations(int iterations)
Constraint solver iterations per substep (default 4).
Definition Cloth3D.cpp:372
void update(float dt)
Updates .
Definition Cloth3D.cpp:1204
void setDamping(float damping)
Damping applied to Verlet velocity [0,1] (default 0.01).
Definition Cloth3D.cpp:374
float getWindVelocityY() const
Return configured air velocity along Y in m/s.
Definition Cloth3D.cpp:432
float getParticleInverseMass(int index) const
Return per-particle inverse mass, or zero for an invalid index.
Definition Cloth3D.cpp:510
void setParticleMass(float mass)
Implicit particle mass in kg (default 0.1). Used for mass-proportional momentum exchange when collidi...
Definition Cloth3D.cpp:378
void applyForce(float fx, float fy, float fz)
Applies force.
Definition Cloth3D.cpp:549
float getParticleZ(int index) const
Returns the particle z.
Definition Cloth3D.cpp:582
void setParticlePosition(int index, float x, float y, float z)
Sets the particle position.
Definition Cloth3D.cpp:587
void setMaxFoldAngle(float degrees)
Maximum fold angle between adjacent triangles in degrees Range is 0..180 degrees; default is 120....
Definition Cloth3D.cpp:452
int getParticleCount() const
Returns the particle count.
Definition Cloth3D.h:357
float getParticleY(int index) const
Returns the particle y.
Definition Cloth3D.cpp:577
float getAirDensity() const
Return aerodynamic fluid density in kg/m³.
Definition Cloth3D.cpp:442
float getWindVelocityX() const
Return configured air velocity along X in m/s.
Definition Cloth3D.cpp:430
void setFoldStiffness(float k)
Strength of the dihedral fold clamp [0,1] (default 0.5).
Definition Cloth3D.cpp:450
void setAerodynamics(float airDensity, float dragCoefficient, float liftCoefficient)
Configure two-sided triangle aerodynamics.
Definition Cloth3D.cpp:436
Reusable, validated cloth simulation asset.
Definition ClothModel.h:73
static eve::Result< ClothModel > grid(int cols, int rows, float spacing, float originX, float originY, float originZ)
Bake a regular XZ cloth grid with its top row pinned.
void setInterCollision(bool enabled)
Enable or disable only contacts between different sheets.
Definition Cloth3D.cpp:1401
~LayeredCloth3D()
Release owned runtime layers; render resources follow the graphics owner.
void reset()
Restore every layer's authored pose and clear contact statistics.
Definition Cloth3D.cpp:1408
void update(float dt)
Advance all layers by finite dt in [0,0.05], without dropping time.
Definition Cloth3D.cpp:1415
Cloth3D & layer(int index)
Borrow a layer for synchronous configuration; valid until owner destruction. Do not destroy or indepe...
Definition Cloth3D.cpp:1390
int getLayerCount() const
Return the number of owned sheets.
Definition Cloth3D.cpp:1394
void setSolver(int substeps, int passes)
Configure substeps [1,32] and coupling passes [1,16]; throws on invalid input.
Definition Cloth3D.cpp:1395
void setWindVelocity(float x, float y, float z)
Set the air velocity of every sheet; throws on nonfinite input.
Definition Cloth3D.cpp:1404
int getContactCount() const
Return projected contacts in the most recent update, including repeated passes.
Definition Cloth3D.cpp:1403
LayeredCloth3D(int count, int cols, int rows, float spacing, float gap, float x, float y, float z)
Construct parallel XZ grids, separated along +Y.
Definition Cloth3D.cpp:1368
void draw(graphics::Graphics *gfx)
Draw owned cloth surfaces in an open 3D frame.
Definition Cloth3D.cpp:1412
bool getInterCollision() const
Return whether inter-layer contacts are enabled.
Definition Cloth3D.cpp:1402
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
bool isValid() const
True while the underlying Box3D world is alive.
Definition World3D.cpp:239
ClothProbeStatus pointProbeFiltered(float x, float y, float z, float radius, ClothContact3D *out, uint64_t categoryBits, uint64_t maskBits) const
Probe a cloth particle using symmetric category/mask filtering.
Snapshot project(Files files, Object::Ptr stats, std::string defaultProjectId, std::string projectDir)
Build a candidate evidence graph without touching the published snapshot.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
JPH::uint64 pairKey(JPH::BodyID a, JPH::BodyID b)
Counts suppression references for one native pair; sequence numbers prevent reuse aliases.
Definition JoltJoint.cpp:8
JPH::SixDOFConstraint::EAxis A
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
Vec3 sub(Vec3 a, Vec3 b)
Vec3 mul(Vec3 a, float scale)
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29
glm::vec4 Color
Render-neutral RGBA color shared by graphics-facing modules.
Definition RenderTypes.h:8
bool enabled
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Duration delta
Fixed simulation duration for this step.
Definition Time.h:162
Observable backend progress shared by CPU and accelerator providers.
Validated solver policy for one simulation step.
glm::vec4 bounds
uint32_t pad[2]