more game engine bug-fixes, hooked up 'formfactor' as inertia tensor tweaker, frictio...
[blender-staging.git] / source / gameengine / Physics / Bullet / CcdPhysicsEnvironment.cpp
1 #include "CcdPhysicsEnvironment.h"
2 #include "CcdPhysicsController.h"
3
4 #include <algorithm>
5 #include "SimdTransform.h"
6 #include "Dynamics/RigidBody.h"
7 #include "BroadphaseCollision/BroadphaseInterface.h"
8 #include "BroadphaseCollision/SimpleBroadphase.h"
9
10 #include "CollisionShapes/ConvexShape.h"
11 #include "BroadphaseCollision/CollisionDispatcher.h"
12 #include "NarrowPhaseCollision/PersistentManifold.h"
13 #include "CollisionShapes/TriangleMeshShape.h"
14 #include "ConstraintSolver/OdeConstraintSolver.h"
15 #include "ConstraintSolver/SimpleConstraintSolver.h"
16
17 #include "IDebugDraw.h"
18
19 #include "NarrowPhaseCollision/VoronoiSimplexSolver.h"
20 #include "NarrowPhaseCollision/SubSimplexConvexCast.h"
21
22 #include "CollisionDispatch/ToiContactDispatcher.h"
23
24
25 #include "CollisionDispatch/EmptyCollisionAlgorithm.h"
26 #include "CollisionDispatch/UnionFind.h"
27
28 #include "NarrowPhaseCollision/RaycastCallback.h"
29 #include "CollisionShapes/SphereShape.h"
30
31 bool useIslands = true;
32
33 #include "ConstraintSolver/ConstraintSolver.h"
34 #include "ConstraintSolver/Point2PointConstraint.h"
35 //#include "BroadphaseCollision/QueryDispatcher.h"
36 //#include "BroadphaseCollision/QueryBox.h"
37 //todo: change this to allow dynamic registration of types!
38
39 #ifdef WIN32
40 void DrawRasterizerLine(const float* from,const float* to,int color);
41 #endif
42
43
44 #include "ConstraintSolver/ContactConstraint.h"
45
46
47
48 #include <stdio.h>
49
50
51
52
53 static void DrawAabb(IDebugDraw* debugDrawer,const SimdVector3& from,const SimdVector3& to,const SimdVector3& color)
54 {
55         SimdVector3 halfExtents = (to-from)* 0.5f;
56         SimdVector3 center = (to+from) *0.5f;
57         int i,j;
58
59         SimdVector3 edgecoord(1.f,1.f,1.f),pa,pb;
60         for (i=0;i<4;i++)
61         {
62                 for (j=0;j<3;j++)
63                 {
64                         pa = SimdVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1],              
65                                 edgecoord[2]*halfExtents[2]);
66                         pa+=center;
67                         
68                         int othercoord = j%3;
69                         edgecoord[othercoord]*=-1.f;
70                         pb = SimdVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1],      
71                                 edgecoord[2]*halfExtents[2]);
72                         pb+=center;
73                         
74                         debugDrawer->DrawLine(pa,pb,color);
75                 }
76                 edgecoord = SimdVector3(-1.f,-1.f,-1.f);
77                 if (i<3)
78                         edgecoord[i]*=-1.f;
79         }
80
81
82 }
83
84
85
86
87
88
89 CcdPhysicsEnvironment::CcdPhysicsEnvironment(ToiContactDispatcher* dispatcher,BroadphaseInterface* bp)
90 :m_dispatcher(dispatcher),
91 m_broadphase(bp),
92 m_scalingPropagated(false),
93 m_numIterations(30),
94 m_ccdMode(0),
95 m_solverType(-1)
96 {
97
98         if (!m_dispatcher)
99         {
100                 setSolverType(0);
101         }
102
103         if (!m_broadphase)
104         {
105                 m_broadphase = new SimpleBroadphase();
106         }
107         
108         m_debugDrawer = 0;
109         m_gravity = SimdVector3(0.f,-10.f,0.f);
110         
111
112 }
113
114 void    CcdPhysicsEnvironment::addCcdPhysicsController(CcdPhysicsController* ctrl)
115 {
116         ctrl->GetRigidBody()->setGravity( m_gravity );
117         m_controllers.push_back(ctrl);
118         
119         BroadphaseInterface* scene =  m_broadphase;
120         
121         CollisionShape* shapeinterface = ctrl->GetCollisionShape();
122         
123         assert(shapeinterface);
124         
125         const SimdTransform& t = ctrl->GetRigidBody()->getCenterOfMassTransform();
126         
127         RigidBody* body = ctrl->GetRigidBody();
128         
129         SimdPoint3 minAabb,maxAabb;
130         
131         shapeinterface->GetAabb(t,minAabb,maxAabb);
132         
133         float timeStep = 0.02f;
134         
135         
136         //extent it with the motion
137         
138         SimdVector3 linMotion = body->getLinearVelocity()*timeStep;
139         
140         float maxAabbx = maxAabb.getX();
141         float maxAabby = maxAabb.getY();
142         float maxAabbz = maxAabb.getZ();
143         float minAabbx = minAabb.getX();
144         float minAabby = minAabb.getY();
145         float minAabbz = minAabb.getZ();
146
147         if (linMotion.x() > 0.f)
148                 maxAabbx += linMotion.x(); 
149         else
150                 minAabbx += linMotion.x();
151         if (linMotion.y() > 0.f)
152                 maxAabby += linMotion.y(); 
153         else
154                 minAabby += linMotion.y();
155         if (linMotion.z() > 0.f)
156                 maxAabbz += linMotion.z(); 
157         else
158                 minAabbz += linMotion.z();
159         
160
161         minAabb = SimdVector3(minAabbx,minAabby,minAabbz);
162         maxAabb = SimdVector3(maxAabbx,maxAabby,maxAabbz);
163         
164         if (!ctrl->m_broadphaseHandle)
165         {
166                 int type = shapeinterface->GetShapeType();
167                 ctrl->m_broadphaseHandle = scene->CreateProxy(
168                         ctrl->GetRigidBody(),
169                         type,
170                         minAabb, 
171                         maxAabb);
172         }
173         
174         body->SetCollisionShape( shapeinterface );
175         
176         
177         
178 }
179
180 void    CcdPhysicsEnvironment::removeCcdPhysicsController(CcdPhysicsController* ctrl)
181 {
182         
183         //also remove constraint
184         
185         {
186                 std::vector<Point2PointConstraint*>::iterator i;
187                 
188                 for (i=m_p2pConstraints.begin();
189                 !(i==m_p2pConstraints.end()); i++)
190                 {
191                         Point2PointConstraint* p2p = (*i);
192                         if  ((&p2p->GetRigidBodyA() == ctrl->GetRigidBody() ||
193                                 (&p2p->GetRigidBodyB() == ctrl->GetRigidBody())))
194                         {
195                                  removeConstraint(p2p);
196                                 //only 1 constraint per constroller
197                                 break;
198                         }
199                 }
200         }
201         
202         {
203                 std::vector<Point2PointConstraint*>::iterator i;
204                 
205                 for (i=m_p2pConstraints.begin();
206                 !(i==m_p2pConstraints.end()); i++)
207                 {
208                         Point2PointConstraint* p2p = (*i);
209                         if  ((&p2p->GetRigidBodyA() == ctrl->GetRigidBody() ||
210                                 (&p2p->GetRigidBodyB() == ctrl->GetRigidBody())))
211                         {
212                                 removeConstraint(p2p);
213                                 //only 1 constraint per constroller
214                                 break;
215                         }
216                 }
217         }
218         
219         
220         
221         bool removeFromBroadphase = false;
222         
223         {
224                 BroadphaseInterface* scene = m_broadphase;
225                 BroadphaseProxy* bp = (BroadphaseProxy*)ctrl->m_broadphaseHandle;
226                 
227                 if (removeFromBroadphase)
228                 {
229
230                 }
231                 //
232                 // only clear the cached algorithms
233                 //
234                 scene->CleanProxyFromPairs(bp);
235                 scene->DestroyProxy(bp);//??
236         }
237         {
238                 std::vector<CcdPhysicsController*>::iterator i =
239                         std::find(m_controllers.begin(), m_controllers.end(), ctrl);
240                 if (!(i == m_controllers.end()))
241                 {
242                         std::swap(*i, m_controllers.back());
243                         m_controllers.pop_back();
244                 }
245         }
246 }
247
248 void    CcdPhysicsEnvironment::UpdateActivationState()
249 {
250         m_dispatcher->InitUnionFind();
251         
252         // put the index into m_controllers into m_tag  
253         {
254                 std::vector<CcdPhysicsController*>::iterator i;
255                 
256                 int index = 0;
257                 for (i=m_controllers.begin();
258                 !(i==m_controllers.end()); i++)
259                 {
260                         CcdPhysicsController* ctrl = (*i);
261                         RigidBody* body = ctrl->GetRigidBody();
262                         body->m_islandTag1 = index;
263                         body->m_hitFraction = 1.f;
264                         index++;
265                         
266                 }
267         }
268         // do the union find
269         
270         m_dispatcher->FindUnions();
271         
272         // put the islandId ('find' value) into m_tag   
273         {
274                 UnionFind& unionFind = m_dispatcher->GetUnionFind();
275                 
276                 std::vector<CcdPhysicsController*>::iterator i;
277                 
278                 int index = 0;
279                 for (i=m_controllers.begin();
280                 !(i==m_controllers.end()); i++)
281                 {
282                         CcdPhysicsController* ctrl = (*i);
283                         RigidBody* body = ctrl->GetRigidBody();
284                         
285                         
286                         if (body->mergesSimulationIslands())
287                         {
288                                 body->m_islandTag1 = unionFind.find(index);
289                         } else
290                         {
291                                 body->m_islandTag1 = -1;
292                         }
293                         index++;
294                 }
295         }
296         
297 }
298
299
300
301 /// Perform an integration step of duration 'timeStep'.
302 bool    CcdPhysicsEnvironment::proceedDeltaTime(double curTime,float timeStep)
303 {
304         
305         
306 //      printf("CcdPhysicsEnvironment::proceedDeltaTime\n");
307         
308         if (timeStep == 0.f)
309                 return true;
310
311         if (m_debugDrawer)
312         {
313                 gDisableDeactivation = (m_debugDrawer->GetDebugMode() & IDebugDraw::DBG_NoDeactivation);
314         }
315
316
317
318         //clamp hardcoded for now
319         if (timeStep > 0.02)
320                 timeStep = 0.02;
321         
322         //this is needed because scaling is not known in advance, and scaling has to propagate to the shape
323         if (!m_scalingPropagated)
324         {
325                 //SyncMotionStates(timeStep);
326                 //m_scalingPropagated = true;
327         }
328
329
330
331         {
332 //              std::vector<CcdPhysicsController*>::iterator i;
333                 
334                 
335                 
336                 int k;
337                 for (k=0;k<GetNumControllers();k++)
338                 {
339                         CcdPhysicsController* ctrl = m_controllers[k];
340                         //              SimdTransform predictedTrans;
341                         RigidBody* body = ctrl->GetRigidBody();
342                         if (body->GetActivationState() != ISLAND_SLEEPING)
343                         {
344                                 body->applyForces( timeStep);
345                                 body->integrateVelocities( timeStep);
346                         }
347                         
348                 }
349         }
350         BroadphaseInterface*    scene = m_broadphase;
351         
352         
353         //
354         // collision detection (?)
355         //
356         
357         
358         
359         
360         
361         int numsubstep = m_numIterations;
362         
363         
364         DispatcherInfo dispatchInfo;
365         dispatchInfo.m_timeStep = timeStep;
366         dispatchInfo.m_stepCount = 0;
367
368         scene->DispatchAllCollisionPairs(*m_dispatcher,dispatchInfo);///numsubstep,g);
369
370
371
372         
373                 
374         
375         int numRigidBodies = m_controllers.size();
376         
377         UpdateActivationState();
378
379         //contacts
380
381         
382         m_dispatcher->SolveConstraints(timeStep, m_numIterations ,numRigidBodies,m_debugDrawer);
383
384         for (int g=0;g<numsubstep;g++)
385         {
386                 //
387                 // constraint solving
388                 //
389                 
390                 
391                 int i;
392                 int numPoint2Point = m_p2pConstraints.size();
393                 
394                 //point to point constraints
395                 for (i=0;i< numPoint2Point ; i++ )
396                 {
397                         Point2PointConstraint* p2p = m_p2pConstraints[i];
398                         
399                         p2p->BuildJacobian();
400                         p2p->SolveConstraint( timeStep );
401                         
402                 }
403                 /*
404                 //vehicles
405                 int numVehicles = m_vehicles.size();
406                 for (i=0;i<numVehicles;i++)
407                 {
408                         Vehicle* vehicle = m_vehicles[i];
409                         vehicle->UpdateVehicle( timeStep );
410                 }
411                 */
412                 
413                 
414                 
415         }
416         
417         {
418                 
419                 
420                 
421                 {
422                         
423                         std::vector<CcdPhysicsController*>::iterator i;
424                         
425                         //
426                         // update aabbs, only for moving objects (!)
427                         //
428                         for (i=m_controllers.begin();
429                         !(i==m_controllers.end()); i++)
430                         {
431                                 CcdPhysicsController* ctrl = (*i);
432                                 RigidBody* body = ctrl->GetRigidBody();
433                                 
434                                 
435                                 SimdPoint3 minAabb,maxAabb;
436                                 CollisionShape* shapeinterface = ctrl->GetCollisionShape();
437
438
439
440                                 shapeinterface->CalculateTemporalAabb(body->getCenterOfMassTransform(),
441                                         body->getLinearVelocity(),body->getAngularVelocity(),
442                                         timeStep,minAabb,maxAabb);
443
444                                 shapeinterface->GetAabb(body->getCenterOfMassTransform(),
445                                         minAabb,maxAabb);
446
447                                 SimdVector3 manifoldExtraExtents(gContactBreakingTreshold,gContactBreakingTreshold,gContactBreakingTreshold);
448                                 minAabb -= manifoldExtraExtents;
449                                 maxAabb += manifoldExtraExtents;
450                                 
451                                 BroadphaseProxy* bp = (BroadphaseProxy*) ctrl->m_broadphaseHandle;
452                                 if (bp)
453                                 {
454                                         
455 #ifdef WIN32
456                                         SimdVector3 color (1,1,0);
457                                         
458                                         if (m_debugDrawer)
459                                         {       
460                                                 //draw aabb
461                                                 switch (body->GetActivationState())
462                                                 {
463                                                 case ISLAND_SLEEPING:
464                                                         {
465                                                                 color.setValue(1,1,1);
466                                                                 break;
467                                                         }
468                                                 case WANTS_DEACTIVATION:
469                                                         {
470                                                                 color.setValue(0,0,1);
471                                                                 break;
472                                                         }
473                                                 case ACTIVE_TAG:
474                                                         {
475                                                                 break;
476                                                         }
477                                                         
478                                                 };
479
480                                                 if (m_debugDrawer->GetDebugMode() & IDebugDraw::DBG_DrawAabb)
481                                                 {
482                                                         DrawAabb(m_debugDrawer,minAabb,maxAabb,color);
483                                                 }
484                                         }
485 #endif
486
487                                         scene->SetAabb(bp,minAabb,maxAabb);
488
489
490                                         
491                                 }
492                         }
493                         
494                         float toi = 1.f;
495
496
497                         
498                         if (m_ccdMode == 3)
499                         {
500                                 DispatcherInfo dispatchInfo;
501                                 dispatchInfo.m_timeStep = timeStep;
502                                 dispatchInfo.m_stepCount = 0;
503                                 dispatchInfo.m_dispatchFunc = DispatcherInfo::DISPATCH_CONTINUOUS;
504                                 
505                                 scene->DispatchAllCollisionPairs( *m_dispatcher,dispatchInfo);///numsubstep,g);
506                                 toi = dispatchInfo.m_timeOfImpact;
507                         }
508                         
509                         //
510                         // integrating solution
511                         //
512                         
513                         {
514                                 std::vector<CcdPhysicsController*>::iterator i;
515                                 
516                                 for (i=m_controllers.begin();
517                                 !(i==m_controllers.end()); i++)
518                                 {
519                                         
520                                         CcdPhysicsController* ctrl = *i;
521                                         
522                                         SimdTransform predictedTrans;
523                                         RigidBody* body = ctrl->GetRigidBody();
524                                         if (body->GetActivationState() != ISLAND_SLEEPING)
525                                         {
526                                                 body->predictIntegratedTransform(timeStep*      toi, predictedTrans);
527                                                 body->proceedToTransform( predictedTrans);
528
529                                         }
530                                 }
531                                 
532                         }
533                         
534                         
535                         
536                         
537                         
538                         //
539                         // disable sleeping physics objects
540                         //
541                         
542                         std::vector<CcdPhysicsController*> m_sleepingControllers;
543                         
544                         for (i=m_controllers.begin();
545                         !(i==m_controllers.end()); i++)
546                         {
547                                 CcdPhysicsController* ctrl = (*i);
548                                 RigidBody* body = ctrl->GetRigidBody();
549
550                                 ctrl->UpdateDeactivation(timeStep);
551
552                                 
553                                 if (ctrl->wantsSleeping())
554                                 {
555                                         if (body->GetActivationState() == ACTIVE_TAG)
556                                                 body->SetActivationState( WANTS_DEACTIVATION );
557                                 } else
558                                 {
559                                         body->SetActivationState( ACTIVE_TAG );
560                                 }
561
562                                 if (useIslands)
563                                 {
564                                         if (body->GetActivationState() == ISLAND_SLEEPING)
565                                         {
566                                                 m_sleepingControllers.push_back(ctrl);
567                                         }
568                                 } else
569                                 {
570                                         if (ctrl->wantsSleeping())
571                                         {
572                                                 m_sleepingControllers.push_back(ctrl);
573                                         }
574                                 }
575                         }
576                         
577         
578                         
579                         
580         }
581         
582         SyncMotionStates(timeStep);
583
584         }
585         return true;
586 }
587
588 void            CcdPhysicsEnvironment::setDebugMode(int debugMode)
589 {
590         if (m_debugDrawer){
591                 m_debugDrawer->SetDebugMode(debugMode);
592         }
593 }
594
595 void            CcdPhysicsEnvironment::setNumIterations(int numIter)
596 {
597         m_numIterations = numIter;
598 }
599 void            CcdPhysicsEnvironment::setDeactivationTime(float dTime)
600 {
601         gDeactivationTime = dTime;
602 }
603 void            CcdPhysicsEnvironment::setDeactivationLinearTreshold(float linTresh)
604 {
605         gLinearSleepingTreshold = linTresh;
606 }
607 void            CcdPhysicsEnvironment::setDeactivationAngularTreshold(float angTresh) 
608 {
609         gAngularSleepingTreshold = angTresh;
610 }
611 void            CcdPhysicsEnvironment::setContactBreakingTreshold(float contactBreakingTreshold)
612 {
613         gContactBreakingTreshold = contactBreakingTreshold;
614         
615 }
616
617
618 void            CcdPhysicsEnvironment::setCcdMode(int ccdMode)
619 {
620         m_ccdMode = ccdMode;
621 }
622
623
624 void            CcdPhysicsEnvironment::setSolverSorConstant(float sor)
625 {
626         m_dispatcher->SetSor(sor);
627 }
628
629 void            CcdPhysicsEnvironment::setSolverTau(float tau)
630 {
631         m_dispatcher->SetTau(tau);
632 }
633 void            CcdPhysicsEnvironment::setSolverDamping(float damping)
634 {
635         m_dispatcher->SetDamping(damping);
636 }
637
638
639 void            CcdPhysicsEnvironment::setLinearAirDamping(float damping)
640 {
641         gLinearAirDamping = damping;
642 }
643
644 void            CcdPhysicsEnvironment::setUseEpa(bool epa)
645 {
646         gUseEpa = epa;
647 }
648
649 void            CcdPhysicsEnvironment::setSolverType(int solverType)
650 {
651
652         switch (solverType)
653         {
654         case 1:
655                 {
656                         if (m_solverType != solverType)
657                         {
658                                 if (m_dispatcher)
659                                         delete m_dispatcher;
660
661                                 SimpleConstraintSolver* solver= new SimpleConstraintSolver();
662                                 m_dispatcher = new ToiContactDispatcher(solver);
663                                 break;
664                         }
665                 }
666         
667         case 0:
668         default:
669                         if (m_solverType != solverType)
670                         {
671                                 if (m_dispatcher)
672                                         delete m_dispatcher;
673
674                                 OdeConstraintSolver* solver= new OdeConstraintSolver();
675                                 m_dispatcher = new ToiContactDispatcher(solver);
676                                 break;
677                         }
678
679         };
680         
681         m_solverType = solverType ;
682 }
683
684
685
686
687
688 void    CcdPhysicsEnvironment::SyncMotionStates(float timeStep)
689 {
690         std::vector<CcdPhysicsController*>::iterator i;
691
692         //
693         // synchronize the physics and graphics transformations
694         //
695
696         for (i=m_controllers.begin();
697         !(i==m_controllers.end()); i++)
698         {
699                 CcdPhysicsController* ctrl = (*i);
700                 ctrl->SynchronizeMotionStates(timeStep);
701                 
702         }
703
704 }
705 void            CcdPhysicsEnvironment::setGravity(float x,float y,float z)
706 {
707         m_gravity = SimdVector3(x,y,z);
708
709         std::vector<CcdPhysicsController*>::iterator i;
710
711         //todo: review this gravity stuff
712         for (i=m_controllers.begin();
713         !(i==m_controllers.end()); i++)
714         {
715
716                 CcdPhysicsController* ctrl = (*i);
717                 ctrl->GetRigidBody()->setGravity(m_gravity);
718
719         }
720 }
721
722
723 int                     CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl0,class PHY_IPhysicsController* ctrl1,PHY_ConstraintType type,
724                                                                                                                 float pivotX,float pivotY,float pivotZ,
725                                                                                                                 float axisX,float axisY,float axisZ)
726 {
727         
728         
729         CcdPhysicsController* c0 = (CcdPhysicsController*)ctrl0;
730         CcdPhysicsController* c1 = (CcdPhysicsController*)ctrl1;
731         
732         RigidBody* rb0 = c0 ? c0->GetRigidBody() : 0;
733         RigidBody* rb1 = c1 ? c1->GetRigidBody() : 0;
734         
735         ASSERT(rb0);
736         
737         SimdVector3 pivotInA(pivotX,pivotY,pivotZ);
738         SimdVector3 pivotInB = rb1 ? rb1->getCenterOfMassTransform().inverse()(rb0->getCenterOfMassTransform()(pivotInA)) : pivotInA;
739         
740         switch (type)
741         {
742         case PHY_POINT2POINT_CONSTRAINT:
743                 {
744                         
745                         Point2PointConstraint* p2p = 0;
746                         
747                         if (rb1)
748                         {
749                                 p2p = new Point2PointConstraint(*rb0,
750                                         *rb1,pivotInA,pivotInB);
751                         } else
752                         {
753                                 p2p = new Point2PointConstraint(*rb0,
754                                         pivotInA);
755                         }
756                         
757                         m_p2pConstraints.push_back(p2p);
758                         return 0;
759                         
760                         break;
761                 }
762         default:
763                 {
764                 }
765         };
766         
767         //RigidBody& rbA,RigidBody& rbB, const SimdVector3& pivotInA,const SimdVector3& pivotInB
768         
769         return 0;
770         
771 }
772
773 void            CcdPhysicsEnvironment::removeConstraint(void* p2p)
774 {
775         std::vector<Point2PointConstraint*>::iterator i =
776                 std::find(m_p2pConstraints.begin(), m_p2pConstraints.end(), 
777                                 (Point2PointConstraint *)p2p);
778         
779         if (!(i == m_p2pConstraints.end()) )
780         {
781                 std::swap(*i, m_p2pConstraints.back());
782                 m_p2pConstraints.pop_back();
783         }
784         
785 }
786 PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IPhysicsController* ignoreClient, float fromX,float fromY,float fromZ, float toX,float toY,float toZ, 
787                                                                 float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
788 {
789
790         float minFraction = 1.f;
791
792         SimdTransform   rayFromTrans,rayToTrans;
793         rayFromTrans.setIdentity();
794         rayFromTrans.setOrigin(SimdVector3(fromX,fromY,fromZ));
795         rayToTrans.setIdentity();
796         rayToTrans.setOrigin(SimdVector3(toX,toY,toZ));
797
798
799         CcdPhysicsController* nearestHit = 0;
800         
801         std::vector<CcdPhysicsController*>::iterator i;
802         SphereShape pointShape(0.0f);
803
804         /// brute force go over all objects. Once there is a broadphase, use that, or
805         /// add a raycast against aabb first.
806         for (i=m_controllers.begin();
807         !(i==m_controllers.end()); i++)
808         {
809                 CcdPhysicsController* ctrl = (*i);
810                 RigidBody* body = ctrl->GetRigidBody();
811
812                 if (body->GetCollisionShape()->IsConvex())
813                 {
814                         ConvexCast::CastResult rayResult;
815                         rayResult.m_fraction = 1.f;
816
817                         ConvexShape* convexShape = (ConvexShape*) body->GetCollisionShape();
818                         VoronoiSimplexSolver    simplexSolver;
819                         SubsimplexConvexCast convexCaster(&pointShape,convexShape,&simplexSolver);
820                         
821                         if (convexCaster.calcTimeOfImpact(rayFromTrans,rayToTrans,body->getCenterOfMassTransform(),body->getCenterOfMassTransform(),rayResult))
822                         {
823                                 //add hit
824                                 rayResult.m_normal.normalize();
825                                 if (rayResult.m_fraction < minFraction)
826                                 {
827
828
829                                         minFraction = rayResult.m_fraction;
830                                         nearestHit = ctrl;
831                                         normalX = rayResult.m_normal.getX();
832                                         normalY = rayResult.m_normal.getY();
833                                         normalZ = rayResult.m_normal.getZ();
834                                         hitX = rayResult.m_hitTransformA.getOrigin().getX();
835                                         hitY = rayResult.m_hitTransformA.getOrigin().getY();
836                                         hitZ = rayResult.m_hitTransformA.getOrigin().getZ();
837                                 }
838                         }
839                 }
840                 else
841                 {
842                                 if (body->GetCollisionShape()->IsConcave())
843                                 {
844
845                                         TriangleMeshShape* triangleMesh = (TriangleMeshShape*)body->GetCollisionShape();
846                                         
847                                         SimdTransform worldToBody = body->getCenterOfMassTransform().inverse();
848
849                                         SimdVector3 rayFromLocal = worldToBody * rayFromTrans.getOrigin();
850                                         SimdVector3 rayToLocal = worldToBody * rayToTrans.getOrigin();
851
852                                         RaycastCallback rcb(rayFromLocal,rayToLocal);
853                                         rcb.m_hitFraction = minFraction;
854
855                                         SimdVector3 aabbMax(1e30f,1e30f,1e30f);
856
857                                         triangleMesh->ProcessAllTriangles(&rcb,-aabbMax,aabbMax);
858                                         if (rcb.m_hitFound)// && (rcb.m_hitFraction < minFraction))
859                                         {
860                                                 nearestHit = ctrl;
861                                                 minFraction = rcb.m_hitFraction;
862                                                 SimdVector3 hitNormalWorld = body->getCenterOfMassTransform()(rcb.m_hitNormalLocal);
863
864                                                 normalX = hitNormalWorld.getX();
865                                                 normalY = hitNormalWorld.getY();
866                                                 normalZ = hitNormalWorld.getZ();
867                                                 SimdVector3 hitWorld;
868                                                 hitWorld.setInterpolate3(rayFromTrans.getOrigin(),rayToTrans.getOrigin(),rcb.m_hitFraction);
869                                                 hitX = hitWorld.getX();
870                                                 hitY = hitWorld.getY();
871                                                 hitZ = hitWorld.getZ();
872                                                 
873                                         }
874                                 }
875                 }
876         }
877
878         return nearestHit;
879 }
880
881
882
883 int     CcdPhysicsEnvironment::getNumContactPoints()
884 {
885         return 0;
886 }
887
888 void CcdPhysicsEnvironment::getContactPoint(int i,float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
889 {
890         
891 }
892
893
894
895
896
897 Dispatcher* CcdPhysicsEnvironment::GetDispatcher()
898 {
899         return m_dispatcher;
900 }
901
902 CcdPhysicsEnvironment::~CcdPhysicsEnvironment()
903 {
904         
905         
906         m_vehicles.clear();
907         
908         //m_broadphase->DestroyScene();
909         //delete broadphase ? release reference on broadphase ?
910         
911         //first delete scene, then dispatcher, because pairs have to release manifolds on the dispatcher
912         delete m_dispatcher;
913         
914 }
915
916
917 int     CcdPhysicsEnvironment::GetNumControllers()
918 {
919         return m_controllers.size();
920 }
921
922
923 CcdPhysicsController* CcdPhysicsEnvironment::GetPhysicsController( int index)
924 {
925         return m_controllers[index];
926 }
927
928
929 int     CcdPhysicsEnvironment::GetNumManifolds() const
930 {
931         return m_dispatcher->GetNumManifolds();
932 }
933
934 const PersistentManifold*       CcdPhysicsEnvironment::GetManifold(int index) const
935 {
936         return m_dispatcher->GetManifoldByIndexInternal(index);
937 }