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