ClosestPoint.h 16 KB

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