btSoftBody.h 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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 "LinearMath/btVector3.h"
  20. #include "BulletDynamics/Dynamics/btRigidBody.h"
  21. #include "BulletCollision/CollisionShapes/btConcaveShape.h"
  22. #include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
  23. #include "btSparseSDF.h"
  24. #include "BulletCollision/BroadphaseCollision/btDbvt.h"
  25. #include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
  26. #include "BulletDynamics/Featherstone/btMultiBodyConstraint.h"
  27. //#ifdef BT_USE_DOUBLE_PRECISION
  28. //#define btRigidBodyData btRigidBodyDoubleData
  29. //#define btRigidBodyDataName "btRigidBodyDoubleData"
  30. //#else
  31. #define btSoftBodyData btSoftBodyFloatData
  32. #define btSoftBodyDataName "btSoftBodyFloatData"
  33. static const btScalar OVERLAP_REDUCTION_FACTOR = 0.1;
  34. static unsigned long seed = 243703;
  35. //#endif //BT_USE_DOUBLE_PRECISION
  36. class btBroadphaseInterface;
  37. class btDispatcher;
  38. class btSoftBodySolver;
  39. /* btSoftBodyWorldInfo */
  40. struct btSoftBodyWorldInfo
  41. {
  42. btScalar air_density;
  43. btScalar water_density;
  44. btScalar water_offset;
  45. btScalar m_maxDisplacement;
  46. btVector3 water_normal;
  47. btBroadphaseInterface* m_broadphase;
  48. btDispatcher* m_dispatcher;
  49. btVector3 m_gravity;
  50. btSparseSdf<3> m_sparsesdf;
  51. btSoftBodyWorldInfo()
  52. : air_density((btScalar)1.2),
  53. water_density(0),
  54. water_offset(0),
  55. m_maxDisplacement(1000.f), //avoid soft body from 'exploding' so use some upper threshold of maximum motion that a node can travel per frame
  56. water_normal(0, 0, 0),
  57. m_broadphase(0),
  58. m_dispatcher(0),
  59. m_gravity(0, -10, 0)
  60. {
  61. }
  62. };
  63. ///The btSoftBody is an class to simulate cloth and volumetric soft bodies.
  64. ///There is two-way interaction between btSoftBody and btRigidBody/btCollisionObject.
  65. class btSoftBody : public btCollisionObject
  66. {
  67. public:
  68. btAlignedObjectArray<const class btCollisionObject*> m_collisionDisabledObjects;
  69. // The solver object that handles this soft body
  70. btSoftBodySolver* m_softBodySolver;
  71. //
  72. // Enumerations
  73. //
  74. ///eAeroModel
  75. struct eAeroModel
  76. {
  77. enum _
  78. {
  79. V_Point, ///Vertex normals are oriented toward velocity
  80. V_TwoSided, ///Vertex normals are flipped to match velocity
  81. V_TwoSidedLiftDrag, ///Vertex normals are flipped to match velocity and lift and drag forces are applied
  82. V_OneSided, ///Vertex normals are taken as it is
  83. F_TwoSided, ///Face normals are flipped to match velocity
  84. F_TwoSidedLiftDrag, ///Face normals are flipped to match velocity and lift and drag forces are applied
  85. F_OneSided, ///Face normals are taken as it is
  86. END
  87. };
  88. };
  89. ///eVSolver : velocities solvers
  90. struct eVSolver
  91. {
  92. enum _
  93. {
  94. Linear, ///Linear solver
  95. END
  96. };
  97. };
  98. ///ePSolver : positions solvers
  99. struct ePSolver
  100. {
  101. enum _
  102. {
  103. Linear, ///Linear solver
  104. Anchors, ///Anchor solver
  105. RContacts, ///Rigid contacts solver
  106. SContacts, ///Soft contacts solver
  107. END
  108. };
  109. };
  110. ///eSolverPresets
  111. struct eSolverPresets
  112. {
  113. enum _
  114. {
  115. Positions,
  116. Velocities,
  117. Default = Positions,
  118. END
  119. };
  120. };
  121. ///eFeature
  122. struct eFeature
  123. {
  124. enum _
  125. {
  126. None,
  127. Node,
  128. Link,
  129. Face,
  130. Tetra,
  131. END
  132. };
  133. };
  134. typedef btAlignedObjectArray<eVSolver::_> tVSolverArray;
  135. typedef btAlignedObjectArray<ePSolver::_> tPSolverArray;
  136. //
  137. // Flags
  138. //
  139. ///fCollision
  140. struct fCollision
  141. {
  142. enum _
  143. {
  144. RVSmask = 0x000f, ///Rigid versus soft mask
  145. SDF_RS = 0x0001, ///SDF based rigid vs soft
  146. CL_RS = 0x0002, ///Cluster vs convex rigid vs soft
  147. SDF_RD = 0x0004, ///rigid vs deformable
  148. SVSmask = 0x00f0, ///Rigid versus soft mask
  149. VF_SS = 0x0010, ///Vertex vs face soft vs soft handling
  150. CL_SS = 0x0020, ///Cluster vs cluster soft vs soft handling
  151. CL_SELF = 0x0040, ///Cluster soft body self collision
  152. VF_DD = 0x0080, ///Vertex vs face soft vs soft handling
  153. RVDFmask = 0x0f00, /// Rigid versus deformable face mask
  154. SDF_RDF = 0x0100, /// GJK based Rigid vs. deformable face
  155. SDF_MDF = 0x0200, /// GJK based Multibody vs. deformable face
  156. SDF_RDN = 0x0400, /// SDF based Rigid vs. deformable node
  157. /* presets */
  158. Default = SDF_RS,
  159. END
  160. };
  161. };
  162. ///fMaterial
  163. struct fMaterial
  164. {
  165. enum _
  166. {
  167. DebugDraw = 0x0001, /// Enable debug draw
  168. /* presets */
  169. Default = DebugDraw,
  170. END
  171. };
  172. };
  173. //
  174. // API Types
  175. //
  176. /* sRayCast */
  177. struct sRayCast
  178. {
  179. btSoftBody* body; /// soft body
  180. eFeature::_ feature; /// feature type
  181. int index; /// feature index
  182. btScalar fraction; /// time of impact fraction (rayorg+(rayto-rayfrom)*fraction)
  183. };
  184. /* ImplicitFn */
  185. struct ImplicitFn
  186. {
  187. virtual ~ImplicitFn() {}
  188. virtual btScalar Eval(const btVector3& x) = 0;
  189. };
  190. //
  191. // Internal types
  192. //
  193. typedef btAlignedObjectArray<btScalar> tScalarArray;
  194. typedef btAlignedObjectArray<btVector3> tVector3Array;
  195. /* sCti is Softbody contact info */
  196. struct sCti
  197. {
  198. const btCollisionObject* m_colObj; /* Rigid body */
  199. btVector3 m_normal; /* Outward normal */
  200. btScalar m_offset; /* Offset from origin */
  201. btVector3 m_bary; /* Barycentric weights for faces */
  202. };
  203. /* sMedium */
  204. struct sMedium
  205. {
  206. btVector3 m_velocity; /* Velocity */
  207. btScalar m_pressure; /* Pressure */
  208. btScalar m_density; /* Density */
  209. };
  210. /* Base type */
  211. struct Element
  212. {
  213. void* m_tag; // User data
  214. Element() : m_tag(0) {}
  215. };
  216. /* Material */
  217. struct Material : Element
  218. {
  219. btScalar m_kLST; // Linear stiffness coefficient [0,1]
  220. btScalar m_kAST; // Area/Angular stiffness coefficient [0,1]
  221. btScalar m_kVST; // Volume stiffness coefficient [0,1]
  222. int m_flags; // Flags
  223. };
  224. /* Feature */
  225. struct Feature : Element
  226. {
  227. Material* m_material; // Material
  228. };
  229. /* Node */
  230. struct RenderNode
  231. {
  232. btVector3 m_x;
  233. btVector3 m_uv1;
  234. btVector3 m_normal;
  235. };
  236. struct Node : Feature
  237. {
  238. btVector3 m_x; // Position
  239. btVector3 m_q; // Previous step position/Test position
  240. btVector3 m_v; // Velocity
  241. btVector3 m_vn; // Previous step velocity
  242. btVector3 m_f; // Force accumulator
  243. btVector3 m_n; // Normal
  244. btScalar m_im; // 1/mass
  245. btScalar m_area; // Area
  246. btDbvtNode* m_leaf; // Leaf data
  247. int m_constrained; // depth of penetration
  248. int m_battach : 1; // Attached
  249. int index;
  250. btVector3 m_splitv; // velocity associated with split impulse
  251. btMatrix3x3 m_effectiveMass; // effective mass in contact
  252. btMatrix3x3 m_effectiveMass_inv; // inverse of effective mass
  253. };
  254. /* Link */
  255. ATTRIBUTE_ALIGNED16(struct)
  256. Link : Feature
  257. {
  258. btVector3 m_c3; // gradient
  259. Node* m_n[2]; // Node pointers
  260. btScalar m_rl; // Rest length
  261. int m_bbending : 1; // Bending link
  262. btScalar m_c0; // (ima+imb)*kLST
  263. btScalar m_c1; // rl^2
  264. btScalar m_c2; // |gradient|^2/c0
  265. BT_DECLARE_ALIGNED_ALLOCATOR();
  266. };
  267. struct RenderFace
  268. {
  269. RenderNode* m_n[3]; // Node pointers
  270. };
  271. /* Face */
  272. struct Face : Feature
  273. {
  274. Node* m_n[3]; // Node pointers
  275. btVector3 m_normal; // Normal
  276. btScalar m_ra; // Rest area
  277. btDbvtNode* m_leaf; // Leaf data
  278. btVector4 m_pcontact; // barycentric weights of the persistent contact
  279. btVector3 m_n0, m_n1, m_vn;
  280. int m_index;
  281. };
  282. /* Tetra */
  283. struct Tetra : Feature
  284. {
  285. Node* m_n[4]; // Node pointers
  286. btScalar m_rv; // Rest volume
  287. btDbvtNode* m_leaf; // Leaf data
  288. btVector3 m_c0[4]; // gradients
  289. btScalar m_c1; // (4*kVST)/(im0+im1+im2+im3)
  290. btScalar m_c2; // m_c1/sum(|g0..3|^2)
  291. btMatrix3x3 m_Dm_inverse; // rest Dm^-1
  292. btMatrix3x3 m_F;
  293. btScalar m_element_measure;
  294. btVector4 m_P_inv[3]; // first three columns of P_inv matrix
  295. };
  296. /* TetraScratch */
  297. struct TetraScratch
  298. {
  299. btMatrix3x3 m_F; // deformation gradient F
  300. btScalar m_trace; // trace of F^T * F
  301. btScalar m_J; // det(F)
  302. btMatrix3x3 m_cofF; // cofactor of F
  303. btMatrix3x3 m_corotation; // corotatio of the tetra
  304. };
  305. /* RContact */
  306. struct RContact
  307. {
  308. sCti m_cti; // Contact infos
  309. Node* m_node; // Owner node
  310. btMatrix3x3 m_c0; // Impulse matrix
  311. btVector3 m_c1; // Relative anchor
  312. btScalar m_c2; // ima*dt
  313. btScalar m_c3; // Friction
  314. btScalar m_c4; // Hardness
  315. // jacobians and unit impulse responses for multibody
  316. btMultiBodyJacobianData jacobianData_normal;
  317. btMultiBodyJacobianData jacobianData_t1;
  318. btMultiBodyJacobianData jacobianData_t2;
  319. btVector3 t1;
  320. btVector3 t2;
  321. };
  322. class DeformableRigidContact
  323. {
  324. public:
  325. sCti m_cti; // Contact infos
  326. btMatrix3x3 m_c0; // Impulse matrix
  327. btVector3 m_c1; // Relative anchor
  328. btScalar m_c2; // inverse mass of node/face
  329. btScalar m_c3; // Friction
  330. btScalar m_c4; // Hardness
  331. btMatrix3x3 m_c5; // inverse effective mass
  332. // jacobians and unit impulse responses for multibody
  333. btMultiBodyJacobianData jacobianData_normal;
  334. btMultiBodyJacobianData jacobianData_t1;
  335. btMultiBodyJacobianData jacobianData_t2;
  336. btVector3 t1;
  337. btVector3 t2;
  338. };
  339. class DeformableNodeRigidContact : public DeformableRigidContact
  340. {
  341. public:
  342. Node* m_node; // Owner node
  343. };
  344. class DeformableNodeRigidAnchor : public DeformableNodeRigidContact
  345. {
  346. public:
  347. btVector3 m_local; // Anchor position in body space
  348. };
  349. class DeformableFaceRigidContact : public DeformableRigidContact
  350. {
  351. public:
  352. Face* m_face; // Owner face
  353. btVector3 m_contactPoint; // Contact point
  354. btVector3 m_bary; // Barycentric weights
  355. btVector3 m_weights; // v_contactPoint * m_weights[i] = m_face->m_node[i]->m_v;
  356. };
  357. struct DeformableFaceNodeContact
  358. {
  359. Node* m_node; // Node
  360. Face* m_face; // Face
  361. btVector3 m_bary; // Barycentric weights
  362. btVector3 m_weights; // v_contactPoint * m_weights[i] = m_face->m_node[i]->m_v;
  363. btVector3 m_normal; // Normal
  364. btScalar m_margin; // Margin
  365. btScalar m_friction; // Friction
  366. btScalar m_imf; // inverse mass of the face at contact point
  367. btScalar m_c0; // scale of the impulse matrix;
  368. };
  369. /* SContact */
  370. struct SContact
  371. {
  372. Node* m_node; // Node
  373. Face* m_face; // Face
  374. btVector3 m_weights; // Weigths
  375. btVector3 m_normal; // Normal
  376. btScalar m_margin; // Margin
  377. btScalar m_friction; // Friction
  378. btScalar m_cfm[2]; // Constraint force mixing
  379. };
  380. /* Anchor */
  381. struct Anchor
  382. {
  383. Node* m_node; // Node pointer
  384. btVector3 m_local; // Anchor position in body space
  385. btRigidBody* m_body; // Body
  386. btScalar m_influence;
  387. btMatrix3x3 m_c0; // Impulse matrix
  388. btVector3 m_c1; // Relative anchor
  389. btScalar m_c2; // ima*dt
  390. };
  391. /* Note */
  392. struct Note : Element
  393. {
  394. const char* m_text; // Text
  395. btVector3 m_offset; // Offset
  396. int m_rank; // Rank
  397. Node* m_nodes[4]; // Nodes
  398. btScalar m_coords[4]; // Coordinates
  399. };
  400. /* Pose */
  401. struct Pose
  402. {
  403. bool m_bvolume; // Is valid
  404. bool m_bframe; // Is frame
  405. btScalar m_volume; // Rest volume
  406. tVector3Array m_pos; // Reference positions
  407. tScalarArray m_wgh; // Weights
  408. btVector3 m_com; // COM
  409. btMatrix3x3 m_rot; // Rotation
  410. btMatrix3x3 m_scl; // Scale
  411. btMatrix3x3 m_aqq; // Base scaling
  412. };
  413. /* Cluster */
  414. struct Cluster
  415. {
  416. tScalarArray m_masses;
  417. btAlignedObjectArray<Node*> m_nodes;
  418. tVector3Array m_framerefs;
  419. btTransform m_framexform;
  420. btScalar m_idmass;
  421. btScalar m_imass;
  422. btMatrix3x3 m_locii;
  423. btMatrix3x3 m_invwi;
  424. btVector3 m_com;
  425. btVector3 m_vimpulses[2];
  426. btVector3 m_dimpulses[2];
  427. int m_nvimpulses;
  428. int m_ndimpulses;
  429. btVector3 m_lv;
  430. btVector3 m_av;
  431. btDbvtNode* m_leaf;
  432. btScalar m_ndamping; /* Node damping */
  433. btScalar m_ldamping; /* Linear damping */
  434. btScalar m_adamping; /* Angular damping */
  435. btScalar m_matching;
  436. btScalar m_maxSelfCollisionImpulse;
  437. btScalar m_selfCollisionImpulseFactor;
  438. bool m_containsAnchor;
  439. bool m_collide;
  440. int m_clusterIndex;
  441. Cluster() : m_leaf(0), m_ndamping(0), m_ldamping(0), m_adamping(0), m_matching(0), m_maxSelfCollisionImpulse(100.f), m_selfCollisionImpulseFactor(0.01f), m_containsAnchor(false)
  442. {
  443. }
  444. };
  445. /* Impulse */
  446. struct Impulse
  447. {
  448. btVector3 m_velocity;
  449. btVector3 m_drift;
  450. int m_asVelocity : 1;
  451. int m_asDrift : 1;
  452. Impulse() : m_velocity(0, 0, 0), m_drift(0, 0, 0), m_asVelocity(0), m_asDrift(0) {}
  453. Impulse operator-() const
  454. {
  455. Impulse i = *this;
  456. i.m_velocity = -i.m_velocity;
  457. i.m_drift = -i.m_drift;
  458. return (i);
  459. }
  460. Impulse operator*(btScalar x) const
  461. {
  462. Impulse i = *this;
  463. i.m_velocity *= x;
  464. i.m_drift *= x;
  465. return (i);
  466. }
  467. };
  468. /* Body */
  469. struct Body
  470. {
  471. Cluster* m_soft;
  472. btRigidBody* m_rigid;
  473. const btCollisionObject* m_collisionObject;
  474. Body() : m_soft(0), m_rigid(0), m_collisionObject(0) {}
  475. Body(Cluster* p) : m_soft(p), m_rigid(0), m_collisionObject(0) {}
  476. Body(const btCollisionObject* colObj) : m_soft(0), m_collisionObject(colObj)
  477. {
  478. m_rigid = (btRigidBody*)btRigidBody::upcast(m_collisionObject);
  479. }
  480. void activate() const
  481. {
  482. if (m_rigid)
  483. m_rigid->activate();
  484. if (m_collisionObject)
  485. m_collisionObject->activate();
  486. }
  487. const btMatrix3x3& invWorldInertia() const
  488. {
  489. static const btMatrix3x3 iwi(0, 0, 0, 0, 0, 0, 0, 0, 0);
  490. if (m_rigid) return (m_rigid->getInvInertiaTensorWorld());
  491. if (m_soft) return (m_soft->m_invwi);
  492. return (iwi);
  493. }
  494. btScalar invMass() const
  495. {
  496. if (m_rigid) return (m_rigid->getInvMass());
  497. if (m_soft) return (m_soft->m_imass);
  498. return (0);
  499. }
  500. const btTransform& xform() const
  501. {
  502. static const btTransform identity = btTransform::getIdentity();
  503. if (m_collisionObject) return (m_collisionObject->getWorldTransform());
  504. if (m_soft) return (m_soft->m_framexform);
  505. return (identity);
  506. }
  507. btVector3 linearVelocity() const
  508. {
  509. if (m_rigid) return (m_rigid->getLinearVelocity());
  510. if (m_soft) return (m_soft->m_lv);
  511. return (btVector3(0, 0, 0));
  512. }
  513. btVector3 angularVelocity(const btVector3& rpos) const
  514. {
  515. if (m_rigid) return (btCross(m_rigid->getAngularVelocity(), rpos));
  516. if (m_soft) return (btCross(m_soft->m_av, rpos));
  517. return (btVector3(0, 0, 0));
  518. }
  519. btVector3 angularVelocity() const
  520. {
  521. if (m_rigid) return (m_rigid->getAngularVelocity());
  522. if (m_soft) return (m_soft->m_av);
  523. return (btVector3(0, 0, 0));
  524. }
  525. btVector3 velocity(const btVector3& rpos) const
  526. {
  527. return (linearVelocity() + angularVelocity(rpos));
  528. }
  529. void applyVImpulse(const btVector3& impulse, const btVector3& rpos) const
  530. {
  531. if (m_rigid) m_rigid->applyImpulse(impulse, rpos);
  532. if (m_soft) btSoftBody::clusterVImpulse(m_soft, rpos, impulse);
  533. }
  534. void applyDImpulse(const btVector3& impulse, const btVector3& rpos) const
  535. {
  536. if (m_rigid) m_rigid->applyImpulse(impulse, rpos);
  537. if (m_soft) btSoftBody::clusterDImpulse(m_soft, rpos, impulse);
  538. }
  539. void applyImpulse(const Impulse& impulse, const btVector3& rpos) const
  540. {
  541. if (impulse.m_asVelocity)
  542. {
  543. // printf("impulse.m_velocity = %f,%f,%f\n",impulse.m_velocity.getX(),impulse.m_velocity.getY(),impulse.m_velocity.getZ());
  544. applyVImpulse(impulse.m_velocity, rpos);
  545. }
  546. if (impulse.m_asDrift)
  547. {
  548. // printf("impulse.m_drift = %f,%f,%f\n",impulse.m_drift.getX(),impulse.m_drift.getY(),impulse.m_drift.getZ());
  549. applyDImpulse(impulse.m_drift, rpos);
  550. }
  551. }
  552. void applyVAImpulse(const btVector3& impulse) const
  553. {
  554. if (m_rigid) m_rigid->applyTorqueImpulse(impulse);
  555. if (m_soft) btSoftBody::clusterVAImpulse(m_soft, impulse);
  556. }
  557. void applyDAImpulse(const btVector3& impulse) const
  558. {
  559. if (m_rigid) m_rigid->applyTorqueImpulse(impulse);
  560. if (m_soft) btSoftBody::clusterDAImpulse(m_soft, impulse);
  561. }
  562. void applyAImpulse(const Impulse& impulse) const
  563. {
  564. if (impulse.m_asVelocity) applyVAImpulse(impulse.m_velocity);
  565. if (impulse.m_asDrift) applyDAImpulse(impulse.m_drift);
  566. }
  567. void applyDCImpulse(const btVector3& impulse) const
  568. {
  569. if (m_rigid) m_rigid->applyCentralImpulse(impulse);
  570. if (m_soft) btSoftBody::clusterDCImpulse(m_soft, impulse);
  571. }
  572. };
  573. /* Joint */
  574. struct Joint
  575. {
  576. struct eType
  577. {
  578. enum _
  579. {
  580. Linear = 0,
  581. Angular,
  582. Contact
  583. };
  584. };
  585. struct Specs
  586. {
  587. Specs() : erp(1), cfm(1), split(1) {}
  588. btScalar erp;
  589. btScalar cfm;
  590. btScalar split;
  591. };
  592. Body m_bodies[2];
  593. btVector3 m_refs[2];
  594. btScalar m_cfm;
  595. btScalar m_erp;
  596. btScalar m_split;
  597. btVector3 m_drift;
  598. btVector3 m_sdrift;
  599. btMatrix3x3 m_massmatrix;
  600. bool m_delete;
  601. virtual ~Joint() {}
  602. Joint() : m_delete(false) {}
  603. virtual void Prepare(btScalar dt, int iterations);
  604. virtual void Solve(btScalar dt, btScalar sor) = 0;
  605. virtual void Terminate(btScalar dt) = 0;
  606. virtual eType::_ Type() const = 0;
  607. };
  608. /* LJoint */
  609. struct LJoint : Joint
  610. {
  611. struct Specs : Joint::Specs
  612. {
  613. btVector3 position;
  614. };
  615. btVector3 m_rpos[2];
  616. void Prepare(btScalar dt, int iterations);
  617. void Solve(btScalar dt, btScalar sor);
  618. void Terminate(btScalar dt);
  619. eType::_ Type() const { return (eType::Linear); }
  620. };
  621. /* AJoint */
  622. struct AJoint : Joint
  623. {
  624. struct IControl
  625. {
  626. virtual ~IControl() {}
  627. virtual void Prepare(AJoint*) {}
  628. virtual btScalar Speed(AJoint*, btScalar current) { return (current); }
  629. static IControl* Default()
  630. {
  631. static IControl def;
  632. return (&def);
  633. }
  634. };
  635. struct Specs : Joint::Specs
  636. {
  637. Specs() : icontrol(IControl::Default()) {}
  638. btVector3 axis;
  639. IControl* icontrol;
  640. };
  641. btVector3 m_axis[2];
  642. IControl* m_icontrol;
  643. void Prepare(btScalar dt, int iterations);
  644. void Solve(btScalar dt, btScalar sor);
  645. void Terminate(btScalar dt);
  646. eType::_ Type() const { return (eType::Angular); }
  647. };
  648. /* CJoint */
  649. struct CJoint : Joint
  650. {
  651. int m_life;
  652. int m_maxlife;
  653. btVector3 m_rpos[2];
  654. btVector3 m_normal;
  655. btScalar m_friction;
  656. void Prepare(btScalar dt, int iterations);
  657. void Solve(btScalar dt, btScalar sor);
  658. void Terminate(btScalar dt);
  659. eType::_ Type() const { return (eType::Contact); }
  660. };
  661. /* Config */
  662. struct Config
  663. {
  664. eAeroModel::_ aeromodel; // Aerodynamic model (default: V_Point)
  665. btScalar kVCF; // Velocities correction factor (Baumgarte)
  666. btScalar kDP; // Damping coefficient [0,1]
  667. btScalar kDG; // Drag coefficient [0,+inf]
  668. btScalar kLF; // Lift coefficient [0,+inf]
  669. btScalar kPR; // Pressure coefficient [-inf,+inf]
  670. btScalar kVC; // Volume conversation coefficient [0,+inf]
  671. btScalar kDF; // Dynamic friction coefficient [0,1]
  672. btScalar kMT; // Pose matching coefficient [0,1]
  673. btScalar kCHR; // Rigid contacts hardness [0,1]
  674. btScalar kKHR; // Kinetic contacts hardness [0,1]
  675. btScalar kSHR; // Soft contacts hardness [0,1]
  676. btScalar kAHR; // Anchors hardness [0,1]
  677. btScalar kSRHR_CL; // Soft vs rigid hardness [0,1] (cluster only)
  678. btScalar kSKHR_CL; // Soft vs kinetic hardness [0,1] (cluster only)
  679. btScalar kSSHR_CL; // Soft vs soft hardness [0,1] (cluster only)
  680. btScalar kSR_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
  681. btScalar kSK_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
  682. btScalar kSS_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
  683. btScalar maxvolume; // Maximum volume ratio for pose
  684. btScalar timescale; // Time scale
  685. int viterations; // Velocities solver iterations
  686. int piterations; // Positions solver iterations
  687. int diterations; // Drift solver iterations
  688. int citerations; // Cluster solver iterations
  689. int collisions; // Collisions flags
  690. tVSolverArray m_vsequence; // Velocity solvers sequence
  691. tPSolverArray m_psequence; // Position solvers sequence
  692. tPSolverArray m_dsequence; // Drift solvers sequence
  693. btScalar drag; // deformable air drag
  694. btScalar m_maxStress; // Maximum principle first Piola stress
  695. };
  696. /* SolverState */
  697. struct SolverState
  698. {
  699. //if you add new variables, always initialize them!
  700. SolverState()
  701. : sdt(0),
  702. isdt(0),
  703. velmrg(0),
  704. radmrg(0),
  705. updmrg(0)
  706. {
  707. }
  708. btScalar sdt; // dt*timescale
  709. btScalar isdt; // 1/sdt
  710. btScalar velmrg; // velocity margin
  711. btScalar radmrg; // radial margin
  712. btScalar updmrg; // Update margin
  713. };
  714. /// RayFromToCaster takes a ray from, ray to (instead of direction!)
  715. struct RayFromToCaster : btDbvt::ICollide
  716. {
  717. btVector3 m_rayFrom;
  718. btVector3 m_rayTo;
  719. btVector3 m_rayNormalizedDirection;
  720. btScalar m_mint;
  721. Face* m_face;
  722. int m_tests;
  723. RayFromToCaster(const btVector3& rayFrom, const btVector3& rayTo, btScalar mxt);
  724. void Process(const btDbvtNode* leaf);
  725. static /*inline*/ btScalar rayFromToTriangle(const btVector3& rayFrom,
  726. const btVector3& rayTo,
  727. const btVector3& rayNormalizedDirection,
  728. const btVector3& a,
  729. const btVector3& b,
  730. const btVector3& c,
  731. btScalar maxt = SIMD_INFINITY);
  732. };
  733. //
  734. // Typedefs
  735. //
  736. typedef void (*psolver_t)(btSoftBody*, btScalar, btScalar);
  737. typedef void (*vsolver_t)(btSoftBody*, btScalar);
  738. typedef btAlignedObjectArray<Cluster*> tClusterArray;
  739. typedef btAlignedObjectArray<Note> tNoteArray;
  740. typedef btAlignedObjectArray<Node> tNodeArray;
  741. typedef btAlignedObjectArray< RenderNode> tRenderNodeArray;
  742. typedef btAlignedObjectArray<btDbvtNode*> tLeafArray;
  743. typedef btAlignedObjectArray<Link> tLinkArray;
  744. typedef btAlignedObjectArray<Face> tFaceArray;
  745. typedef btAlignedObjectArray<RenderFace> tRenderFaceArray;
  746. typedef btAlignedObjectArray<Tetra> tTetraArray;
  747. typedef btAlignedObjectArray<Anchor> tAnchorArray;
  748. typedef btAlignedObjectArray<RContact> tRContactArray;
  749. typedef btAlignedObjectArray<SContact> tSContactArray;
  750. typedef btAlignedObjectArray<Material*> tMaterialArray;
  751. typedef btAlignedObjectArray<Joint*> tJointArray;
  752. typedef btAlignedObjectArray<btSoftBody*> tSoftBodyArray;
  753. //
  754. // Fields
  755. //
  756. Config m_cfg; // Configuration
  757. SolverState m_sst; // Solver state
  758. Pose m_pose; // Pose
  759. void* m_tag; // User data
  760. btSoftBodyWorldInfo* m_worldInfo; // World info
  761. tNoteArray m_notes; // Notes
  762. tNodeArray m_nodes; // Nodes
  763. tRenderNodeArray m_renderNodes; // Render Nodes
  764. tLinkArray m_links; // Links
  765. tFaceArray m_faces; // Faces
  766. tRenderFaceArray m_renderFaces; // Faces
  767. tTetraArray m_tetras; // Tetras
  768. btAlignedObjectArray<TetraScratch> m_tetraScratches;
  769. btAlignedObjectArray<TetraScratch> m_tetraScratchesTn;
  770. tAnchorArray m_anchors; // Anchors
  771. btAlignedObjectArray<DeformableNodeRigidAnchor> m_deformableAnchors;
  772. tRContactArray m_rcontacts; // Rigid contacts
  773. btAlignedObjectArray<DeformableNodeRigidContact> m_nodeRigidContacts;
  774. btAlignedObjectArray<DeformableFaceNodeContact> m_faceNodeContacts;
  775. btAlignedObjectArray<DeformableFaceRigidContact> m_faceRigidContacts;
  776. tSContactArray m_scontacts; // Soft contacts
  777. tJointArray m_joints; // Joints
  778. tMaterialArray m_materials; // Materials
  779. btScalar m_timeacc; // Time accumulator
  780. btVector3 m_bounds[2]; // Spatial bounds
  781. bool m_bUpdateRtCst; // Update runtime constants
  782. btDbvt m_ndbvt; // Nodes tree
  783. btDbvt m_fdbvt; // Faces tree
  784. btDbvntNode* m_fdbvnt; // Faces tree with normals
  785. btDbvt m_cdbvt; // Clusters tree
  786. tClusterArray m_clusters; // Clusters
  787. btScalar m_dampingCoefficient; // Damping Coefficient
  788. btScalar m_sleepingThreshold;
  789. btScalar m_maxSpeedSquared;
  790. btAlignedObjectArray<btVector3> m_quads; // quadrature points for collision detection
  791. btScalar m_repulsionStiffness;
  792. btScalar m_gravityFactor;
  793. bool m_cacheBarycenter;
  794. btAlignedObjectArray<btVector3> m_X; // initial positions
  795. btAlignedObjectArray<btVector4> m_renderNodesInterpolationWeights;
  796. btAlignedObjectArray<btAlignedObjectArray<const btSoftBody::Node*> > m_renderNodesParents;
  797. btAlignedObjectArray<btScalar> m_z; // vertical distance used in extrapolation
  798. bool m_useSelfCollision;
  799. bool m_softSoftCollision;
  800. btAlignedObjectArray<bool> m_clusterConnectivity; //cluster connectivity, for self-collision
  801. btVector3 m_windVelocity;
  802. btScalar m_restLengthScale;
  803. //
  804. // Api
  805. //
  806. /* ctor */
  807. btSoftBody(btSoftBodyWorldInfo* worldInfo, int node_count, const btVector3* x, const btScalar* m);
  808. /* ctor */
  809. btSoftBody(btSoftBodyWorldInfo* worldInfo);
  810. void initDefaults();
  811. /* dtor */
  812. virtual ~btSoftBody();
  813. /* Check for existing link */
  814. btAlignedObjectArray<int> m_userIndexMapping;
  815. btSoftBodyWorldInfo* getWorldInfo()
  816. {
  817. return m_worldInfo;
  818. }
  819. void setDampingCoefficient(btScalar damping_coeff)
  820. {
  821. m_dampingCoefficient = damping_coeff;
  822. }
  823. ///@todo: avoid internal softbody shape hack and move collision code to collision library
  824. virtual void setCollisionShape(btCollisionShape* collisionShape)
  825. {
  826. }
  827. bool checkLink(int node0,
  828. int node1) const;
  829. bool checkLink(const Node* node0,
  830. const Node* node1) const;
  831. /* Check for existring face */
  832. bool checkFace(int node0,
  833. int node1,
  834. int node2) const;
  835. /* Append material */
  836. Material* appendMaterial();
  837. /* Append note */
  838. void appendNote(const char* text,
  839. const btVector3& o,
  840. const btVector4& c = btVector4(1, 0, 0, 0),
  841. Node* n0 = 0,
  842. Node* n1 = 0,
  843. Node* n2 = 0,
  844. Node* n3 = 0);
  845. void appendNote(const char* text,
  846. const btVector3& o,
  847. Node* feature);
  848. void appendNote(const char* text,
  849. const btVector3& o,
  850. Link* feature);
  851. void appendNote(const char* text,
  852. const btVector3& o,
  853. Face* feature);
  854. /* Append node */
  855. void appendNode(const btVector3& x, btScalar m);
  856. /* Append link */
  857. void appendLink(int model = -1, Material* mat = 0);
  858. void appendLink(int node0,
  859. int node1,
  860. Material* mat = 0,
  861. bool bcheckexist = false);
  862. void appendLink(Node* node0,
  863. Node* node1,
  864. Material* mat = 0,
  865. bool bcheckexist = false);
  866. /* Append face */
  867. void appendFace(int model = -1, Material* mat = 0);
  868. void appendFace(int node0,
  869. int node1,
  870. int node2,
  871. Material* mat = 0);
  872. void appendTetra(int model, Material* mat);
  873. //
  874. void appendTetra(int node0,
  875. int node1,
  876. int node2,
  877. int node3,
  878. Material* mat = 0);
  879. /* Append anchor */
  880. void appendDeformableAnchor(int node, btRigidBody* body);
  881. void appendDeformableAnchor(int node, btMultiBodyLinkCollider* link);
  882. void appendAnchor(int node,
  883. btRigidBody* body, bool disableCollisionBetweenLinkedBodies = false, btScalar influence = 1);
  884. void appendAnchor(int node, btRigidBody* body, const btVector3& localPivot, bool disableCollisionBetweenLinkedBodies = false, btScalar influence = 1);
  885. void removeAnchor(int node);
  886. /* Append linear joint */
  887. void appendLinearJoint(const LJoint::Specs& specs, Cluster* body0, Body body1);
  888. void appendLinearJoint(const LJoint::Specs& specs, Body body = Body());
  889. void appendLinearJoint(const LJoint::Specs& specs, btSoftBody* body);
  890. /* Append linear joint */
  891. void appendAngularJoint(const AJoint::Specs& specs, Cluster* body0, Body body1);
  892. void appendAngularJoint(const AJoint::Specs& specs, Body body = Body());
  893. void appendAngularJoint(const AJoint::Specs& specs, btSoftBody* body);
  894. /* Add force (or gravity) to the entire body */
  895. void addForce(const btVector3& force);
  896. /* Add force (or gravity) to a node of the body */
  897. void addForce(const btVector3& force,
  898. int node);
  899. /* Add aero force to a node of the body */
  900. void addAeroForceToNode(const btVector3& windVelocity, int nodeIndex);
  901. /* Add aero force to a face of the body */
  902. void addAeroForceToFace(const btVector3& windVelocity, int faceIndex);
  903. /* Add velocity to the entire body */
  904. void addVelocity(const btVector3& velocity);
  905. /* Set velocity for the entire body */
  906. void setVelocity(const btVector3& velocity);
  907. /* Add velocity to a node of the body */
  908. void addVelocity(const btVector3& velocity,
  909. int node);
  910. /* Set mass */
  911. void setMass(int node,
  912. btScalar mass);
  913. /* Get mass */
  914. btScalar getMass(int node) const;
  915. /* Get total mass */
  916. btScalar getTotalMass() const;
  917. /* Set total mass (weighted by previous masses) */
  918. void setTotalMass(btScalar mass,
  919. bool fromfaces = false);
  920. /* Set total density */
  921. void setTotalDensity(btScalar density);
  922. /* Set volume mass (using tetrahedrons) */
  923. void setVolumeMass(btScalar mass);
  924. /* Set volume density (using tetrahedrons) */
  925. void setVolumeDensity(btScalar density);
  926. /* Get the linear velocity of the center of mass */
  927. btVector3 getLinearVelocity();
  928. /* Set the linear velocity of the center of mass */
  929. void setLinearVelocity(const btVector3& linVel);
  930. /* Set the angular velocity of the center of mass */
  931. void setAngularVelocity(const btVector3& angVel);
  932. /* Get best fit rigid transform */
  933. btTransform getRigidTransform();
  934. /* Transform to given pose */
  935. void transformTo(const btTransform& trs);
  936. /* Transform */
  937. void transform(const btTransform& trs);
  938. /* Translate */
  939. void translate(const btVector3& trs);
  940. /* Rotate */
  941. void rotate(const btQuaternion& rot);
  942. /* Scale */
  943. void scale(const btVector3& scl);
  944. /* Get link resting lengths scale */
  945. btScalar getRestLengthScale();
  946. /* Scale resting length of all springs */
  947. void setRestLengthScale(btScalar restLength);
  948. /* Set current state as pose */
  949. void setPose(bool bvolume,
  950. bool bframe);
  951. /* Set current link lengths as resting lengths */
  952. void resetLinkRestLengths();
  953. /* Return the volume */
  954. btScalar getVolume() const;
  955. /* Cluster count */
  956. btVector3 getCenterOfMass() const
  957. {
  958. btVector3 com(0, 0, 0);
  959. for (int i = 0; i < m_nodes.size(); i++)
  960. {
  961. com += (m_nodes[i].m_x * this->getMass(i));
  962. }
  963. com /= this->getTotalMass();
  964. return com;
  965. }
  966. int clusterCount() const;
  967. /* Cluster center of mass */
  968. static btVector3 clusterCom(const Cluster* cluster);
  969. btVector3 clusterCom(int cluster) const;
  970. /* Cluster velocity at rpos */
  971. static btVector3 clusterVelocity(const Cluster* cluster, const btVector3& rpos);
  972. /* Cluster impulse */
  973. static void clusterVImpulse(Cluster* cluster, const btVector3& rpos, const btVector3& impulse);
  974. static void clusterDImpulse(Cluster* cluster, const btVector3& rpos, const btVector3& impulse);
  975. static void clusterImpulse(Cluster* cluster, const btVector3& rpos, const Impulse& impulse);
  976. static void clusterVAImpulse(Cluster* cluster, const btVector3& impulse);
  977. static void clusterDAImpulse(Cluster* cluster, const btVector3& impulse);
  978. static void clusterAImpulse(Cluster* cluster, const Impulse& impulse);
  979. static void clusterDCImpulse(Cluster* cluster, const btVector3& impulse);
  980. /* Generate bending constraints based on distance in the adjency graph */
  981. int generateBendingConstraints(int distance,
  982. Material* mat = 0);
  983. /* Randomize constraints to reduce solver bias */
  984. void randomizeConstraints();
  985. /* Release clusters */
  986. void releaseCluster(int index);
  987. void releaseClusters();
  988. /* Generate clusters (K-mean) */
  989. ///generateClusters with k=0 will create a convex cluster for each tetrahedron or triangle
  990. ///otherwise an approximation will be used (better performance)
  991. int generateClusters(int k, int maxiterations = 8192);
  992. /* Refine */
  993. void refine(ImplicitFn* ifn, btScalar accurary, bool cut);
  994. /* CutLink */
  995. bool cutLink(int node0, int node1, btScalar position);
  996. bool cutLink(const Node* node0, const Node* node1, btScalar position);
  997. ///Ray casting using rayFrom and rayTo in worldspace, (not direction!)
  998. bool rayTest(const btVector3& rayFrom,
  999. const btVector3& rayTo,
  1000. sRayCast& results);
  1001. bool rayFaceTest(const btVector3& rayFrom,
  1002. const btVector3& rayTo,
  1003. sRayCast& results);
  1004. int rayFaceTest(const btVector3& rayFrom, const btVector3& rayTo,
  1005. btScalar& mint, int& index) const;
  1006. /* Solver presets */
  1007. void setSolver(eSolverPresets::_ preset);
  1008. /* predictMotion */
  1009. void predictMotion(btScalar dt);
  1010. /* solveConstraints */
  1011. void solveConstraints();
  1012. /* staticSolve */
  1013. void staticSolve(int iterations);
  1014. /* solveCommonConstraints */
  1015. static void solveCommonConstraints(btSoftBody** bodies, int count, int iterations);
  1016. /* solveClusters */
  1017. static void solveClusters(const btAlignedObjectArray<btSoftBody*>& bodies);
  1018. /* integrateMotion */
  1019. void integrateMotion();
  1020. /* defaultCollisionHandlers */
  1021. void defaultCollisionHandler(const btCollisionObjectWrapper* pcoWrap);
  1022. void defaultCollisionHandler(btSoftBody* psb);
  1023. void setSelfCollision(bool useSelfCollision);
  1024. bool useSelfCollision();
  1025. void updateDeactivation(btScalar timeStep);
  1026. void setZeroVelocity();
  1027. bool wantsSleeping();
  1028. //
  1029. // Functionality to deal with new accelerated solvers.
  1030. //
  1031. /**
  1032. * Set a wind velocity for interaction with the air.
  1033. */
  1034. void setWindVelocity(const btVector3& velocity);
  1035. /**
  1036. * Return the wind velocity for interaction with the air.
  1037. */
  1038. const btVector3& getWindVelocity();
  1039. //
  1040. // Set the solver that handles this soft body
  1041. // Should not be allowed to get out of sync with reality
  1042. // Currently called internally on addition to the world
  1043. void setSoftBodySolver(btSoftBodySolver* softBodySolver)
  1044. {
  1045. m_softBodySolver = softBodySolver;
  1046. }
  1047. //
  1048. // Return the solver that handles this soft body
  1049. //
  1050. btSoftBodySolver* getSoftBodySolver()
  1051. {
  1052. return m_softBodySolver;
  1053. }
  1054. //
  1055. // Return the solver that handles this soft body
  1056. //
  1057. btSoftBodySolver* getSoftBodySolver() const
  1058. {
  1059. return m_softBodySolver;
  1060. }
  1061. //
  1062. // Cast
  1063. //
  1064. static const btSoftBody* upcast(const btCollisionObject* colObj)
  1065. {
  1066. if (colObj->getInternalType() == CO_SOFT_BODY)
  1067. return (const btSoftBody*)colObj;
  1068. return 0;
  1069. }
  1070. static btSoftBody* upcast(btCollisionObject* colObj)
  1071. {
  1072. if (colObj->getInternalType() == CO_SOFT_BODY)
  1073. return (btSoftBody*)colObj;
  1074. return 0;
  1075. }
  1076. //
  1077. // ::btCollisionObject
  1078. //
  1079. virtual void getAabb(btVector3& aabbMin, btVector3& aabbMax) const
  1080. {
  1081. aabbMin = m_bounds[0];
  1082. aabbMax = m_bounds[1];
  1083. }
  1084. //
  1085. // Private
  1086. //
  1087. void pointersToIndices();
  1088. void indicesToPointers(const int* map = 0);
  1089. int rayTest(const btVector3& rayFrom, const btVector3& rayTo,
  1090. btScalar& mint, eFeature::_& feature, int& index, bool bcountonly) const;
  1091. void initializeFaceTree();
  1092. void rebuildNodeTree();
  1093. btVector3 evaluateCom() const;
  1094. bool checkDeformableContact(const btCollisionObjectWrapper* colObjWrap, const btVector3& x, btScalar margin, btSoftBody::sCti& cti, bool predict = false) const;
  1095. bool checkDeformableFaceContact(const btCollisionObjectWrapper* colObjWrap, Face& f, btVector3& contact_point, btVector3& bary, btScalar margin, btSoftBody::sCti& cti, bool predict = false) const;
  1096. bool checkContact(const btCollisionObjectWrapper* colObjWrap, const btVector3& x, btScalar margin, btSoftBody::sCti& cti) const;
  1097. void updateNormals();
  1098. void updateBounds();
  1099. void updatePose();
  1100. void updateConstants();
  1101. void updateLinkConstants();
  1102. void updateArea(bool averageArea = true);
  1103. void initializeClusters();
  1104. void updateClusters();
  1105. void cleanupClusters();
  1106. void prepareClusters(int iterations);
  1107. void solveClusters(btScalar sor);
  1108. void applyClusters(bool drift);
  1109. void dampClusters();
  1110. void setSpringStiffness(btScalar k);
  1111. void setGravityFactor(btScalar gravFactor);
  1112. void setCacheBarycenter(bool cacheBarycenter);
  1113. void initializeDmInverse();
  1114. void updateDeformation();
  1115. void advanceDeformation();
  1116. void applyForces();
  1117. void setMaxStress(btScalar maxStress);
  1118. void interpolateRenderMesh();
  1119. void setCollisionQuadrature(int N);
  1120. static void PSolve_Anchors(btSoftBody* psb, btScalar kst, btScalar ti);
  1121. static void PSolve_RContacts(btSoftBody* psb, btScalar kst, btScalar ti);
  1122. static void PSolve_SContacts(btSoftBody* psb, btScalar, btScalar ti);
  1123. static void PSolve_Links(btSoftBody* psb, btScalar kst, btScalar ti);
  1124. static void VSolve_Links(btSoftBody* psb, btScalar kst);
  1125. static psolver_t getSolver(ePSolver::_ solver);
  1126. static vsolver_t getSolver(eVSolver::_ solver);
  1127. void geometricCollisionHandler(btSoftBody* psb);
  1128. #define SAFE_EPSILON SIMD_EPSILON * 100.0
  1129. void updateNode(btDbvtNode* node, bool use_velocity, bool margin)
  1130. {
  1131. if (node->isleaf())
  1132. {
  1133. btSoftBody::Node* n = (btSoftBody::Node*)(node->data);
  1134. ATTRIBUTE_ALIGNED16(btDbvtVolume)
  1135. vol;
  1136. btScalar pad = margin ? m_sst.radmrg : SAFE_EPSILON; // use user defined margin or margin for floating point precision
  1137. if (use_velocity)
  1138. {
  1139. btVector3 points[2] = {n->m_x, n->m_x + m_sst.sdt * n->m_v};
  1140. vol = btDbvtVolume::FromPoints(points, 2);
  1141. vol.Expand(btVector3(pad, pad, pad));
  1142. }
  1143. else
  1144. {
  1145. vol = btDbvtVolume::FromCR(n->m_x, pad);
  1146. }
  1147. node->volume = vol;
  1148. return;
  1149. }
  1150. else
  1151. {
  1152. updateNode(node->childs[0], use_velocity, margin);
  1153. updateNode(node->childs[1], use_velocity, margin);
  1154. ATTRIBUTE_ALIGNED16(btDbvtVolume)
  1155. vol;
  1156. Merge(node->childs[0]->volume, node->childs[1]->volume, vol);
  1157. node->volume = vol;
  1158. }
  1159. }
  1160. void updateNodeTree(bool use_velocity, bool margin)
  1161. {
  1162. if (m_ndbvt.m_root)
  1163. updateNode(m_ndbvt.m_root, use_velocity, margin);
  1164. }
  1165. template <class DBVTNODE> // btDbvtNode or btDbvntNode
  1166. void updateFace(DBVTNODE* node, bool use_velocity, bool margin)
  1167. {
  1168. if (node->isleaf())
  1169. {
  1170. btSoftBody::Face* f = (btSoftBody::Face*)(node->data);
  1171. btScalar pad = margin ? m_sst.radmrg : SAFE_EPSILON; // use user defined margin or margin for floating point precision
  1172. ATTRIBUTE_ALIGNED16(btDbvtVolume)
  1173. vol;
  1174. if (use_velocity)
  1175. {
  1176. btVector3 points[6] = {f->m_n[0]->m_x, f->m_n[0]->m_x + m_sst.sdt * f->m_n[0]->m_v,
  1177. f->m_n[1]->m_x, f->m_n[1]->m_x + m_sst.sdt * f->m_n[1]->m_v,
  1178. f->m_n[2]->m_x, f->m_n[2]->m_x + m_sst.sdt * f->m_n[2]->m_v};
  1179. vol = btDbvtVolume::FromPoints(points, 6);
  1180. }
  1181. else
  1182. {
  1183. btVector3 points[3] = {f->m_n[0]->m_x,
  1184. f->m_n[1]->m_x,
  1185. f->m_n[2]->m_x};
  1186. vol = btDbvtVolume::FromPoints(points, 3);
  1187. }
  1188. vol.Expand(btVector3(pad, pad, pad));
  1189. node->volume = vol;
  1190. return;
  1191. }
  1192. else
  1193. {
  1194. updateFace(node->childs[0], use_velocity, margin);
  1195. updateFace(node->childs[1], use_velocity, margin);
  1196. ATTRIBUTE_ALIGNED16(btDbvtVolume)
  1197. vol;
  1198. Merge(node->childs[0]->volume, node->childs[1]->volume, vol);
  1199. node->volume = vol;
  1200. }
  1201. }
  1202. void updateFaceTree(bool use_velocity, bool margin)
  1203. {
  1204. if (m_fdbvt.m_root)
  1205. updateFace(m_fdbvt.m_root, use_velocity, margin);
  1206. if (m_fdbvnt)
  1207. updateFace(m_fdbvnt, use_velocity, margin);
  1208. }
  1209. template <typename T>
  1210. static inline T BaryEval(const T& a,
  1211. const T& b,
  1212. const T& c,
  1213. const btVector3& coord)
  1214. {
  1215. return (a * coord.x() + b * coord.y() + c * coord.z());
  1216. }
  1217. void applyRepulsionForce(btScalar timeStep, bool applySpringForce)
  1218. {
  1219. btAlignedObjectArray<int> indices;
  1220. {
  1221. // randomize the order of repulsive force
  1222. indices.resize(m_faceNodeContacts.size());
  1223. for (int i = 0; i < m_faceNodeContacts.size(); ++i)
  1224. indices[i] = i;
  1225. #define NEXTRAND (seed = (1664525L * seed + 1013904223L) & 0xffffffff)
  1226. int i, ni;
  1227. for (i = 0, ni = indices.size(); i < ni; ++i)
  1228. {
  1229. btSwap(indices[i], indices[NEXTRAND % ni]);
  1230. }
  1231. }
  1232. for (int k = 0; k < m_faceNodeContacts.size(); ++k)
  1233. {
  1234. int idx = indices[k];
  1235. btSoftBody::DeformableFaceNodeContact& c = m_faceNodeContacts[idx];
  1236. btSoftBody::Node* node = c.m_node;
  1237. btSoftBody::Face* face = c.m_face;
  1238. const btVector3& w = c.m_bary;
  1239. const btVector3& n = c.m_normal;
  1240. btVector3 l = node->m_x - BaryEval(face->m_n[0]->m_x, face->m_n[1]->m_x, face->m_n[2]->m_x, w);
  1241. btScalar d = c.m_margin - n.dot(l);
  1242. d = btMax(btScalar(0), d);
  1243. const btVector3& va = node->m_v;
  1244. btVector3 vb = BaryEval(face->m_n[0]->m_v, face->m_n[1]->m_v, face->m_n[2]->m_v, w);
  1245. btVector3 vr = va - vb;
  1246. const btScalar vn = btDot(vr, n); // dn < 0 <==> opposing
  1247. if (vn > OVERLAP_REDUCTION_FACTOR * d / timeStep)
  1248. continue;
  1249. btVector3 vt = vr - vn * n;
  1250. btScalar I = 0;
  1251. btScalar mass = node->m_im == 0 ? 0 : btScalar(1) / node->m_im;
  1252. if (applySpringForce)
  1253. I = -btMin(m_repulsionStiffness * timeStep * d, mass * (OVERLAP_REDUCTION_FACTOR * d / timeStep - vn));
  1254. if (vn < 0)
  1255. I += 0.5 * mass * vn;
  1256. int face_penetration = 0, node_penetration = node->m_constrained;
  1257. for (int i = 0; i < 3; ++i)
  1258. face_penetration |= face->m_n[i]->m_constrained;
  1259. btScalar I_tilde = 2.0 * I / (1.0 + w.length2());
  1260. // double the impulse if node or face is constrained.
  1261. if (face_penetration > 0 || node_penetration > 0)
  1262. {
  1263. I_tilde *= 2.0;
  1264. }
  1265. if (face_penetration <= 0)
  1266. {
  1267. for (int j = 0; j < 3; ++j)
  1268. face->m_n[j]->m_v += w[j] * n * I_tilde * node->m_im;
  1269. }
  1270. if (node_penetration <= 0)
  1271. {
  1272. node->m_v -= I_tilde * node->m_im * n;
  1273. }
  1274. // apply frictional impulse
  1275. btScalar vt_norm = vt.safeNorm();
  1276. if (vt_norm > SIMD_EPSILON)
  1277. {
  1278. btScalar delta_vn = -2 * I * node->m_im;
  1279. btScalar mu = c.m_friction;
  1280. btScalar vt_new = btMax(btScalar(1) - mu * delta_vn / (vt_norm + SIMD_EPSILON), btScalar(0)) * vt_norm;
  1281. I = 0.5 * mass * (vt_norm - vt_new);
  1282. vt.safeNormalize();
  1283. I_tilde = 2.0 * I / (1.0 + w.length2());
  1284. // double the impulse if node or face is constrained.
  1285. if (face_penetration > 0 || node_penetration > 0)
  1286. I_tilde *= 2.0;
  1287. if (face_penetration <= 0)
  1288. {
  1289. for (int j = 0; j < 3; ++j)
  1290. face->m_n[j]->m_v += w[j] * vt * I_tilde * (face->m_n[j])->m_im;
  1291. }
  1292. if (node_penetration <= 0)
  1293. {
  1294. node->m_v -= I_tilde * node->m_im * vt;
  1295. }
  1296. }
  1297. }
  1298. }
  1299. virtual int calculateSerializeBufferSize() const;
  1300. ///fills the dataBuffer and returns the struct name (and 0 on failure)
  1301. virtual const char* serialize(void* dataBuffer, class btSerializer* serializer) const;
  1302. };
  1303. #endif //_BT_SOFT_BODY_H