btConvexConvexAlgorithm.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. ///Specialized capsule-capsule collision algorithm has been added for Bullet 2.75 release to increase ragdoll performance
  14. ///If you experience problems with capsule-capsule collision, try to define BT_DISABLE_CAPSULE_CAPSULE_COLLIDER and report it in the Bullet forums
  15. ///with reproduction case
  16. //#define BT_DISABLE_CAPSULE_CAPSULE_COLLIDER 1
  17. //#define ZERO_MARGIN
  18. #include "btConvexConvexAlgorithm.h"
  19. //#include <stdio.h>
  20. #include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"
  21. #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"
  22. #include "BulletCollision/CollisionDispatch/btCollisionObject.h"
  23. #include "BulletCollision/CollisionShapes/btConvexShape.h"
  24. #include "BulletCollision/CollisionShapes/btCapsuleShape.h"
  25. #include "BulletCollision/CollisionShapes/btTriangleShape.h"
  26. #include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
  27. #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
  28. #include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
  29. #include "BulletCollision/CollisionShapes/btBoxShape.h"
  30. #include "BulletCollision/CollisionDispatch/btManifoldResult.h"
  31. #include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h"
  32. #include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h"
  33. #include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"
  34. #include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h"
  35. #include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
  36. #include "BulletCollision/CollisionShapes/btSphereShape.h"
  37. #include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h"
  38. #include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h"
  39. #include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
  40. #include "BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.h"
  41. #include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
  42. ///////////
  43. static SIMD_FORCE_INLINE void segmentsClosestPoints(
  44. btVector3& ptsVector,
  45. btVector3& offsetA,
  46. btVector3& offsetB,
  47. btScalar& tA, btScalar& tB,
  48. const btVector3& translation,
  49. const btVector3& dirA, btScalar hlenA,
  50. const btVector3& dirB, btScalar hlenB )
  51. {
  52. // compute the parameters of the closest points on each line segment
  53. btScalar dirA_dot_dirB = btDot(dirA,dirB);
  54. btScalar dirA_dot_trans = btDot(dirA,translation);
  55. btScalar dirB_dot_trans = btDot(dirB,translation);
  56. btScalar denom = 1.0f - dirA_dot_dirB * dirA_dot_dirB;
  57. if ( denom == 0.0f ) {
  58. tA = 0.0f;
  59. } else {
  60. tA = ( dirA_dot_trans - dirB_dot_trans * dirA_dot_dirB ) / denom;
  61. if ( tA < -hlenA )
  62. tA = -hlenA;
  63. else if ( tA > hlenA )
  64. tA = hlenA;
  65. }
  66. tB = tA * dirA_dot_dirB - dirB_dot_trans;
  67. if ( tB < -hlenB ) {
  68. tB = -hlenB;
  69. tA = tB * dirA_dot_dirB + dirA_dot_trans;
  70. if ( tA < -hlenA )
  71. tA = -hlenA;
  72. else if ( tA > hlenA )
  73. tA = hlenA;
  74. } else if ( tB > hlenB ) {
  75. tB = hlenB;
  76. tA = tB * dirA_dot_dirB + dirA_dot_trans;
  77. if ( tA < -hlenA )
  78. tA = -hlenA;
  79. else if ( tA > hlenA )
  80. tA = hlenA;
  81. }
  82. // compute the closest points relative to segment centers.
  83. offsetA = dirA * tA;
  84. offsetB = dirB * tB;
  85. ptsVector = translation - offsetA + offsetB;
  86. }
  87. static SIMD_FORCE_INLINE btScalar capsuleCapsuleDistance(
  88. btVector3& normalOnB,
  89. btVector3& pointOnB,
  90. btScalar capsuleLengthA,
  91. btScalar capsuleRadiusA,
  92. btScalar capsuleLengthB,
  93. btScalar capsuleRadiusB,
  94. int capsuleAxisA,
  95. int capsuleAxisB,
  96. const btTransform& transformA,
  97. const btTransform& transformB,
  98. btScalar distanceThreshold )
  99. {
  100. btVector3 directionA = transformA.getBasis().getColumn(capsuleAxisA);
  101. btVector3 translationA = transformA.getOrigin();
  102. btVector3 directionB = transformB.getBasis().getColumn(capsuleAxisB);
  103. btVector3 translationB = transformB.getOrigin();
  104. // translation between centers
  105. btVector3 translation = translationB - translationA;
  106. // compute the closest points of the capsule line segments
  107. btVector3 ptsVector; // the vector between the closest points
  108. btVector3 offsetA, offsetB; // offsets from segment centers to their closest points
  109. btScalar tA, tB; // parameters on line segment
  110. segmentsClosestPoints( ptsVector, offsetA, offsetB, tA, tB, translation,
  111. directionA, capsuleLengthA, directionB, capsuleLengthB );
  112. btScalar distance = ptsVector.length() - capsuleRadiusA - capsuleRadiusB;
  113. if ( distance > distanceThreshold )
  114. return distance;
  115. btScalar lenSqr = ptsVector.length2();
  116. if (lenSqr<= (SIMD_EPSILON*SIMD_EPSILON))
  117. {
  118. //degenerate case where 2 capsules are likely at the same location: take a vector tangential to 'directionA'
  119. btVector3 q;
  120. btPlaneSpace1(directionA,normalOnB,q);
  121. } else
  122. {
  123. // compute the contact normal
  124. normalOnB = ptsVector*-btRecipSqrt(lenSqr);
  125. }
  126. pointOnB = transformB.getOrigin()+offsetB + normalOnB * capsuleRadiusB;
  127. return distance;
  128. }
  129. //////////
  130. btConvexConvexAlgorithm::CreateFunc::CreateFunc(btConvexPenetrationDepthSolver* pdSolver)
  131. {
  132. m_numPerturbationIterations = 0;
  133. m_minimumPointsPerturbationThreshold = 3;
  134. m_pdSolver = pdSolver;
  135. }
  136. btConvexConvexAlgorithm::CreateFunc::~CreateFunc()
  137. {
  138. }
  139. btConvexConvexAlgorithm::btConvexConvexAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,btConvexPenetrationDepthSolver* pdSolver,int numPerturbationIterations, int minimumPointsPerturbationThreshold)
  140. : btActivatingCollisionAlgorithm(ci,body0Wrap,body1Wrap),
  141. m_pdSolver(pdSolver),
  142. m_ownManifold (false),
  143. m_manifoldPtr(mf),
  144. m_lowLevelOfDetail(false),
  145. #ifdef USE_SEPDISTANCE_UTIL2
  146. m_sepDistance((static_cast<btConvexShape*>(body0->getCollisionShape()))->getAngularMotionDisc(),
  147. (static_cast<btConvexShape*>(body1->getCollisionShape()))->getAngularMotionDisc()),
  148. #endif
  149. m_numPerturbationIterations(numPerturbationIterations),
  150. m_minimumPointsPerturbationThreshold(minimumPointsPerturbationThreshold)
  151. {
  152. (void)body0Wrap;
  153. (void)body1Wrap;
  154. }
  155. btConvexConvexAlgorithm::~btConvexConvexAlgorithm()
  156. {
  157. if (m_ownManifold)
  158. {
  159. if (m_manifoldPtr)
  160. m_dispatcher->releaseManifold(m_manifoldPtr);
  161. }
  162. }
  163. void btConvexConvexAlgorithm ::setLowLevelOfDetail(bool useLowLevel)
  164. {
  165. m_lowLevelOfDetail = useLowLevel;
  166. }
  167. struct btPerturbedContactResult : public btManifoldResult
  168. {
  169. btManifoldResult* m_originalManifoldResult;
  170. btTransform m_transformA;
  171. btTransform m_transformB;
  172. btTransform m_unPerturbedTransform;
  173. bool m_perturbA;
  174. btIDebugDraw* m_debugDrawer;
  175. btPerturbedContactResult(btManifoldResult* originalResult,const btTransform& transformA,const btTransform& transformB,const btTransform& unPerturbedTransform,bool perturbA,btIDebugDraw* debugDrawer)
  176. :m_originalManifoldResult(originalResult),
  177. m_transformA(transformA),
  178. m_transformB(transformB),
  179. m_unPerturbedTransform(unPerturbedTransform),
  180. m_perturbA(perturbA),
  181. m_debugDrawer(debugDrawer)
  182. {
  183. }
  184. virtual ~ btPerturbedContactResult()
  185. {
  186. }
  187. virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar orgDepth)
  188. {
  189. btVector3 endPt,startPt;
  190. btScalar newDepth;
  191. btVector3 newNormal;
  192. if (m_perturbA)
  193. {
  194. btVector3 endPtOrg = pointInWorld + normalOnBInWorld*orgDepth;
  195. endPt = (m_unPerturbedTransform*m_transformA.inverse())(endPtOrg);
  196. newDepth = (endPt - pointInWorld).dot(normalOnBInWorld);
  197. startPt = endPt+normalOnBInWorld*newDepth;
  198. } else
  199. {
  200. endPt = pointInWorld + normalOnBInWorld*orgDepth;
  201. startPt = (m_unPerturbedTransform*m_transformB.inverse())(pointInWorld);
  202. newDepth = (endPt - startPt).dot(normalOnBInWorld);
  203. }
  204. //#define DEBUG_CONTACTS 1
  205. #ifdef DEBUG_CONTACTS
  206. m_debugDrawer->drawLine(startPt,endPt,btVector3(1,0,0));
  207. m_debugDrawer->drawSphere(startPt,0.05,btVector3(0,1,0));
  208. m_debugDrawer->drawSphere(endPt,0.05,btVector3(0,0,1));
  209. #endif //DEBUG_CONTACTS
  210. m_originalManifoldResult->addContactPoint(normalOnBInWorld,startPt,newDepth);
  211. }
  212. };
  213. extern btScalar gContactBreakingThreshold;
  214. //
  215. // Convex-Convex collision algorithm
  216. //
  217. void btConvexConvexAlgorithm ::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
  218. {
  219. if (!m_manifoldPtr)
  220. {
  221. //swapped?
  222. m_manifoldPtr = m_dispatcher->getNewManifold(body0Wrap->getCollisionObject(),body1Wrap->getCollisionObject());
  223. m_ownManifold = true;
  224. }
  225. resultOut->setPersistentManifold(m_manifoldPtr);
  226. //comment-out next line to test multi-contact generation
  227. //resultOut->getPersistentManifold()->clearManifold();
  228. const btConvexShape* min0 = static_cast<const btConvexShape*>(body0Wrap->getCollisionShape());
  229. const btConvexShape* min1 = static_cast<const btConvexShape*>(body1Wrap->getCollisionShape());
  230. btVector3 normalOnB;
  231. btVector3 pointOnBWorld;
  232. #ifndef BT_DISABLE_CAPSULE_CAPSULE_COLLIDER
  233. if ((min0->getShapeType() == CAPSULE_SHAPE_PROXYTYPE) && (min1->getShapeType() == CAPSULE_SHAPE_PROXYTYPE))
  234. {
  235. //m_manifoldPtr->clearManifold();
  236. btCapsuleShape* capsuleA = (btCapsuleShape*) min0;
  237. btCapsuleShape* capsuleB = (btCapsuleShape*) min1;
  238. btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
  239. btScalar dist = capsuleCapsuleDistance(normalOnB, pointOnBWorld,capsuleA->getHalfHeight(),capsuleA->getRadius(),
  240. capsuleB->getHalfHeight(),capsuleB->getRadius(),capsuleA->getUpAxis(),capsuleB->getUpAxis(),
  241. body0Wrap->getWorldTransform(),body1Wrap->getWorldTransform(),threshold);
  242. if (dist<threshold)
  243. {
  244. btAssert(normalOnB.length2()>=(SIMD_EPSILON*SIMD_EPSILON));
  245. resultOut->addContactPoint(normalOnB,pointOnBWorld,dist);
  246. }
  247. resultOut->refreshContactPoints();
  248. return;
  249. }
  250. if ((min0->getShapeType() == CAPSULE_SHAPE_PROXYTYPE) && (min1->getShapeType() == SPHERE_SHAPE_PROXYTYPE))
  251. {
  252. //m_manifoldPtr->clearManifold();
  253. btCapsuleShape* capsuleA = (btCapsuleShape*) min0;
  254. btSphereShape* capsuleB = (btSphereShape*) min1;
  255. btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
  256. btScalar dist = capsuleCapsuleDistance(normalOnB, pointOnBWorld,capsuleA->getHalfHeight(),capsuleA->getRadius(),
  257. 0.,capsuleB->getRadius(),capsuleA->getUpAxis(),1,
  258. body0Wrap->getWorldTransform(),body1Wrap->getWorldTransform(),threshold);
  259. if (dist<threshold)
  260. {
  261. btAssert(normalOnB.length2()>=(SIMD_EPSILON*SIMD_EPSILON));
  262. resultOut->addContactPoint(normalOnB,pointOnBWorld,dist);
  263. }
  264. resultOut->refreshContactPoints();
  265. return;
  266. }
  267. if ((min0->getShapeType() == SPHERE_SHAPE_PROXYTYPE) && (min1->getShapeType() == CAPSULE_SHAPE_PROXYTYPE))
  268. {
  269. //m_manifoldPtr->clearManifold();
  270. btSphereShape* capsuleA = (btSphereShape*) min0;
  271. btCapsuleShape* capsuleB = (btCapsuleShape*) min1;
  272. btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
  273. btScalar dist = capsuleCapsuleDistance(normalOnB, pointOnBWorld,0.,capsuleA->getRadius(),
  274. capsuleB->getHalfHeight(),capsuleB->getRadius(),1,capsuleB->getUpAxis(),
  275. body0Wrap->getWorldTransform(),body1Wrap->getWorldTransform(),threshold);
  276. if (dist<threshold)
  277. {
  278. btAssert(normalOnB.length2()>=(SIMD_EPSILON*SIMD_EPSILON));
  279. resultOut->addContactPoint(normalOnB,pointOnBWorld,dist);
  280. }
  281. resultOut->refreshContactPoints();
  282. return;
  283. }
  284. #endif //BT_DISABLE_CAPSULE_CAPSULE_COLLIDER
  285. #ifdef USE_SEPDISTANCE_UTIL2
  286. if (dispatchInfo.m_useConvexConservativeDistanceUtil)
  287. {
  288. m_sepDistance.updateSeparatingDistance(body0->getWorldTransform(),body1->getWorldTransform());
  289. }
  290. if (!dispatchInfo.m_useConvexConservativeDistanceUtil || m_sepDistance.getConservativeSeparatingDistance()<=0.f)
  291. #endif //USE_SEPDISTANCE_UTIL2
  292. {
  293. btGjkPairDetector::ClosestPointInput input;
  294. btVoronoiSimplexSolver simplexSolver;
  295. btGjkPairDetector gjkPairDetector( min0, min1, &simplexSolver, m_pdSolver );
  296. //TODO: if (dispatchInfo.m_useContinuous)
  297. gjkPairDetector.setMinkowskiA(min0);
  298. gjkPairDetector.setMinkowskiB(min1);
  299. #ifdef USE_SEPDISTANCE_UTIL2
  300. if (dispatchInfo.m_useConvexConservativeDistanceUtil)
  301. {
  302. input.m_maximumDistanceSquared = BT_LARGE_FLOAT;
  303. } else
  304. #endif //USE_SEPDISTANCE_UTIL2
  305. {
  306. //if (dispatchInfo.m_convexMaxDistanceUseCPT)
  307. //{
  308. // input.m_maximumDistanceSquared = min0->getMargin() + min1->getMargin() + m_manifoldPtr->getContactProcessingThreshold();
  309. //} else
  310. //{
  311. input.m_maximumDistanceSquared = min0->getMargin() + min1->getMargin() + m_manifoldPtr->getContactBreakingThreshold()+resultOut->m_closestPointDistanceThreshold;
  312. // }
  313. input.m_maximumDistanceSquared*= input.m_maximumDistanceSquared;
  314. }
  315. input.m_transformA = body0Wrap->getWorldTransform();
  316. input.m_transformB = body1Wrap->getWorldTransform();
  317. #ifdef USE_SEPDISTANCE_UTIL2
  318. btScalar sepDist = 0.f;
  319. if (dispatchInfo.m_useConvexConservativeDistanceUtil)
  320. {
  321. sepDist = gjkPairDetector.getCachedSeparatingDistance();
  322. if (sepDist>SIMD_EPSILON)
  323. {
  324. sepDist += dispatchInfo.m_convexConservativeDistanceThreshold;
  325. //now perturbe directions to get multiple contact points
  326. }
  327. }
  328. #endif //USE_SEPDISTANCE_UTIL2
  329. if (min0->isPolyhedral() && min1->isPolyhedral())
  330. {
  331. struct btDummyResult : public btDiscreteCollisionDetectorInterface::Result
  332. {
  333. virtual void setShapeIdentifiersA(int partId0,int index0){}
  334. virtual void setShapeIdentifiersB(int partId1,int index1){}
  335. virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth)
  336. {
  337. }
  338. };
  339. struct btWithoutMarginResult : public btDiscreteCollisionDetectorInterface::Result
  340. {
  341. btDiscreteCollisionDetectorInterface::Result* m_originalResult;
  342. btVector3 m_reportedNormalOnWorld;
  343. btScalar m_marginOnA;
  344. btScalar m_marginOnB;
  345. btScalar m_reportedDistance;
  346. bool m_foundResult;
  347. btWithoutMarginResult(btDiscreteCollisionDetectorInterface::Result* result, btScalar marginOnA, btScalar marginOnB)
  348. :m_originalResult(result),
  349. m_marginOnA(marginOnA),
  350. m_marginOnB(marginOnB),
  351. m_foundResult(false)
  352. {
  353. }
  354. virtual void setShapeIdentifiersA(int partId0,int index0){}
  355. virtual void setShapeIdentifiersB(int partId1,int index1){}
  356. virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorldOrg,btScalar depthOrg)
  357. {
  358. m_reportedDistance = depthOrg;
  359. m_reportedNormalOnWorld = normalOnBInWorld;
  360. btVector3 adjustedPointB = pointInWorldOrg - normalOnBInWorld*m_marginOnB;
  361. m_reportedDistance = depthOrg+(m_marginOnA+m_marginOnB);
  362. if (m_reportedDistance<0.f)
  363. {
  364. m_foundResult = true;
  365. }
  366. m_originalResult->addContactPoint(normalOnBInWorld,adjustedPointB,m_reportedDistance);
  367. }
  368. };
  369. btDummyResult dummy;
  370. ///btBoxShape is an exception: its vertices are created WITH margin so don't subtract it
  371. btScalar min0Margin = min0->getShapeType()==BOX_SHAPE_PROXYTYPE? 0.f : min0->getMargin();
  372. btScalar min1Margin = min1->getShapeType()==BOX_SHAPE_PROXYTYPE? 0.f : min1->getMargin();
  373. btWithoutMarginResult withoutMargin(resultOut, min0Margin,min1Margin);
  374. btPolyhedralConvexShape* polyhedronA = (btPolyhedralConvexShape*) min0;
  375. btPolyhedralConvexShape* polyhedronB = (btPolyhedralConvexShape*) min1;
  376. if (polyhedronA->getConvexPolyhedron() && polyhedronB->getConvexPolyhedron())
  377. {
  378. btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
  379. btScalar minDist = -1e30f;
  380. btVector3 sepNormalWorldSpace;
  381. bool foundSepAxis = true;
  382. if (dispatchInfo.m_enableSatConvex)
  383. {
  384. foundSepAxis = btPolyhedralContactClipping::findSeparatingAxis(
  385. *polyhedronA->getConvexPolyhedron(), *polyhedronB->getConvexPolyhedron(),
  386. body0Wrap->getWorldTransform(),
  387. body1Wrap->getWorldTransform(),
  388. sepNormalWorldSpace,*resultOut);
  389. } else
  390. {
  391. #ifdef ZERO_MARGIN
  392. gjkPairDetector.setIgnoreMargin(true);
  393. gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
  394. #else
  395. gjkPairDetector.getClosestPoints(input,withoutMargin,dispatchInfo.m_debugDraw);
  396. //gjkPairDetector.getClosestPoints(input,dummy,dispatchInfo.m_debugDraw);
  397. #endif //ZERO_MARGIN
  398. //btScalar l2 = gjkPairDetector.getCachedSeparatingAxis().length2();
  399. //if (l2>SIMD_EPSILON)
  400. {
  401. sepNormalWorldSpace = withoutMargin.m_reportedNormalOnWorld;//gjkPairDetector.getCachedSeparatingAxis()*(1.f/l2);
  402. //minDist = -1e30f;//gjkPairDetector.getCachedSeparatingDistance();
  403. minDist = withoutMargin.m_reportedDistance;//gjkPairDetector.getCachedSeparatingDistance()+min0->getMargin()+min1->getMargin();
  404. #ifdef ZERO_MARGIN
  405. foundSepAxis = true;//gjkPairDetector.getCachedSeparatingDistance()<0.f;
  406. #else
  407. foundSepAxis = withoutMargin.m_foundResult && minDist<0;//-(min0->getMargin()+min1->getMargin());
  408. #endif
  409. }
  410. }
  411. if (foundSepAxis)
  412. {
  413. // printf("sepNormalWorldSpace=%f,%f,%f\n",sepNormalWorldSpace.getX(),sepNormalWorldSpace.getY(),sepNormalWorldSpace.getZ());
  414. worldVertsB1.resize(0);
  415. btPolyhedralContactClipping::clipHullAgainstHull(sepNormalWorldSpace, *polyhedronA->getConvexPolyhedron(), *polyhedronB->getConvexPolyhedron(),
  416. body0Wrap->getWorldTransform(),
  417. body1Wrap->getWorldTransform(), minDist-threshold, threshold, worldVertsB1,worldVertsB2,
  418. *resultOut);
  419. }
  420. if (m_ownManifold)
  421. {
  422. resultOut->refreshContactPoints();
  423. }
  424. return;
  425. } else
  426. {
  427. //we can also deal with convex versus triangle (without connectivity data)
  428. if (polyhedronA->getConvexPolyhedron() && polyhedronB->getShapeType()==TRIANGLE_SHAPE_PROXYTYPE)
  429. {
  430. btVertexArray vertices;
  431. btTriangleShape* tri = (btTriangleShape*)polyhedronB;
  432. vertices.push_back( body1Wrap->getWorldTransform()*tri->m_vertices1[0]);
  433. vertices.push_back( body1Wrap->getWorldTransform()*tri->m_vertices1[1]);
  434. vertices.push_back( body1Wrap->getWorldTransform()*tri->m_vertices1[2]);
  435. //tri->initializePolyhedralFeatures();
  436. btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
  437. btVector3 sepNormalWorldSpace;
  438. btScalar minDist =-1e30f;
  439. btScalar maxDist = threshold;
  440. bool foundSepAxis = false;
  441. if (0)
  442. {
  443. polyhedronB->initializePolyhedralFeatures();
  444. foundSepAxis = btPolyhedralContactClipping::findSeparatingAxis(
  445. *polyhedronA->getConvexPolyhedron(), *polyhedronB->getConvexPolyhedron(),
  446. body0Wrap->getWorldTransform(),
  447. body1Wrap->getWorldTransform(),
  448. sepNormalWorldSpace,*resultOut);
  449. // printf("sepNormalWorldSpace=%f,%f,%f\n",sepNormalWorldSpace.getX(),sepNormalWorldSpace.getY(),sepNormalWorldSpace.getZ());
  450. } else
  451. {
  452. #ifdef ZERO_MARGIN
  453. gjkPairDetector.setIgnoreMargin(true);
  454. gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
  455. #else
  456. gjkPairDetector.getClosestPoints(input,dummy,dispatchInfo.m_debugDraw);
  457. #endif//ZERO_MARGIN
  458. btScalar l2 = gjkPairDetector.getCachedSeparatingAxis().length2();
  459. if (l2>SIMD_EPSILON)
  460. {
  461. sepNormalWorldSpace = gjkPairDetector.getCachedSeparatingAxis()*(1.f/l2);
  462. //minDist = gjkPairDetector.getCachedSeparatingDistance();
  463. //maxDist = threshold;
  464. minDist = gjkPairDetector.getCachedSeparatingDistance()-min0->getMargin()-min1->getMargin();
  465. foundSepAxis = true;
  466. }
  467. }
  468. if (foundSepAxis)
  469. {
  470. worldVertsB2.resize(0);
  471. btPolyhedralContactClipping::clipFaceAgainstHull(sepNormalWorldSpace, *polyhedronA->getConvexPolyhedron(),
  472. body0Wrap->getWorldTransform(), vertices, worldVertsB2,minDist-threshold, maxDist, *resultOut);
  473. }
  474. if (m_ownManifold)
  475. {
  476. resultOut->refreshContactPoints();
  477. }
  478. return;
  479. }
  480. }
  481. }
  482. gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
  483. //now perform 'm_numPerturbationIterations' collision queries with the perturbated collision objects
  484. //perform perturbation when more then 'm_minimumPointsPerturbationThreshold' points
  485. if (m_numPerturbationIterations && resultOut->getPersistentManifold()->getNumContacts() < m_minimumPointsPerturbationThreshold)
  486. {
  487. int i;
  488. btVector3 v0,v1;
  489. btVector3 sepNormalWorldSpace;
  490. btScalar l2 = gjkPairDetector.getCachedSeparatingAxis().length2();
  491. if (l2>SIMD_EPSILON)
  492. {
  493. sepNormalWorldSpace = gjkPairDetector.getCachedSeparatingAxis()*(1.f/l2);
  494. btPlaneSpace1(sepNormalWorldSpace,v0,v1);
  495. bool perturbeA = true;
  496. const btScalar angleLimit = 0.125f * SIMD_PI;
  497. btScalar perturbeAngle;
  498. btScalar radiusA = min0->getAngularMotionDisc();
  499. btScalar radiusB = min1->getAngularMotionDisc();
  500. if (radiusA < radiusB)
  501. {
  502. perturbeAngle = gContactBreakingThreshold /radiusA;
  503. perturbeA = true;
  504. } else
  505. {
  506. perturbeAngle = gContactBreakingThreshold / radiusB;
  507. perturbeA = false;
  508. }
  509. if ( perturbeAngle > angleLimit )
  510. perturbeAngle = angleLimit;
  511. btTransform unPerturbedTransform;
  512. if (perturbeA)
  513. {
  514. unPerturbedTransform = input.m_transformA;
  515. } else
  516. {
  517. unPerturbedTransform = input.m_transformB;
  518. }
  519. for ( i=0;i<m_numPerturbationIterations;i++)
  520. {
  521. if (v0.length2()>SIMD_EPSILON)
  522. {
  523. btQuaternion perturbeRot(v0,perturbeAngle);
  524. btScalar iterationAngle = i*(SIMD_2_PI/btScalar(m_numPerturbationIterations));
  525. btQuaternion rotq(sepNormalWorldSpace,iterationAngle);
  526. if (perturbeA)
  527. {
  528. input.m_transformA.setBasis( btMatrix3x3(rotq.inverse()*perturbeRot*rotq)*body0Wrap->getWorldTransform().getBasis());
  529. input.m_transformB = body1Wrap->getWorldTransform();
  530. #ifdef DEBUG_CONTACTS
  531. dispatchInfo.m_debugDraw->drawTransform(input.m_transformA,10.0);
  532. #endif //DEBUG_CONTACTS
  533. } else
  534. {
  535. input.m_transformA = body0Wrap->getWorldTransform();
  536. input.m_transformB.setBasis( btMatrix3x3(rotq.inverse()*perturbeRot*rotq)*body1Wrap->getWorldTransform().getBasis());
  537. #ifdef DEBUG_CONTACTS
  538. dispatchInfo.m_debugDraw->drawTransform(input.m_transformB,10.0);
  539. #endif
  540. }
  541. btPerturbedContactResult perturbedResultOut(resultOut,input.m_transformA,input.m_transformB,unPerturbedTransform,perturbeA,dispatchInfo.m_debugDraw);
  542. gjkPairDetector.getClosestPoints(input,perturbedResultOut,dispatchInfo.m_debugDraw);
  543. }
  544. }
  545. }
  546. }
  547. #ifdef USE_SEPDISTANCE_UTIL2
  548. if (dispatchInfo.m_useConvexConservativeDistanceUtil && (sepDist>SIMD_EPSILON))
  549. {
  550. m_sepDistance.initSeparatingDistance(gjkPairDetector.getCachedSeparatingAxis(),sepDist,body0->getWorldTransform(),body1->getWorldTransform());
  551. }
  552. #endif //USE_SEPDISTANCE_UTIL2
  553. }
  554. if (m_ownManifold)
  555. {
  556. resultOut->refreshContactPoints();
  557. }
  558. }
  559. bool disableCcd = false;
  560. btScalar btConvexConvexAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
  561. {
  562. (void)resultOut;
  563. (void)dispatchInfo;
  564. ///Rather then checking ALL pairs, only calculate TOI when motion exceeds threshold
  565. ///Linear motion for one of objects needs to exceed m_ccdSquareMotionThreshold
  566. ///col0->m_worldTransform,
  567. btScalar resultFraction = btScalar(1.);
  568. btScalar squareMot0 = (col0->getInterpolationWorldTransform().getOrigin() - col0->getWorldTransform().getOrigin()).length2();
  569. btScalar squareMot1 = (col1->getInterpolationWorldTransform().getOrigin() - col1->getWorldTransform().getOrigin()).length2();
  570. if (squareMot0 < col0->getCcdSquareMotionThreshold() &&
  571. squareMot1 < col1->getCcdSquareMotionThreshold())
  572. return resultFraction;
  573. if (disableCcd)
  574. return btScalar(1.);
  575. //An adhoc way of testing the Continuous Collision Detection algorithms
  576. //One object is approximated as a sphere, to simplify things
  577. //Starting in penetration should report no time of impact
  578. //For proper CCD, better accuracy and handling of 'allowed' penetration should be added
  579. //also the mainloop of the physics should have a kind of toi queue (something like Brian Mirtich's application of Timewarp for Rigidbodies)
  580. /// Convex0 against sphere for Convex1
  581. {
  582. btConvexShape* convex0 = static_cast<btConvexShape*>(col0->getCollisionShape());
  583. btSphereShape sphere1(col1->getCcdSweptSphereRadius()); //todo: allow non-zero sphere sizes, for better approximation
  584. btConvexCast::CastResult result;
  585. btVoronoiSimplexSolver voronoiSimplex;
  586. //SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex);
  587. ///Simplification, one object is simplified as a sphere
  588. btGjkConvexCast ccd1( convex0 ,&sphere1,&voronoiSimplex);
  589. //ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0);
  590. if (ccd1.calcTimeOfImpact(col0->getWorldTransform(),col0->getInterpolationWorldTransform(),
  591. col1->getWorldTransform(),col1->getInterpolationWorldTransform(),result))
  592. {
  593. //store result.m_fraction in both bodies
  594. if (col0->getHitFraction()> result.m_fraction)
  595. col0->setHitFraction( result.m_fraction );
  596. if (col1->getHitFraction() > result.m_fraction)
  597. col1->setHitFraction( result.m_fraction);
  598. if (resultFraction > result.m_fraction)
  599. resultFraction = result.m_fraction;
  600. }
  601. }
  602. /// Sphere (for convex0) against Convex1
  603. {
  604. btConvexShape* convex1 = static_cast<btConvexShape*>(col1->getCollisionShape());
  605. btSphereShape sphere0(col0->getCcdSweptSphereRadius()); //todo: allow non-zero sphere sizes, for better approximation
  606. btConvexCast::CastResult result;
  607. btVoronoiSimplexSolver voronoiSimplex;
  608. //SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex);
  609. ///Simplification, one object is simplified as a sphere
  610. btGjkConvexCast ccd1(&sphere0,convex1,&voronoiSimplex);
  611. //ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0);
  612. if (ccd1.calcTimeOfImpact(col0->getWorldTransform(),col0->getInterpolationWorldTransform(),
  613. col1->getWorldTransform(),col1->getInterpolationWorldTransform(),result))
  614. {
  615. //store result.m_fraction in both bodies
  616. if (col0->getHitFraction() > result.m_fraction)
  617. col0->setHitFraction( result.m_fraction);
  618. if (col1->getHitFraction() > result.m_fraction)
  619. col1->setHitFraction( result.m_fraction);
  620. if (resultFraction > result.m_fraction)
  621. resultFraction = result.m_fraction;
  622. }
  623. }
  624. return resultFraction;
  625. }