btSoftBody.h 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. ///btSoftBody implementation by Nathanael Presson
  14. #ifndef _BT_SOFT_BODY_H
  15. #define _BT_SOFT_BODY_H
  16. #include "LinearMath/btAlignedObjectArray.h"
  17. #include "LinearMath/btTransform.h"
  18. #include "LinearMath/btIDebugDraw.h"
  19. #include "BulletDynamics/Dynamics/btRigidBody.h"
  20. #include "BulletCollision/CollisionShapes/btConcaveShape.h"
  21. #include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
  22. #include "btSparseSDF.h"
  23. #include "BulletCollision/BroadphaseCollision/btDbvt.h"
  24. //#ifdef BT_USE_DOUBLE_PRECISION
  25. //#define btRigidBodyData btRigidBodyDoubleData
  26. //#define btRigidBodyDataName "btRigidBodyDoubleData"
  27. //#else
  28. #define btSoftBodyData btSoftBodyFloatData
  29. #define btSoftBodyDataName "btSoftBodyFloatData"
  30. //#endif //BT_USE_DOUBLE_PRECISION
  31. class btBroadphaseInterface;
  32. class btDispatcher;
  33. class btSoftBodySolver;
  34. /* btSoftBodyWorldInfo */
  35. struct btSoftBodyWorldInfo
  36. {
  37. btScalar air_density;
  38. btScalar water_density;
  39. btScalar water_offset;
  40. btScalar m_maxDisplacement;
  41. btVector3 water_normal;
  42. btBroadphaseInterface* m_broadphase;
  43. btDispatcher* m_dispatcher;
  44. btVector3 m_gravity;
  45. btSparseSdf<3> m_sparsesdf;
  46. btSoftBodyWorldInfo()
  47. :air_density((btScalar)1.2),
  48. water_density(0),
  49. water_offset(0),
  50. m_maxDisplacement(1000.f),//avoid soft body from 'exploding' so use some upper threshold of maximum motion that a node can travel per frame
  51. water_normal(0,0,0),
  52. m_broadphase(0),
  53. m_dispatcher(0),
  54. m_gravity(0,-10,0)
  55. {
  56. }
  57. };
  58. ///The btSoftBody is an class to simulate cloth and volumetric soft bodies.
  59. ///There is two-way interaction between btSoftBody and btRigidBody/btCollisionObject.
  60. class btSoftBody : public btCollisionObject
  61. {
  62. public:
  63. btAlignedObjectArray<const class btCollisionObject*> m_collisionDisabledObjects;
  64. // The solver object that handles this soft body
  65. btSoftBodySolver *m_softBodySolver;
  66. //
  67. // Enumerations
  68. //
  69. ///eAeroModel
  70. struct eAeroModel { enum _ {
  71. V_Point, ///Vertex normals are oriented toward velocity
  72. V_TwoSided, ///Vertex normals are flipped to match velocity
  73. V_TwoSidedLiftDrag, ///Vertex normals are flipped to match velocity and lift and drag forces are applied
  74. V_OneSided, ///Vertex normals are taken as it is
  75. F_TwoSided, ///Face normals are flipped to match velocity
  76. F_TwoSidedLiftDrag, ///Face normals are flipped to match velocity and lift and drag forces are applied
  77. F_OneSided, ///Face normals are taken as it is
  78. END
  79. };};
  80. ///eVSolver : velocities solvers
  81. struct eVSolver { enum _ {
  82. Linear, ///Linear solver
  83. END
  84. };};
  85. ///ePSolver : positions solvers
  86. struct ePSolver { enum _ {
  87. Linear, ///Linear solver
  88. Anchors, ///Anchor solver
  89. RContacts, ///Rigid contacts solver
  90. SContacts, ///Soft contacts solver
  91. END
  92. };};
  93. ///eSolverPresets
  94. struct eSolverPresets { enum _ {
  95. Positions,
  96. Velocities,
  97. Default = Positions,
  98. END
  99. };};
  100. ///eFeature
  101. struct eFeature { enum _ {
  102. None,
  103. Node,
  104. Link,
  105. Face,
  106. Tetra,
  107. END
  108. };};
  109. typedef btAlignedObjectArray<eVSolver::_> tVSolverArray;
  110. typedef btAlignedObjectArray<ePSolver::_> tPSolverArray;
  111. //
  112. // Flags
  113. //
  114. ///fCollision
  115. struct fCollision { enum _ {
  116. RVSmask = 0x000f, ///Rigid versus soft mask
  117. SDF_RS = 0x0001, ///SDF based rigid vs soft
  118. CL_RS = 0x0002, ///Cluster vs convex rigid vs soft
  119. SVSmask = 0x0030, ///Rigid versus soft mask
  120. VF_SS = 0x0010, ///Vertex vs face soft vs soft handling
  121. CL_SS = 0x0020, ///Cluster vs cluster soft vs soft handling
  122. CL_SELF = 0x0040, ///Cluster soft body self collision
  123. /* presets */
  124. Default = SDF_RS,
  125. END
  126. };};
  127. ///fMaterial
  128. struct fMaterial { enum _ {
  129. DebugDraw = 0x0001, /// Enable debug draw
  130. /* presets */
  131. Default = DebugDraw,
  132. END
  133. };};
  134. //
  135. // API Types
  136. //
  137. /* sRayCast */
  138. struct sRayCast
  139. {
  140. btSoftBody* body; /// soft body
  141. eFeature::_ feature; /// feature type
  142. int index; /// feature index
  143. btScalar fraction; /// time of impact fraction (rayorg+(rayto-rayfrom)*fraction)
  144. };
  145. /* ImplicitFn */
  146. struct ImplicitFn
  147. {
  148. virtual ~ImplicitFn() {}
  149. virtual btScalar Eval(const btVector3& x)=0;
  150. };
  151. //
  152. // Internal types
  153. //
  154. typedef btAlignedObjectArray<btScalar> tScalarArray;
  155. typedef btAlignedObjectArray<btVector3> tVector3Array;
  156. /* sCti is Softbody contact info */
  157. struct sCti
  158. {
  159. const btCollisionObject* m_colObj; /* Rigid body */
  160. btVector3 m_normal; /* Outward normal */
  161. btScalar m_offset; /* Offset from origin */
  162. };
  163. /* sMedium */
  164. struct sMedium
  165. {
  166. btVector3 m_velocity; /* Velocity */
  167. btScalar m_pressure; /* Pressure */
  168. btScalar m_density; /* Density */
  169. };
  170. /* Base type */
  171. struct Element
  172. {
  173. void* m_tag; // User data
  174. Element() : m_tag(0) {}
  175. };
  176. /* Material */
  177. struct Material : Element
  178. {
  179. btScalar m_kLST; // Linear stiffness coefficient [0,1]
  180. btScalar m_kAST; // Area/Angular stiffness coefficient [0,1]
  181. btScalar m_kVST; // Volume stiffness coefficient [0,1]
  182. int m_flags; // Flags
  183. };
  184. /* Feature */
  185. struct Feature : Element
  186. {
  187. Material* m_material; // Material
  188. };
  189. /* Node */
  190. struct Node : Feature
  191. {
  192. btVector3 m_x; // Position
  193. btVector3 m_q; // Previous step position
  194. btVector3 m_v; // Velocity
  195. btVector3 m_f; // Force accumulator
  196. btVector3 m_n; // Normal
  197. btScalar m_im; // 1/mass
  198. btScalar m_area; // Area
  199. btDbvtNode* m_leaf; // Leaf data
  200. int m_battach:1; // Attached
  201. };
  202. /* Link */
  203. ATTRIBUTE_ALIGNED16(struct) Link : Feature
  204. {
  205. btVector3 m_c3; // gradient
  206. Node* m_n[2]; // Node pointers
  207. btScalar m_rl; // Rest length
  208. int m_bbending:1; // Bending link
  209. btScalar m_c0; // (ima+imb)*kLST
  210. btScalar m_c1; // rl^2
  211. btScalar m_c2; // |gradient|^2/c0
  212. BT_DECLARE_ALIGNED_ALLOCATOR();
  213. };
  214. /* Face */
  215. struct Face : Feature
  216. {
  217. Node* m_n[3]; // Node pointers
  218. btVector3 m_normal; // Normal
  219. btScalar m_ra; // Rest area
  220. btDbvtNode* m_leaf; // Leaf data
  221. };
  222. /* Tetra */
  223. struct Tetra : Feature
  224. {
  225. Node* m_n[4]; // Node pointers
  226. btScalar m_rv; // Rest volume
  227. btDbvtNode* m_leaf; // Leaf data
  228. btVector3 m_c0[4]; // gradients
  229. btScalar m_c1; // (4*kVST)/(im0+im1+im2+im3)
  230. btScalar m_c2; // m_c1/sum(|g0..3|^2)
  231. };
  232. /* RContact */
  233. struct RContact
  234. {
  235. sCti m_cti; // Contact infos
  236. Node* m_node; // Owner node
  237. btMatrix3x3 m_c0; // Impulse matrix
  238. btVector3 m_c1; // Relative anchor
  239. btScalar m_c2; // ima*dt
  240. btScalar m_c3; // Friction
  241. btScalar m_c4; // Hardness
  242. };
  243. /* SContact */
  244. struct SContact
  245. {
  246. Node* m_node; // Node
  247. Face* m_face; // Face
  248. btVector3 m_weights; // Weigths
  249. btVector3 m_normal; // Normal
  250. btScalar m_margin; // Margin
  251. btScalar m_friction; // Friction
  252. btScalar m_cfm[2]; // Constraint force mixing
  253. };
  254. /* Anchor */
  255. struct Anchor
  256. {
  257. Node* m_node; // Node pointer
  258. btVector3 m_local; // Anchor position in body space
  259. btRigidBody* m_body; // Body
  260. btScalar m_influence;
  261. btMatrix3x3 m_c0; // Impulse matrix
  262. btVector3 m_c1; // Relative anchor
  263. btScalar m_c2; // ima*dt
  264. };
  265. /* Note */
  266. struct Note : Element
  267. {
  268. const char* m_text; // Text
  269. btVector3 m_offset; // Offset
  270. int m_rank; // Rank
  271. Node* m_nodes[4]; // Nodes
  272. btScalar m_coords[4]; // Coordinates
  273. };
  274. /* Pose */
  275. struct Pose
  276. {
  277. bool m_bvolume; // Is valid
  278. bool m_bframe; // Is frame
  279. btScalar m_volume; // Rest volume
  280. tVector3Array m_pos; // Reference positions
  281. tScalarArray m_wgh; // Weights
  282. btVector3 m_com; // COM
  283. btMatrix3x3 m_rot; // Rotation
  284. btMatrix3x3 m_scl; // Scale
  285. btMatrix3x3 m_aqq; // Base scaling
  286. };
  287. /* Cluster */
  288. struct Cluster
  289. {
  290. tScalarArray m_masses;
  291. btAlignedObjectArray<Node*> m_nodes;
  292. tVector3Array m_framerefs;
  293. btTransform m_framexform;
  294. btScalar m_idmass;
  295. btScalar m_imass;
  296. btMatrix3x3 m_locii;
  297. btMatrix3x3 m_invwi;
  298. btVector3 m_com;
  299. btVector3 m_vimpulses[2];
  300. btVector3 m_dimpulses[2];
  301. int m_nvimpulses;
  302. int m_ndimpulses;
  303. btVector3 m_lv;
  304. btVector3 m_av;
  305. btDbvtNode* m_leaf;
  306. btScalar m_ndamping; /* Node damping */
  307. btScalar m_ldamping; /* Linear damping */
  308. btScalar m_adamping; /* Angular damping */
  309. btScalar m_matching;
  310. btScalar m_maxSelfCollisionImpulse;
  311. btScalar m_selfCollisionImpulseFactor;
  312. bool m_containsAnchor;
  313. bool m_collide;
  314. int m_clusterIndex;
  315. Cluster() : m_leaf(0),m_ndamping(0),m_ldamping(0),m_adamping(0),m_matching(0)
  316. ,m_maxSelfCollisionImpulse(100.f),
  317. m_selfCollisionImpulseFactor(0.01f),
  318. m_containsAnchor(false)
  319. {}
  320. };
  321. /* Impulse */
  322. struct Impulse
  323. {
  324. btVector3 m_velocity;
  325. btVector3 m_drift;
  326. int m_asVelocity:1;
  327. int m_asDrift:1;
  328. Impulse() : m_velocity(0,0,0),m_drift(0,0,0),m_asVelocity(0),m_asDrift(0) {}
  329. Impulse operator -() const
  330. {
  331. Impulse i=*this;
  332. i.m_velocity=-i.m_velocity;
  333. i.m_drift=-i.m_drift;
  334. return(i);
  335. }
  336. Impulse operator*(btScalar x) const
  337. {
  338. Impulse i=*this;
  339. i.m_velocity*=x;
  340. i.m_drift*=x;
  341. return(i);
  342. }
  343. };
  344. /* Body */
  345. struct Body
  346. {
  347. Cluster* m_soft;
  348. btRigidBody* m_rigid;
  349. const btCollisionObject* m_collisionObject;
  350. Body() : m_soft(0),m_rigid(0),m_collisionObject(0) {}
  351. Body(Cluster* p) : m_soft(p),m_rigid(0),m_collisionObject(0) {}
  352. Body(const btCollisionObject* colObj) : m_soft(0),m_collisionObject(colObj)
  353. {
  354. m_rigid = (btRigidBody*)btRigidBody::upcast(m_collisionObject);
  355. }
  356. void activate() const
  357. {
  358. if(m_rigid)
  359. m_rigid->activate();
  360. if (m_collisionObject)
  361. m_collisionObject->activate();
  362. }
  363. const btMatrix3x3& invWorldInertia() const
  364. {
  365. static const btMatrix3x3 iwi(0,0,0,0,0,0,0,0,0);
  366. if(m_rigid) return(m_rigid->getInvInertiaTensorWorld());
  367. if(m_soft) return(m_soft->m_invwi);
  368. return(iwi);
  369. }
  370. btScalar invMass() const
  371. {
  372. if(m_rigid) return(m_rigid->getInvMass());
  373. if(m_soft) return(m_soft->m_imass);
  374. return(0);
  375. }
  376. const btTransform& xform() const
  377. {
  378. static const btTransform identity=btTransform::getIdentity();
  379. if(m_collisionObject) return(m_collisionObject->getWorldTransform());
  380. if(m_soft) return(m_soft->m_framexform);
  381. return(identity);
  382. }
  383. btVector3 linearVelocity() const
  384. {
  385. if(m_rigid) return(m_rigid->getLinearVelocity());
  386. if(m_soft) return(m_soft->m_lv);
  387. return(btVector3(0,0,0));
  388. }
  389. btVector3 angularVelocity(const btVector3& rpos) const
  390. {
  391. if(m_rigid) return(btCross(m_rigid->getAngularVelocity(),rpos));
  392. if(m_soft) return(btCross(m_soft->m_av,rpos));
  393. return(btVector3(0,0,0));
  394. }
  395. btVector3 angularVelocity() const
  396. {
  397. if(m_rigid) return(m_rigid->getAngularVelocity());
  398. if(m_soft) return(m_soft->m_av);
  399. return(btVector3(0,0,0));
  400. }
  401. btVector3 velocity(const btVector3& rpos) const
  402. {
  403. return(linearVelocity()+angularVelocity(rpos));
  404. }
  405. void applyVImpulse(const btVector3& impulse,const btVector3& rpos) const
  406. {
  407. if(m_rigid) m_rigid->applyImpulse(impulse,rpos);
  408. if(m_soft) btSoftBody::clusterVImpulse(m_soft,rpos,impulse);
  409. }
  410. void applyDImpulse(const btVector3& impulse,const btVector3& rpos) const
  411. {
  412. if(m_rigid) m_rigid->applyImpulse(impulse,rpos);
  413. if(m_soft) btSoftBody::clusterDImpulse(m_soft,rpos,impulse);
  414. }
  415. void applyImpulse(const Impulse& impulse,const btVector3& rpos) const
  416. {
  417. if(impulse.m_asVelocity)
  418. {
  419. // printf("impulse.m_velocity = %f,%f,%f\n",impulse.m_velocity.getX(),impulse.m_velocity.getY(),impulse.m_velocity.getZ());
  420. applyVImpulse(impulse.m_velocity,rpos);
  421. }
  422. if(impulse.m_asDrift)
  423. {
  424. // printf("impulse.m_drift = %f,%f,%f\n",impulse.m_drift.getX(),impulse.m_drift.getY(),impulse.m_drift.getZ());
  425. applyDImpulse(impulse.m_drift,rpos);
  426. }
  427. }
  428. void applyVAImpulse(const btVector3& impulse) const
  429. {
  430. if(m_rigid) m_rigid->applyTorqueImpulse(impulse);
  431. if(m_soft) btSoftBody::clusterVAImpulse(m_soft,impulse);
  432. }
  433. void applyDAImpulse(const btVector3& impulse) const
  434. {
  435. if(m_rigid) m_rigid->applyTorqueImpulse(impulse);
  436. if(m_soft) btSoftBody::clusterDAImpulse(m_soft,impulse);
  437. }
  438. void applyAImpulse(const Impulse& impulse) const
  439. {
  440. if(impulse.m_asVelocity) applyVAImpulse(impulse.m_velocity);
  441. if(impulse.m_asDrift) applyDAImpulse(impulse.m_drift);
  442. }
  443. void applyDCImpulse(const btVector3& impulse) const
  444. {
  445. if(m_rigid) m_rigid->applyCentralImpulse(impulse);
  446. if(m_soft) btSoftBody::clusterDCImpulse(m_soft,impulse);
  447. }
  448. };
  449. /* Joint */
  450. struct Joint
  451. {
  452. struct eType { enum _ {
  453. Linear=0,
  454. Angular,
  455. Contact
  456. };};
  457. struct Specs
  458. {
  459. Specs() : erp(1),cfm(1),split(1) {}
  460. btScalar erp;
  461. btScalar cfm;
  462. btScalar split;
  463. };
  464. Body m_bodies[2];
  465. btVector3 m_refs[2];
  466. btScalar m_cfm;
  467. btScalar m_erp;
  468. btScalar m_split;
  469. btVector3 m_drift;
  470. btVector3 m_sdrift;
  471. btMatrix3x3 m_massmatrix;
  472. bool m_delete;
  473. virtual ~Joint() {}
  474. Joint() : m_delete(false) {}
  475. virtual void Prepare(btScalar dt,int iterations);
  476. virtual void Solve(btScalar dt,btScalar sor)=0;
  477. virtual void Terminate(btScalar dt)=0;
  478. virtual eType::_ Type() const=0;
  479. };
  480. /* LJoint */
  481. struct LJoint : Joint
  482. {
  483. struct Specs : Joint::Specs
  484. {
  485. btVector3 position;
  486. };
  487. btVector3 m_rpos[2];
  488. void Prepare(btScalar dt,int iterations);
  489. void Solve(btScalar dt,btScalar sor);
  490. void Terminate(btScalar dt);
  491. eType::_ Type() const { return(eType::Linear); }
  492. };
  493. /* AJoint */
  494. struct AJoint : Joint
  495. {
  496. struct IControl
  497. {
  498. virtual ~IControl() {}
  499. virtual void Prepare(AJoint*) {}
  500. virtual btScalar Speed(AJoint*,btScalar current) { return(current); }
  501. static IControl* Default() { static IControl def;return(&def); }
  502. };
  503. struct Specs : Joint::Specs
  504. {
  505. Specs() : icontrol(IControl::Default()) {}
  506. btVector3 axis;
  507. IControl* icontrol;
  508. };
  509. btVector3 m_axis[2];
  510. IControl* m_icontrol;
  511. void Prepare(btScalar dt,int iterations);
  512. void Solve(btScalar dt,btScalar sor);
  513. void Terminate(btScalar dt);
  514. eType::_ Type() const { return(eType::Angular); }
  515. };
  516. /* CJoint */
  517. struct CJoint : Joint
  518. {
  519. int m_life;
  520. int m_maxlife;
  521. btVector3 m_rpos[2];
  522. btVector3 m_normal;
  523. btScalar m_friction;
  524. void Prepare(btScalar dt,int iterations);
  525. void Solve(btScalar dt,btScalar sor);
  526. void Terminate(btScalar dt);
  527. eType::_ Type() const { return(eType::Contact); }
  528. };
  529. /* Config */
  530. struct Config
  531. {
  532. eAeroModel::_ aeromodel; // Aerodynamic model (default: V_Point)
  533. btScalar kVCF; // Velocities correction factor (Baumgarte)
  534. btScalar kDP; // Damping coefficient [0,1]
  535. btScalar kDG; // Drag coefficient [0,+inf]
  536. btScalar kLF; // Lift coefficient [0,+inf]
  537. btScalar kPR; // Pressure coefficient [-inf,+inf]
  538. btScalar kVC; // Volume conversation coefficient [0,+inf]
  539. btScalar kDF; // Dynamic friction coefficient [0,1]
  540. btScalar kMT; // Pose matching coefficient [0,1]
  541. btScalar kCHR; // Rigid contacts hardness [0,1]
  542. btScalar kKHR; // Kinetic contacts hardness [0,1]
  543. btScalar kSHR; // Soft contacts hardness [0,1]
  544. btScalar kAHR; // Anchors hardness [0,1]
  545. btScalar kSRHR_CL; // Soft vs rigid hardness [0,1] (cluster only)
  546. btScalar kSKHR_CL; // Soft vs kinetic hardness [0,1] (cluster only)
  547. btScalar kSSHR_CL; // Soft vs soft hardness [0,1] (cluster only)
  548. btScalar kSR_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
  549. btScalar kSK_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
  550. btScalar kSS_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
  551. btScalar maxvolume; // Maximum volume ratio for pose
  552. btScalar timescale; // Time scale
  553. int viterations; // Velocities solver iterations
  554. int piterations; // Positions solver iterations
  555. int diterations; // Drift solver iterations
  556. int citerations; // Cluster solver iterations
  557. int collisions; // Collisions flags
  558. tVSolverArray m_vsequence; // Velocity solvers sequence
  559. tPSolverArray m_psequence; // Position solvers sequence
  560. tPSolverArray m_dsequence; // Drift solvers sequence
  561. };
  562. /* SolverState */
  563. struct SolverState
  564. {
  565. btScalar sdt; // dt*timescale
  566. btScalar isdt; // 1/sdt
  567. btScalar velmrg; // velocity margin
  568. btScalar radmrg; // radial margin
  569. btScalar updmrg; // Update margin
  570. };
  571. /// RayFromToCaster takes a ray from, ray to (instead of direction!)
  572. struct RayFromToCaster : btDbvt::ICollide
  573. {
  574. btVector3 m_rayFrom;
  575. btVector3 m_rayTo;
  576. btVector3 m_rayNormalizedDirection;
  577. btScalar m_mint;
  578. Face* m_face;
  579. int m_tests;
  580. RayFromToCaster(const btVector3& rayFrom,const btVector3& rayTo,btScalar mxt);
  581. void Process(const btDbvtNode* leaf);
  582. static /*inline*/ btScalar rayFromToTriangle(const btVector3& rayFrom,
  583. const btVector3& rayTo,
  584. const btVector3& rayNormalizedDirection,
  585. const btVector3& a,
  586. const btVector3& b,
  587. const btVector3& c,
  588. btScalar maxt=SIMD_INFINITY);
  589. };
  590. //
  591. // Typedefs
  592. //
  593. typedef void (*psolver_t)(btSoftBody*,btScalar,btScalar);
  594. typedef void (*vsolver_t)(btSoftBody*,btScalar);
  595. typedef btAlignedObjectArray<Cluster*> tClusterArray;
  596. typedef btAlignedObjectArray<Note> tNoteArray;
  597. typedef btAlignedObjectArray<Node> tNodeArray;
  598. typedef btAlignedObjectArray<btDbvtNode*> tLeafArray;
  599. typedef btAlignedObjectArray<Link> tLinkArray;
  600. typedef btAlignedObjectArray<Face> tFaceArray;
  601. typedef btAlignedObjectArray<Tetra> tTetraArray;
  602. typedef btAlignedObjectArray<Anchor> tAnchorArray;
  603. typedef btAlignedObjectArray<RContact> tRContactArray;
  604. typedef btAlignedObjectArray<SContact> tSContactArray;
  605. typedef btAlignedObjectArray<Material*> tMaterialArray;
  606. typedef btAlignedObjectArray<Joint*> tJointArray;
  607. typedef btAlignedObjectArray<btSoftBody*> tSoftBodyArray;
  608. //
  609. // Fields
  610. //
  611. Config m_cfg; // Configuration
  612. SolverState m_sst; // Solver state
  613. Pose m_pose; // Pose
  614. void* m_tag; // User data
  615. btSoftBodyWorldInfo* m_worldInfo; // World info
  616. tNoteArray m_notes; // Notes
  617. tNodeArray m_nodes; // Nodes
  618. tLinkArray m_links; // Links
  619. tFaceArray m_faces; // Faces
  620. tTetraArray m_tetras; // Tetras
  621. tAnchorArray m_anchors; // Anchors
  622. tRContactArray m_rcontacts; // Rigid contacts
  623. tSContactArray m_scontacts; // Soft contacts
  624. tJointArray m_joints; // Joints
  625. tMaterialArray m_materials; // Materials
  626. btScalar m_timeacc; // Time accumulator
  627. btVector3 m_bounds[2]; // Spatial bounds
  628. bool m_bUpdateRtCst; // Update runtime constants
  629. btDbvt m_ndbvt; // Nodes tree
  630. btDbvt m_fdbvt; // Faces tree
  631. btDbvt m_cdbvt; // Clusters tree
  632. tClusterArray m_clusters; // Clusters
  633. btAlignedObjectArray<bool>m_clusterConnectivity;//cluster connectivity, for self-collision
  634. btTransform m_initialWorldTransform;
  635. btVector3 m_windVelocity;
  636. btScalar m_restLengthScale;
  637. //
  638. // Api
  639. //
  640. /* ctor */
  641. btSoftBody( btSoftBodyWorldInfo* worldInfo,int node_count, const btVector3* x, const btScalar* m);
  642. /* ctor */
  643. btSoftBody( btSoftBodyWorldInfo* worldInfo);
  644. void initDefaults();
  645. /* dtor */
  646. virtual ~btSoftBody();
  647. /* Check for existing link */
  648. btAlignedObjectArray<int> m_userIndexMapping;
  649. btSoftBodyWorldInfo* getWorldInfo()
  650. {
  651. return m_worldInfo;
  652. }
  653. ///@todo: avoid internal softbody shape hack and move collision code to collision library
  654. virtual void setCollisionShape(btCollisionShape* collisionShape)
  655. {
  656. }
  657. bool checkLink( int node0,
  658. int node1) const;
  659. bool checkLink( const Node* node0,
  660. const Node* node1) const;
  661. /* Check for existring face */
  662. bool checkFace( int node0,
  663. int node1,
  664. int node2) const;
  665. /* Append material */
  666. Material* appendMaterial();
  667. /* Append note */
  668. void appendNote( const char* text,
  669. const btVector3& o,
  670. const btVector4& c=btVector4(1,0,0,0),
  671. Node* n0=0,
  672. Node* n1=0,
  673. Node* n2=0,
  674. Node* n3=0);
  675. void appendNote( const char* text,
  676. const btVector3& o,
  677. Node* feature);
  678. void appendNote( const char* text,
  679. const btVector3& o,
  680. Link* feature);
  681. void appendNote( const char* text,
  682. const btVector3& o,
  683. Face* feature);
  684. /* Append node */
  685. void appendNode( const btVector3& x,btScalar m);
  686. /* Append link */
  687. void appendLink(int model=-1,Material* mat=0);
  688. void appendLink( int node0,
  689. int node1,
  690. Material* mat=0,
  691. bool bcheckexist=false);
  692. void appendLink( Node* node0,
  693. Node* node1,
  694. Material* mat=0,
  695. bool bcheckexist=false);
  696. /* Append face */
  697. void appendFace(int model=-1,Material* mat=0);
  698. void appendFace( int node0,
  699. int node1,
  700. int node2,
  701. Material* mat=0);
  702. void appendTetra(int model,Material* mat);
  703. //
  704. void appendTetra(int node0,
  705. int node1,
  706. int node2,
  707. int node3,
  708. Material* mat=0);
  709. /* Append anchor */
  710. void appendAnchor( int node,
  711. btRigidBody* body, bool disableCollisionBetweenLinkedBodies=false,btScalar influence = 1);
  712. void appendAnchor(int node,btRigidBody* body, const btVector3& localPivot,bool disableCollisionBetweenLinkedBodies=false,btScalar influence = 1);
  713. /* Append linear joint */
  714. void appendLinearJoint(const LJoint::Specs& specs,Cluster* body0,Body body1);
  715. void appendLinearJoint(const LJoint::Specs& specs,Body body=Body());
  716. void appendLinearJoint(const LJoint::Specs& specs,btSoftBody* body);
  717. /* Append linear joint */
  718. void appendAngularJoint(const AJoint::Specs& specs,Cluster* body0,Body body1);
  719. void appendAngularJoint(const AJoint::Specs& specs,Body body=Body());
  720. void appendAngularJoint(const AJoint::Specs& specs,btSoftBody* body);
  721. /* Add force (or gravity) to the entire body */
  722. void addForce( const btVector3& force);
  723. /* Add force (or gravity) to a node of the body */
  724. void addForce( const btVector3& force,
  725. int node);
  726. /* Add aero force to a node of the body */
  727. void addAeroForceToNode(const btVector3& windVelocity,int nodeIndex);
  728. /* Add aero force to a face of the body */
  729. void addAeroForceToFace(const btVector3& windVelocity,int faceIndex);
  730. /* Add velocity to the entire body */
  731. void addVelocity( const btVector3& velocity);
  732. /* Set velocity for the entire body */
  733. void setVelocity( const btVector3& velocity);
  734. /* Add velocity to a node of the body */
  735. void addVelocity( const btVector3& velocity,
  736. int node);
  737. /* Set mass */
  738. void setMass( int node,
  739. btScalar mass);
  740. /* Get mass */
  741. btScalar getMass( int node) const;
  742. /* Get total mass */
  743. btScalar getTotalMass() const;
  744. /* Set total mass (weighted by previous masses) */
  745. void setTotalMass( btScalar mass,
  746. bool fromfaces=false);
  747. /* Set total density */
  748. void setTotalDensity(btScalar density);
  749. /* Set volume mass (using tetrahedrons) */
  750. void setVolumeMass( btScalar mass);
  751. /* Set volume density (using tetrahedrons) */
  752. void setVolumeDensity( btScalar density);
  753. /* Transform */
  754. void transform( const btTransform& trs);
  755. /* Translate */
  756. void translate( const btVector3& trs);
  757. /* Rotate */
  758. void rotate( const btQuaternion& rot);
  759. /* Scale */
  760. void scale( const btVector3& scl);
  761. /* Get link resting lengths scale */
  762. btScalar getRestLengthScale();
  763. /* Scale resting length of all springs */
  764. void setRestLengthScale(btScalar restLength);
  765. /* Set current state as pose */
  766. void setPose( bool bvolume,
  767. bool bframe);
  768. /* Set current link lengths as resting lengths */
  769. void resetLinkRestLengths();
  770. /* Return the volume */
  771. btScalar getVolume() const;
  772. /* Cluster count */
  773. int clusterCount() const;
  774. /* Cluster center of mass */
  775. static btVector3 clusterCom(const Cluster* cluster);
  776. btVector3 clusterCom(int cluster) const;
  777. /* Cluster velocity at rpos */
  778. static btVector3 clusterVelocity(const Cluster* cluster,const btVector3& rpos);
  779. /* Cluster impulse */
  780. static void clusterVImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse);
  781. static void clusterDImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse);
  782. static void clusterImpulse(Cluster* cluster,const btVector3& rpos,const Impulse& impulse);
  783. static void clusterVAImpulse(Cluster* cluster,const btVector3& impulse);
  784. static void clusterDAImpulse(Cluster* cluster,const btVector3& impulse);
  785. static void clusterAImpulse(Cluster* cluster,const Impulse& impulse);
  786. static void clusterDCImpulse(Cluster* cluster,const btVector3& impulse);
  787. /* Generate bending constraints based on distance in the adjency graph */
  788. int generateBendingConstraints( int distance,
  789. Material* mat=0);
  790. /* Randomize constraints to reduce solver bias */
  791. void randomizeConstraints();
  792. /* Release clusters */
  793. void releaseCluster(int index);
  794. void releaseClusters();
  795. /* Generate clusters (K-mean) */
  796. ///generateClusters with k=0 will create a convex cluster for each tetrahedron or triangle
  797. ///otherwise an approximation will be used (better performance)
  798. int generateClusters(int k,int maxiterations=8192);
  799. /* Refine */
  800. void refine(ImplicitFn* ifn,btScalar accurary,bool cut);
  801. /* CutLink */
  802. bool cutLink(int node0,int node1,btScalar position);
  803. bool cutLink(const Node* node0,const Node* node1,btScalar position);
  804. ///Ray casting using rayFrom and rayTo in worldspace, (not direction!)
  805. bool rayTest(const btVector3& rayFrom,
  806. const btVector3& rayTo,
  807. sRayCast& results);
  808. /* Solver presets */
  809. void setSolver(eSolverPresets::_ preset);
  810. /* predictMotion */
  811. void predictMotion(btScalar dt);
  812. /* solveConstraints */
  813. void solveConstraints();
  814. /* staticSolve */
  815. void staticSolve(int iterations);
  816. /* solveCommonConstraints */
  817. static void solveCommonConstraints(btSoftBody** bodies,int count,int iterations);
  818. /* solveClusters */
  819. static void solveClusters(const btAlignedObjectArray<btSoftBody*>& bodies);
  820. /* integrateMotion */
  821. void integrateMotion();
  822. /* defaultCollisionHandlers */
  823. void defaultCollisionHandler(const btCollisionObjectWrapper* pcoWrap);
  824. void defaultCollisionHandler(btSoftBody* psb);
  825. //
  826. // Functionality to deal with new accelerated solvers.
  827. //
  828. /**
  829. * Set a wind velocity for interaction with the air.
  830. */
  831. void setWindVelocity( const btVector3 &velocity );
  832. /**
  833. * Return the wind velocity for interaction with the air.
  834. */
  835. const btVector3& getWindVelocity();
  836. //
  837. // Set the solver that handles this soft body
  838. // Should not be allowed to get out of sync with reality
  839. // Currently called internally on addition to the world
  840. void setSoftBodySolver( btSoftBodySolver *softBodySolver )
  841. {
  842. m_softBodySolver = softBodySolver;
  843. }
  844. //
  845. // Return the solver that handles this soft body
  846. //
  847. btSoftBodySolver *getSoftBodySolver()
  848. {
  849. return m_softBodySolver;
  850. }
  851. //
  852. // Return the solver that handles this soft body
  853. //
  854. btSoftBodySolver *getSoftBodySolver() const
  855. {
  856. return m_softBodySolver;
  857. }
  858. //
  859. // Cast
  860. //
  861. static const btSoftBody* upcast(const btCollisionObject* colObj)
  862. {
  863. if (colObj->getInternalType()==CO_SOFT_BODY)
  864. return (const btSoftBody*)colObj;
  865. return 0;
  866. }
  867. static btSoftBody* upcast(btCollisionObject* colObj)
  868. {
  869. if (colObj->getInternalType()==CO_SOFT_BODY)
  870. return (btSoftBody*)colObj;
  871. return 0;
  872. }
  873. //
  874. // ::btCollisionObject
  875. //
  876. virtual void getAabb(btVector3& aabbMin,btVector3& aabbMax) const
  877. {
  878. aabbMin = m_bounds[0];
  879. aabbMax = m_bounds[1];
  880. }
  881. //
  882. // Private
  883. //
  884. void pointersToIndices();
  885. void indicesToPointers(const int* map=0);
  886. int rayTest(const btVector3& rayFrom,const btVector3& rayTo,
  887. btScalar& mint,eFeature::_& feature,int& index,bool bcountonly) const;
  888. void initializeFaceTree();
  889. btVector3 evaluateCom() const;
  890. bool checkContact(const btCollisionObjectWrapper* colObjWrap,const btVector3& x,btScalar margin,btSoftBody::sCti& cti) const;
  891. void updateNormals();
  892. void updateBounds();
  893. void updatePose();
  894. void updateConstants();
  895. void updateLinkConstants();
  896. void updateArea(bool averageArea = true);
  897. void initializeClusters();
  898. void updateClusters();
  899. void cleanupClusters();
  900. void prepareClusters(int iterations);
  901. void solveClusters(btScalar sor);
  902. void applyClusters(bool drift);
  903. void dampClusters();
  904. void applyForces();
  905. static void PSolve_Anchors(btSoftBody* psb,btScalar kst,btScalar ti);
  906. static void PSolve_RContacts(btSoftBody* psb,btScalar kst,btScalar ti);
  907. static void PSolve_SContacts(btSoftBody* psb,btScalar,btScalar ti);
  908. static void PSolve_Links(btSoftBody* psb,btScalar kst,btScalar ti);
  909. static void VSolve_Links(btSoftBody* psb,btScalar kst);
  910. static psolver_t getSolver(ePSolver::_ solver);
  911. static vsolver_t getSolver(eVSolver::_ solver);
  912. virtual int calculateSerializeBufferSize() const;
  913. ///fills the dataBuffer and returns the struct name (and 0 on failure)
  914. virtual const char* serialize(void* dataBuffer, class btSerializer* serializer) const;
  915. //virtual void serializeSingleObject(class btSerializer* serializer) const;
  916. };
  917. #endif //_BT_SOFT_BODY_H