btSoftBody.h 30 KB

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