added 'disable sleeping' option for rigidbodies. + bugfix of out of sync wheels for...
[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
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         m_body->setGravity( m_cci.m_gravity);
77         m_body->setDamping(m_cci.m_linearDamping, m_cci.m_angularDamping);
78         m_body->setCenterOfMassTransform( trans );
79
80
81 }
82
83 CcdPhysicsController::~CcdPhysicsController()
84 {
85         //will be reference counted, due to sharing
86         m_cci.m_physicsEnv->removeCcdPhysicsController(this);
87         delete m_MotionState;
88         delete m_body;
89 }
90
91                 /**
92                         SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
93                 */
94 bool            CcdPhysicsController::SynchronizeMotionStates(float time)
95 {
96         const SimdVector3& worldPos = m_body->getCenterOfMassPosition();
97         m_MotionState->setWorldPosition(worldPos[0],worldPos[1],worldPos[2]);
98         
99         const SimdQuaternion& worldquat = m_body->getOrientation();
100         m_MotionState->setWorldOrientation(worldquat[0],worldquat[1],worldquat[2],worldquat[3]);
101
102         m_MotionState->calculateWorldTransformations();
103
104         float scale[3];
105         m_MotionState->getWorldScaling(scale[0],scale[1],scale[2]);
106         SimdVector3 scaling(scale[0],scale[1],scale[2]);
107         GetCollisionShape()->setLocalScaling(scaling);
108
109         return true;
110 }
111
112                 /**
113                         WriteMotionStateToDynamics synchronizes dynas, kinematic and deformable entities (and do 'late binding')
114                 */
115                 
116 void            CcdPhysicsController::WriteMotionStateToDynamics(bool nondynaonly)
117 {
118
119 }
120 void            CcdPhysicsController::WriteDynamicsToMotionState()
121 {
122 }
123                 // controller replication
124 void            CcdPhysicsController::PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl)
125 {
126         m_MotionState = motionstate;
127
128         
129
130         m_body = 0;
131         CreateRigidbody();
132         
133         m_cci.m_physicsEnv->addCcdPhysicsController(this);
134
135
136 /*      SM_Object* dynaparent=0;
137         SumoPhysicsController* sumoparentctrl = (SumoPhysicsController* )parentctrl;
138         
139         if (sumoparentctrl)
140         {
141                 dynaparent = sumoparentctrl->GetSumoObject();
142         }
143         
144         SM_Object* orgsumoobject = m_sumoObj;
145         
146         
147         m_sumoObj       =       new SM_Object(
148                 orgsumoobject->getShapeHandle(), 
149                 orgsumoobject->getMaterialProps(),                      
150                 orgsumoobject->getShapeProps(),
151                 dynaparent);
152         
153         m_sumoObj->setRigidBody(orgsumoobject->isRigidBody());
154         
155         m_sumoObj->setMargin(orgsumoobject->getMargin());
156         m_sumoObj->setPosition(orgsumoobject->getPosition());
157         m_sumoObj->setOrientation(orgsumoobject->getOrientation());
158         //if it is a dyna, register for a callback
159         m_sumoObj->registerCallback(*this);
160         
161         m_sumoScene->add(* (m_sumoObj));
162         */
163
164
165
166 }
167
168                 // kinematic methods
169 void            CcdPhysicsController::RelativeTranslate(float dlocX,float dlocY,float dlocZ,bool local)
170 {
171         SimdVector3 dloc(dlocX,dlocY,dlocZ);
172         SimdTransform xform = m_body->getCenterOfMassTransform();
173
174         if (local)
175         {
176                 dloc = xform.getBasis()*dloc;
177         }
178
179         xform.setOrigin(xform.getOrigin() + dloc);
180         this->m_body->setCenterOfMassTransform(xform);
181
182 }
183
184 void            CcdPhysicsController::RelativeRotate(const float rotval[9],bool local)
185 {
186         if (m_body )
187         {
188                 SimdMatrix3x3 drotmat(  rotval[0],rotval[1],rotval[2],
189                                                                 rotval[4],rotval[5],rotval[6],
190                                                                 rotval[8],rotval[9],rotval[10]);
191
192
193                 SimdMatrix3x3 currentOrn;
194                 GetWorldOrientation(currentOrn);
195
196                 SimdTransform xform = m_body->getCenterOfMassTransform();
197
198                 xform.setBasis(xform.getBasis()*(local ? 
199                 drotmat : (currentOrn.inverse() * drotmat * currentOrn)));
200
201                 m_body->setCenterOfMassTransform(xform);
202         }
203
204 }
205
206 void CcdPhysicsController::GetWorldOrientation(SimdMatrix3x3& mat)
207 {
208         float orn[4];
209         m_MotionState->getWorldOrientation(orn[0],orn[1],orn[2],orn[3]);
210         SimdQuaternion quat(orn[0],orn[1],orn[2],orn[3]);
211         mat.setRotation(quat);
212 }
213
214 void            CcdPhysicsController::getOrientation(float &quatImag0,float &quatImag1,float &quatImag2,float &quatReal)
215 {
216         SimdQuaternion q = m_body->getCenterOfMassTransform().getRotation();
217         quatImag0 = q[0];
218         quatImag1 = q[1];
219         quatImag2 = q[2];
220         quatReal = q[3];
221 }
222 void            CcdPhysicsController::setOrientation(float quatImag0,float quatImag1,float quatImag2,float quatReal)
223 {
224         m_body->activate();
225
226         SimdTransform xform  = m_body->getCenterOfMassTransform();
227         xform.setRotation(SimdQuaternion(quatImag0,quatImag1,quatImag2,quatReal));
228         m_body->setCenterOfMassTransform(xform);
229
230 }
231
232 void            CcdPhysicsController::setPosition(float posX,float posY,float posZ)
233 {
234         m_body->activate();
235
236         SimdTransform xform  = m_body->getCenterOfMassTransform();
237         xform.setOrigin(SimdVector3(posX,posY,posZ));
238         m_body->setCenterOfMassTransform(xform);
239
240 }
241 void            CcdPhysicsController::resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ)
242 {
243 }
244
245 void            CcdPhysicsController::getPosition(PHY__Vector3& pos) const
246 {
247         const SimdTransform& xform = m_body->getCenterOfMassTransform();
248         pos[0] = xform.getOrigin().x();
249         pos[1] = xform.getOrigin().y();
250         pos[2] = xform.getOrigin().z();
251 }
252
253 void            CcdPhysicsController::setScaling(float scaleX,float scaleY,float scaleZ)
254 {
255         if (!SimdFuzzyZero(m_cci.m_scaling.x()-scaleX) ||
256                 !SimdFuzzyZero(m_cci.m_scaling.y()-scaleY) ||
257                 !SimdFuzzyZero(m_cci.m_scaling.z()-scaleZ))
258         {
259                 m_cci.m_scaling = SimdVector3(scaleX,scaleY,scaleZ);
260
261                 if (m_body && m_body->GetCollisionShape())
262                 {
263                         m_body->GetCollisionShape()->setLocalScaling(m_cci.m_scaling);
264                         m_body->GetCollisionShape()->CalculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor);
265                         m_body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor);
266                 }
267         }
268 }
269                 
270                 // physics methods
271 void            CcdPhysicsController::ApplyTorque(float torqueX,float torqueY,float torqueZ,bool local)
272 {
273         SimdVector3 torque(torqueX,torqueY,torqueZ);
274         SimdTransform xform = m_body->getCenterOfMassTransform();
275         if (local)
276         {
277                 torque  = xform.getBasis()*torque;
278         }
279         m_body->applyTorque(torque);
280 }
281
282 void            CcdPhysicsController::ApplyForce(float forceX,float forceY,float forceZ,bool local)
283 {
284         SimdVector3 force(forceX,forceY,forceZ);
285         SimdTransform xform = m_body->getCenterOfMassTransform();
286         if (local)
287         {
288                 force   = xform.getBasis()*force;
289         }
290         m_body->applyCentralForce(force);
291 }
292 void            CcdPhysicsController::SetAngularVelocity(float ang_velX,float ang_velY,float ang_velZ,bool local)
293 {
294         SimdVector3 angvel(ang_velX,ang_velY,ang_velZ);
295         SimdTransform xform = m_body->getCenterOfMassTransform();
296         if (local)
297         {
298                 angvel  = xform.getBasis()*angvel;
299         }
300
301         m_body->setAngularVelocity(angvel);
302
303 }
304 void            CcdPhysicsController::SetLinearVelocity(float lin_velX,float lin_velY,float lin_velZ,bool local)
305 {
306         SimdVector3 linVel(lin_velX,lin_velY,lin_velZ);
307         SimdTransform xform = m_body->getCenterOfMassTransform();
308         if (local)
309         {
310                 linVel  = xform.getBasis()*linVel;
311         }
312         m_body->setLinearVelocity(linVel);
313 }
314 void            CcdPhysicsController::applyImpulse(float attachX,float attachY,float attachZ, float impulseX,float impulseY,float impulseZ)
315 {
316         
317         SimdVector3 impulse(impulseX,impulseY,impulseZ);
318         SimdVector3 pos(attachX,attachY,attachZ);
319
320         m_body->activate();
321
322         m_body->applyImpulse(impulse,pos);
323
324 }
325 void            CcdPhysicsController::SetActive(bool active)
326 {
327 }
328                 // reading out information from physics
329 void            CcdPhysicsController::GetLinearVelocity(float& linvX,float& linvY,float& linvZ)
330 {
331         const SimdVector3& linvel = this->m_body->getLinearVelocity();
332         linvX = linvel.x();
333         linvY = linvel.y();
334         linvZ = linvel.z();
335
336 }
337
338 void            CcdPhysicsController::GetAngularVelocity(float& angVelX,float& angVelY,float& angVelZ)
339 {
340         const SimdVector3& angvel= m_body->getAngularVelocity();
341         angVelX = angvel.x();
342         angVelY = angvel.y();
343         angVelZ = angvel.z();
344 }
345
346 void            CcdPhysicsController::GetVelocity(const float posX,const float posY,const float posZ,float& linvX,float& linvY,float& linvZ)
347 {
348         SimdVector3 pos(posX,posY,posZ);
349         SimdVector3 rel_pos = pos-m_body->getCenterOfMassPosition();
350         SimdVector3 linvel = m_body->getVelocityInLocalPoint(rel_pos);
351         linvX = linvel.x();
352         linvY = linvel.y();
353         linvZ = linvel.z();
354 }
355 void            CcdPhysicsController::getReactionForce(float& forceX,float& forceY,float& forceZ)
356 {
357 }
358
359                 // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted 
360 void            CcdPhysicsController::setRigidBody(bool rigid)
361 {
362 }
363
364                 // clientinfo for raycasts for example
365 void*           CcdPhysicsController::getNewClientInfo()
366 {
367         return m_newClientInfo;
368 }
369 void            CcdPhysicsController::setNewClientInfo(void* clientinfo)
370 {
371         m_newClientInfo = clientinfo;
372 }
373
374
375 void    CcdPhysicsController::UpdateDeactivation(float timeStep)
376 {
377         if ( (m_body->GetActivationState() == ISLAND_SLEEPING) || (m_body->GetActivationState() == DISABLE_DEACTIVATION))
378                 return;
379
380         if ((m_body->getLinearVelocity().length2() < gLinearSleepingTreshold*gLinearSleepingTreshold) &&
381                 (m_body->getAngularVelocity().length2() < gAngularSleepingTreshold*gAngularSleepingTreshold))
382         {
383                 m_body->m_deactivationTime += timeStep;
384         } else
385         {
386                 m_body->m_deactivationTime=0.f;
387                 m_body->SetActivationState(0);
388         }
389
390 }
391
392 bool CcdPhysicsController::wantsSleeping()
393 {
394
395         if (m_body->GetActivationState() == DISABLE_DEACTIVATION)
396                 return false;
397
398         //disable deactivation
399         if (gDisableDeactivation || (gDeactivationTime == 0.f))
400                 return false;
401
402         if ( (m_body->GetActivationState() == ISLAND_SLEEPING) || (m_body->GetActivationState() == WANTS_DEACTIVATION))
403                 return true;
404
405         if (m_body->m_deactivationTime> gDeactivationTime)
406         {
407                 return true;
408         }
409         return false;
410 }
411