Rise
The Vieneo Province
Loading...
Searching...
No Matches
RigidProp.h
Go to the documentation of this file.
1#pragma once
2#include <algorithm>
3#include <array>
4#include <cmath>
5#include <cstdint>
6#include <limits>
7#include <vector>
8
9// One convex rigid prop against fixed triangles. No renderer or world-unit dependencies.
10// Lengths in authored model units, seconds, normalized mass (1). Right handed +Z up.
11namespace RigidProp {
12struct Vec {
13 double x=0, y=0, z=0;
14 Vec operator+(Vec b) const { return {x+b.x,y+b.y,z+b.z}; }
15 Vec operator-(Vec b) const { return {x-b.x,y-b.y,z-b.z}; }
16 Vec operator-() const { return {-x,-y,-z}; }
17 Vec operator*(double s) const { return {x*s,y*s,z*s}; }
18 Vec operator/(double s) const { return *this*(1/s); }
19 Vec& operator+=(Vec b) { return *this=*this+b; }
20 Vec& operator-=(Vec b) { return *this=*this-b; }
21};
22inline double Dot(Vec a,Vec b) { return a.x*b.x+a.y*b.y+a.z*b.z; }
23inline Vec Cross(Vec a,Vec 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}; }
24inline double Length(Vec a) { return std::sqrt(Dot(a,a)); }
25inline Vec Unit(Vec a) { double n=Length(a); return n>1e-12?a/n:Vec{0,0,1}; }
26inline bool Finite(Vec a) { return std::isfinite(a.x)&&std::isfinite(a.y)&&std::isfinite(a.z); }
27struct Quat {
28 double x=0,y=0,z=0,w=1;
29 Quat operator*(Quat b) const {
30 return {w*b.x+x*b.w+y*b.z-z*b.y,w*b.y-x*b.z+y*b.w+z*b.x,
31 w*b.z+x*b.y-y*b.x+z*b.w,w*b.w-x*b.x-y*b.y-z*b.z};
32 }
33 Vec Rotate(Vec v) const { Vec t=Cross({x,y,z},v)*2; return v+t*w+Cross({x,y,z},t); }
34 Vec Unrotate(Vec v) const { return Quat{-x,-y,-z,w}.Rotate(v); }
35 void Normalize() { double n=std::sqrt(x*x+y*y+z*z+w*w); x/=n;y/=n;z/=n;w/=n; }
36 static Quat Axis(Vec axis,double angle) {
37 double s=std::sin(angle*.5); axis=Unit(axis); return {axis.x*s,axis.y*s,axis.z*s,std::cos(angle*.5)};
38 }
39 static Quat Ypr(double yaw,double pitch,double roll) {
40 return Axis({0,1,0},yaw)*Axis({1,0,0},pitch)*Axis({0,0,1},roll);
41 }
42};
43struct Triangle { Vec a,b,c; };
44struct Hull { std::vector<Vec> vertices; };
46inline bool Finite(const Pose& p) {
47 return Finite(p.position) && std::isfinite(p.rotation.x) && std::isfinite(p.rotation.y) &&
48 std::isfinite(p.rotation.z) && std::isfinite(p.rotation.w);
49}
50struct Body {
53 // Uniform cylinder approximation for Sparko: R=sqrt(18), half height=8.
54 Vec inertia{25.8333333333333,25.8333333333333,9};
55 double radius=std::sqrt(82.0); // encloses every mesh vertex
56 bool sleeping=false;
57 double quietTime=0;
58};
59inline Vec InverseInertia(const Body& b,Vec v) {
60 v=b.pose.rotation.Unrotate(v);
61 return b.pose.rotation.Rotate({v.x/b.inertia.x,v.y/b.inertia.y,v.z/b.inertia.z});
62}
63inline Vec Support(const Hull& h,const Pose& p,Vec d) {
64 Vec ld=p.rotation.Unrotate(d), best=h.vertices.front();
65 for(Vec v:h.vertices) if(Dot(v,ld)>Dot(best,ld)) best=v;
66 return p.position+p.rotation.Rotate(best);
67}
68inline Vec Support(const Triangle& t,Vec d) {
69 Vec v=Dot(t.a,d)>Dot(t.b,d)?t.a:t.b; return Dot(t.c,d)>Dot(v,d)?t.c:v;
70}
72struct Distance { double gap=0; Vec normal,point; };
73
74// Closest point on a simplex: enumerate its (at most 15) affine faces and
75// retain the closest nonnegative barycentric solution. Also retains witnesses.
76inline Vec Reduce(std::vector<SupportPoint>& simplex, Vec& witness) {
77 double best=std::numeric_limits<double>::max();
78 std::array<double,4> weights{};
79 const int n=static_cast<int>(simplex.size());
80 for(int mask=1;mask<(1<<n);++mask) {
81 int ids[4],m=0; for(int i=0;i<n;++i) if(mask&(1<<i)) ids[m++]=i;
82 double a[3][4]={}, w[4]={1,0,0,0}; bool valid=true;
83 Vec base=simplex[ids[0]].difference;
84 for(int i=1;i<m;++i) {
85 Vec edge=simplex[ids[i]].difference-base;
86 for(int j=1;j<m;++j) a[i-1][j-1]=Dot(edge,simplex[ids[j]].difference-base);
87 a[i-1][m-1]=-Dot(edge,base);
88 }
89 for(int col=0;col<m-1;++col) {
90 int pivot=col;
91 for(int row=col+1;row<m-1;++row) if(std::abs(a[row][col])>std::abs(a[pivot][col])) pivot=row;
92 if(std::abs(a[pivot][col])<1e-12) {valid=false;break;}
93 for(int k=col;k<m;++k) std::swap(a[col][k],a[pivot][k]);
94 double div=a[col][col]; for(int k=col;k<m;++k) a[col][k]/=div;
95 for(int row=0;row<m-1;++row) if(row!=col) {
96 double mul=a[row][col]; for(int k=col;k<m;++k) a[row][k]-=mul*a[col][k];
97 }
98 }
99 if(!valid) continue;
100 for(int i=1;i<m;++i) {w[i]=a[i-1][m-1];w[0]-=w[i];}
101 Vec closest{};
102 for(int i=0;i<m;++i) {if(w[i]<-1e-9) valid=false;closest+=simplex[ids[i]].difference*w[i];}
103 if(valid && Dot(closest,closest)<best) {
104 best=Dot(closest,closest); weights.fill(0);
105 for(int i=0;i<m;++i) weights[ids[i]]=w[i];
106 }
107 }
108 Vec closest{};witness={}; std::vector<SupportPoint> reduced;
109 for(int i=0;i<n;++i) if(weights[i]>1e-10) {
110 closest+=simplex[i].difference*weights[i]; witness+=simplex[i].body*weights[i];
111 reduced.push_back(simplex[i]);
112 }
113 simplex=std::move(reduced); return closest;
114}
115
116inline Distance Query(const Hull& h,const Pose& p,const Triangle& t) {
117 auto support=[&](Vec d) {Vec a=Support(h,p,d),b=Support(t,-d);return SupportPoint{a-b,a,b};};
118 std::vector<SupportPoint> simplex{support(p.position-(t.a+t.b+t.c)/3)};
119 Vec witness{},v=Reduce(simplex,witness);
120 for(int iter=0;iter<32 && Dot(v,v)>1e-14;++iter) {
121 SupportPoint next=support(-v);
122 if(Dot(v,v)-Dot(v,next.difference)<1e-10*std::max(1.0,Dot(v,v))) break;
123 if(simplex.size()==4) break;
124 simplex.push_back(next); v=Reduce(simplex,witness);
125 }
126 double gap=Length(v);
127 if(gap>1e-6) {
128 Vec normal=v/gap;
129 // Use the separating-axis lower bound, not the simplex's upper bound
130 // on distance, so even an iteration-limited query remains safe for CCD.
131 double separation=Dot(Support(h,p,-normal)-Support(t,normal),normal);
132 return {std::max(0.0,separation),normal,witness};
133 }
134 // Only used for tiny initial/contact overlap. CCD preserves the incoming
135 // side; normal projection then repairs that overlap without a centre clamp.
136 Vec n=Unit(Cross(t.b-t.a,t.c-t.a));
137 if(Dot(n,p.position-t.a)<0) n=-n;
138 Vec point=Support(h,p,-n);
139 return {Dot(n,point-t.a),n,point};
140}
141inline bool Near(const Body& b,const Triangle& t,double extra) {
142 double r=b.radius+extra;
143 return b.pose.position.x+r>=std::min({t.a.x,t.b.x,t.c.x}) && b.pose.position.x-r<=std::max({t.a.x,t.b.x,t.c.x}) &&
144 b.pose.position.y+r>=std::min({t.a.y,t.b.y,t.c.y}) && b.pose.position.y-r<=std::max({t.a.y,t.b.y,t.c.y}) &&
145 b.pose.position.z+r>=std::min({t.a.z,t.b.z,t.c.z}) && b.pose.position.z-r<=std::max({t.a.z,t.b.z,t.c.z});
146}
147inline bool Inside(Vec p,const Triangle& t) {
148 Vec n=Cross(t.b-t.a,t.c-t.a);
149 return Dot(Cross(t.b-t.a,p-t.a),n)>=-1e-7 && Dot(Cross(t.c-t.b,p-t.b),n)>=-1e-7 &&
150 Dot(Cross(t.a-t.c,p-t.c),n)>=-1e-7;
151}
153struct Material {
154 // Artistic dry cabin tuning; not Earth atmospheric coefficients.
156};
157inline void Impulse(Body& b,Vec arm,Vec j) { b.velocity+=j; b.omega+=InverseInertia(b,Cross(arm,j)); }
158inline double Mass(const Body& b,Vec r,Vec n) { return 1+Dot(n,Cross(InverseInertia(b,Cross(r,n)),r)); }
159inline void Solve(Body& b,std::vector<Contact>& contacts,const Material& material,double dt) {
160 for(auto& c:contacts) {
161 double vn=Dot(b.velocity+Cross(b.omega,c.arm),c.normal);
162 if(vn < -material.bounceThreshold) c.target=-vn*material.restitution;
163 }
164 for(int iter=0;iter<12;++iter) for(auto& c:contacts) {
165 Vec v=b.velocity+Cross(b.omega,c.arm);
166 double next=std::max(0.0,c.normalImpulse+(c.target-Dot(v,c.normal))/Mass(b,c.arm,c.normal));
167 Impulse(b,c.arm,c.normal*(next-c.normalImpulse));c.normalImpulse=next;
168 v=b.velocity+Cross(b.omega,c.arm); Vec tangent=v-c.normal*Dot(v,c.normal);
169 double speed=Length(tangent);
170 if(speed>1e-10) {
171 Vec direction=tangent/speed;
172 Vec trial=c.tangentImpulse-direction*(speed/Mass(b,c.arm,direction));
173 double limit=material.friction*c.normalImpulse, mag=Length(trial);
174 if(mag>limit) trial=trial*(limit/mag);
175 Impulse(b,c.arm,trial-c.tangentImpulse);c.tangentImpulse=trial;
176 }
177 }
178 double normalImpulse=0; for(const auto& c:contacts) normalImpulse+=c.normalImpulse;
179 // Contact-only rolling/spin loss, impulse scaled; no damping in free flight.
180 double spin=Length(b.omega);
181 if(spin>0) b.omega=b.omega*(std::max(0.0,spin-material.rollingResistance*normalImpulse*4.24/9)/spin);
182 (void)dt;
183}
184
186// Per-frame accounting, in model units and seconds. No logging or changes to
187// integration decisions here: diagnostics must observe the exact solver path.
198inline Vec Acceleration(const Body& b,const Motion& m) {
199 Vec arm=b.pose.position-m.origin;
203}
206 std::vector<Triangle> triangles;
208 double accumulator=0;
210 static constexpr double Skin=.035; // 0.23 mm for this authored scale
211 void Correct(Vec normal,double amount,int triangle) {
212 body.pose.position+=normal*amount;
213 stats.positionCorrection+=normal*amount;
214 if(amount>stats.maxCorrection) {
216 }
217 }
218 void Contacts(std::vector<Contact>& contacts,std::vector<int>& active) {
219 for(size_t i=0;i<triangles.size();++i) {
220 const auto& t=triangles[i]; if(!Near(body,t,2*Skin)) continue;
222 if(d.gap>Skin*1.5) continue;
223 if(d.gap<Skin*.5) Correct(d.normal,Skin*.5-d.gap,static_cast<int>(i));
224 active.push_back(static_cast<int>(i));
225 if(i<192) stats.contactMask[i/64]|=std::uint64_t(1)<<(i%64);
226 bool vertices=false;
227 // Face manifold, including both can rims. Triangle edges fall back
228 // to the GJK witnesses to generate the correct off-centre impulse.
229 double low=Dot(Support(hull,body.pose,-d.normal),d.normal);
230 for(Vec local:hull.vertices) {
232 if(Dot(p,d.normal)-low>Skin) continue;
233 Vec projected=p-d.normal*Dot(p-t.a,d.normal);
234 if(std::abs(Dot(Unit(Cross(t.b-t.a,t.c-t.a)),d.normal))>.999 && Inside(projected,t)) {
235 contacts.push_back({d.normal,p-body.pose.position});contacts.back().triangle=static_cast<int>(i);vertices=true;
236 }
237 }
238 if(!vertices) {contacts.push_back({d.normal,d.point-body.pose.position});contacts.back().triangle=static_cast<int>(i);}
239 }
240 }
241 void Step(double dt,const Motion& motion) {
243 Vec forceDeltaV=Acceleration(body,motion)*dt;
244 body.velocity+=forceDeltaV;stats.forceDeltaV+=forceDeltaV;
245 // Relative angular velocity in the moving cabin. Gyroscopic term for
246 // the anisotropic can plus the rotating-coordinate derivative.
247 Vec absolute=body.omega+motion.angularVelocity;
248 Vec local=body.pose.rotation.Unrotate(absolute);
249 Vec momentum=body.pose.rotation.Rotate({local.x*body.inertia.x,local.y*body.inertia.y,local.z*body.inertia.z});
250 Vec forceDeltaOmega=-(InverseInertia(body,Cross(absolute,momentum))+
252 body.omega+=forceDeltaOmega;stats.forceDeltaOmega+=forceDeltaOmega;
253 double remaining=dt;
254 for(int iteration=0;remaining>1e-9 && iteration<512;++iteration) {
255 ++stats.sweeps;
256 std::vector<Contact> contacts; std::vector<int> active;
257 Contacts(contacts,active);
258 for(const auto& c:contacts)
260 Vec velocityBefore=body.velocity,omegaBefore=body.omega;
261 Solve(body,contacts,material,dt);
262 stats.contactDeltaV+=body.velocity-velocityBefore;stats.contactDeltaOmega+=body.omega-omegaBefore;
263 stats.contacts+=static_cast<unsigned>(contacts.size());stats.lastContacts=static_cast<unsigned>(contacts.size());
264 for(const auto& c:contacts) if(c.normalImpulse>stats.maxNormalImpulse) {
265 stats.maxNormalImpulse=c.normalImpulse;stats.impulseTriangle=c.triangle;stats.largestImpulseNormal=c.normal;
266 }
268 // Angular and translational travel are bounded together. This also
269 // bounds the error when projecting an existing contact manifold.
270 double advance=std::min(remaining,.12/std::max(speed,1e-12));
271 for(size_t i=0;i<triangles.size();++i) {
272 if(std::find(active.begin(),active.end(),static_cast<int>(i))!=active.end()) continue;
273 if(!Near(body,triangles[i],speed*advance+Skin)) continue;
275 // GJK distance / maximum point speed is a conservative swept
276 // bound for translation AND rotation, including thin triangles.
277 advance=std::min(advance,std::max(1e-9,(d.gap-Skin)*.8/std::max(speed,1e-12)));
278 }
279 Pose before=body.pose;
280 body.pose.position+=body.velocity*advance;
282 double spin=Length(body.omega);
283 if(spin>1e-12) {body.pose.rotation=Quat::Axis(body.omega,spin*advance)*body.pose.rotation;body.pose.rotation.Normalize();}
284 // Keep the incoming side of contacts. Never choose a new normal
285 // from a centre that has crossed the surface of a thin obstacle.
286 for(int index:active) {
287 const Triangle& t=triangles[index];
288 Distance old=Query(hull,before,t), now=Query(hull,body.pose,t);
289 if(now.gap<Skin*.5) {
290 double depth=Dot(Support(hull,body.pose,-old.normal)-Support(t,old.normal),old.normal);
291 if(depth<Skin*.5) Correct(old.normal,Skin*.5-depth,index);
292 }
293 }
294 remaining-=advance;
295 }
296 // A pathological impulse may exhaust the sweep budget; discard residual
297 // motion rather than taking an unchecked step through cabin geometry.
298 if(remaining>1e-9) {
301 }
302 if(Length(body.velocity)<.15 && Length(body.omega)<.025) body.quietTime+=dt;
303 else body.quietTime=0;
304 if(body.quietTime>.5) {
306 body.sleeping=true;body.velocity={};body.omega={};
307 }
308 }
309public:
314 Simulation(Hull shape,std::vector<Triangle> scene,Pose pose):hull(std::move(shape)),triangles(std::move(scene)),initial(pose) {Reset();}
315 const Hull& Shape() const {return hull;}
316 const std::vector<Triangle>& Scene() const {return triangles;}
317 void DiscardMotion(const char* reason="discard") {
318 // A missed/invalid frame is not a relocation. Keep the last cabin pose
319 // and discard stale integration state instead of respawning the prop.
324 }
325 void Reset() {
327 // Resolve the authored 0.123-unit floor overlap using the full hull.
328 for(int i=0;i<4;++i) {std::vector<Contact> c;std::vector<int> a;Contacts(c,a);}
330 stats={};
331 }
332 void Update(double dt,const Motion& motion) {
333 stats={};
334 if(!std::isfinite(dt)||dt<0||dt>.25||!Finite(motion.acceleration)||!Finite(motion.angularVelocity)||!Finite(motion.angularAcceleration)||!Finite(motion.origin)) {DiscardMotion("invalid_step_input");return;}
335 if(!Finite(body.pose)||!Finite(body.velocity)||!Finite(body.omega)) {body.pose=lastValidPose;DiscardMotion("invalid_body_before_step");return;}
336 if(dt==0) return;
340 body.sleeping=false;body.quietTime=0;
341 }
342 if(body.sleeping) return;
343 lastMotion=motion;
344 accumulator+=dt;
345 constexpr double fixed=1.0/240;
346 while(accumulator+1e-10>=fixed) {Step(fixed,motion);accumulator-=fixed;}
347 if(!Finite(body.pose)||!Finite(body.velocity)||!Finite(body.omega)) {body.pose=lastValidPose;DiscardMotion("invalid_body_after_step");}
349 }
350};
351}
Simulation(Hull shape, std::vector< Triangle > scene, Pose pose)
Definition RigidProp.h:314
void Correct(Vec normal, double amount, int triangle)
Definition RigidProp.h:211
static constexpr double Skin
Definition RigidProp.h:210
void Update(double dt, const Motion &motion)
Definition RigidProp.h:332
void DiscardMotion(const char *reason="discard")
Definition RigidProp.h:317
const std::vector< Triangle > & Scene() const
Definition RigidProp.h:316
unsigned sweepBudgetStops
Definition RigidProp.h:313
std::vector< Triangle > triangles
Definition RigidProp.h:206
void Step(double dt, const Motion &motion)
Definition RigidProp.h:241
const Hull & Shape() const
Definition RigidProp.h:315
void Contacts(std::vector< Contact > &contacts, std::vector< int > &active)
Definition RigidProp.h:218
void Solve(Body &b, std::vector< Contact > &contacts, const Material &material, double dt)
Definition RigidProp.h:159
Vec InverseInertia(const Body &b, Vec v)
Definition RigidProp.h:59
Vec Cross(Vec a, Vec b)
Definition RigidProp.h:23
Vec Support(const Hull &h, const Pose &p, Vec d)
Definition RigidProp.h:63
void Impulse(Body &b, Vec arm, Vec j)
Definition RigidProp.h:157
bool Near(const Body &b, const Triangle &t, double extra)
Definition RigidProp.h:141
double Length(Vec a)
Definition RigidProp.h:24
Distance Query(const Hull &h, const Pose &p, const Triangle &t)
Definition RigidProp.h:116
bool Inside(Vec p, const Triangle &t)
Definition RigidProp.h:147
Vec Reduce(std::vector< SupportPoint > &simplex, Vec &witness)
Definition RigidProp.h:76
double Mass(const Body &b, Vec r, Vec n)
Definition RigidProp.h:158
double Dot(Vec a, Vec b)
Definition RigidProp.h:22
bool Finite(Vec a)
Definition RigidProp.h:26
Vec Unit(Vec a)
Definition RigidProp.h:25
Vec Acceleration(const Body &b, const Motion &m)
Definition RigidProp.h:198
typedef void(S_CALLTYPE *SteamAPIWarningMessageHook_t)(int
double quietTime
Definition RigidProp.h:57
std::array< std::uint64_t, 3 > contactMask
Definition RigidProp.h:195
const char * recovery
Definition RigidProp.h:196
std::vector< Vec > vertices
Definition RigidProp.h:44
Vec Rotate(Vec v) const
Definition RigidProp.h:33
static Quat Axis(Vec axis, double angle)
Definition RigidProp.h:36
Quat operator*(Quat b) const
Definition RigidProp.h:29
Vec Unrotate(Vec v) const
Definition RigidProp.h:34
void Normalize()
Definition RigidProp.h:35
static Quat Ypr(double yaw, double pitch, double roll)
Definition RigidProp.h:39
Vec operator-(Vec b) const
Definition RigidProp.h:15
Vec & operator+=(Vec b)
Definition RigidProp.h:19
Vec operator*(double s) const
Definition RigidProp.h:17
Vec & operator-=(Vec b)
Definition RigidProp.h:20
Vec operator/(double s) const
Definition RigidProp.h:18
Vec operator+(Vec b) const
Definition RigidProp.h:14
Vec operator-() const
Definition RigidProp.h:16