ClosestPoint.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. JPH_NAMESPACE_BEGIN
  6. // Turn off fused multiply add instruction because it makes the equations of the form a * b - c * d inaccurate below
  7. JPH_PRECISE_MATH_ON
  8. /// Helper utils to find the closest point to a line segment, triangle or tetrahedron
  9. namespace ClosestPoint
  10. {
  11. /// Compute barycentric coordinates of closest point to origin for infinite line defined by (inA, inB)
  12. /// Point can then be computed as inA * outU + inB * outV
  13. inline void GetBaryCentricCoordinates(Vec3Arg inA, Vec3Arg inB, float &outU, float &outV)
  14. {
  15. Vec3 ab = inB - inA;
  16. float denominator = ab.LengthSq();
  17. if (denominator < Square(FLT_EPSILON))
  18. {
  19. // Degenerate line segment, fallback to points
  20. if (inA.LengthSq() < inB.LengthSq())
  21. {
  22. // A closest
  23. outU = 1.0f;
  24. outV = 0.0f;
  25. }
  26. else
  27. {
  28. // B closest
  29. outU = 0.0f;
  30. outV = 1.0f;
  31. }
  32. }
  33. else
  34. {
  35. outV = -inA.Dot(ab) / denominator;
  36. outU = 1.0f - outV;
  37. }
  38. }
  39. /// Compute barycentric coordinates of closest point to origin for plane defined by (inA, inB, inC)
  40. /// Point can then be computed as inA * outU + inB * outV + inC * outW
  41. inline void GetBaryCentricCoordinates(Vec3Arg inA, Vec3Arg inB, Vec3Arg inC, float &outU, float &outV, float &outW)
  42. {
  43. // Taken from: Real-Time Collision Detection - Christer Ericson (Section: Barycentric Coordinates)
  44. // With p = 0
  45. // Adjusted to always include the shortest edge of the triangle in the calculation to improve numerical accuracy
  46. // First calculate the three edges
  47. Vec3 v0 = inB - inA;
  48. Vec3 v1 = inC - inA;
  49. Vec3 v2 = inC - inB;
  50. // Make sure that the shortest edge is included in the calculation to keep the products a * b - c * d as small as possible to preserve accuracy
  51. float d00 = v0.Dot(v0);
  52. float d11 = v1.Dot(v1);
  53. float d22 = v2.Dot(v2);
  54. if (d00 <= d22)
  55. {
  56. // Use v0 and v1 to calculate barycentric coordinates
  57. float d01 = v0.Dot(v1);
  58. float denominator = d00 * d11 - d01 * d01;
  59. if (abs(denominator) < 1.0e-12f)
  60. {
  61. // Degenerate triangle, return coordinates along longest edge
  62. if (d00 > d11)
  63. {
  64. GetBaryCentricCoordinates(inA, inB, outU, outV);
  65. outW = 0.0f;
  66. }
  67. else
  68. {
  69. GetBaryCentricCoordinates(inA, inC, outU, outW);
  70. outV = 0.0f;
  71. }
  72. }
  73. else
  74. {
  75. float a0 = inA.Dot(v0);
  76. float a1 = inA.Dot(v1);
  77. outV = (d01 * a1 - d11 * a0) / denominator;
  78. outW = (d01 * a0 - d00 * a1) / denominator;
  79. outU = 1.0f - outV - outW;
  80. }
  81. }
  82. else
  83. {
  84. // Use v1 and v2 to calculate barycentric coordinates
  85. float d12 = v1.Dot(v2);
  86. float denominator = d11 * d22 - d12 * d12;
  87. if (abs(denominator) < 1.0e-12f)
  88. {
  89. // Degenerate triangle, return coordinates along longest edge
  90. if (d11 > d22)
  91. {
  92. GetBaryCentricCoordinates(inA, inC, outU, outW);
  93. outV = 0.0f;
  94. }
  95. else
  96. {
  97. GetBaryCentricCoordinates(inB, inC, outV, outW);
  98. outU = 0.0f;
  99. }
  100. }
  101. else
  102. {
  103. float c1 = inC.Dot(v1);
  104. float c2 = inC.Dot(v2);
  105. outU = (d22 * c1 - d12 * c2) / denominator;
  106. outV = (d11 * c2 - d12 * c1) / denominator;
  107. outW = 1.0f - outU - outV;
  108. }
  109. }
  110. }
  111. /// Get the closest point to the origin of line (inA, inB)
  112. /// outSet describes which features are closest: 1 = a, 2 = b, 3 = line segment ab
  113. inline Vec3 GetClosestPointOnLine(Vec3Arg inA, Vec3Arg inB, uint32 &outSet)
  114. {
  115. float u, v;
  116. GetBaryCentricCoordinates(inA, inB, u, v);
  117. if (v <= 0.0f)
  118. {
  119. // inA is closest point
  120. outSet = 0b0001;
  121. return inA;
  122. }
  123. else if (u <= 0.0f)
  124. {
  125. // inB is closest point
  126. outSet = 0b0010;
  127. return inB;
  128. }
  129. else
  130. {
  131. // Closest point lies on line inA inB
  132. outSet = 0b0011;
  133. return u * inA + v * inB;
  134. }
  135. }
  136. /// Get the closest point to the origin of triangle (inA, inB, inC)
  137. /// outSet describes which features are closest: 1 = a, 2 = b, 4 = c, 5 = line segment ac, 7 = triangle interior etc.
  138. /// If MustIncludeC is true, the function assumes that C is part of the closest feature (vertex, edge, face) and does less work, if the assumption is not true then a closest point to the other features is returned.
  139. template <bool MustIncludeC = false>
  140. inline Vec3 GetClosestPointOnTriangle(Vec3Arg inA, Vec3Arg inB, Vec3Arg inC, uint32 &outSet)
  141. {
  142. // Taken from: Real-Time Collision Detection - Christer Ericson (Section: Closest Point on Triangle to Point)
  143. // With p = 0
  144. // The most accurate normal is calculated by using the two shortest edges
  145. // See: https://box2d.org/posts/2014/01/troublesome-triangle/
  146. // The difference in normals is most pronounced when one edge is much smaller than the others (in which case the other 2 must have roughly the same length).
  147. // Therefore we can suffice by just picking the shortest from 2 edges and use that with the 3rd edge to calculate the normal.
  148. // We first check which of the edges is shorter and if bc is shorter than ac then we swap a with c to a is always on the shortest edge
  149. UVec4 swap_ac;
  150. {
  151. Vec3 ac = inC - inA;
  152. Vec3 bc = inC - inB;
  153. swap_ac = Vec4::sLess(bc.DotV4(bc), ac.DotV4(ac));
  154. }
  155. Vec3 a = Vec3::sSelect(inA, inC, swap_ac);
  156. Vec3 c = Vec3::sSelect(inC, inA, swap_ac);
  157. // Calculate normal
  158. Vec3 ab = inB - a;
  159. Vec3 ac = c - a;
  160. Vec3 n = ab.Cross(ac);
  161. float n_len_sq = n.LengthSq();
  162. // Check degenerate
  163. if (n_len_sq < 1.0e-11f) // Square(FLT_EPSILON) was too small and caused numerical problems, see test case TestCollideParallelTriangleVsCapsule
  164. {
  165. // Degenerate, fallback to vertices and edges
  166. // Start with vertex C being the closest
  167. uint32 closest_set = 0b0100;
  168. Vec3 closest_point = inC;
  169. float best_dist_sq = inC.LengthSq();
  170. // If the closest point must include C then A or B cannot be closest
  171. if constexpr (!MustIncludeC)
  172. {
  173. // Try vertex A
  174. float a_len_sq = inA.LengthSq();
  175. if (a_len_sq < best_dist_sq)
  176. {
  177. closest_set = 0b0001;
  178. closest_point = inA;
  179. best_dist_sq = a_len_sq;
  180. }
  181. // Try vertex B
  182. float b_len_sq = inB.LengthSq();
  183. if (b_len_sq < best_dist_sq)
  184. {
  185. closest_set = 0b0010;
  186. closest_point = inB;
  187. best_dist_sq = b_len_sq;
  188. }
  189. // Edge AB
  190. float ab_len_sq = ab.LengthSq();
  191. if (ab_len_sq > Square(FLT_EPSILON))
  192. {
  193. float v = Clamp(-a.Dot(ab) / ab_len_sq, 0.0f, 1.0f);
  194. Vec3 q = a + v * ab;
  195. float dist_sq = q.LengthSq();
  196. if (dist_sq < best_dist_sq)
  197. {
  198. closest_set = swap_ac.GetX()? 0b0110 : 0b0011;
  199. closest_point = q;
  200. best_dist_sq = dist_sq;
  201. }
  202. }
  203. }
  204. // Edge AC
  205. float ac_len_sq = ac.LengthSq();
  206. if (ac_len_sq > Square(FLT_EPSILON))
  207. {
  208. float v = Clamp(-a.Dot(ac) / ac_len_sq, 0.0f, 1.0f);
  209. Vec3 q = a + v * ac;
  210. float dist_sq = q.LengthSq();
  211. if (dist_sq < best_dist_sq)
  212. {
  213. closest_set = 0b0101;
  214. closest_point = q;
  215. best_dist_sq = dist_sq;
  216. }
  217. }
  218. // Edge BC
  219. Vec3 bc = c - inB;
  220. float bc_len_sq = bc.LengthSq();
  221. if (bc_len_sq > Square(FLT_EPSILON))
  222. {
  223. float v = Clamp(-inB.Dot(bc) / bc_len_sq, 0.0f, 1.0f);
  224. Vec3 q = inB + v * bc;
  225. float dist_sq = q.LengthSq();
  226. if (dist_sq < best_dist_sq)
  227. {
  228. closest_set = swap_ac.GetX()? 0b0011 : 0b0110;
  229. closest_point = q;
  230. best_dist_sq = dist_sq;
  231. }
  232. }
  233. outSet = closest_set;
  234. return closest_point;
  235. }
  236. // Check if P in vertex region outside A
  237. Vec3 ap = -a;
  238. float d1 = ab.Dot(ap);
  239. float d2 = ac.Dot(ap);
  240. if (d1 <= 0.0f && d2 <= 0.0f)
  241. {
  242. outSet = swap_ac.GetX()? 0b0100 : 0b0001;
  243. return a; // barycentric coordinates (1,0,0)
  244. }
  245. // Check if P in vertex region outside B
  246. Vec3 bp = -inB;
  247. float d3 = ab.Dot(bp);
  248. float d4 = ac.Dot(bp);
  249. if (d3 >= 0.0f && d4 <= d3)
  250. {
  251. outSet = 0b0010;
  252. return inB; // barycentric coordinates (0,1,0)
  253. }
  254. // Check if P in edge region of AB, if so return projection of P onto AB
  255. if (d1 * d4 <= d3 * d2 && d1 >= 0.0f && d3 <= 0.0f)
  256. {
  257. float v = d1 / (d1 - d3);
  258. outSet = swap_ac.GetX()? 0b0110 : 0b0011;
  259. return a + v * ab; // barycentric coordinates (1-v,v,0)
  260. }
  261. // Check if P in vertex region outside C
  262. Vec3 cp = -c;
  263. float d5 = ab.Dot(cp);
  264. float d6 = ac.Dot(cp);
  265. if (d6 >= 0.0f && d5 <= d6)
  266. {
  267. outSet = swap_ac.GetX()? 0b0001 : 0b0100;
  268. return c; // barycentric coordinates (0,0,1)
  269. }
  270. // Check if P in edge region of AC, if so return projection of P onto AC
  271. if (d5 * d2 <= d1 * d6 && d2 >= 0.0f && d6 <= 0.0f)
  272. {
  273. float w = d2 / (d2 - d6);
  274. outSet = 0b0101;
  275. return a + w * ac; // barycentric coordinates (1-w,0,w)
  276. }
  277. // Check if P in edge region of BC, if so return projection of P onto BC
  278. float d4_d3 = d4 - d3;
  279. float d5_d6 = d5 - d6;
  280. if (d3 * d6 <= d5 * d4 && d4_d3 >= 0.0f && d5_d6 >= 0.0f)
  281. {
  282. float w = d4_d3 / (d4_d3 + d5_d6);
  283. outSet = swap_ac.GetX()? 0b0011 : 0b0110;
  284. return inB + w * (c - inB); // barycentric coordinates (0,1-w,w)
  285. }
  286. // P inside face region.
  287. // Here we deviate from Christer Ericson's article to improve accuracy.
  288. // Determine distance between triangle and origin: distance = (centroid - origin) . normal / |normal|
  289. // Closest point to origin is then: distance . normal / |normal|
  290. // Note that this way of calculating the closest point is much more accurate than first calculating barycentric coordinates
  291. // and then calculating the closest point based on those coordinates.
  292. outSet = 0b0111;
  293. return n * (a + inB + c).Dot(n) / (3.0f * n_len_sq);
  294. }
  295. /// Check if the origin is outside the plane of triangle (inA, inB, inC). inD specifies the front side of the plane.
  296. inline bool OriginOutsideOfPlane(Vec3Arg inA, Vec3Arg inB, Vec3Arg inC, Vec3Arg inD)
  297. {
  298. // Taken from: Real-Time Collision Detection - Christer Ericson (Section: Closest Point on Tetrahedron to Point)
  299. // With p = 0
  300. // Test if point p and d lie on opposite sides of plane through abc
  301. Vec3 n = (inB - inA).Cross(inC - inA);
  302. float signp = inA.Dot(n); // [AP AB AC]
  303. float signd = (inD - inA).Dot(n); // [AD AB AC]
  304. // Points on opposite sides if expression signs are the same
  305. // Note that we left out the minus sign in signp so we need to check > 0 instead of < 0 as in Christer's book
  306. // We compare against a small negative value to allow for a little bit of slop in the calculations
  307. return signp * signd > -FLT_EPSILON;
  308. }
  309. /// Returns for each of the planes of the tetrahedron if the origin is inside it
  310. /// Roughly equivalent to:
  311. /// [OriginOutsideOfPlane(inA, inB, inC, inD),
  312. /// OriginOutsideOfPlane(inA, inC, inD, inB),
  313. /// OriginOutsideOfPlane(inA, inD, inB, inC),
  314. /// OriginOutsideOfPlane(inB, inD, inC, inA)]
  315. inline UVec4 OriginOutsideOfTetrahedronPlanes(Vec3Arg inA, Vec3Arg inB, Vec3Arg inC, Vec3Arg inD)
  316. {
  317. Vec3 ab = inB - inA;
  318. Vec3 ac = inC - inA;
  319. Vec3 ad = inD - inA;
  320. Vec3 bd = inD - inB;
  321. Vec3 bc = inC - inB;
  322. Vec3 ab_cross_ac = ab.Cross(ac);
  323. Vec3 ac_cross_ad = ac.Cross(ad);
  324. Vec3 ad_cross_ab = ad.Cross(ab);
  325. Vec3 bd_cross_bc = bd.Cross(bc);
  326. // For each plane get the side on which the origin is
  327. float signp0 = inA.Dot(ab_cross_ac); // ABC
  328. float signp1 = inA.Dot(ac_cross_ad); // ACD
  329. float signp2 = inA.Dot(ad_cross_ab); // ADB
  330. float signp3 = inB.Dot(bd_cross_bc); // BDC
  331. Vec4 signp(signp0, signp1, signp2, signp3);
  332. // For each plane get the side that is outside (determined by the 4th point)
  333. float signd0 = ad.Dot(ab_cross_ac); // D
  334. float signd1 = ab.Dot(ac_cross_ad); // B
  335. float signd2 = ac.Dot(ad_cross_ab); // C
  336. float signd3 = -ab.Dot(bd_cross_bc); // A
  337. Vec4 signd(signd0, signd1, signd2, signd3);
  338. // The winding of all triangles has been chosen so that signd should have the
  339. // same sign for all components. If this is not the case the tetrahedron
  340. // is degenerate and we return that the origin is in front of all sides
  341. int sign_bits = signd.GetSignBits();
  342. switch (sign_bits)
  343. {
  344. case 0:
  345. // All positive
  346. return Vec4::sGreaterOrEqual(signp, Vec4::sReplicate(-FLT_EPSILON));
  347. case 0xf:
  348. // All negative
  349. return Vec4::sLessOrEqual(signp, Vec4::sReplicate(FLT_EPSILON));
  350. default:
  351. // Mixed signs, degenerate tetrahedron
  352. return UVec4::sReplicate(0xffffffff);
  353. }
  354. }
  355. /// Get the closest point between tetrahedron (inA, inB, inC, inD) to the origin
  356. /// outSet specifies which feature was closest, 1 = a, 2 = b, 4 = c, 8 = d. Edges have 2 bits set, triangles 3 and if the point is in the interior 4 bits are set.
  357. /// If MustIncludeD is true, the function assumes that D is part of the closest feature (vertex, edge, face, tetrahedron) and does less work, if the assumption is not true then a closest point to the other features is returned.
  358. template <bool MustIncludeD = false>
  359. inline Vec3 GetClosestPointOnTetrahedron(Vec3Arg inA, Vec3Arg inB, Vec3Arg inC, Vec3Arg inD, uint32 &outSet)
  360. {
  361. // Taken from: Real-Time Collision Detection - Christer Ericson (Section: Closest Point on Tetrahedron to Point)
  362. // With p = 0
  363. // Start out assuming point inside all halfspaces, so closest to itself
  364. uint32 closest_set = 0b1111;
  365. Vec3 closest_point = Vec3::sZero();
  366. float best_dist_sq = FLT_MAX;
  367. // Determine for each of the faces of the tetrahedron if the origin is in front of the plane
  368. UVec4 origin_out_of_planes = OriginOutsideOfTetrahedronPlanes(inA, inB, inC, inD);
  369. // If point outside face abc then compute closest point on abc
  370. if (origin_out_of_planes.GetX()) // OriginOutsideOfPlane(inA, inB, inC, inD)
  371. {
  372. if constexpr (MustIncludeD)
  373. {
  374. // If the closest point must include D then ABC cannot be closest but the closest point
  375. // cannot be an interior point either so we return A as closest point
  376. closest_set = 0b0001;
  377. closest_point = inA;
  378. }
  379. else
  380. {
  381. // Test the face normally
  382. closest_point = GetClosestPointOnTriangle<false>(inA, inB, inC, closest_set);
  383. }
  384. best_dist_sq = closest_point.LengthSq();
  385. }
  386. // Repeat test for face acd
  387. if (origin_out_of_planes.GetY()) // OriginOutsideOfPlane(inA, inC, inD, inB)
  388. {
  389. uint32 set;
  390. Vec3 q = GetClosestPointOnTriangle<MustIncludeD>(inA, inC, inD, set);
  391. float dist_sq = q.LengthSq();
  392. if (dist_sq < best_dist_sq)
  393. {
  394. best_dist_sq = dist_sq;
  395. closest_point = q;
  396. closest_set = (set & 0b0001) + ((set & 0b0110) << 1);
  397. }
  398. }
  399. // Repeat test for face adb
  400. if (origin_out_of_planes.GetZ()) // OriginOutsideOfPlane(inA, inD, inB, inC)
  401. {
  402. // Keep original vertex order, it doesn't matter if the triangle is facing inward or outward
  403. // and it improves consistency for GJK which will always add a new vertex D and keep the closest
  404. // feature from the previous iteration in ABC
  405. uint32 set;
  406. Vec3 q = GetClosestPointOnTriangle<MustIncludeD>(inA, inB, inD, set);
  407. float dist_sq = q.LengthSq();
  408. if (dist_sq < best_dist_sq)
  409. {
  410. best_dist_sq = dist_sq;
  411. closest_point = q;
  412. closest_set = (set & 0b0011) + ((set & 0b0100) << 1);
  413. }
  414. }
  415. // Repeat test for face bdc
  416. if (origin_out_of_planes.GetW()) // OriginOutsideOfPlane(inB, inD, inC, inA)
  417. {
  418. // Keep original vertex order, it doesn't matter if the triangle is facing inward or outward
  419. // and it improves consistency for GJK which will always add a new vertex D and keep the closest
  420. // feature from the previous iteration in ABC
  421. uint32 set;
  422. Vec3 q = GetClosestPointOnTriangle<MustIncludeD>(inB, inC, inD, set);
  423. float dist_sq = q.LengthSq();
  424. if (dist_sq < best_dist_sq)
  425. {
  426. closest_point = q;
  427. closest_set = set << 1;
  428. }
  429. }
  430. outSet = closest_set;
  431. return closest_point;
  432. }
  433. };
  434. JPH_PRECISE_MATH_OFF
  435. JPH_NAMESPACE_END