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