BGE bug #17688 fixed: Near Sensor Reset not working (for Gamekit)
[blender.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         bool            m_do_fh;                 ///< Should the object have a linear Fh spring?
268         bool            m_do_rot_fh;             ///< Should the object have an angular Fh spring?
269         btScalar        m_fh_spring;             ///< Spring constant (both linear and angular)
270         btScalar        m_fh_damping;            ///< Damping factor (linear and angular) in range [0, 1]
271         btScalar        m_fh_distance;           ///< The range above the surface where Fh is active.    
272         bool            m_fh_normal;             ///< Should the object slide off slopes?
273         float           m_radius;//for fh backwards compatibility
274
275 };
276
277
278 class btRigidBody;
279 class btCollisionObject;
280 class btSoftBody;
281
282 ///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution.
283 class CcdPhysicsController : public PHY_IPhysicsController      
284 {
285
286         btCollisionObject* m_object;
287         
288
289         class PHY_IMotionState*         m_MotionState;
290         btMotionState*  m_bulletMotionState;
291         class btCollisionShape* m_collisionShape;
292         class CcdShapeConstructionInfo* m_shapeInfo;
293
294         friend class CcdPhysicsEnvironment;     // needed when updating the controller
295
296         //some book keeping for replication
297         bool    m_softbodyMappingDone;
298         bool    m_softBodyTransformInitialized;
299         bool    m_prototypeTransformInitialized;
300         btTransform     m_softbodyStartTrans;
301
302
303         void*           m_newClientInfo;
304         int                     m_registerCount;        // needed when multiple sensors use the same controller
305         CcdConstructionInfo     m_cci;//needed for replication
306
307         CcdPhysicsController* m_parentCtrl;
308
309         void GetWorldOrientation(btMatrix3x3& mat);
310
311         void CreateRigidbody();
312
313         bool Register() { 
314                 return (m_registerCount++ == 0) ? true : false;
315         }
316         bool Unregister() {
317                 return (--m_registerCount == 0) ? true : false;
318         }
319
320         protected:
321                 void setWorldOrientation(const btMatrix3x3& mat);
322
323         public:
324         
325                 int                             m_collisionDelay;
326         
327
328                 CcdPhysicsController (const CcdConstructionInfo& ci);
329
330                 virtual ~CcdPhysicsController();
331
332                 CcdConstructionInfo& getConstructionInfo()
333                 {
334                         return m_cci;
335                 }
336                 const CcdConstructionInfo& getConstructionInfo() const
337                 {
338                         return m_cci;
339                 }
340
341
342                 btRigidBody* GetRigidBody();
343                 btCollisionObject*      GetCollisionObject();
344                 btSoftBody* GetSoftBody();
345
346                 CcdShapeConstructionInfo* GetShapeInfo() { return m_shapeInfo; }
347
348                 btCollisionShape*       GetCollisionShape() { 
349                         return m_object->getCollisionShape();
350                 }
351                 ////////////////////////////////////
352                 // PHY_IPhysicsController interface
353                 ////////////////////////////////////
354
355
356                 /**
357                         SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
358                 */
359                 virtual bool            SynchronizeMotionStates(float time);
360                 /**
361                         WriteMotionStateToDynamics ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
362                 */
363                 
364                 virtual void            WriteMotionStateToDynamics(bool nondynaonly);
365                 virtual void            WriteDynamicsToMotionState();
366                 // controller replication
367                 virtual void            PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl);
368
369                 // kinematic methods
370                 virtual void            RelativeTranslate(float dlocX,float dlocY,float dlocZ,bool local);
371                 virtual void            RelativeRotate(const float drot[9],bool local);
372                 virtual void            getOrientation(float &quatImag0,float &quatImag1,float &quatImag2,float &quatReal);
373                 virtual void            setOrientation(float quatImag0,float quatImag1,float quatImag2,float quatReal);
374                 virtual void            setPosition(float posX,float posY,float posZ);
375                 virtual void            getPosition(PHY__Vector3&       pos) const;
376
377                 virtual void            setScaling(float scaleX,float scaleY,float scaleZ);
378                 
379                 // physics methods
380                 virtual void            ApplyTorque(float torqueX,float torqueY,float torqueZ,bool local);
381                 virtual void            ApplyForce(float forceX,float forceY,float forceZ,bool local);
382                 virtual void            SetAngularVelocity(float ang_velX,float ang_velY,float ang_velZ,bool local);
383                 virtual void            SetLinearVelocity(float lin_velX,float lin_velY,float lin_velZ,bool local);
384                 virtual void            applyImpulse(float attachX,float attachY,float attachZ, float impulseX,float impulseY,float impulseZ);
385                 virtual void            SetActive(bool active);
386
387                 // reading out information from physics
388                 virtual void            GetLinearVelocity(float& linvX,float& linvY,float& linvZ);
389                 virtual void            GetAngularVelocity(float& angVelX,float& angVelY,float& angVelZ);
390                 virtual void            GetVelocity(const float posX,const float posY,const float posZ,float& linvX,float& linvY,float& linvZ); 
391                 virtual void            getReactionForce(float& forceX,float& forceY,float& forceZ);
392
393                 // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted 
394                 virtual void            setRigidBody(bool rigid);
395
396                 
397                 virtual void            resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ);
398
399                 // clientinfo for raycasts for example
400                 virtual void*                           getNewClientInfo();
401                 virtual void                            setNewClientInfo(void* clientinfo);
402                 virtual PHY_IPhysicsController* GetReplica();
403                 
404                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
405                 short int       GetCollisionFilterGroup() const
406                 {
407                         return m_cci.m_collisionFilterGroup;
408                 }
409                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
410                 short int       GetCollisionFilterMask() const
411                 {
412                         return m_cci.m_collisionFilterMask;
413                 }
414
415                 virtual void    calcXform() {} ;
416                 virtual void SetMargin(float margin) 
417                 {
418                         if (m_collisionShape)
419                                 m_collisionShape->setMargin(btScalar(margin));
420                 }
421                 virtual float GetMargin() const 
422                 {
423                         return (m_collisionShape) ? m_collisionShape->getMargin() : 0.f;
424                 }
425                 virtual float GetRadius() const 
426                 { 
427                         // this is not the actual shape radius, it's only used for Fh support
428                         return m_cci.m_radius;
429                 }
430                 virtual void  SetRadius(float margin) 
431                 {
432                         if (m_collisionShape && m_collisionShape->getShapeType() == SPHERE_SHAPE_PROXYTYPE)
433                         {
434                                 btSphereShape* sphereShape = static_cast<btSphereShape*>(m_collisionShape);
435                                 sphereShape->setUnscaledRadius(margin);
436                         }
437                         m_cci.m_radius = margin;
438                 }
439
440
441                 bool    wantsSleeping();
442
443                 void    UpdateDeactivation(float timeStep);
444
445                 void    SetCenterOfMassTransform(btTransform& xform);
446
447                 static btTransform      GetTransformFromMotionState(PHY_IMotionState* motionState);
448
449                 void    setAabb(const btVector3& aabbMin,const btVector3& aabbMax);
450
451
452                 class   PHY_IMotionState*                       GetMotionState()
453                 {
454                         return m_MotionState;
455                 }
456
457                 const class     PHY_IMotionState*                       GetMotionState() const
458                 {
459                         return m_MotionState;
460                 }
461
462                 class CcdPhysicsEnvironment* GetPhysicsEnvironment()
463                 {
464                         return m_cci.m_physicsEnv;
465                 }
466
467                 void    setParentCtrl(CcdPhysicsController* parentCtrl)
468                 {
469                         m_parentCtrl = parentCtrl;
470                 }
471
472                 CcdPhysicsController*   getParentCtrl()
473                 {
474                         return m_parentCtrl;
475                 }
476
477                 const CcdPhysicsController*     getParentCtrl() const
478                 {
479                         return m_parentCtrl;
480                 }
481
482
483                 
484 };
485
486
487
488
489 ///DefaultMotionState implements standard motionstate, using btTransform
490 class   DefaultMotionState : public PHY_IMotionState
491
492 {
493         public:
494                 DefaultMotionState();
495
496                 virtual ~DefaultMotionState();
497
498                 virtual void    getWorldPosition(float& posX,float& posY,float& posZ);
499                 virtual void    getWorldScaling(float& scaleX,float& scaleY,float& scaleZ);
500                 virtual void    getWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal);
501                 
502                 virtual void    setWorldPosition(float posX,float posY,float posZ);
503                 virtual void    setWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal);
504                 
505                 virtual void    calculateWorldTransformations();
506                 
507                 btTransform     m_worldTransform;
508                 btVector3               m_localScaling;
509
510 };
511
512
513 #endif //BULLET2_PHYSICSCONTROLLER_H