added anisotropic friction support for Bullet. Both for static and dynamic objects
[blender-staging.git] / source / gameengine / Physics / Bullet / CcdPhysicsController.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
16
17 #ifndef BULLET2_PHYSICSCONTROLLER_H
18 #define BULLET2_PHYSICSCONTROLLER_H
19
20 #include <vector>
21 #include <map>
22
23 #include "PHY_IPhysicsController.h"
24
25 ///     PHY_IPhysicsController is the abstract simplified Interface to a physical object.
26 ///     It contains the IMotionState and IDeformableMesh Interfaces.
27 #include "btBulletDynamicsCommon.h"
28 #include "LinearMath/btTransform.h"
29
30 #include "PHY_IMotionState.h"
31
32 extern float gDeactivationTime;
33 extern float gLinearSleepingTreshold;
34 extern float gAngularSleepingTreshold;
35 extern bool gDisableDeactivation;
36 class CcdPhysicsEnvironment;
37 class btMotionState;
38 class RAS_MeshObject;
39 class btCollisionShape;
40
41
42 #define CCD_BSB_SHAPE_MATCHING  2
43 #define CCD_BSB_BENDING_CONSTRAINTS 8
44 #define CCD_BSB_AERO_VPOINT 16 /* aero model, Vertex normals are oriented toward velocity*/
45 #define CCD_BSB_AERO_VTWOSIDE 32 /* aero model, Vertex normals are flipped to match velocity */
46
47 /* BulletSoftBody.collisionflags */
48 #define CCD_BSB_COL_SDF_RS      2 /* SDF based rigid vs soft */
49 #define CCD_BSB_COL_CL_RS       4 /* Cluster based rigid vs soft */
50 #define CCD_BSB_COL_CL_SS       8 /* Cluster based soft vs soft */
51 #define CCD_BSB_COL_VF_SS       16 /* Vertex/Face based soft vs soft */
52
53
54
55 // Shape contructor
56 // It contains all the information needed to create a simple bullet shape at runtime
57 class CcdShapeConstructionInfo
58 {
59 public:
60         
61
62         static CcdShapeConstructionInfo* FindMesh(RAS_MeshObject* mesh, bool polytope);
63
64         CcdShapeConstructionInfo() :
65                 m_shapeType(PHY_SHAPE_NONE),
66                 m_radius(1.0),
67                 m_height(1.0),
68                 m_halfExtend(0.f,0.f,0.f),
69                 m_childScale(1.0f,1.0f,1.0f),
70                 m_refCount(1),
71                 m_meshObject(NULL),
72                 m_unscaledShape(NULL),
73                 m_useGimpact(false),
74                 m_weldingThreshold(0.f)
75         {
76                 m_childTrans.setIdentity();
77         }
78
79         ~CcdShapeConstructionInfo();
80
81         CcdShapeConstructionInfo* AddRef()
82         { 
83                 m_refCount++;
84                 return this;
85         }
86
87         int Release()
88         {
89                 if (--m_refCount > 0)
90                         return m_refCount;
91                 delete this;
92                 return 0;
93         }
94
95         void AddShape(CcdShapeConstructionInfo* shapeInfo);
96
97         btTriangleMeshShape* GetMeshShape(void)
98         {
99                 return m_unscaledShape;
100         }
101         CcdShapeConstructionInfo* GetChildShape(int i)
102         {
103                 if (i < 0 || i >= m_shapeArray.size())
104                         return NULL;
105
106                 return m_shapeArray.at(i);
107         }
108
109         bool SetMesh(RAS_MeshObject* mesh, bool polytope,bool useGimpact);
110         RAS_MeshObject* GetMesh(void)
111         {
112                 return m_meshObject;
113         }
114
115         btCollisionShape* CreateBulletShape();
116
117         // member variables
118         PHY_ShapeType                   m_shapeType;
119         btScalar                                m_radius;
120         btScalar                                m_height;
121         btVector3                               m_halfExtend;
122         btTransform                             m_childTrans;
123         btVector3                               m_childScale;
124         std::vector<btPoint3>   m_vertexArray;  // Contains both vertex array for polytope shape and
125                                                                                         // triangle array for concave mesh shape.
126                                                                                         // In this case a triangle is made of 3 consecutive points
127         std::vector<int>                m_polygonIndexArray;    // Contains the array of polygon index in the 
128                                                                                                         // original mesh that correspond to shape triangles.
129                                                                                                         // only set for concave mesh shape.
130
131         void    setVertexWeldingThreshold(float threshold)
132         {
133                 m_weldingThreshold  = threshold;
134         }
135         float   getVertexWeldingThreshold() const
136         {
137                 return m_weldingThreshold;
138         }
139 protected:
140         static std::map<RAS_MeshObject*, CcdShapeConstructionInfo*> m_meshShapeMap;
141         int                                             m_refCount;             // this class is shared between replicas
142                                                                                         // keep track of users so that we can release it 
143         RAS_MeshObject* m_meshObject;                   // Keep a pointer to the original mesh 
144         btBvhTriangleMeshShape* m_unscaledShape;// holds the shared unscale BVH mesh shape, 
145                                                                                         // the actual shape is of type btScaledBvhTriangleMeshShape
146         std::vector<CcdShapeConstructionInfo*> m_shapeArray;    // for compound shapes
147         bool    m_useGimpact; //use gimpact for concave dynamic/moving collision detection
148         float   m_weldingThreshold;     //welding closeby vertices together can improve softbody stability etc.
149
150 };
151
152 struct CcdConstructionInfo
153 {
154
155         ///CollisionFilterGroups provides some optional usage of basic collision filtering
156         ///this is done during broadphase, so very early in the pipeline
157         ///more advanced collision filtering should be done in btCollisionDispatcher::NeedsCollision
158         enum CollisionFilterGroups
159         {
160                 DefaultFilter = 1,
161                 StaticFilter = 2,
162                 KinematicFilter = 4,
163                 DebrisFilter = 8,
164                         SensorFilter = 16,
165                 AllFilter = DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorFilter,
166         };
167
168
169         CcdConstructionInfo()
170                 : m_localInertiaTensor(1.f, 1.f, 1.f),
171                 m_gravity(0,0,0),
172                 m_scaling(1.f,1.f,1.f),
173                 m_mass(0.f),
174                 m_restitution(0.1f),
175                 m_friction(0.5f),
176                 m_linearDamping(0.1f),
177                 m_angularDamping(0.1f),
178                 m_margin(0.06f),
179                 m_gamesoftFlag(0),
180                 m_collisionFlags(0),
181                 m_bRigid(false),
182                 m_bSoft(false),
183                 m_collisionFilterGroup(DefaultFilter),
184                 m_collisionFilterMask(AllFilter),
185                 m_collisionShape(0),
186                 m_MotionState(0),
187                 m_shapeInfo(0),
188                 m_physicsEnv(0),
189                 m_inertiaFactor(1.f),
190                 m_do_anisotropic(false),
191                 m_anisotropicFriction(1.f,1.f,1.f)
192         {
193         }
194
195         btVector3       m_localInertiaTensor;
196         btVector3       m_gravity;
197         btVector3       m_scaling;
198         btScalar        m_mass;
199         btScalar        m_restitution;
200         btScalar        m_friction;
201         btScalar        m_linearDamping;
202         btScalar        m_angularDamping;
203         btScalar        m_margin;
204
205         ////////////////////
206         int             m_gamesoftFlag;
207         float   m_soft_linStiff;                        /* linear stiffness 0..1 */
208         float   m_soft_angStiff;                /* angular stiffness 0..1 */
209         float   m_soft_volume;                  /* volume preservation 0..1 */
210
211         int             m_soft_viterations;             /* Velocities solver iterations */
212         int             m_soft_piterations;             /* Positions solver iterations */
213         int             m_soft_diterations;             /* Drift solver iterations */
214         int             m_soft_citerations;             /* Cluster solver iterations */
215
216         float   m_soft_kSRHR_CL;                /* Soft vs rigid hardness [0,1] (cluster only) */
217         float   m_soft_kSKHR_CL;                /* Soft vs kinetic hardness [0,1] (cluster only) */
218         float   m_soft_kSSHR_CL;                /* Soft vs soft hardness [0,1] (cluster only) */
219         float   m_soft_kSR_SPLT_CL;     /* Soft vs rigid impulse split [0,1] (cluster only) */
220
221         float   m_soft_kSK_SPLT_CL;     /* Soft vs rigid impulse split [0,1] (cluster only) */
222         float   m_soft_kSS_SPLT_CL;     /* Soft vs rigid impulse split [0,1] (cluster only) */
223         float   m_soft_kVCF;                    /* Velocities correction factor (Baumgarte) */
224         float   m_soft_kDP;                     /* Damping coefficient [0,1] */
225
226         float   m_soft_kDG;                     /* Drag coefficient [0,+inf] */
227         float   m_soft_kLF;                     /* Lift coefficient [0,+inf] */
228         float   m_soft_kPR;                     /* Pressure coefficient [-inf,+inf] */
229         float   m_soft_kVC;                     /* Volume conversation coefficient [0,+inf] */
230
231         float   m_soft_kDF;                     /* Dynamic friction coefficient [0,1] */
232         float   m_soft_kMT;                     /* Pose matching coefficient [0,1] */
233         float   m_soft_kCHR;                    /* Rigid contacts hardness [0,1] */
234         float   m_soft_kKHR;                    /* Kinetic contacts hardness [0,1] */
235
236         float   m_soft_kSHR;                    /* Soft contacts hardness [0,1] */
237         float   m_soft_kAHR;                    /* Anchors hardness [0,1] */
238         int             m_soft_collisionflags;  /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
239         int             m_soft_numclusteriterations;    /* number of iterations to refine collision clusters*/
240 ///////////////////
241
242
243
244         int                     m_collisionFlags;
245         bool            m_bRigid;
246         bool            m_bSoft;
247
248         ///optional use of collision group/mask:
249         ///only collision with object goups that match the collision mask.
250         ///this is very basic early out. advanced collision filtering should be
251         ///done in the btCollisionDispatcher::NeedsCollision and NeedsResponse
252         ///both values default to 1
253         short int       m_collisionFilterGroup;
254         short int       m_collisionFilterMask;
255
256         ///these pointers are used as argument passing for the CcdPhysicsController constructor
257         ///and not anymore after that
258         class btCollisionShape* m_collisionShape;
259         class PHY_IMotionState* m_MotionState;
260         class CcdShapeConstructionInfo* m_shapeInfo;
261         
262         CcdPhysicsEnvironment*  m_physicsEnv; //needed for self-replication
263         float   m_inertiaFactor;//tweak the inertia (hooked up to Blender 'formfactor'
264         bool    m_do_anisotropic;
265         btVector3 m_anisotropicFriction;
266
267 };
268
269
270 class btRigidBody;
271 class btCollisionObject;
272 class btSoftBody;
273
274 ///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution.
275 class CcdPhysicsController : public PHY_IPhysicsController      
276 {
277
278         btCollisionObject* m_object;
279         
280
281         class PHY_IMotionState*         m_MotionState;
282         btMotionState*  m_bulletMotionState;
283         class btCollisionShape* m_collisionShape;
284         class CcdShapeConstructionInfo* m_shapeInfo;
285
286         friend class CcdPhysicsEnvironment;     // needed when updating the controller
287
288         //some book keeping for replication
289         bool    m_softbodyMappingDone;
290         bool    m_softBodyTransformInitialized;
291         bool    m_prototypeTransformInitialized;
292         btTransform     m_softbodyStartTrans;
293
294
295         void*           m_newClientInfo;
296         int                     m_registerCount;        // needed when multiple sensors use the same controller
297         CcdConstructionInfo     m_cci;//needed for replication
298         void GetWorldOrientation(btMatrix3x3& mat);
299
300         void CreateRigidbody();
301
302         bool Register() { 
303                 return (m_registerCount++ == 0) ? true : false;
304         }
305         bool Unregister() {
306                 return (--m_registerCount == 0) ? true : false;
307         }
308
309         protected:
310                 void setWorldOrientation(const btMatrix3x3& mat);
311
312         public:
313         
314                 int                             m_collisionDelay;
315         
316
317                 CcdPhysicsController (const CcdConstructionInfo& ci);
318
319                 virtual ~CcdPhysicsController();
320
321
322                 btRigidBody* GetRigidBody();
323                 btCollisionObject*      GetCollisionObject();
324                 btSoftBody* GetSoftBody();
325
326                 CcdShapeConstructionInfo* GetShapeInfo() { return m_shapeInfo; }
327
328                 btCollisionShape*       GetCollisionShape() { 
329                         return m_object->getCollisionShape();
330                 }
331                 ////////////////////////////////////
332                 // PHY_IPhysicsController interface
333                 ////////////////////////////////////
334
335
336                 /**
337                         SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
338                 */
339                 virtual bool            SynchronizeMotionStates(float time);
340                 /**
341                         WriteMotionStateToDynamics ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
342                 */
343                 
344                 virtual void            WriteMotionStateToDynamics(bool nondynaonly);
345                 virtual void            WriteDynamicsToMotionState();
346                 // controller replication
347                 virtual void            PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl);
348
349                 // kinematic methods
350                 virtual void            RelativeTranslate(float dlocX,float dlocY,float dlocZ,bool local);
351                 virtual void            RelativeRotate(const float drot[9],bool local);
352                 virtual void            getOrientation(float &quatImag0,float &quatImag1,float &quatImag2,float &quatReal);
353                 virtual void            setOrientation(float quatImag0,float quatImag1,float quatImag2,float quatReal);
354                 virtual void            setPosition(float posX,float posY,float posZ);
355                 virtual void            getPosition(PHY__Vector3&       pos) const;
356
357                 virtual void            setScaling(float scaleX,float scaleY,float scaleZ);
358                 
359                 // physics methods
360                 virtual void            ApplyTorque(float torqueX,float torqueY,float torqueZ,bool local);
361                 virtual void            ApplyForce(float forceX,float forceY,float forceZ,bool local);
362                 virtual void            SetAngularVelocity(float ang_velX,float ang_velY,float ang_velZ,bool local);
363                 virtual void            SetLinearVelocity(float lin_velX,float lin_velY,float lin_velZ,bool local);
364                 virtual void            applyImpulse(float attachX,float attachY,float attachZ, float impulseX,float impulseY,float impulseZ);
365                 virtual void            SetActive(bool active);
366
367                 // reading out information from physics
368                 virtual void            GetLinearVelocity(float& linvX,float& linvY,float& linvZ);
369                 virtual void            GetAngularVelocity(float& angVelX,float& angVelY,float& angVelZ);
370                 virtual void            GetVelocity(const float posX,const float posY,const float posZ,float& linvX,float& linvY,float& linvZ); 
371                 virtual void            getReactionForce(float& forceX,float& forceY,float& forceZ);
372
373                 // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted 
374                 virtual void            setRigidBody(bool rigid);
375
376                 
377                 virtual void            resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ);
378
379                 // clientinfo for raycasts for example
380                 virtual void*                           getNewClientInfo();
381                 virtual void                            setNewClientInfo(void* clientinfo);
382                 virtual PHY_IPhysicsController* GetReplica();
383                 
384                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
385                 short int       GetCollisionFilterGroup() const
386                 {
387                         return m_cci.m_collisionFilterGroup;
388                 }
389                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
390                 short int       GetCollisionFilterMask() const
391                 {
392                         return m_cci.m_collisionFilterMask;
393                 }
394
395                 virtual void    calcXform() {} ;
396                 virtual void SetMargin(float margin) {};
397                 virtual float GetMargin() const {return 0.f;};
398
399
400                 bool    wantsSleeping();
401
402                 void    UpdateDeactivation(float timeStep);
403
404                 void    SetCenterOfMassTransform(btTransform& xform);
405
406                 static btTransform      GetTransformFromMotionState(PHY_IMotionState* motionState);
407
408                 void    setAabb(const btVector3& aabbMin,const btVector3& aabbMax);
409
410
411                 class   PHY_IMotionState*                       GetMotionState()
412                 {
413                         return m_MotionState;
414                 }
415
416                 const class     PHY_IMotionState*                       GetMotionState() const
417                 {
418                         return m_MotionState;
419                 }
420
421                 class CcdPhysicsEnvironment* GetPhysicsEnvironment()
422                 {
423                         return m_cci.m_physicsEnv;
424                 }
425                 
426 };
427
428
429
430
431 ///DefaultMotionState implements standard motionstate, using btTransform
432 class   DefaultMotionState : public PHY_IMotionState
433
434 {
435         public:
436                 DefaultMotionState();
437
438                 virtual ~DefaultMotionState();
439
440                 virtual void    getWorldPosition(float& posX,float& posY,float& posZ);
441                 virtual void    getWorldScaling(float& scaleX,float& scaleY,float& scaleZ);
442                 virtual void    getWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal);
443                 
444                 virtual void    setWorldPosition(float posX,float posY,float posZ);
445                 virtual void    setWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal);
446                 
447                 virtual void    calculateWorldTransformations();
448                 
449                 btTransform     m_worldTransform;
450                 btVector3               m_localScaling;
451
452 };
453
454
455 #endif //BULLET2_PHYSICSCONTROLLER_H