BGE patch: fix transform bug on compound shape: child shape didn't take into account...
[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
22 #include "PHY_IPhysicsController.h"
23
24 ///     PHY_IPhysicsController is the abstract simplified Interface to a physical object.
25 ///     It contains the IMotionState and IDeformableMesh Interfaces.
26 #include "btBulletDynamicsCommon.h"
27 #include "LinearMath/btTransform.h"
28
29 #include "PHY_IMotionState.h"
30
31 extern float gDeactivationTime;
32 extern float gLinearSleepingTreshold;
33 extern float gAngularSleepingTreshold;
34 extern bool gDisableDeactivation;
35 class CcdPhysicsEnvironment;
36 class btMotionState;
37 class RAS_MeshObject;
38 class btCollisionShape;
39
40 // Shape contructor
41 // It contains all the information needed to create a simple bullet shape at runtime
42 class CcdShapeConstructionInfo
43 {
44 public:
45         CcdShapeConstructionInfo() :
46                 m_shapeType(PHY_SHAPE_NONE),
47                 m_radius(1.0),
48                 m_height(1.0),
49                 m_halfExtend(0.f,0.f,0.f),
50                 m_childScale(1.0f,1.0f,1.0f),
51                 m_nextShape(NULL),
52                 m_refCount(1)
53         {
54                 m_childTrans.setIdentity();
55         }
56
57         ~CcdShapeConstructionInfo();
58
59         CcdShapeConstructionInfo* AddRef()
60         { 
61                 m_refCount++;
62                 return this;
63         }
64
65         int Release()
66         {
67                 if (--m_refCount > 0)
68                         return m_refCount;
69                 delete this;
70                 return 0;
71         }
72
73         void AddShape(CcdShapeConstructionInfo* shapeInfo);
74
75         CcdShapeConstructionInfo* GetNextShape()
76         {
77                 return m_nextShape;
78         }
79         CcdShapeConstructionInfo* GetChildShape(int i)
80         {
81                 CcdShapeConstructionInfo* shape = m_nextShape;
82                 while (i > 0 && shape != NULL)
83                 {
84                         shape = shape->m_nextShape;
85                         i--;
86                 }
87                 return shape;
88         }
89
90         bool SetMesh(RAS_MeshObject* mesh, bool polytope);
91
92         btCollisionShape* CreateBulletShape();
93
94         // member variables
95         PHY_ShapeType                   m_shapeType;
96         btScalar                                m_radius;
97         btScalar                                m_height;
98         btVector3                               m_halfExtend;
99         btTransform                             m_childTrans;
100         btVector3                               m_childScale;
101         std::vector<btPoint3>   m_vertexArray;  // Contains both vertex array for polytope shape and
102                                                                                         // triangle array for concave mesh shape.
103                                                                                         // In this case a triangle is made of 3 consecutive points
104         std::vector<int>                m_polygonIndexArray;    // Contains the array of polygon index in the 
105                                                                                                         // original mesh that correspond to shape triangles.
106                                                                                                         // only set for concave mesh shape.
107         const RAS_MeshObject*   m_meshObject;   // Keep a pointer to the original mesh 
108
109 protected:
110         CcdShapeConstructionInfo* m_nextShape;  // for compound shape
111         int                                             m_refCount;             // this class is shared between replicas
112                                                                                         // keep track of users so that we can release it 
113 };
114
115 struct CcdConstructionInfo
116 {
117
118         ///CollisionFilterGroups provides some optional usage of basic collision filtering
119         ///this is done during broadphase, so very early in the pipeline
120         ///more advanced collision filtering should be done in btCollisionDispatcher::NeedsCollision
121         enum CollisionFilterGroups
122         {
123                 DefaultFilter = 1,
124                 StaticFilter = 2,
125                 KinematicFilter = 4,
126                 DebrisFilter = 8,
127                         SensorFilter = 16,
128                 AllFilter = DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorFilter,
129         };
130
131
132         CcdConstructionInfo()
133                 : m_localInertiaTensor(1.f, 1.f, 1.f),
134                 m_gravity(0,0,0),
135                 m_scaling(1.f,1.f,1.f),
136                 m_mass(0.f),
137                 m_restitution(0.1f),
138                 m_friction(0.5f),
139                 m_linearDamping(0.1f),
140                 m_angularDamping(0.1f),
141                 m_collisionFlags(0),
142                 m_bRigid(false),
143                 m_collisionFilterGroup(DefaultFilter),
144                 m_collisionFilterMask(AllFilter),
145                 m_collisionShape(0),
146                 m_MotionState(0),
147                 m_shapeInfo(0),
148                 m_physicsEnv(0),
149                 m_inertiaFactor(1.f)
150         {
151         }
152
153         btVector3       m_localInertiaTensor;
154         btVector3       m_gravity;
155         btVector3       m_scaling;
156         btScalar        m_mass;
157         btScalar        m_restitution;
158         btScalar        m_friction;
159         btScalar        m_linearDamping;
160         btScalar        m_angularDamping;
161         int                     m_collisionFlags;
162         bool            m_bRigid;
163
164         ///optional use of collision group/mask:
165         ///only collision with object goups that match the collision mask.
166         ///this is very basic early out. advanced collision filtering should be
167         ///done in the btCollisionDispatcher::NeedsCollision and NeedsResponse
168         ///both values default to 1
169         short int       m_collisionFilterGroup;
170         short int       m_collisionFilterMask;
171
172         ///these pointers are used as argument passing for the CcdPhysicsController constructor
173         ///and not anymore after that
174         class btCollisionShape* m_collisionShape;
175         class PHY_IMotionState* m_MotionState;
176         class CcdShapeConstructionInfo* m_shapeInfo;
177         
178         CcdPhysicsEnvironment*  m_physicsEnv; //needed for self-replication
179         float   m_inertiaFactor;//tweak the inertia (hooked up to Blender 'formfactor'
180 };
181
182
183 class btRigidBody;
184
185
186 ///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution.
187 class CcdPhysicsController : public PHY_IPhysicsController      
188 {
189         btRigidBody* m_body;
190         class PHY_IMotionState*         m_MotionState;
191         btMotionState*  m_bulletMotionState;
192         class btCollisionShape* m_collisionShape;
193         class CcdShapeConstructionInfo* m_shapeInfo;
194
195         friend class CcdPhysicsEnvironment;     // needed when updating the controller
196
197
198         void*           m_newClientInfo;
199         int                     m_registerCount;        // needed when multiple sensors use the same controller
200         CcdConstructionInfo     m_cci;//needed for replication
201         void GetWorldOrientation(btMatrix3x3& mat);
202
203         void CreateRigidbody();
204
205         bool Register() { 
206                 return (m_registerCount++ == 0) ? true : false;
207         }
208         bool Unregister() {
209                 return (--m_registerCount == 0) ? true : false;
210         }
211
212         protected:
213                 void setWorldOrientation(const btMatrix3x3& mat);
214
215         public:
216         
217                 int                             m_collisionDelay;
218         
219
220                 CcdPhysicsController (const CcdConstructionInfo& ci);
221
222                 virtual ~CcdPhysicsController();
223
224
225                 btRigidBody* GetRigidBody() { return m_body;}
226                 CcdShapeConstructionInfo* GetShapeInfo() { return m_shapeInfo; }
227
228                 btCollisionShape*       GetCollisionShape() { 
229                         return m_body->getCollisionShape();
230                 }
231                 ////////////////////////////////////
232                 // PHY_IPhysicsController interface
233                 ////////////////////////////////////
234
235
236                 /**
237                         SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
238                 */
239                 virtual bool            SynchronizeMotionStates(float time);
240                 /**
241                         WriteMotionStateToDynamics ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
242                 */
243                 
244                 virtual void            WriteMotionStateToDynamics(bool nondynaonly);
245                 virtual void            WriteDynamicsToMotionState();
246                 // controller replication
247                 virtual void            PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl);
248
249                 // kinematic methods
250                 virtual void            RelativeTranslate(float dlocX,float dlocY,float dlocZ,bool local);
251                 virtual void            RelativeRotate(const float drot[9],bool local);
252                 virtual void            getOrientation(float &quatImag0,float &quatImag1,float &quatImag2,float &quatReal);
253                 virtual void            setOrientation(float quatImag0,float quatImag1,float quatImag2,float quatReal);
254                 virtual void            setPosition(float posX,float posY,float posZ);
255                 virtual void            getPosition(PHY__Vector3&       pos) const;
256
257                 virtual void            setScaling(float scaleX,float scaleY,float scaleZ);
258                 
259                 // physics methods
260                 virtual void            ApplyTorque(float torqueX,float torqueY,float torqueZ,bool local);
261                 virtual void            ApplyForce(float forceX,float forceY,float forceZ,bool local);
262                 virtual void            SetAngularVelocity(float ang_velX,float ang_velY,float ang_velZ,bool local);
263                 virtual void            SetLinearVelocity(float lin_velX,float lin_velY,float lin_velZ,bool local);
264                 virtual void            applyImpulse(float attachX,float attachY,float attachZ, float impulseX,float impulseY,float impulseZ);
265                 virtual void            SetActive(bool active);
266
267                 // reading out information from physics
268                 virtual void            GetLinearVelocity(float& linvX,float& linvY,float& linvZ);
269                 virtual void            GetAngularVelocity(float& angVelX,float& angVelY,float& angVelZ);
270                 virtual void            GetVelocity(const float posX,const float posY,const float posZ,float& linvX,float& linvY,float& linvZ); 
271                 virtual void            getReactionForce(float& forceX,float& forceY,float& forceZ);
272
273                 // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted 
274                 virtual void            setRigidBody(bool rigid);
275
276                 
277                 virtual void            resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ);
278
279                 // clientinfo for raycasts for example
280                 virtual void*                           getNewClientInfo();
281                 virtual void                            setNewClientInfo(void* clientinfo);
282                 virtual PHY_IPhysicsController* GetReplica();
283                 
284                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
285                 short int       GetCollisionFilterGroup() const
286                 {
287                         return m_cci.m_collisionFilterGroup;
288                 }
289                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
290                 short int       GetCollisionFilterMask() const
291                 {
292                         return m_cci.m_collisionFilterMask;
293                 }
294
295                 virtual void    calcXform() {} ;
296                 virtual void SetMargin(float margin) {};
297                 virtual float GetMargin() const {return 0.f;};
298
299
300                 bool    wantsSleeping();
301
302                 void    UpdateDeactivation(float timeStep);
303
304                 static btTransform      GetTransformFromMotionState(PHY_IMotionState* motionState);
305
306                 void    setAabb(const btVector3& aabbMin,const btVector3& aabbMax);
307
308
309                 class   PHY_IMotionState*                       GetMotionState()
310                 {
311                         return m_MotionState;
312                 }
313
314                 const class     PHY_IMotionState*                       GetMotionState() const
315                 {
316                         return m_MotionState;
317                 }
318
319                 class CcdPhysicsEnvironment* GetPhysicsEnvironment()
320                 {
321                         return m_cci.m_physicsEnv;
322                 }
323                 
324 };
325
326
327
328
329 ///DefaultMotionState implements standard motionstate, using btTransform
330 class   DefaultMotionState : public PHY_IMotionState
331
332 {
333         public:
334                 DefaultMotionState();
335
336                 virtual ~DefaultMotionState();
337
338                 virtual void    getWorldPosition(float& posX,float& posY,float& posZ);
339                 virtual void    getWorldScaling(float& scaleX,float& scaleY,float& scaleZ);
340                 virtual void    getWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal);
341                 
342                 virtual void    setWorldPosition(float posX,float posY,float posZ);
343                 virtual void    setWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal);
344                 
345                 virtual void    calculateWorldTransformations();
346                 
347                 btTransform     m_worldTransform;
348                 btVector3               m_localScaling;
349
350 };
351
352
353 #endif //BULLET2_PHYSICSCONTROLLER_H