2
0

GJKClosestPoint.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Core/NonCopyable.h>
  6. #include <Jolt/Core/FPException.h>
  7. #include <Jolt/Geometry/ClosestPoint.h>
  8. #include <Jolt/Geometry/ConvexSupport.h>
  9. //#define JPH_GJK_DEBUG
  10. #ifdef JPH_GJK_DEBUG
  11. #include <Jolt/Core/StringTools.h>
  12. #include <Jolt/Renderer/DebugRenderer.h>
  13. #endif
  14. JPH_NAMESPACE_BEGIN
  15. /// Convex vs convex collision detection
  16. /// Based on: A Fast and Robust GJK Implementation for Collision Detection of Convex Objects - Gino van den Bergen
  17. class GJKClosestPoint : public NonCopyable
  18. {
  19. private:
  20. /// Get new closest point to origin given simplex mY of mNumPoints points
  21. ///
  22. /// @param inPrevVLenSq Length of |outV|^2 from the previous iteration, used as a maximum value when selecting a new closest point.
  23. /// @param outV Closest point
  24. /// @param outVLenSq |outV|^2
  25. /// @param outSet Set of points that form the new simplex closest to the origin (bit 1 = mY[0], bit 2 = mY[1], ...)
  26. ///
  27. /// If LastPointPartOfClosestFeature is true then the last point added will be assumed to be part of the closest feature and the function will do less work.
  28. ///
  29. /// @return True if new closest point was found.
  30. /// False if the function failed, in this case the output variables are not modified
  31. template <bool LastPointPartOfClosestFeature>
  32. bool GetClosest(float inPrevVLenSq, Vec3 &outV, float &outVLenSq, uint32 &outSet) const
  33. {
  34. #ifdef JPH_GJK_DEBUG
  35. for (int i = 0; i < mNumPoints; ++i)
  36. Trace("y[%d] = [%s], |y[%d]| = %g", i, ConvertToString(mY[i]).c_str(), i, (double)mY[i].Length());
  37. #endif
  38. uint32 set;
  39. Vec3 v;
  40. switch (mNumPoints)
  41. {
  42. case 1:
  43. // Single point
  44. set = 0b0001;
  45. v = mY[0];
  46. break;
  47. case 2:
  48. // Line segment
  49. v = ClosestPoint::GetClosestPointOnLine(mY[0], mY[1], set);
  50. break;
  51. case 3:
  52. // Triangle
  53. v = ClosestPoint::GetClosestPointOnTriangle<LastPointPartOfClosestFeature>(mY[0], mY[1], mY[2], set);
  54. break;
  55. case 4:
  56. // Tetrahedron
  57. v = ClosestPoint::GetClosestPointOnTetrahedron<LastPointPartOfClosestFeature>(mY[0], mY[1], mY[2], mY[3], set);
  58. break;
  59. default:
  60. JPH_ASSERT(false);
  61. return false;
  62. }
  63. #ifdef JPH_GJK_DEBUG
  64. Trace("GetClosest: set = 0b%s, v = [%s], |v| = %g", NibbleToBinary(set), ConvertToString(v).c_str(), (double)v.Length());
  65. #endif
  66. float v_len_sq = v.LengthSq();
  67. if (v_len_sq < inPrevVLenSq) // Note, comparison order important: If v_len_sq is NaN then this expression will be false so we will return false
  68. {
  69. // Return closest point
  70. outV = v;
  71. outVLenSq = v_len_sq;
  72. outSet = set;
  73. return true;
  74. }
  75. // No better match found
  76. #ifdef JPH_GJK_DEBUG
  77. Trace("New closer point is further away, failed to converge");
  78. #endif
  79. return false;
  80. }
  81. // Get max(|Y_0|^2 .. |Y_n|^2)
  82. float GetMaxYLengthSq() const
  83. {
  84. float y_len_sq = mY[0].LengthSq();
  85. for (int i = 1; i < mNumPoints; ++i)
  86. y_len_sq = max(y_len_sq, mY[i].LengthSq());
  87. return y_len_sq;
  88. }
  89. // Remove points that are not in the set, only updates mY
  90. void UpdatePointSetY(uint32 inSet)
  91. {
  92. int num_points = 0;
  93. for (int i = 0; i < mNumPoints; ++i)
  94. if ((inSet & (1 << i)) != 0)
  95. {
  96. mY[num_points] = mY[i];
  97. ++num_points;
  98. }
  99. mNumPoints = num_points;
  100. }
  101. // Remove points that are not in the set, only updates mP
  102. void UpdatePointSetP(uint32 inSet)
  103. {
  104. int num_points = 0;
  105. for (int i = 0; i < mNumPoints; ++i)
  106. if ((inSet & (1 << i)) != 0)
  107. {
  108. mP[num_points] = mP[i];
  109. ++num_points;
  110. }
  111. mNumPoints = num_points;
  112. }
  113. // Remove points that are not in the set, only updates mP and mQ
  114. void UpdatePointSetPQ(uint32 inSet)
  115. {
  116. int num_points = 0;
  117. for (int i = 0; i < mNumPoints; ++i)
  118. if ((inSet & (1 << i)) != 0)
  119. {
  120. mP[num_points] = mP[i];
  121. mQ[num_points] = mQ[i];
  122. ++num_points;
  123. }
  124. mNumPoints = num_points;
  125. }
  126. // Remove points that are not in the set, updates mY, mP and mQ
  127. void UpdatePointSetYPQ(uint32 inSet)
  128. {
  129. int num_points = 0;
  130. for (int i = 0; i < mNumPoints; ++i)
  131. if ((inSet & (1 << i)) != 0)
  132. {
  133. mY[num_points] = mY[i];
  134. mP[num_points] = mP[i];
  135. mQ[num_points] = mQ[i];
  136. ++num_points;
  137. }
  138. mNumPoints = num_points;
  139. }
  140. // Calculate closest points on A and B
  141. void CalculatePointAAndB(Vec3 &outPointA, Vec3 &outPointB) const
  142. {
  143. switch (mNumPoints)
  144. {
  145. case 1:
  146. outPointA = mP[0];
  147. outPointB = mQ[0];
  148. break;
  149. case 2:
  150. {
  151. float u, v;
  152. ClosestPoint::GetBaryCentricCoordinates(mY[0], mY[1], u, v);
  153. outPointA = u * mP[0] + v * mP[1];
  154. outPointB = u * mQ[0] + v * mQ[1];
  155. }
  156. break;
  157. case 3:
  158. {
  159. float u, v, w;
  160. ClosestPoint::GetBaryCentricCoordinates(mY[0], mY[1], mY[2], u, v, w);
  161. outPointA = u * mP[0] + v * mP[1] + w * mP[2];
  162. outPointB = u * mQ[0] + v * mQ[1] + w * mQ[2];
  163. }
  164. break;
  165. case 4:
  166. #ifdef JPH_DEBUG
  167. memset(&outPointA, 0xcd, sizeof(outPointA));
  168. memset(&outPointB, 0xcd, sizeof(outPointB));
  169. #endif
  170. break;
  171. }
  172. }
  173. public:
  174. /// Test if inA and inB intersect
  175. ///
  176. /// @param inA The convex object A, must support the GetSupport(Vec3) function.
  177. /// @param inB The convex object B, must support the GetSupport(Vec3) function.
  178. /// @param inTolerance Minimal distance between objects when the objects are considered to be colliding
  179. /// @param ioV is used as initial separating axis (provide a zero vector if you don't know yet)
  180. ///
  181. /// @return True if they intersect (in which case ioV = (0, 0, 0)).
  182. /// False if they don't intersect in which case ioV is a separating axis in the direction from A to B (magnitude is meaningless)
  183. template <typename A, typename B>
  184. bool Intersects(const A &inA, const B &inB, float inTolerance, Vec3 &ioV)
  185. {
  186. float tolerance_sq = Square(inTolerance);
  187. // Reset state
  188. mNumPoints = 0;
  189. #ifdef JPH_GJK_DEBUG
  190. for (int i = 0; i < 4; ++i)
  191. mY[i] = Vec3::sZero();
  192. #endif
  193. // Previous length^2 of v
  194. float prev_v_len_sq = FLT_MAX;
  195. for (;;)
  196. {
  197. #ifdef JPH_GJK_DEBUG
  198. Trace("v = [%s], num_points = %d", ConvertToString(ioV).c_str(), mNumPoints);
  199. #endif
  200. // Get support points for shape A and B in the direction of v
  201. Vec3 p = inA.GetSupport(ioV);
  202. Vec3 q = inB.GetSupport(-ioV);
  203. // Get support point of the minkowski sum A - B of v
  204. Vec3 w = p - q;
  205. // If the support point sA-B(v) is in the opposite direction as v, then we have found a separating axis and there is no intersection
  206. if (ioV.Dot(w) < 0.0f)
  207. {
  208. // Separating axis found
  209. #ifdef JPH_GJK_DEBUG
  210. Trace("Separating axis");
  211. #endif
  212. return false;
  213. }
  214. // Store the point for later use
  215. mY[mNumPoints] = w;
  216. ++mNumPoints;
  217. #ifdef JPH_GJK_DEBUG
  218. Trace("w = [%s]", ConvertToString(w).c_str());
  219. #endif
  220. // Determine the new closest point
  221. float v_len_sq; // Length^2 of v
  222. uint32 set; // Set of points that form the new simplex
  223. if (!GetClosest<true>(prev_v_len_sq, ioV, v_len_sq, set))
  224. return false;
  225. // If there are 4 points, the origin is inside the tetrahedron and we're done
  226. if (set == 0xf)
  227. {
  228. #ifdef JPH_GJK_DEBUG
  229. Trace("Full simplex");
  230. #endif
  231. ioV = Vec3::sZero();
  232. return true;
  233. }
  234. // If v is very close to zero, we consider this a collision
  235. if (v_len_sq <= tolerance_sq)
  236. {
  237. #ifdef JPH_GJK_DEBUG
  238. Trace("Distance zero");
  239. #endif
  240. ioV = Vec3::sZero();
  241. return true;
  242. }
  243. // If v is very small compared to the length of y, we also consider this a collision
  244. if (v_len_sq <= FLT_EPSILON * GetMaxYLengthSq())
  245. {
  246. #ifdef JPH_GJK_DEBUG
  247. Trace("Machine precision reached");
  248. #endif
  249. ioV = Vec3::sZero();
  250. return true;
  251. }
  252. // The next separation axis to test is the negative of the closest point of the Minkowski sum to the origin
  253. // Note: This must be done before terminating as converged since the separating axis is -v
  254. ioV = -ioV;
  255. // If the squared length of v is not changing enough, we've converged and there is no collision
  256. JPH_ASSERT(prev_v_len_sq >= v_len_sq);
  257. if (prev_v_len_sq - v_len_sq <= FLT_EPSILON * prev_v_len_sq)
  258. {
  259. // v is a separating axis
  260. #ifdef JPH_GJK_DEBUG
  261. Trace("Converged");
  262. #endif
  263. return false;
  264. }
  265. prev_v_len_sq = v_len_sq;
  266. // Update the points of the simplex
  267. UpdatePointSetY(set);
  268. }
  269. }
  270. /// Get closest points between inA and inB
  271. ///
  272. /// @param inA The convex object A, must support the GetSupport(Vec3) function.
  273. /// @param inB The convex object B, must support the GetSupport(Vec3) function.
  274. /// @param inTolerance The minimal distance between A and B before the objects are considered colliding and processing is terminated.
  275. /// @param inMaxDistSq The maximum squared distance between A and B before the objects are considered infinitely far away and processing is terminated.
  276. /// @param ioV Initial guess for the separating axis. Start with any non-zero vector if you don't know.
  277. /// If return value is 0, ioV = (0, 0, 0).
  278. /// If the return value is bigger than 0 but smaller than FLT_MAX, ioV will be the separating axis in the direction from A to B and its length the squared distance between A and B.
  279. /// If the return value is FLT_MAX, ioV will be the separating axis in the direction from A to B and the magnitude of the vector is meaningless.
  280. /// @param outPointA , outPointB
  281. /// If the return value is 0 the points are invalid.
  282. /// If the return value is bigger than 0 but smaller than FLT_MAX these will contain the closest point on A and B.
  283. /// If the return value is FLT_MAX the points are invalid.
  284. ///
  285. /// @return The squared distance between A and B or FLT_MAX when they are further away than inMaxDistSq.
  286. template <typename A, typename B>
  287. float GetClosestPoints(const A &inA, const B &inB, float inTolerance, float inMaxDistSq, Vec3 &ioV, Vec3 &outPointA, Vec3 &outPointB)
  288. {
  289. float tolerance_sq = Square(inTolerance);
  290. // Reset state
  291. mNumPoints = 0;
  292. #ifdef JPH_GJK_DEBUG
  293. // Generate the hull of the Minkowski difference for visualization
  294. MinkowskiDifference diff(inA, inB);
  295. mGeometry = DebugRenderer::sInstance->CreateTriangleGeometryForConvex([&diff](Vec3Arg inDirection) { return diff.GetSupport(inDirection); });
  296. for (int i = 0; i < 4; ++i)
  297. {
  298. mY[i] = Vec3::sZero();
  299. mP[i] = Vec3::sZero();
  300. mQ[i] = Vec3::sZero();
  301. }
  302. #endif
  303. // Length^2 of v
  304. float v_len_sq = ioV.LengthSq();
  305. // Previous length^2 of v
  306. float prev_v_len_sq = FLT_MAX;
  307. for (;;)
  308. {
  309. #ifdef JPH_GJK_DEBUG
  310. Trace("v = [%s], num_points = %d", ConvertToString(ioV).c_str(), mNumPoints);
  311. #endif
  312. // Get support points for shape A and B in the direction of v
  313. Vec3 p = inA.GetSupport(ioV);
  314. Vec3 q = inB.GetSupport(-ioV);
  315. // Get support point of the minkowski sum A - B of v
  316. Vec3 w = p - q;
  317. float dot = ioV.Dot(w);
  318. #ifdef JPH_GJK_DEBUG
  319. // Draw -ioV to show the closest point to the origin from the previous simplex
  320. DebugRenderer::sInstance->DrawArrow(mOffset, mOffset - ioV, Color::sOrange, 0.05f);
  321. // Draw ioV to show where we're probing next
  322. DebugRenderer::sInstance->DrawArrow(mOffset, mOffset + ioV, Color::sCyan, 0.05f);
  323. // Draw w, the support point
  324. DebugRenderer::sInstance->DrawArrow(mOffset, mOffset + w, Color::sGreen, 0.05f);
  325. DebugRenderer::sInstance->DrawMarker(mOffset + w, Color::sGreen, 1.0f);
  326. // Draw the simplex and the Minkowski difference around it
  327. DrawState();
  328. #endif
  329. // Test if we have a separation of more than inMaxDistSq, in which case we terminate early
  330. if (dot < 0.0f && dot * dot > v_len_sq * inMaxDistSq)
  331. {
  332. #ifdef JPH_GJK_DEBUG
  333. Trace("Distance bigger than max");
  334. #endif
  335. #ifdef JPH_DEBUG
  336. memset(&outPointA, 0xcd, sizeof(outPointA));
  337. memset(&outPointB, 0xcd, sizeof(outPointB));
  338. #endif
  339. return FLT_MAX;
  340. }
  341. // Store the point for later use
  342. mY[mNumPoints] = w;
  343. mP[mNumPoints] = p;
  344. mQ[mNumPoints] = q;
  345. ++mNumPoints;
  346. #ifdef JPH_GJK_DEBUG
  347. Trace("w = [%s]", ConvertToString(w).c_str());
  348. #endif
  349. uint32 set;
  350. if (!GetClosest<true>(prev_v_len_sq, ioV, v_len_sq, set))
  351. {
  352. --mNumPoints; // Undo add last point
  353. break;
  354. }
  355. // If there are 4 points, the origin is inside the tetrahedron and we're done
  356. if (set == 0xf)
  357. {
  358. #ifdef JPH_GJK_DEBUG
  359. Trace("Full simplex");
  360. #endif
  361. ioV = Vec3::sZero();
  362. v_len_sq = 0.0f;
  363. break;
  364. }
  365. // Update the points of the simplex
  366. UpdatePointSetYPQ(set);
  367. // If v is very close to zero, we consider this a collision
  368. if (v_len_sq <= tolerance_sq)
  369. {
  370. #ifdef JPH_GJK_DEBUG
  371. Trace("Distance zero");
  372. #endif
  373. ioV = Vec3::sZero();
  374. v_len_sq = 0.0f;
  375. break;
  376. }
  377. // If v is very small compared to the length of y, we also consider this a collision
  378. #ifdef JPH_GJK_DEBUG
  379. Trace("Check v small compared to y: %g <= %g", (double)v_len_sq, (double)(FLT_EPSILON * GetMaxYLengthSq()));
  380. #endif
  381. if (v_len_sq <= FLT_EPSILON * GetMaxYLengthSq())
  382. {
  383. #ifdef JPH_GJK_DEBUG
  384. Trace("Machine precision reached");
  385. #endif
  386. ioV = Vec3::sZero();
  387. v_len_sq = 0.0f;
  388. break;
  389. }
  390. // The next separation axis to test is the negative of the closest point of the Minkowski sum to the origin
  391. // Note: This must be done before terminating as converged since the separating axis is -v
  392. ioV = -ioV;
  393. // If the squared length of v is not changing enough, we've converged and there is no collision
  394. #ifdef JPH_GJK_DEBUG
  395. Trace("Check v not changing enough: %g <= %g", (double)(prev_v_len_sq - v_len_sq), (double)(FLT_EPSILON * prev_v_len_sq));
  396. #endif
  397. JPH_ASSERT(prev_v_len_sq >= v_len_sq);
  398. if (prev_v_len_sq - v_len_sq <= FLT_EPSILON * prev_v_len_sq)
  399. {
  400. // v is a separating axis
  401. #ifdef JPH_GJK_DEBUG
  402. Trace("Converged");
  403. #endif
  404. break;
  405. }
  406. prev_v_len_sq = v_len_sq;
  407. }
  408. // Get the closest points
  409. CalculatePointAAndB(outPointA, outPointB);
  410. #ifdef JPH_GJK_DEBUG
  411. Trace("Return: v = [%s], |v| = %g", ConvertToString(ioV).c_str(), (double)ioV.Length());
  412. // Draw -ioV to show the closest point to the origin from the previous simplex
  413. DebugRenderer::sInstance->DrawArrow(mOffset, mOffset - ioV, Color::sOrange, 0.05f);
  414. // Draw the closest points
  415. DebugRenderer::sInstance->DrawMarker(mOffset + outPointA, Color::sGreen, 1.0f);
  416. DebugRenderer::sInstance->DrawMarker(mOffset + outPointB, Color::sPurple, 1.0f);
  417. // Draw the simplex and the Minkowski difference around it
  418. DrawState();
  419. #endif
  420. JPH_ASSERT(ioV.LengthSq() == v_len_sq);
  421. return v_len_sq;
  422. }
  423. /// Get the resulting simplex after the GetClosestPoints algorithm finishes.
  424. /// If it returned a squared distance of 0, the origin will be contained in the simplex.
  425. void GetClosestPointsSimplex(Vec3 *outY, Vec3 *outP, Vec3 *outQ, uint &outNumPoints) const
  426. {
  427. uint size = sizeof(Vec3) * mNumPoints;
  428. memcpy(outY, mY, size);
  429. memcpy(outP, mP, size);
  430. memcpy(outQ, mQ, size);
  431. outNumPoints = mNumPoints;
  432. }
  433. /// Test if a ray inRayOrigin + lambda * inRayDirection for lambda e [0, ioLambda> intersects inA
  434. ///
  435. /// Code based upon: Ray Casting against General Convex Objects with Application to Continuous Collision Detection - Gino van den Bergen
  436. ///
  437. /// @param inRayOrigin Origin of the ray
  438. /// @param inRayDirection Direction of the ray (ioLambda * inDirection determines length)
  439. /// @param inTolerance The minimal distance between the ray and A before it is considered colliding
  440. /// @param inA A convex object that has the GetSupport(Vec3) function
  441. /// @param ioLambda The max fraction along the ray, on output updated with the actual collision fraction.
  442. ///
  443. /// @return true if a hit was found, ioLambda is the solution for lambda.
  444. template <typename A>
  445. bool CastRay(Vec3Arg inRayOrigin, Vec3Arg inRayDirection, float inTolerance, const A &inA, float &ioLambda)
  446. {
  447. float tolerance_sq = Square(inTolerance);
  448. // Reset state
  449. mNumPoints = 0;
  450. float lambda = 0.0f;
  451. Vec3 x = inRayOrigin;
  452. Vec3 v = x - inA.GetSupport(Vec3::sZero());
  453. float v_len_sq = FLT_MAX;
  454. bool allow_restart = false;
  455. for (;;)
  456. {
  457. #ifdef JPH_GJK_DEBUG
  458. Trace("v = [%s], num_points = %d", ConvertToString(v).c_str(), mNumPoints);
  459. #endif
  460. // Get new support point
  461. Vec3 p = inA.GetSupport(v);
  462. Vec3 w = x - p;
  463. #ifdef JPH_GJK_DEBUG
  464. Trace("w = [%s]", ConvertToString(w).c_str());
  465. #endif
  466. float v_dot_w = v.Dot(w);
  467. #ifdef JPH_GJK_DEBUG
  468. Trace("v . w = %g", (double)v_dot_w);
  469. #endif
  470. if (v_dot_w > 0.0f)
  471. {
  472. // If ray and normal are in the same direction, we've passed A and there's no collision
  473. float v_dot_r = v.Dot(inRayDirection);
  474. #ifdef JPH_GJK_DEBUG
  475. Trace("v . r = %g", (double)v_dot_r);
  476. #endif
  477. if (v_dot_r >= 0.0f)
  478. return false;
  479. // Update the lower bound for lambda
  480. float delta = v_dot_w / v_dot_r;
  481. float old_lambda = lambda;
  482. lambda -= delta;
  483. #ifdef JPH_GJK_DEBUG
  484. Trace("lambda = %g, delta = %g", (double)lambda, (double)delta);
  485. #endif
  486. // If lambda didn't change, we cannot converge any further and we assume a hit
  487. if (old_lambda == lambda)
  488. break;
  489. // If lambda is bigger or equal than max, we don't have a hit
  490. if (lambda >= ioLambda)
  491. return false;
  492. // Update x to new closest point on the ray
  493. x = inRayOrigin + lambda * inRayDirection;
  494. // We've shifted x, so reset v_len_sq so that it is not used as early out for GetClosest
  495. v_len_sq = FLT_MAX;
  496. // We allow rebuilding the simplex once after x changes because the simplex was built
  497. // for another x and numerical round off builds up as you keep adding points to an
  498. // existing simplex
  499. allow_restart = true;
  500. }
  501. // Add p to set P: P = P U {p}
  502. mP[mNumPoints] = p;
  503. ++mNumPoints;
  504. // Calculate Y = {x} - P
  505. for (int i = 0; i < mNumPoints; ++i)
  506. mY[i] = x - mP[i];
  507. // Determine the new closest point from Y to origin
  508. uint32 set; // Set of points that form the new simplex
  509. if (!GetClosest<false>(v_len_sq, v, v_len_sq, set))
  510. {
  511. #ifdef JPH_GJK_DEBUG
  512. Trace("Failed to converge");
  513. #endif
  514. // Only allow 1 restart, if we still can't get a closest point
  515. // we're so close that we return this as a hit
  516. if (!allow_restart)
  517. break;
  518. // If we fail to converge, we start again with the last point as simplex
  519. #ifdef JPH_GJK_DEBUG
  520. Trace("Restarting");
  521. #endif
  522. allow_restart = false;
  523. mP[0] = p;
  524. mNumPoints = 1;
  525. v = x - p;
  526. v_len_sq = FLT_MAX;
  527. continue;
  528. }
  529. else if (set == 0xf)
  530. {
  531. #ifdef JPH_GJK_DEBUG
  532. Trace("Full simplex");
  533. #endif
  534. // We're inside the tetrahedron, we have a hit (verify that length of v is 0)
  535. JPH_ASSERT(v_len_sq == 0.0f);
  536. break;
  537. }
  538. // Update the points P to form the new simplex
  539. // Note: We're not updating Y as Y will shift with x so we have to calculate it every iteration
  540. UpdatePointSetP(set);
  541. // Check if x is close enough to inA
  542. if (v_len_sq <= tolerance_sq)
  543. {
  544. #ifdef JPH_GJK_DEBUG
  545. Trace("Converged");
  546. #endif
  547. break;
  548. }
  549. }
  550. // Store hit fraction
  551. ioLambda = lambda;
  552. return true;
  553. }
  554. /// Test if a cast shape inA moving from inStart to lambda * inStart.GetTranslation() + inDirection where lambda e [0, ioLambda> intersects inB
  555. ///
  556. /// @param inStart Start position and orientation of the convex object
  557. /// @param inDirection Direction of the sweep (ioLambda * inDirection determines length)
  558. /// @param inTolerance The minimal distance between A and B before they are considered colliding
  559. /// @param inA The convex object A, must support the GetSupport(Vec3) function.
  560. /// @param inB The convex object B, must support the GetSupport(Vec3) function.
  561. /// @param ioLambda The max fraction along the sweep, on output updated with the actual collision fraction.
  562. ///
  563. /// @return true if a hit was found, ioLambda is the solution for lambda.
  564. template <typename A, typename B>
  565. bool CastShape(Mat44Arg inStart, Vec3Arg inDirection, float inTolerance, const A &inA, const B &inB, float &ioLambda)
  566. {
  567. // Transform the shape to be cast to the starting position
  568. TransformedConvexObject transformed_a(inStart, inA);
  569. // Calculate the minkowski difference inB - inA
  570. // inA is moving, so we need to add the back side of inB to the front side of inA
  571. MinkowskiDifference difference(inB, transformed_a);
  572. // Do a raycast against the Minkowski difference
  573. return CastRay(Vec3::sZero(), inDirection, inTolerance, difference, ioLambda);
  574. }
  575. /// Test if a cast shape inA moving from inStart to lambda * inStart.GetTranslation() + inDirection where lambda e [0, ioLambda> intersects inB
  576. ///
  577. /// @param inStart Start position and orientation of the convex object
  578. /// @param inDirection Direction of the sweep (ioLambda * inDirection determines length)
  579. /// @param inTolerance The minimal distance between A and B before they are considered colliding
  580. /// @param inA The convex object A, must support the GetSupport(Vec3) function.
  581. /// @param inB The convex object B, must support the GetSupport(Vec3) function.
  582. /// @param inConvexRadiusA The convex radius of A, this will be added on all sides to pad A.
  583. /// @param inConvexRadiusB The convex radius of B, this will be added on all sides to pad B.
  584. /// @param ioLambda The max fraction along the sweep, on output updated with the actual collision fraction.
  585. /// @param outPointA is the contact point on A (if outSeparatingAxis is near zero, this may not be not the deepest point)
  586. /// @param outPointB is the contact point on B (if outSeparatingAxis is near zero, this may not be not the deepest point)
  587. /// @param outSeparatingAxis On return this will contain a vector that points from A to B along the smallest distance of separation.
  588. /// The length of this vector indicates the separation of A and B without their convex radius.
  589. /// If it is near zero, the direction may not be accurate as the bodies may overlap when lambda = 0.
  590. ///
  591. /// @return true if a hit was found, ioLambda is the solution for lambda and outPoint and outSeparatingAxis are valid.
  592. template <typename A, typename B>
  593. bool CastShape(Mat44Arg inStart, Vec3Arg inDirection, float inTolerance, const A &inA, const B &inB, float inConvexRadiusA, float inConvexRadiusB, float &ioLambda, Vec3 &outPointA, Vec3 &outPointB, Vec3 &outSeparatingAxis)
  594. {
  595. float tolerance_sq = Square(inTolerance);
  596. // Calculate how close A and B (without their convex radius) need to be to each other in order for us to consider this a collision
  597. float sum_convex_radius = inConvexRadiusA + inConvexRadiusB;
  598. // Transform the shape to be cast to the starting position
  599. TransformedConvexObject transformed_a(inStart, inA);
  600. // Reset state
  601. mNumPoints = 0;
  602. float lambda = 0.0f;
  603. Vec3 x = Vec3::sZero(); // Since A is already transformed we can start the cast from zero
  604. Vec3 v = -inB.GetSupport(Vec3::sZero()) + transformed_a.GetSupport(Vec3::sZero()); // See CastRay: v = x - inA.GetSupport(Vec3::sZero()) where inA is the Minkowski difference inB - transformed_a (see CastShape above) and x is zero
  605. float v_len_sq = FLT_MAX;
  606. bool allow_restart = false;
  607. // Keeps track of separating axis of the previous iteration.
  608. // Initialized at zero as we don't know if our first v is actually a separating axis.
  609. Vec3 prev_v = Vec3::sZero();
  610. for (;;)
  611. {
  612. #ifdef JPH_GJK_DEBUG
  613. Trace("v = [%s], num_points = %d", ConvertToString(v).c_str(), mNumPoints);
  614. #endif
  615. // Calculate the minkowski difference inB - inA
  616. // inA is moving, so we need to add the back side of inB to the front side of inA
  617. // Keep the support points on A and B separate so that in the end we can calculate a contact point
  618. Vec3 p = transformed_a.GetSupport(-v);
  619. Vec3 q = inB.GetSupport(v);
  620. Vec3 w = x - (q - p);
  621. #ifdef JPH_GJK_DEBUG
  622. Trace("w = [%s]", ConvertToString(w).c_str());
  623. #endif
  624. // Difference from article to this code:
  625. // We did not include the convex radius in p and q in order to be able to calculate a good separating axis at the end of the algorithm.
  626. // However when moving forward along inDirection we do need to take this into account so that we keep A and B separated by the sum of their convex radii.
  627. // From p we have to subtract: inConvexRadiusA * v / |v|
  628. // To q we have to add: inConvexRadiusB * v / |v|
  629. // This means that to w we have to add: -(inConvexRadiusA + inConvexRadiusB) * v / |v|
  630. // So to v . w we have to add: v . (-(inConvexRadiusA + inConvexRadiusB) * v / |v|) = -(inConvexRadiusA + inConvexRadiusB) * |v|
  631. float v_dot_w = v.Dot(w) - sum_convex_radius * v.Length();
  632. #ifdef JPH_GJK_DEBUG
  633. Trace("v . w = %g", (double)v_dot_w);
  634. #endif
  635. if (v_dot_w > 0.0f)
  636. {
  637. // If ray and normal are in the same direction, we've passed A and there's no collision
  638. float v_dot_r = v.Dot(inDirection);
  639. #ifdef JPH_GJK_DEBUG
  640. Trace("v . r = %g", (double)v_dot_r);
  641. #endif
  642. if (v_dot_r >= 0.0f)
  643. return false;
  644. // Update the lower bound for lambda
  645. float delta = v_dot_w / v_dot_r;
  646. float old_lambda = lambda;
  647. lambda -= delta;
  648. #ifdef JPH_GJK_DEBUG
  649. Trace("lambda = %g, delta = %g", (double)lambda, (double)delta);
  650. #endif
  651. // If lambda didn't change, we cannot converge any further and we assume a hit
  652. if (old_lambda == lambda)
  653. break;
  654. // If lambda is bigger or equal than max, we don't have a hit
  655. if (lambda >= ioLambda)
  656. return false;
  657. // Update x to new closest point on the ray
  658. x = lambda * inDirection;
  659. // We've shifted x, so reset v_len_sq so that it is not used as early out when GetClosest returns false
  660. v_len_sq = FLT_MAX;
  661. // Now that we've moved, we know that A and B are not intersecting at lambda = 0, so we can update our tolerance to stop iterating
  662. // as soon as A and B are inConvexRadiusA + inConvexRadiusB apart
  663. tolerance_sq = Square(inTolerance + sum_convex_radius);
  664. // We allow rebuilding the simplex once after x changes because the simplex was built
  665. // for another x and numerical round off builds up as you keep adding points to an
  666. // existing simplex
  667. allow_restart = true;
  668. }
  669. // Add p to set P, q to set Q: P = P U {p}, Q = Q U {q}
  670. mP[mNumPoints] = p;
  671. mQ[mNumPoints] = q;
  672. ++mNumPoints;
  673. // Calculate Y = {x} - (Q - P)
  674. for (int i = 0; i < mNumPoints; ++i)
  675. mY[i] = x - (mQ[i] - mP[i]);
  676. // Determine the new closest point from Y to origin
  677. uint32 set; // Set of points that form the new simplex
  678. if (!GetClosest<false>(v_len_sq, v, v_len_sq, set))
  679. {
  680. #ifdef JPH_GJK_DEBUG
  681. Trace("Failed to converge");
  682. #endif
  683. // Only allow 1 restart, if we still can't get a closest point
  684. // we're so close that we return this as a hit
  685. if (!allow_restart)
  686. break;
  687. // If we fail to converge, we start again with the last point as simplex
  688. #ifdef JPH_GJK_DEBUG
  689. Trace("Restarting");
  690. #endif
  691. allow_restart = false;
  692. mP[0] = p;
  693. mQ[0] = q;
  694. mNumPoints = 1;
  695. v = x - q;
  696. v_len_sq = FLT_MAX;
  697. continue;
  698. }
  699. else if (set == 0xf)
  700. {
  701. #ifdef JPH_GJK_DEBUG
  702. Trace("Full simplex");
  703. #endif
  704. // We're inside the tetrahedron, we have a hit (verify that length of v is 0)
  705. JPH_ASSERT(v_len_sq == 0.0f);
  706. break;
  707. }
  708. // Update the points P and Q to form the new simplex
  709. // Note: We're not updating Y as Y will shift with x so we have to calculate it every iteration
  710. UpdatePointSetPQ(set);
  711. // Check if A and B are touching according to our tolerance
  712. if (v_len_sq <= tolerance_sq)
  713. {
  714. #ifdef JPH_GJK_DEBUG
  715. Trace("Converged");
  716. #endif
  717. break;
  718. }
  719. // Store our v to return as separating axis
  720. prev_v = v;
  721. }
  722. // Calculate Y = {x} - (Q - P) again so we can calculate the contact points
  723. for (int i = 0; i < mNumPoints; ++i)
  724. mY[i] = x - (mQ[i] - mP[i]);
  725. // Calculate the offset we need to apply to A and B to correct for the convex radius
  726. Vec3 normalized_v = v.NormalizedOr(Vec3::sZero());
  727. Vec3 convex_radius_a = inConvexRadiusA * normalized_v;
  728. Vec3 convex_radius_b = inConvexRadiusB * normalized_v;
  729. // Get the contact point
  730. // Note that A and B will coincide when lambda > 0. In this case we calculate only B as it is more accurate as it contains less terms.
  731. switch (mNumPoints)
  732. {
  733. case 1:
  734. outPointB = mQ[0] + convex_radius_b;
  735. outPointA = lambda > 0.0f? outPointB : mP[0] - convex_radius_a;
  736. break;
  737. case 2:
  738. {
  739. float bu, bv;
  740. ClosestPoint::GetBaryCentricCoordinates(mY[0], mY[1], bu, bv);
  741. outPointB = bu * mQ[0] + bv * mQ[1] + convex_radius_b;
  742. outPointA = lambda > 0.0f? outPointB : bu * mP[0] + bv * mP[1] - convex_radius_a;
  743. }
  744. break;
  745. case 3:
  746. case 4: // A full simplex, we can't properly determine a contact point! As contact point we take the closest point of the previous iteration.
  747. {
  748. float bu, bv, bw;
  749. ClosestPoint::GetBaryCentricCoordinates(mY[0], mY[1], mY[2], bu, bv, bw);
  750. outPointB = bu * mQ[0] + bv * mQ[1] + bw * mQ[2] + convex_radius_b;
  751. outPointA = lambda > 0.0f? outPointB : bu * mP[0] + bv * mP[1] + bw * mP[2] - convex_radius_a;
  752. }
  753. break;
  754. }
  755. // Store separating axis, in case we have a convex radius we can just return v,
  756. // otherwise v will be very small and we resort to returning previous v as an approximation.
  757. outSeparatingAxis = sum_convex_radius > 0.0f? -v : -prev_v;
  758. // Store hit fraction
  759. ioLambda = lambda;
  760. return true;
  761. }
  762. private:
  763. #ifdef JPH_GJK_DEBUG
  764. /// Draw state of algorithm
  765. void DrawState()
  766. {
  767. RMat44 origin = RMat44::sTranslation(mOffset);
  768. // Draw origin
  769. DebugRenderer::sInstance->DrawCoordinateSystem(origin, 1.0f);
  770. // Draw the hull
  771. DebugRenderer::sInstance->DrawGeometry(origin, mGeometry->mBounds.Transformed(origin), mGeometry->mBounds.GetExtent().LengthSq(), Color::sYellow, mGeometry);
  772. // Draw Y
  773. for (int i = 0; i < mNumPoints; ++i)
  774. {
  775. // Draw support point
  776. RVec3 y_i = origin * mY[i];
  777. DebugRenderer::sInstance->DrawMarker(y_i, Color::sRed, 1.0f);
  778. for (int j = i + 1; j < mNumPoints; ++j)
  779. {
  780. // Draw edge
  781. RVec3 y_j = origin * mY[j];
  782. DebugRenderer::sInstance->DrawLine(y_i, y_j, Color::sRed);
  783. for (int k = j + 1; k < mNumPoints; ++k)
  784. {
  785. // Make sure triangle faces the origin
  786. RVec3 y_k = origin * mY[k];
  787. RVec3 center = (y_i + y_j + y_k) / Real(3);
  788. RVec3 normal = (y_j - y_i).Cross(y_k - y_i);
  789. if (normal.Dot(center) < Real(0))
  790. DebugRenderer::sInstance->DrawTriangle(y_i, y_j, y_k, Color::sLightGrey);
  791. else
  792. DebugRenderer::sInstance->DrawTriangle(y_i, y_k, y_j, Color::sLightGrey);
  793. }
  794. }
  795. }
  796. // Offset to the right
  797. mOffset += Vec3(mGeometry->mBounds.GetSize().GetX() + 2.0f, 0, 0);
  798. }
  799. #endif // JPH_GJK_DEBUG
  800. Vec3 mY[4]; ///< Support points on A - B
  801. Vec3 mP[4]; ///< Support point on A
  802. Vec3 mQ[4]; ///< Support point on B
  803. int mNumPoints = 0; ///< Number of points in mY, mP and mQ that are valid
  804. #ifdef JPH_GJK_DEBUG
  805. DebugRenderer::GeometryRef mGeometry; ///< A visualization of the minkowski difference for state drawing
  806. RVec3 mOffset = RVec3::sZero(); ///< Offset to use for state drawing
  807. #endif
  808. };
  809. JPH_NAMESPACE_END