added support for 'Ghost' object and collision sensor (preliminary)
[blender-staging.git] / source / gameengine / Physics / Bullet / CcdPhysicsController.cpp
1 #include "CcdPhysicsController.h"
2
3 #include "Dynamics/RigidBody.h"
4 #include "PHY_IMotionState.h"
5 #include "BroadphaseCollision/BroadphaseProxy.h"
6 #include "BroadphaseCollision/BroadphaseInterface.h"
7 #include "CollisionShapes/ConvexShape.h"
8 #include "CcdPhysicsEnvironment.h"
9 #include "SimdTransformUtil.h"
10
11 class BP_Proxy;
12
13 ///todo: fill all the empty CcdPhysicsController methods, hook them up to the RigidBody class
14
15 //'temporarily' global variables
16 float   gDeactivationTime = 2.f;
17 bool    gDisableDeactivation = false;
18
19 float gLinearSleepingTreshold = 0.8f;
20 float gAngularSleepingTreshold = 1.0f;
21
22 #include "Dynamics/MassProps.h"
23
24 SimdVector3 startVel(0,0,0);//-10000);
25 CcdPhysicsController::CcdPhysicsController (const CcdConstructionInfo& ci)
26 :m_cci(ci)
27 {
28         m_collisionDelay = 0;
29         m_newClientInfo = 0;
30         
31         m_MotionState = ci.m_MotionState;
32
33         
34         
35         CreateRigidbody();
36         
37
38         
39         #ifdef WIN32
40         if (m_body->getInvMass())
41                 m_body->setLinearVelocity(startVel);
42         #endif
43
44 }
45
46 SimdTransform   CcdPhysicsController::GetTransformFromMotionState(PHY_IMotionState* motionState)
47 {
48         SimdTransform trans;
49         float tmp[3];
50         motionState->getWorldPosition(tmp[0],tmp[1],tmp[2]);
51         trans.setOrigin(SimdVector3(tmp[0],tmp[1],tmp[2]));
52
53         SimdQuaternion orn;
54         motionState->getWorldOrientation(orn[0],orn[1],orn[2],orn[3]);
55         trans.setRotation(orn);
56         return trans;
57
58 }
59
60 void CcdPhysicsController::CreateRigidbody()
61 {
62
63         SimdTransform trans = GetTransformFromMotionState(m_cci.m_MotionState);
64
65         MassProps mp(m_cci.m_mass, m_cci.m_localInertiaTensor);
66
67         m_body = new RigidBody(mp,0,0,m_cci.m_friction,m_cci.m_restitution);
68         m_body->m_collisionShape = m_cci.m_collisionShape;
69         
70
71         //
72         // init the rigidbody properly
73         //
74         
75         m_body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
76         //setMassProps this also sets collisionFlags
77         m_body->m_collisionFlags = m_cci.m_collisionFlags;
78         
79         m_body->setGravity( m_cci.m_gravity);
80         m_body->setDamping(m_cci.m_linearDamping, m_cci.m_angularDamping);
81         m_body->setCenterOfMassTransform( trans );
82
83
84 }
85
86 CcdPhysicsController::~CcdPhysicsController()
87 {
88         //will be reference counted, due to sharing
89         m_cci.m_physicsEnv->removeCcdPhysicsController(this);
90         delete m_MotionState;
91         delete m_body;
92 }
93
94                 /**
95                         SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
96                 */
97 bool            CcdPhysicsController::SynchronizeMotionStates(float time)
98 {
99         //sync non-static to motionstate, and static from motionstate (todo: add kinematic etc.)
100
101         if (!m_body->IsStatic())
102         {
103                 const SimdVector3& worldPos = m_body->getCenterOfMassPosition();
104                 m_MotionState->setWorldPosition(worldPos[0],worldPos[1],worldPos[2]);
105                 
106                 const SimdQuaternion& worldquat = m_body->getOrientation();
107                 m_MotionState->setWorldOrientation(worldquat[0],worldquat[1],worldquat[2],worldquat[3]);
108
109                 m_MotionState->calculateWorldTransformations();
110
111                 float scale[3];
112                 m_MotionState->getWorldScaling(scale[0],scale[1],scale[2]);
113                 SimdVector3 scaling(scale[0],scale[1],scale[2]);
114                 GetCollisionShape()->setLocalScaling(scaling);
115         } else
116         {
117                 SimdVector3 worldPos;
118                 SimdQuaternion worldquat;
119
120                 m_MotionState->getWorldPosition(worldPos[0],worldPos[1],worldPos[2]);
121                 m_MotionState->getWorldOrientation(worldquat[0],worldquat[1],worldquat[2],worldquat[3]);
122                 SimdTransform oldTrans = m_body->getCenterOfMassTransform();
123                 SimdTransform newTrans(worldquat,worldPos);
124                 
125                 m_body->setCenterOfMassTransform(newTrans);
126                 //need to keep track of previous position for friction effects...
127                 
128                 m_MotionState->calculateWorldTransformations();
129
130                 float scale[3];
131                 m_MotionState->getWorldScaling(scale[0],scale[1],scale[2]);
132                 SimdVector3 scaling(scale[0],scale[1],scale[2]);
133                 GetCollisionShape()->setLocalScaling(scaling);
134         }
135         return true;
136
137 }
138
139                 /**
140                         WriteMotionStateToDynamics synchronizes dynas, kinematic and deformable entities (and do 'late binding')
141                 */
142                 
143 void            CcdPhysicsController::WriteMotionStateToDynamics(bool nondynaonly)
144 {
145
146 }
147 void            CcdPhysicsController::WriteDynamicsToMotionState()
148 {
149 }
150                 // controller replication
151 void            CcdPhysicsController::PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl)
152 {
153         m_MotionState = motionstate;
154
155         
156
157         m_body = 0;
158         CreateRigidbody();
159         
160         m_cci.m_physicsEnv->addCcdPhysicsController(this);
161
162
163 /*      SM_Object* dynaparent=0;
164         SumoPhysicsController* sumoparentctrl = (SumoPhysicsController* )parentctrl;
165         
166         if (sumoparentctrl)
167         {
168                 dynaparent = sumoparentctrl->GetSumoObject();
169         }
170         
171         SM_Object* orgsumoobject = m_sumoObj;
172         
173         
174         m_sumoObj       =       new SM_Object(
175                 orgsumoobject->getShapeHandle(), 
176                 orgsumoobject->getMaterialProps(),                      
177                 orgsumoobject->getShapeProps(),
178                 dynaparent);
179         
180         m_sumoObj->setRigidBody(orgsumoobject->isRigidBody());
181         
182         m_sumoObj->setMargin(orgsumoobject->getMargin());
183         m_sumoObj->setPosition(orgsumoobject->getPosition());
184         m_sumoObj->setOrientation(orgsumoobject->getOrientation());
185         //if it is a dyna, register for a callback
186         m_sumoObj->registerCallback(*this);
187         
188         m_sumoScene->add(* (m_sumoObj));
189         */
190
191
192
193 }
194
195                 // kinematic methods
196 void            CcdPhysicsController::RelativeTranslate(float dlocX,float dlocY,float dlocZ,bool local)
197 {
198         SimdVector3 dloc(dlocX,dlocY,dlocZ);
199         SimdTransform xform = m_body->getCenterOfMassTransform();
200
201         if (local)
202         {
203                 dloc = xform.getBasis()*dloc;
204         }
205
206         xform.setOrigin(xform.getOrigin() + dloc);
207         this->m_body->setCenterOfMassTransform(xform);
208
209 }
210
211 void            CcdPhysicsController::RelativeRotate(const float rotval[9],bool local)
212 {
213         if (m_body )
214         {
215                 SimdMatrix3x3 drotmat(  rotval[0],rotval[1],rotval[2],
216                                                                 rotval[4],rotval[5],rotval[6],
217                                                                 rotval[8],rotval[9],rotval[10]);
218
219
220                 SimdMatrix3x3 currentOrn;
221                 GetWorldOrientation(currentOrn);
222
223                 SimdTransform xform = m_body->getCenterOfMassTransform();
224
225                 xform.setBasis(xform.getBasis()*(local ? 
226                 drotmat : (currentOrn.inverse() * drotmat * currentOrn)));
227
228                 m_body->setCenterOfMassTransform(xform);
229         }
230
231 }
232
233 void CcdPhysicsController::GetWorldOrientation(SimdMatrix3x3& mat)
234 {
235         float orn[4];
236         m_MotionState->getWorldOrientation(orn[0],orn[1],orn[2],orn[3]);
237         SimdQuaternion quat(orn[0],orn[1],orn[2],orn[3]);
238         mat.setRotation(quat);
239 }
240
241 void            CcdPhysicsController::getOrientation(float &quatImag0,float &quatImag1,float &quatImag2,float &quatReal)
242 {
243         SimdQuaternion q = m_body->getCenterOfMassTransform().getRotation();
244         quatImag0 = q[0];
245         quatImag1 = q[1];
246         quatImag2 = q[2];
247         quatReal = q[3];
248 }
249 void            CcdPhysicsController::setOrientation(float quatImag0,float quatImag1,float quatImag2,float quatReal)
250 {
251         m_body->activate();
252
253         SimdTransform xform  = m_body->getCenterOfMassTransform();
254         xform.setRotation(SimdQuaternion(quatImag0,quatImag1,quatImag2,quatReal));
255         m_body->setCenterOfMassTransform(xform);
256
257 }
258
259 void            CcdPhysicsController::setPosition(float posX,float posY,float posZ)
260 {
261         m_body->activate();
262
263         SimdTransform xform  = m_body->getCenterOfMassTransform();
264         xform.setOrigin(SimdVector3(posX,posY,posZ));
265         m_body->setCenterOfMassTransform(xform);
266
267 }
268 void            CcdPhysicsController::resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ)
269 {
270 }
271
272 void            CcdPhysicsController::getPosition(PHY__Vector3& pos) const
273 {
274         const SimdTransform& xform = m_body->getCenterOfMassTransform();
275         pos[0] = xform.getOrigin().x();
276         pos[1] = xform.getOrigin().y();
277         pos[2] = xform.getOrigin().z();
278 }
279
280 void            CcdPhysicsController::setScaling(float scaleX,float scaleY,float scaleZ)
281 {
282         if (!SimdFuzzyZero(m_cci.m_scaling.x()-scaleX) ||
283                 !SimdFuzzyZero(m_cci.m_scaling.y()-scaleY) ||
284                 !SimdFuzzyZero(m_cci.m_scaling.z()-scaleZ))
285         {
286                 m_cci.m_scaling = SimdVector3(scaleX,scaleY,scaleZ);
287
288                 if (m_body && m_body->GetCollisionShape())
289                 {
290                         m_body->GetCollisionShape()->setLocalScaling(m_cci.m_scaling);
291                         m_body->GetCollisionShape()->CalculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
292                         m_body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
293                 }
294         }
295 }
296                 
297                 // physics methods
298 void            CcdPhysicsController::ApplyTorque(float torqueX,float torqueY,float torqueZ,bool local)
299 {
300         SimdVector3 torque(torqueX,torqueY,torqueZ);
301         SimdTransform xform = m_body->getCenterOfMassTransform();
302         if (local)
303         {
304                 torque  = xform.getBasis()*torque;
305         }
306         m_body->applyTorque(torque);
307 }
308
309 void            CcdPhysicsController::ApplyForce(float forceX,float forceY,float forceZ,bool local)
310 {
311         SimdVector3 force(forceX,forceY,forceZ);
312         SimdTransform xform = m_body->getCenterOfMassTransform();
313         if (local)
314         {
315                 force   = xform.getBasis()*force;
316         }
317         m_body->applyCentralForce(force);
318 }
319 void            CcdPhysicsController::SetAngularVelocity(float ang_velX,float ang_velY,float ang_velZ,bool local)
320 {
321         SimdVector3 angvel(ang_velX,ang_velY,ang_velZ);
322         SimdTransform xform = m_body->getCenterOfMassTransform();
323         if (local)
324         {
325                 angvel  = xform.getBasis()*angvel;
326         }
327
328         m_body->setAngularVelocity(angvel);
329
330 }
331 void            CcdPhysicsController::SetLinearVelocity(float lin_velX,float lin_velY,float lin_velZ,bool local)
332 {
333         SimdVector3 linVel(lin_velX,lin_velY,lin_velZ);
334         SimdTransform xform = m_body->getCenterOfMassTransform();
335         if (local)
336         {
337                 linVel  = xform.getBasis()*linVel;
338         }
339         m_body->setLinearVelocity(linVel);
340 }
341 void            CcdPhysicsController::applyImpulse(float attachX,float attachY,float attachZ, float impulseX,float impulseY,float impulseZ)
342 {
343         
344         SimdVector3 impulse(impulseX,impulseY,impulseZ);
345         SimdVector3 pos(attachX,attachY,attachZ);
346
347         m_body->activate();
348
349         m_body->applyImpulse(impulse,pos);
350
351 }
352 void            CcdPhysicsController::SetActive(bool active)
353 {
354 }
355                 // reading out information from physics
356 void            CcdPhysicsController::GetLinearVelocity(float& linvX,float& linvY,float& linvZ)
357 {
358         const SimdVector3& linvel = this->m_body->getLinearVelocity();
359         linvX = linvel.x();
360         linvY = linvel.y();
361         linvZ = linvel.z();
362
363 }
364
365 void            CcdPhysicsController::GetAngularVelocity(float& angVelX,float& angVelY,float& angVelZ)
366 {
367         const SimdVector3& angvel= m_body->getAngularVelocity();
368         angVelX = angvel.x();
369         angVelY = angvel.y();
370         angVelZ = angvel.z();
371 }
372
373 void            CcdPhysicsController::GetVelocity(const float posX,const float posY,const float posZ,float& linvX,float& linvY,float& linvZ)
374 {
375         SimdVector3 pos(posX,posY,posZ);
376         SimdVector3 rel_pos = pos-m_body->getCenterOfMassPosition();
377         SimdVector3 linvel = m_body->getVelocityInLocalPoint(rel_pos);
378         linvX = linvel.x();
379         linvY = linvel.y();
380         linvZ = linvel.z();
381 }
382 void            CcdPhysicsController::getReactionForce(float& forceX,float& forceY,float& forceZ)
383 {
384 }
385
386                 // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted 
387 void            CcdPhysicsController::setRigidBody(bool rigid)
388 {
389         if (!rigid)
390         {
391                 //fake it for now
392                 SimdVector3 inertia = m_body->getInvInertiaDiagLocal();
393                 inertia[1] = 0.f;
394                 m_body->setInvInertiaDiagLocal(inertia);
395                 m_body->updateInertiaTensor();
396         }
397 }
398
399                 // clientinfo for raycasts for example
400 void*           CcdPhysicsController::getNewClientInfo()
401 {
402         return m_newClientInfo;
403 }
404 void            CcdPhysicsController::setNewClientInfo(void* clientinfo)
405 {
406         m_newClientInfo = clientinfo;
407 }
408
409
410 void    CcdPhysicsController::UpdateDeactivation(float timeStep)
411 {
412         if ( (m_body->GetActivationState() == ISLAND_SLEEPING) || (m_body->GetActivationState() == DISABLE_DEACTIVATION))
413                 return;
414
415         if ((m_body->getLinearVelocity().length2() < gLinearSleepingTreshold*gLinearSleepingTreshold) &&
416                 (m_body->getAngularVelocity().length2() < gAngularSleepingTreshold*gAngularSleepingTreshold))
417         {
418                 m_body->m_deactivationTime += timeStep;
419         } else
420         {
421                 m_body->m_deactivationTime=0.f;
422                 m_body->SetActivationState(0);
423         }
424
425 }
426
427 bool CcdPhysicsController::wantsSleeping()
428 {
429
430         if (m_body->GetActivationState() == DISABLE_DEACTIVATION)
431                 return false;
432
433         //disable deactivation
434         if (gDisableDeactivation || (gDeactivationTime == 0.f))
435                 return false;
436
437         if ( (m_body->GetActivationState() == ISLAND_SLEEPING) || (m_body->GetActivationState() == WANTS_DEACTIVATION))
438                 return true;
439
440         if (m_body->m_deactivationTime> gDeactivationTime)
441         {
442                 return true;
443         }
444         return false;
445 }
446