remove constructors, they cause compile errors under Fedora
[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         };
209
210         /* Feature              */ 
211         struct  Feature : Element
212         {
213                 Material*                               m_material;             // Material
214         };
215         /* Node                 */ 
216         struct  Node : Feature
217         {
218                 btVector3                               m_x;                    // Position
219                 btVector3                               m_q;                    // Previous step position
220                 btVector3                               m_v;                    // Velocity
221                 btVector3                               m_f;                    // Force accumulator
222                 btVector3                               m_n;                    // Normal
223                 btScalar                                m_im;                   // 1/mass
224                 btScalar                                m_area;                 // Area
225                 btDbvtNode*                             m_leaf;                 // Leaf data
226                 int                                             m_battach:1;    // Attached
227         };
228         /* Link                 */ 
229         struct  Link : Feature
230         {
231                 Node*                                   m_n[2];                 // Node pointers
232                 btScalar                                m_rl;                   // Rest length          
233                 int                                             m_bbending:1;   // Bending link
234                 btScalar                                m_c0;                   // (ima+imb)*kLST
235                 btScalar                                m_c1;                   // rl^2
236                 btScalar                                m_c2;                   // |gradient|^2/c0
237                 btVector3                               m_c3;                   // gradient
238         };
239         /* Face                 */ 
240         struct  Face : Feature
241         {
242                 Node*                                   m_n[3];                 // Node pointers
243                 btVector3                               m_normal;               // Normal
244                 btScalar                                m_ra;                   // Rest area
245                 btDbvtNode*                             m_leaf;                 // Leaf data
246         };
247         /* Tetra                */ 
248         struct  Tetra : Feature
249         {
250                 Node*                                   m_n[4];                 // Node pointers                
251                 btScalar                                m_rv;                   // Rest volume
252                 btDbvtNode*                             m_leaf;                 // Leaf data
253                 btVector3                               m_c0[4];                // gradients
254                 btScalar                                m_c1;                   // (4*kVST)/(im0+im1+im2+im3)
255                 btScalar                                m_c2;                   // m_c1/sum(|g0..3|^2)
256         };
257         /* RContact             */ 
258         struct  RContact
259         {
260                 sCti            m_cti;                  // Contact infos
261                 Node*                                   m_node;                 // Owner node
262                 btMatrix3x3                             m_c0;                   // Impulse matrix
263                 btVector3                               m_c1;                   // Relative anchor
264                 btScalar                                m_c2;                   // ima*dt
265                 btScalar                                m_c3;                   // Friction
266                 btScalar                                m_c4;                   // Hardness
267         };
268         /* SContact             */ 
269         struct  SContact
270         {
271                 Node*                                   m_node;                 // Node
272                 Face*                                   m_face;                 // Face
273                 btVector3                               m_weights;              // Weigths
274                 btVector3                               m_normal;               // Normal
275                 btScalar                                m_margin;               // Margin
276                 btScalar                                m_friction;             // Friction
277                 btScalar                                m_cfm[2];               // Constraint force mixing
278         };
279         /* Anchor               */ 
280         struct  Anchor
281         {
282                 Node*                                   m_node;                 // Node pointer
283                 btVector3                               m_local;                // Anchor position in body space
284                 btRigidBody*                    m_body;                 // Body
285                 btMatrix3x3                             m_c0;                   // Impulse matrix
286                 btVector3                               m_c1;                   // Relative anchor
287                 btScalar                                m_c2;                   // ima*dt
288         };
289         /* Note                 */ 
290         struct  Note : Element
291         {
292                 const char*                             m_text;                 // Text
293                 btVector3                               m_offset;               // Offset
294                 int                                             m_rank;                 // Rank
295                 Node*                                   m_nodes[4];             // Nodes
296                 btScalar                                m_coords[4];    // Coordinates
297         };      
298         /* Pose                 */ 
299         struct  Pose
300         {
301                 bool                                    m_bvolume;              // Is valid
302                 bool                                    m_bframe;               // Is frame
303                 btScalar                                m_volume;               // Rest volume
304                 tVector3Array                   m_pos;                  // Reference positions
305                 tScalarArray                    m_wgh;                  // Weights
306                 btVector3                               m_com;                  // COM
307                 btMatrix3x3                             m_rot;                  // Rotation
308                 btMatrix3x3                             m_scl;                  // Scale
309                 btMatrix3x3                             m_aqq;                  // Base scaling
310         };
311         /* Cluster              */ 
312         struct  Cluster
313         {
314                 tScalarArray                            m_masses;
315                 btAlignedObjectArray<Node*>     m_nodes;                
316                 tVector3Array                           m_framerefs;
317                 btTransform                                     m_framexform;
318                 btScalar                                        m_idmass;
319                 btScalar                                        m_imass;
320                 btMatrix3x3                                     m_locii;
321                 btMatrix3x3                                     m_invwi;
322                 btVector3                                       m_com;
323                 btVector3                                       m_vimpulses[2];
324                 btVector3                                       m_dimpulses[2];
325                 int                                                     m_nvimpulses;
326                 int                                                     m_ndimpulses;
327                 btVector3                                       m_lv;
328                 btVector3                                       m_av;
329                 btDbvtNode*                                     m_leaf;
330                 btScalar                                        m_ndamping;     /* Node damping         */ 
331                 btScalar                                        m_ldamping;     /* Linear damping       */ 
332                 btScalar                                        m_adamping;     /* Angular damping      */ 
333                 btScalar                                        m_matching;
334                 btScalar                                        m_maxSelfCollisionImpulse;
335                 btScalar                                        m_selfCollisionImpulseFactor;
336                 bool                                            m_containsAnchor;
337                 bool                                            m_collide;
338                 int                                                     m_clusterIndex;
339                 Cluster() : m_leaf(0),m_ndamping(0),m_ldamping(0),m_adamping(0),m_matching(0) 
340                 ,m_maxSelfCollisionImpulse(100.f),
341                 m_selfCollisionImpulseFactor(0.01f),
342                 m_containsAnchor(false)
343                 {}
344         };
345         /* Impulse              */ 
346         struct  Impulse
347         {
348                 btVector3                                       m_velocity;
349                 btVector3                                       m_drift;
350                 int                                                     m_asVelocity:1;
351                 int                                                     m_asDrift:1;
352                 Impulse() : m_velocity(0,0,0),m_drift(0,0,0),m_asVelocity(0),m_asDrift(0)       {}
353                 Impulse                                         operator -() const
354                 {
355                         Impulse i=*this;
356                         i.m_velocity=-i.m_velocity;
357                         i.m_drift=-i.m_drift;
358                         return(i);
359                 }
360                 Impulse                                         operator*(btScalar x) const
361                 {
362                         Impulse i=*this;
363                         i.m_velocity*=x;
364                         i.m_drift*=x;
365                         return(i);
366                 }
367         };
368         /* Body                 */ 
369         struct  Body
370         {
371                 Cluster*                        m_soft;
372                 btRigidBody*            m_rigid;
373                 btCollisionObject*      m_collisionObject;
374
375                 Body() : m_soft(0),m_rigid(0),m_collisionObject(0)                              {}
376                 Body(Cluster* p) : m_soft(p),m_rigid(0),m_collisionObject(0)    {}
377                 Body(btCollisionObject* colObj) : m_soft(0),m_collisionObject(colObj)
378                 {
379                         m_rigid = btRigidBody::upcast(m_collisionObject);
380                 }
381
382                 void                                            activate() const
383                 {
384                         if(m_rigid) 
385                                 m_rigid->activate();
386                         if (m_collisionObject)
387                                 m_collisionObject->activate();
388
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 { enum _ {
480                         Linear=0,
481                         Angular,
482                         Contact
483                 };};
484                 struct Specs
485                 {
486                         Specs() : erp(1),cfm(1),split(1) {}
487                         btScalar        erp;
488                         btScalar        cfm;
489                         btScalar        split;
490                 };
491                 Body                                            m_bodies[2];
492                 btVector3                                       m_refs[2];
493                 btScalar                                        m_cfm;
494                 btScalar                                        m_erp;
495                 btScalar                                        m_split;
496                 btVector3                                       m_drift;
497                 btVector3                                       m_sdrift;
498                 btMatrix3x3                                     m_massmatrix;
499                 bool                                            m_delete;
500                 virtual                                         ~Joint() {}
501                 Joint() : m_delete(false) {}
502                 virtual void                            Prepare(btScalar dt,int iterations);
503                 virtual void                            Solve(btScalar dt,btScalar sor)=0;
504                 virtual void                            Terminate(btScalar dt)=0;
505                 virtual eType::_                        Type() const=0;
506         };
507         /* LJoint               */ 
508         struct  LJoint : Joint
509         {
510                 struct Specs : Joint::Specs
511                 {
512                         btVector3       position;
513                 };              
514                 btVector3                                       m_rpos[2];
515                 void                                            Prepare(btScalar dt,int iterations);
516                 void                                            Solve(btScalar dt,btScalar sor);
517                 void                                            Terminate(btScalar dt);
518                 eType::_                                        Type() const { return(eType::Linear); }
519         };
520         /* AJoint               */ 
521         struct  AJoint : Joint
522         {
523                 struct IControl
524                 {
525                         virtual void                    Prepare(AJoint*)                                {}
526                         virtual btScalar                Speed(AJoint*,btScalar current) { return(current); }
527                         static IControl*                Default()                                               { static IControl def;return(&def); }
528                 };
529                 struct Specs : Joint::Specs
530                 {
531                         Specs() : icontrol(IControl::Default()) {}
532                         btVector3       axis;
533                         IControl*       icontrol;
534                 };              
535                 btVector3                                       m_axis[2];
536                 IControl*                                       m_icontrol;
537                 void                                            Prepare(btScalar dt,int iterations);
538                 void                                            Solve(btScalar dt,btScalar sor);
539                 void                                            Terminate(btScalar dt);
540                 eType::_                                        Type() const { return(eType::Angular); }
541         };
542         /* CJoint               */ 
543         struct  CJoint : Joint
544         {               
545                 int                                                     m_life;
546                 int                                                     m_maxlife;
547                 btVector3                                       m_rpos[2];
548                 btVector3                                       m_normal;
549                 btScalar                                        m_friction;
550                 void                                            Prepare(btScalar dt,int iterations);
551                 void                                            Solve(btScalar dt,btScalar sor);
552                 void                                            Terminate(btScalar dt);
553                 eType::_                                        Type() const { return(eType::Contact); }
554         };
555         /* Config               */ 
556         struct  Config
557         {
558                 eAeroModel::_                   aeromodel;              // Aerodynamic model (default: V_Point)
559                 btScalar                                kVCF;                   // Velocities correction factor (Baumgarte)
560                 btScalar                                kDP;                    // Damping coefficient [0,1]
561                 btScalar                                kDG;                    // Drag coefficient [0,+inf]
562                 btScalar                                kLF;                    // Lift coefficient [0,+inf]
563                 btScalar                                kPR;                    // Pressure coefficient [-inf,+inf]
564                 btScalar                                kVC;                    // Volume conversation coefficient [0,+inf]
565                 btScalar                                kDF;                    // Dynamic friction coefficient [0,1]
566                 btScalar                                kMT;                    // Pose matching coefficient [0,1]              
567                 btScalar                                kCHR;                   // Rigid contacts hardness [0,1]
568                 btScalar                                kKHR;                   // Kinetic contacts hardness [0,1]
569                 btScalar                                kSHR;                   // Soft contacts hardness [0,1]
570                 btScalar                                kAHR;                   // Anchors hardness [0,1]
571                 btScalar                                kSRHR_CL;               // Soft vs rigid hardness [0,1] (cluster only)
572                 btScalar                                kSKHR_CL;               // Soft vs kinetic hardness [0,1] (cluster only)
573                 btScalar                                kSSHR_CL;               // Soft vs soft hardness [0,1] (cluster only)
574                 btScalar                                kSR_SPLT_CL;    // Soft vs rigid impulse split [0,1] (cluster only)
575                 btScalar                                kSK_SPLT_CL;    // Soft vs rigid impulse split [0,1] (cluster only)
576                 btScalar                                kSS_SPLT_CL;    // Soft vs rigid impulse split [0,1] (cluster only)
577                 btScalar                                maxvolume;              // Maximum volume ratio for pose
578                 btScalar                                timescale;              // Time scale
579                 int                                             viterations;    // Velocities solver iterations
580                 int                                             piterations;    // Positions solver iterations
581                 int                                             diterations;    // Drift solver iterations
582                 int                                             citerations;    // Cluster solver iterations
583                 int                                             collisions;             // Collisions flags
584                 tVSolverArray                   m_vsequence;    // Velocity solvers sequence
585                 tPSolverArray                   m_psequence;    // Position solvers sequence
586                 tPSolverArray                   m_dsequence;    // Drift solvers sequence
587         };
588         /* SolverState  */ 
589         struct  SolverState
590         {
591                 btScalar                                sdt;                    // dt*timescale
592                 btScalar                                isdt;                   // 1/sdt
593                 btScalar                                velmrg;                 // velocity margin
594                 btScalar                                radmrg;                 // radial margin
595                 btScalar                                updmrg;                 // Update margin
596         };      
597         /// RayFromToCaster takes a ray from, ray to (instead of direction!)
598         struct  RayFromToCaster : btDbvt::ICollide
599         {
600                 btVector3                       m_rayFrom;
601                 btVector3                       m_rayTo;
602                 btVector3                       m_rayNormalizedDirection;
603                 btScalar                        m_mint;
604                 Face*                           m_face;
605                 int                                     m_tests;
606                 RayFromToCaster(const btVector3& rayFrom,const btVector3& rayTo,btScalar mxt);
607                 void                                    Process(const btDbvtNode* leaf);
608
609                 static inline btScalar  rayFromToTriangle(const btVector3& rayFrom,
610                         const btVector3& rayTo,
611                         const btVector3& rayNormalizedDirection,
612                         const btVector3& a,
613                         const btVector3& b,
614                         const btVector3& c,
615                         btScalar maxt=SIMD_INFINITY);
616         };
617
618         //
619         // Typedefs
620         //
621
622         typedef void                                                            (*psolver_t)(btSoftBody*,btScalar,btScalar);
623         typedef void                                                            (*vsolver_t)(btSoftBody*,btScalar);
624         typedef btAlignedObjectArray<Cluster*>          tClusterArray;
625         typedef btAlignedObjectArray<Note>                      tNoteArray;
626         typedef btAlignedObjectArray<Node>                      tNodeArray;
627         typedef btAlignedObjectArray<btDbvtNode*>       tLeafArray;
628         typedef btAlignedObjectArray<Link>                      tLinkArray;
629         typedef btAlignedObjectArray<Face>                      tFaceArray;
630         typedef btAlignedObjectArray<Tetra>                     tTetraArray;
631         typedef btAlignedObjectArray<Anchor>            tAnchorArray;
632         typedef btAlignedObjectArray<RContact>          tRContactArray;
633         typedef btAlignedObjectArray<SContact>          tSContactArray;
634         typedef btAlignedObjectArray<Material*>         tMaterialArray;
635         typedef btAlignedObjectArray<Joint*>            tJointArray;
636         typedef btAlignedObjectArray<btSoftBody*>       tSoftBodyArray; 
637
638         //
639         // Fields
640         //
641
642         Config                                  m_cfg;                  // Configuration
643         SolverState                             m_sst;                  // Solver state
644         Pose                                    m_pose;                 // Pose
645         void*                                   m_tag;                  // User data
646         btSoftBodyWorldInfo*    m_worldInfo;    // World info
647         tNoteArray                              m_notes;                // Notes
648         tNodeArray                              m_nodes;                // Nodes
649         tLinkArray                              m_links;                // Links
650         tFaceArray                              m_faces;                // Faces
651         tTetraArray                             m_tetras;               // Tetras
652         tAnchorArray                    m_anchors;              // Anchors
653         tRContactArray                  m_rcontacts;    // Rigid contacts
654         tSContactArray                  m_scontacts;    // Soft contacts
655         tJointArray                             m_joints;               // Joints
656         tMaterialArray                  m_materials;    // Materials
657         btScalar                                m_timeacc;              // Time accumulator
658         btVector3                               m_bounds[2];    // Spatial bounds       
659         bool                                    m_bUpdateRtCst; // Update runtime constants
660         btDbvt                                  m_ndbvt;                // Nodes tree
661         btDbvt                                  m_fdbvt;                // Faces tree
662         btDbvt                                  m_cdbvt;                // Clusters tree
663         tClusterArray                   m_clusters;             // Clusters
664
665         btAlignedObjectArray<bool>m_clusterConnectivity;//cluster connectivity, for self-collision
666
667         btTransform                     m_initialWorldTransform;
668
669         btVector3                       m_windVelocity;
670         //
671         // Api
672         //
673
674         /* ctor                                                                                                                                 */ 
675         btSoftBody(     btSoftBodyWorldInfo* worldInfo,int node_count,          const btVector3* x,             const btScalar* m);
676
677         /* ctor                                                                                                                                 */ 
678         btSoftBody(     btSoftBodyWorldInfo* worldInfo);
679
680         void    initDefaults();
681
682         /* dtor                                                                                                                                 */ 
683         virtual ~btSoftBody();
684         /* Check for existing link                                                                                              */ 
685
686         btAlignedObjectArray<int>       m_userIndexMapping;
687
688         btSoftBodyWorldInfo*    getWorldInfo()
689         {
690                 return m_worldInfo;
691         }
692
693         ///@todo: avoid internal softbody shape hack and move collision code to collision library
694         virtual void    setCollisionShape(btCollisionShape* collisionShape)
695         {
696                 
697         }
698
699         bool                            checkLink(      int node0,
700                 int node1) const;
701         bool                            checkLink(      const Node* node0,
702                 const Node* node1) const;
703         /* Check for existring face                                                                                             */ 
704         bool                            checkFace(      int node0,
705                 int node1,
706                 int node2) const;
707         /* Append material                                                                                                              */ 
708         Material*                       appendMaterial();
709         /* Append note                                                                                                                  */ 
710         void                            appendNote(     const char* text,
711                 const btVector3& o,
712                 const btVector4& c=btVector4(1,0,0,0),
713                 Node* n0=0,
714                 Node* n1=0,
715                 Node* n2=0,
716                 Node* n3=0);
717         void                            appendNote(     const char* text,
718                 const btVector3& o,
719                 Node* feature);
720         void                            appendNote(     const char* text,
721                 const btVector3& o,
722                 Link* feature);
723         void                            appendNote(     const char* text,
724                 const btVector3& o,
725                 Face* feature);
726         /* Append node                                                                                                                  */ 
727         void                            appendNode(     const btVector3& x,btScalar m);
728         /* Append link                                                                                                                  */ 
729         void                            appendLink(int model=-1,Material* mat=0);
730         void                            appendLink(     int node0,
731                 int node1,
732                 Material* mat=0,
733                 bool bcheckexist=false);
734         void                            appendLink(     Node* node0,
735                 Node* node1,
736                 Material* mat=0,
737                 bool bcheckexist=false);
738         /* Append face                                                                                                                  */ 
739         void                            appendFace(int model=-1,Material* mat=0);
740         void                            appendFace(     int node0,
741                 int node1,
742                 int node2,
743                 Material* mat=0);
744         void                    appendTetra(int model,Material* mat);
745         //
746         void                    appendTetra(int node0,
747                                                                                 int node1,
748                                                                                 int node2,
749                                                                                 int node3,
750                                                                                 Material* mat=0);
751
752
753         /* Append anchor                                                                                                                */ 
754         void                            appendAnchor(   int node,
755                 btRigidBody* body, bool disableCollisionBetweenLinkedBodies=false);
756         void                    appendAnchor(int node,btRigidBody* body, const btVector3& localPivot,bool disableCollisionBetweenLinkedBodies=false);
757         /* Append linear joint                                                                                                  */ 
758         void                            appendLinearJoint(const LJoint::Specs& specs,Cluster* body0,Body body1);
759         void                            appendLinearJoint(const LJoint::Specs& specs,Body body=Body());
760         void                            appendLinearJoint(const LJoint::Specs& specs,btSoftBody* body);
761         /* Append linear joint                                                                                                  */ 
762         void                            appendAngularJoint(const AJoint::Specs& specs,Cluster* body0,Body body1);
763         void                            appendAngularJoint(const AJoint::Specs& specs,Body body=Body());
764         void                            appendAngularJoint(const AJoint::Specs& specs,btSoftBody* body);
765         /* Add force (or gravity) to the entire body                                                    */ 
766         void                            addForce(               const btVector3& force);
767         /* Add force (or gravity) to a node of the body                                                 */ 
768         void                            addForce(               const btVector3& force,
769                 int node);
770         /* Add velocity to the entire body                                                                              */ 
771         void                            addVelocity(    const btVector3& velocity);
772
773         /* Set velocity for the entire body                                                                             */ 
774         void                            setVelocity(    const btVector3& velocity);
775
776         /* Add velocity to a node of the body                                                                   */ 
777         void                            addVelocity(    const btVector3& velocity,
778                 int node);
779         /* Set mass                                                                                                                             */ 
780         void                            setMass(                int node,
781                 btScalar mass);
782         /* Get mass                                                                                                                             */ 
783         btScalar                        getMass(                int node) const;
784         /* Get total mass                                                                                                               */ 
785         btScalar                        getTotalMass() const;
786         /* Set total mass (weighted by previous masses)                                                 */ 
787         void                            setTotalMass(   btScalar mass,
788                 bool fromfaces=false);
789         /* Set total density                                                                                                    */ 
790         void                            setTotalDensity(btScalar density);
791         /* Set volume mass (using tetrahedrons)                                                                 */
792         void                            setVolumeMass(          btScalar mass);
793         /* Set volume density (using tetrahedrons)                                                              */
794         void                            setVolumeDensity(       btScalar density);
795         /* Transform                                                                                                                    */ 
796         void                            transform(              const btTransform& trs);
797         /* Translate                                                                                                                    */ 
798         void                            translate(              const btVector3& trs);
799         /* Rotate                                                                                                                       */ 
800         void                            rotate( const btQuaternion& rot);
801         /* Scale                                                                                                                                */ 
802         void                            scale(  const btVector3& scl);
803         /* Set current state as pose                                                                                    */ 
804         void                            setPose(                bool bvolume,
805                 bool bframe);
806         /* Return the volume                                                                                                    */ 
807         btScalar                        getVolume() const;
808         /* Cluster count                                                                                                                */ 
809         int                                     clusterCount() const;
810         /* Cluster center of mass                                                                                               */ 
811         static btVector3        clusterCom(const Cluster* cluster);
812         btVector3                       clusterCom(int cluster) const;
813         /* Cluster velocity at rpos                                                                                             */ 
814         static btVector3        clusterVelocity(const Cluster* cluster,const btVector3& rpos);
815         /* Cluster impulse                                                                                                              */ 
816         static void                     clusterVImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse);
817         static void                     clusterDImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse);
818         static void                     clusterImpulse(Cluster* cluster,const btVector3& rpos,const Impulse& impulse);
819         static void                     clusterVAImpulse(Cluster* cluster,const btVector3& impulse);
820         static void                     clusterDAImpulse(Cluster* cluster,const btVector3& impulse);
821         static void                     clusterAImpulse(Cluster* cluster,const Impulse& impulse);
822         static void                     clusterDCImpulse(Cluster* cluster,const btVector3& impulse);
823         /* Generate bending constraints based on distance in the adjency graph  */ 
824         int                                     generateBendingConstraints(     int distance,
825                 Material* mat=0);
826         /* Randomize constraints to reduce solver bias                                                  */ 
827         void                            randomizeConstraints();
828         /* Release clusters                                                                                                             */ 
829         void                            releaseCluster(int index);
830         void                            releaseClusters();
831         /* Generate clusters (K-mean)                                                                                   */ 
832         ///generateClusters with k=0 will create a convex cluster for each tetrahedron or triangle
833         ///otherwise an approximation will be used (better performance)
834         int                                     generateClusters(int k,int maxiterations=8192);
835         /* Refine                                                                                                                               */ 
836         void                            refine(ImplicitFn* ifn,btScalar accurary,bool cut);
837         /* CutLink                                                                                                                              */ 
838         bool                            cutLink(int node0,int node1,btScalar position);
839         bool                            cutLink(const Node* node0,const Node* node1,btScalar position);
840
841         ///Ray casting using rayFrom and rayTo in worldspace, (not direction!)
842         bool                            rayTest(const btVector3& rayFrom,
843                 const btVector3& rayTo,
844                 sRayCast& results);
845         /* Solver presets                                                                                                               */ 
846         void                            setSolver(eSolverPresets::_ preset);
847         /* predictMotion                                                                                                                */ 
848         void                            predictMotion(btScalar dt);
849         /* solveConstraints                                                                                                             */ 
850         void                            solveConstraints();
851         /* staticSolve                                                                                                                  */ 
852         void                            staticSolve(int iterations);
853         /* solveCommonConstraints                                                                                               */ 
854         static void                     solveCommonConstraints(btSoftBody** bodies,int count,int iterations);
855         /* solveClusters                                                                                                                */ 
856         static void                     solveClusters(const btAlignedObjectArray<btSoftBody*>& bodies);
857         /* integrateMotion                                                                                                              */ 
858         void                            integrateMotion();
859         /* defaultCollisionHandlers                                                                                             */ 
860         void                            defaultCollisionHandler(btCollisionObject* pco);
861         void                            defaultCollisionHandler(btSoftBody* psb);
862
863
864
865         //
866         // Functionality to deal with new accelerated solvers.
867         //
868
869         /**
870          * Set a wind velocity for interaction with the air.
871          */
872         void setWindVelocity( const btVector3 &velocity );
873
874
875         /**
876          * Return the wind velocity for interaction with the air.
877          */
878         const btVector3& getWindVelocity();
879
880         //
881         // Set the solver that handles this soft body
882         // Should not be allowed to get out of sync with reality
883         // Currently called internally on addition to the world
884         void setSoftBodySolver( btSoftBodySolver *softBodySolver )
885         {
886                 m_softBodySolver = softBodySolver;
887         }
888
889         //
890         // Return the solver that handles this soft body
891         // 
892         btSoftBodySolver *getSoftBodySolver()
893         {
894                 return m_softBodySolver;
895         }
896
897         //
898         // Return the solver that handles this soft body
899         // 
900         btSoftBodySolver *getSoftBodySolver() const
901         {
902                 return m_softBodySolver;
903         }
904
905
906         //
907         // Cast
908         //
909
910         static const btSoftBody*        upcast(const btCollisionObject* colObj)
911         {
912                 if (colObj->getInternalType()==CO_SOFT_BODY)
913                         return (const btSoftBody*)colObj;
914                 return 0;
915         }
916         static btSoftBody*                      upcast(btCollisionObject* colObj)
917         {
918                 if (colObj->getInternalType()==CO_SOFT_BODY)
919                         return (btSoftBody*)colObj;
920                 return 0;
921         }
922
923         //
924         // ::btCollisionObject
925         //
926
927         virtual void getAabb(btVector3& aabbMin,btVector3& aabbMax) const
928         {
929                 aabbMin = m_bounds[0];
930                 aabbMax = m_bounds[1];
931         }
932         //
933         // Private
934         //
935         void                            pointersToIndices();
936         void                            indicesToPointers(const int* map=0);
937
938         int                                     rayTest(const btVector3& rayFrom,const btVector3& rayTo,
939                 btScalar& mint,eFeature::_& feature,int& index,bool bcountonly) const;
940         void                            initializeFaceTree();
941         btVector3                       evaluateCom() const;
942         bool                            checkContact(btCollisionObject* colObj,const btVector3& x,btScalar margin,btSoftBody::sCti& cti) const;
943         void                            updateNormals();
944         void                            updateBounds();
945         void                            updatePose();
946         void                            updateConstants();
947         void                            initializeClusters();
948         void                            updateClusters();
949         void                            cleanupClusters();
950         void                            prepareClusters(int iterations);
951         void                            solveClusters(btScalar sor);
952         void                            applyClusters(bool drift);
953         void                            dampClusters();
954         void                            applyForces();  
955         static void                     PSolve_Anchors(btSoftBody* psb,btScalar kst,btScalar ti);
956         static void                     PSolve_RContacts(btSoftBody* psb,btScalar kst,btScalar ti);
957         static void                     PSolve_SContacts(btSoftBody* psb,btScalar,btScalar ti);
958         static void                     PSolve_Links(btSoftBody* psb,btScalar kst,btScalar ti);
959         static void                     VSolve_Links(btSoftBody* psb,btScalar kst);
960         static psolver_t        getSolver(ePSolver::_ solver);
961         static vsolver_t        getSolver(eVSolver::_ solver);
962
963
964         virtual int     calculateSerializeBufferSize()  const;
965
966         ///fills the dataBuffer and returns the struct name (and 0 on failure)
967         virtual const char*     serialize(void* dataBuffer,  class btSerializer* serializer) const;
968
969         //virtual void serializeSingleObject(class btSerializer* serializer) const;
970
971
972 };
973
974
975
976
977 #endif //_BT_SOFT_BODY_H