75a67e3cb376cec52e14a8113ba213838ba710d2
[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(int(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(int(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 void    CcdPhysicsEnvironment::beginFrame()
300 {
301
302 }
303
304 /// Perform an integration step of duration 'timeStep'.
305 bool    CcdPhysicsEnvironment::proceedDeltaTime(double curTime,float timeStep)
306 {
307         
308         
309 //      printf("CcdPhysicsEnvironment::proceedDeltaTime\n");
310         
311         if (timeStep == 0.f)
312                 return true;
313
314         if (m_debugDrawer)
315         {
316                 gDisableDeactivation = (m_debugDrawer->GetDebugMode() & IDebugDraw::DBG_NoDeactivation);
317         }
318
319
320
321         //clamp hardcoded for now
322         if (timeStep > 0.02)
323                 timeStep = 0.02;
324         
325         //this is needed because scaling is not known in advance, and scaling has to propagate to the shape
326         if (!m_scalingPropagated)
327         {
328                 SyncMotionStates(timeStep);
329                 m_scalingPropagated = true;
330         }
331
332
333
334         {
335 //              std::vector<CcdPhysicsController*>::iterator i;
336                 
337                 
338                 
339                 int k;
340                 for (k=0;k<GetNumControllers();k++)
341                 {
342                         CcdPhysicsController* ctrl = m_controllers[k];
343                         //              SimdTransform predictedTrans;
344                         RigidBody* body = ctrl->GetRigidBody();
345                         if (body->GetActivationState() != ISLAND_SLEEPING)
346                         {
347                                 body->applyForces( timeStep);
348                                 body->integrateVelocities( timeStep);
349                         }
350                         
351                 }
352         }
353         BroadphaseInterface*    scene = m_broadphase;
354         
355         
356         //
357         // collision detection (?)
358         //
359         
360         
361         
362         
363         
364         int numsubstep = m_numIterations;
365         
366         
367         DispatcherInfo dispatchInfo;
368         dispatchInfo.m_timeStep = timeStep;
369         dispatchInfo.m_stepCount = 0;
370
371         scene->DispatchAllCollisionPairs(*m_dispatcher,dispatchInfo);///numsubstep,g);
372
373
374
375         
376                 
377         
378         int numRigidBodies = m_controllers.size();
379         
380         UpdateActivationState();
381
382         //contacts
383
384         
385         m_dispatcher->SolveConstraints(timeStep, m_numIterations ,numRigidBodies,m_debugDrawer);
386
387         for (int g=0;g<numsubstep;g++)
388         {
389                 //
390                 // constraint solving
391                 //
392                 
393                 
394                 int i;
395                 int numPoint2Point = m_p2pConstraints.size();
396                 
397                 //point to point constraints
398                 for (i=0;i< numPoint2Point ; i++ )
399                 {
400                         Point2PointConstraint* p2p = m_p2pConstraints[i];
401                         
402                         p2p->BuildJacobian();
403                         p2p->SolveConstraint( timeStep );
404                         
405                 }
406                 /*
407                 //vehicles
408                 int numVehicles = m_vehicles.size();
409                 for (i=0;i<numVehicles;i++)
410                 {
411                         Vehicle* vehicle = m_vehicles[i];
412                         vehicle->UpdateVehicle( timeStep );
413                 }
414                 */
415                 
416                 
417                 
418         }
419         
420         {
421                 
422                 
423                 
424                 {
425                         
426                         std::vector<CcdPhysicsController*>::iterator i;
427                         
428                         //
429                         // update aabbs, only for moving objects (!)
430                         //
431                         for (i=m_controllers.begin();
432                         !(i==m_controllers.end()); i++)
433                         {
434                                 CcdPhysicsController* ctrl = (*i);
435                                 RigidBody* body = ctrl->GetRigidBody();
436                                 
437                                 
438                                 SimdPoint3 minAabb,maxAabb;
439                                 CollisionShape* shapeinterface = ctrl->GetCollisionShape();
440
441
442
443                                 shapeinterface->CalculateTemporalAabb(body->getCenterOfMassTransform(),
444                                         body->getLinearVelocity(),body->getAngularVelocity(),
445                                         timeStep,minAabb,maxAabb);
446
447                                 shapeinterface->GetAabb(body->getCenterOfMassTransform(),
448                                         minAabb,maxAabb);
449
450                                 SimdVector3 manifoldExtraExtents(gContactBreakingTreshold,gContactBreakingTreshold,gContactBreakingTreshold);
451                                 minAabb -= manifoldExtraExtents;
452                                 maxAabb += manifoldExtraExtents;
453                                 
454                                 BroadphaseProxy* bp = (BroadphaseProxy*) ctrl->m_broadphaseHandle;
455                                 if (bp)
456                                 {
457                                         
458 #ifdef WIN32
459                                         SimdVector3 color (1,1,0);
460                                         
461                                         if (m_debugDrawer)
462                                         {       
463                                                 //draw aabb
464                                                 switch (body->GetActivationState())
465                                                 {
466                                                 case ISLAND_SLEEPING:
467                                                         {
468                                                                 color.setValue(1,1,1);
469                                                                 break;
470                                                         }
471                                                 case WANTS_DEACTIVATION:
472                                                         {
473                                                                 color.setValue(0,0,1);
474                                                                 break;
475                                                         }
476                                                 case ACTIVE_TAG:
477                                                         {
478                                                                 break;
479                                                         }
480                                                         
481                                                 };
482
483                                                 if (m_debugDrawer->GetDebugMode() & IDebugDraw::DBG_DrawAabb)
484                                                 {
485                                                         DrawAabb(m_debugDrawer,minAabb,maxAabb,color);
486                                                 }
487                                         }
488 #endif
489
490                                         scene->SetAabb(bp,minAabb,maxAabb);
491
492
493                                         
494                                 }
495                         }
496                         
497                         float toi = 1.f;
498
499
500                         
501                         if (m_ccdMode == 3)
502                         {
503                                 DispatcherInfo dispatchInfo;
504                                 dispatchInfo.m_timeStep = timeStep;
505                                 dispatchInfo.m_stepCount = 0;
506                                 dispatchInfo.m_dispatchFunc = DispatcherInfo::DISPATCH_CONTINUOUS;
507                                 
508                                 scene->DispatchAllCollisionPairs( *m_dispatcher,dispatchInfo);///numsubstep,g);
509                                 toi = dispatchInfo.m_timeOfImpact;
510                         }
511                         
512                         //
513                         // integrating solution
514                         //
515                         
516                         {
517                                 std::vector<CcdPhysicsController*>::iterator i;
518                                 
519                                 for (i=m_controllers.begin();
520                                 !(i==m_controllers.end()); i++)
521                                 {
522                                         
523                                         CcdPhysicsController* ctrl = *i;
524                                         
525                                         SimdTransform predictedTrans;
526                                         RigidBody* body = ctrl->GetRigidBody();
527                                         if (body->GetActivationState() != ISLAND_SLEEPING)
528                                         {
529                                                 body->predictIntegratedTransform(timeStep*      toi, predictedTrans);
530                                                 body->proceedToTransform( predictedTrans);
531
532                                         }
533                                 }
534                                 
535                         }
536                         
537                         
538                         
539                         
540                         
541                         //
542                         // disable sleeping physics objects
543                         //
544                         
545                         std::vector<CcdPhysicsController*> m_sleepingControllers;
546                         
547                         for (i=m_controllers.begin();
548                         !(i==m_controllers.end()); i++)
549                         {
550                                 CcdPhysicsController* ctrl = (*i);
551                                 RigidBody* body = ctrl->GetRigidBody();
552
553                                 ctrl->UpdateDeactivation(timeStep);
554
555                                 
556                                 if (ctrl->wantsSleeping())
557                                 {
558                                         if (body->GetActivationState() == ACTIVE_TAG)
559                                                 body->SetActivationState( WANTS_DEACTIVATION );
560                                 } else
561                                 {
562                                         body->SetActivationState( ACTIVE_TAG );
563                                 }
564
565                                 if (useIslands)
566                                 {
567                                         if (body->GetActivationState() == ISLAND_SLEEPING)
568                                         {
569                                                 m_sleepingControllers.push_back(ctrl);
570                                         }
571                                 } else
572                                 {
573                                         if (ctrl->wantsSleeping())
574                                         {
575                                                 m_sleepingControllers.push_back(ctrl);
576                                         }
577                                 }
578                         }
579                         
580         
581                         
582                         
583         }
584         
585         SyncMotionStates(timeStep);
586
587         }
588         return true;
589 }
590
591 void            CcdPhysicsEnvironment::setDebugMode(int debugMode)
592 {
593         if (m_debugDrawer){
594                 m_debugDrawer->SetDebugMode(debugMode);
595         }
596 }
597
598 void            CcdPhysicsEnvironment::setNumIterations(int numIter)
599 {
600         m_numIterations = numIter;
601 }
602 void            CcdPhysicsEnvironment::setDeactivationTime(float dTime)
603 {
604         gDeactivationTime = dTime;
605 }
606 void            CcdPhysicsEnvironment::setDeactivationLinearTreshold(float linTresh)
607 {
608         gLinearSleepingTreshold = linTresh;
609 }
610 void            CcdPhysicsEnvironment::setDeactivationAngularTreshold(float angTresh) 
611 {
612         gAngularSleepingTreshold = angTresh;
613 }
614 void            CcdPhysicsEnvironment::setContactBreakingTreshold(float contactBreakingTreshold)
615 {
616         gContactBreakingTreshold = contactBreakingTreshold;
617         
618 }
619
620
621 void            CcdPhysicsEnvironment::setCcdMode(int ccdMode)
622 {
623         m_ccdMode = ccdMode;
624 }
625
626
627 void            CcdPhysicsEnvironment::setSolverSorConstant(float sor)
628 {
629         m_dispatcher->SetSor(sor);
630 }
631
632 void            CcdPhysicsEnvironment::setSolverTau(float tau)
633 {
634         m_dispatcher->SetTau(tau);
635 }
636 void            CcdPhysicsEnvironment::setSolverDamping(float damping)
637 {
638         m_dispatcher->SetDamping(damping);
639 }
640
641
642 void            CcdPhysicsEnvironment::setLinearAirDamping(float damping)
643 {
644         gLinearAirDamping = damping;
645 }
646
647 void            CcdPhysicsEnvironment::setUseEpa(bool epa)
648 {
649         gUseEpa = epa;
650 }
651
652 void            CcdPhysicsEnvironment::setSolverType(int solverType)
653 {
654
655         switch (solverType)
656         {
657         case 1:
658                 {
659                         if (m_solverType != solverType)
660                         {
661                                 if (m_dispatcher)
662                                         delete m_dispatcher;
663
664                                 SimpleConstraintSolver* solver= new SimpleConstraintSolver();
665                                 m_dispatcher = new ToiContactDispatcher(solver);
666                                 break;
667                         }
668                 }
669         
670         case 0:
671         default:
672                         if (m_solverType != solverType)
673                         {
674                                 if (m_dispatcher)
675                                         delete m_dispatcher;
676
677                                 OdeConstraintSolver* solver= new OdeConstraintSolver();
678                                 m_dispatcher = new ToiContactDispatcher(solver);
679                                 break;
680                         }
681
682         };
683         
684         m_solverType = solverType ;
685 }
686
687
688
689
690
691 void    CcdPhysicsEnvironment::SyncMotionStates(float timeStep)
692 {
693         std::vector<CcdPhysicsController*>::iterator i;
694
695         //
696         // synchronize the physics and graphics transformations
697         //
698
699         for (i=m_controllers.begin();
700         !(i==m_controllers.end()); i++)
701         {
702                 CcdPhysicsController* ctrl = (*i);
703                 ctrl->SynchronizeMotionStates(timeStep);
704                 
705         }
706
707 }
708 void            CcdPhysicsEnvironment::setGravity(float x,float y,float z)
709 {
710         m_gravity = SimdVector3(x,y,z);
711
712         std::vector<CcdPhysicsController*>::iterator i;
713
714         //todo: review this gravity stuff
715         for (i=m_controllers.begin();
716         !(i==m_controllers.end()); i++)
717         {
718
719                 CcdPhysicsController* ctrl = (*i);
720                 ctrl->GetRigidBody()->setGravity(m_gravity);
721
722         }
723 }
724
725
726 int                     CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl0,class PHY_IPhysicsController* ctrl1,PHY_ConstraintType type,
727                                                                                                                 float pivotX,float pivotY,float pivotZ,
728                                                                                                                 float axisX,float axisY,float axisZ)
729 {
730         
731         
732         CcdPhysicsController* c0 = (CcdPhysicsController*)ctrl0;
733         CcdPhysicsController* c1 = (CcdPhysicsController*)ctrl1;
734         
735         RigidBody* rb0 = c0 ? c0->GetRigidBody() : 0;
736         RigidBody* rb1 = c1 ? c1->GetRigidBody() : 0;
737         
738         ASSERT(rb0);
739         
740         SimdVector3 pivotInA(pivotX,pivotY,pivotZ);
741         SimdVector3 pivotInB = rb1 ? rb1->getCenterOfMassTransform().inverse()(rb0->getCenterOfMassTransform()(pivotInA)) : pivotInA;
742         
743         switch (type)
744         {
745         case PHY_POINT2POINT_CONSTRAINT:
746                 {
747                         
748                         Point2PointConstraint* p2p = 0;
749                         
750                         if (rb1)
751                         {
752                                 p2p = new Point2PointConstraint(*rb0,
753                                         *rb1,pivotInA,pivotInB);
754                         } else
755                         {
756                                 p2p = new Point2PointConstraint(*rb0,
757                                         pivotInA);
758                         }
759                         
760                         m_p2pConstraints.push_back(p2p);
761                         return 0;
762                         
763                         break;
764                 }
765         default:
766                 {
767                 }
768         };
769         
770         //RigidBody& rbA,RigidBody& rbB, const SimdVector3& pivotInA,const SimdVector3& pivotInB
771         
772         return 0;
773         
774 }
775
776 void            CcdPhysicsEnvironment::removeConstraint(int constraintid)
777 {
778         
779         Point2PointConstraint* p2p = (Point2PointConstraint*) constraintid;
780         
781         std::vector<Point2PointConstraint*>::iterator i =
782                 std::find(m_p2pConstraints.begin(), m_p2pConstraints.end(), p2p);
783         
784         if (!(i == m_p2pConstraints.end()) )
785         {
786                 std::swap(*i, m_p2pConstraints.back());
787                 m_p2pConstraints.pop_back();
788         }
789         
790 }
791 PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IPhysicsController* ignoreClient, float fromX,float fromY,float fromZ, float toX,float toY,float toZ, 
792                                                                 float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
793 {
794
795         float minFraction = 1.f;
796
797         SimdTransform   rayFromTrans,rayToTrans;
798         rayFromTrans.setIdentity();
799         rayFromTrans.setOrigin(SimdVector3(fromX,fromY,fromZ));
800         rayToTrans.setIdentity();
801         rayToTrans.setOrigin(SimdVector3(toX,toY,toZ));
802
803
804         CcdPhysicsController* nearestHit = 0;
805         
806         std::vector<CcdPhysicsController*>::iterator i;
807         SphereShape pointShape(0.0f);
808
809         /// brute force go over all objects. Once there is a broadphase, use that, or
810         /// add a raycast against aabb first.
811         for (i=m_controllers.begin();
812         !(i==m_controllers.end()); i++)
813         {
814                 CcdPhysicsController* ctrl = (*i);
815                 RigidBody* body = ctrl->GetRigidBody();
816
817                 if (body->GetCollisionShape()->IsConvex())
818                 {
819                         ConvexCast::CastResult rayResult;
820                         rayResult.m_fraction = 1.f;
821
822                         ConvexShape* convexShape = (ConvexShape*) body->GetCollisionShape();
823                         VoronoiSimplexSolver    simplexSolver;
824                         SubsimplexConvexCast convexCaster(&pointShape,convexShape,&simplexSolver);
825                         
826                         if (convexCaster.calcTimeOfImpact(rayFromTrans,rayToTrans,body->getCenterOfMassTransform(),body->getCenterOfMassTransform(),rayResult))
827                         {
828                                 //add hit
829                                 rayResult.m_normal.normalize();
830                                 if (rayResult.m_fraction < minFraction)
831                                 {
832
833
834                                         minFraction = rayResult.m_fraction;
835                                         nearestHit = ctrl;
836                                         normalX = rayResult.m_normal.getX();
837                                         normalY = rayResult.m_normal.getY();
838                                         normalZ = rayResult.m_normal.getZ();
839                                         hitX = rayResult.m_hitTransformA.getOrigin().getX();
840                                         hitY = rayResult.m_hitTransformA.getOrigin().getY();
841                                         hitZ = rayResult.m_hitTransformA.getOrigin().getZ();
842                                 }
843                         }
844                 }
845                 else
846                 {
847                                 if (body->GetCollisionShape()->IsConcave())
848                                 {
849
850                                         TriangleMeshShape* triangleMesh = (TriangleMeshShape*)body->GetCollisionShape();
851                                         
852                                         SimdTransform worldToBody = body->getCenterOfMassTransform().inverse();
853
854                                         SimdVector3 rayFromLocal = worldToBody * rayFromTrans.getOrigin();
855                                         SimdVector3 rayToLocal = worldToBody * rayToTrans.getOrigin();
856
857                                         RaycastCallback rcb(rayFromLocal,rayToLocal);
858                                         rcb.m_hitFraction = minFraction;
859
860                                         SimdVector3 aabbMax(1e30f,1e30f,1e30f);
861
862                                         triangleMesh->ProcessAllTriangles(&rcb,-aabbMax,aabbMax);
863                                         if (rcb.m_hitFound)// && (rcb.m_hitFraction < minFraction))
864                                         {
865                                                 nearestHit = ctrl;
866                                                 minFraction = rcb.m_hitFraction;
867                                                 SimdVector3 hitNormalWorld = body->getCenterOfMassTransform()(rcb.m_hitNormalLocal);
868
869                                                 normalX = hitNormalWorld.getX();
870                                                 normalY = hitNormalWorld.getY();
871                                                 normalZ = hitNormalWorld.getZ();
872                                                 SimdVector3 hitWorld;
873                                                 hitWorld.setInterpolate3(rayFromTrans.getOrigin(),rayToTrans.getOrigin(),rcb.m_hitFraction);
874                                                 hitX = hitWorld.getX();
875                                                 hitY = hitWorld.getY();
876                                                 hitZ = hitWorld.getZ();
877                                                 
878                                         }
879                                 }
880                 }
881         }
882
883         return nearestHit;
884 }
885
886
887
888 int     CcdPhysicsEnvironment::getNumContactPoints()
889 {
890         return 0;
891 }
892
893 void CcdPhysicsEnvironment::getContactPoint(int i,float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ)
894 {
895         
896 }
897
898
899
900
901
902 Dispatcher* CcdPhysicsEnvironment::GetDispatcher()
903 {
904         return m_dispatcher;
905 }
906
907 CcdPhysicsEnvironment::~CcdPhysicsEnvironment()
908 {
909         
910         
911         m_vehicles.clear();
912         
913         //m_broadphase->DestroyScene();
914         //delete broadphase ? release reference on broadphase ?
915         
916         //first delete scene, then dispatcher, because pairs have to release manifolds on the dispatcher
917         delete m_dispatcher;
918         
919 }
920
921
922 int     CcdPhysicsEnvironment::GetNumControllers()
923 {
924         return m_controllers.size();
925 }
926
927
928 CcdPhysicsController* CcdPhysicsEnvironment::GetPhysicsController( int index)
929 {
930         return m_controllers[index];
931 }
932
933
934 int     CcdPhysicsEnvironment::GetNumManifolds() const
935 {
936         return m_dispatcher->GetNumManifolds();
937 }
938
939 const PersistentManifold*       CcdPhysicsEnvironment::GetManifold(int index) const
940 {
941         return m_dispatcher->GetManifoldByIndexInternal(index);
942 }