2
0

EPAConvexHullBuilder.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. // Define to validate the integrity of the hull structure
  6. //#define JPH_EPA_CONVEX_BUILDER_VALIDATE
  7. // Define to draw the building of the hull for debugging purposes
  8. //#define JPH_EPA_CONVEX_BUILDER_DRAW
  9. #include <Jolt/Core/NonCopyable.h>
  10. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  11. #include <Jolt/Renderer/DebugRenderer.h>
  12. #include <Jolt/Core/StringTools.h>
  13. #endif
  14. JPH_NAMESPACE_BEGIN
  15. /// A convex hull builder specifically made for the EPA penetration depth calculation. It trades accuracy for speed and will simply abort of the hull forms defects due to numerical precision problems.
  16. class EPAConvexHullBuilder : public NonCopyable
  17. {
  18. private:
  19. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  20. /// Factor to scale convex hull when debug drawing the construction process
  21. static constexpr Real cDrawScale = 10;
  22. #endif
  23. public:
  24. // Due to the Euler characteristic (https://en.wikipedia.org/wiki/Euler_characteristic) we know that Vertices - Edges + Faces = 2
  25. // In our case we only have triangles and they are always fully connected, so each edge is shared exactly between 2 faces: Edges = Faces * 3 / 2
  26. // Substituting: Vertices = Faces / 2 + 2 which is approximately Faces / 2.
  27. static constexpr int cMaxTriangles = 256; ///< Max triangles in hull
  28. static constexpr int cMaxPoints = cMaxTriangles / 2; ///< Max number of points in hull
  29. // Constants
  30. static constexpr int cMaxEdgeLength = 128; ///< Max number of edges in FindEdge
  31. static constexpr float cMinTriangleArea = 1.0e-10f; ///< Minimum area of a triangle before, if smaller than this it will not be added to the priority queue
  32. static constexpr float cBarycentricEpsilon = 1.0e-3f; ///< Epsilon value used to determine if a point is in the interior of a triangle
  33. // Forward declare
  34. class Triangle;
  35. /// Class that holds the information of an edge
  36. class Edge
  37. {
  38. public:
  39. /// Information about neighbouring triangle
  40. Triangle * mNeighbourTriangle; ///< Triangle that neighbours this triangle
  41. int mNeighbourEdge; ///< Index in mEdge that specifies edge that this Edge is connected to
  42. int mStartIdx; ///< Vertex index in mPositions that indicates the start vertex of this edge
  43. };
  44. using Edges = StaticArray<Edge, cMaxEdgeLength>;
  45. using NewTriangles = StaticArray<Triangle *, cMaxEdgeLength>;
  46. /// Class that holds the information of one triangle
  47. class Triangle : public NonCopyable
  48. {
  49. public:
  50. /// Constructor
  51. inline Triangle(int inIdx0, int inIdx1, int inIdx2, const Vec3 *inPositions);
  52. /// Check if triangle is facing inPosition
  53. inline bool IsFacing(Vec3Arg inPosition) const
  54. {
  55. JPH_ASSERT(!mRemoved);
  56. return mNormal.Dot(inPosition - mCentroid) > 0.0f;
  57. }
  58. /// Check if triangle is facing the origin
  59. inline bool IsFacingOrigin() const
  60. {
  61. JPH_ASSERT(!mRemoved);
  62. return mNormal.Dot(mCentroid) < 0.0f;
  63. }
  64. /// Get the next edge of edge inIndex
  65. inline const Edge & GetNextEdge(int inIndex) const
  66. {
  67. return mEdge[(inIndex + 1) % 3];
  68. }
  69. Edge mEdge[3]; ///< 3 edges of this triangle
  70. Vec3 mNormal; ///< Normal of this triangle, length is 2 times area of triangle
  71. Vec3 mCentroid; ///< Center of the triangle
  72. float mClosestLenSq = FLT_MAX; ///< Closest distance^2 from origin to triangle
  73. float mLambda[2]; ///< Barycentric coordinates of closest point to origin on triangle
  74. bool mLambdaRelativeTo0; ///< How to calculate the closest point, true: y0 + l0 * (y1 - y0) + l1 * (y2 - y0), false: y1 + l0 * (y0 - y1) + l1 * (y2 - y1)
  75. bool mClosestPointInterior = false; ///< Flag that indicates that the closest point from this triangle to the origin is an interior point
  76. bool mRemoved = false; ///< Flag that indicates that triangle has been removed
  77. bool mInQueue = false; ///< Flag that indicates that this triangle was placed in the sorted heap (stays true after it is popped because the triangle is freed by the main EPA algorithm loop)
  78. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  79. int mIteration; ///< Iteration that this triangle was created
  80. #endif
  81. };
  82. /// Factory that creates triangles in a fixed size buffer
  83. class TriangleFactory : public NonCopyable
  84. {
  85. private:
  86. /// Struct that stores both a triangle or a next pointer in case the triangle is unused
  87. union alignas(Triangle) Block
  88. {
  89. uint8 mTriangle[sizeof(Triangle)];
  90. Block * mNextFree;
  91. };
  92. /// Storage for triangle data
  93. Block mTriangles[cMaxTriangles]; ///< Storage for triangles
  94. Block * mNextFree = nullptr; ///< List of free triangles
  95. int mHighWatermark = 0; ///< High water mark for used triangles (if mNextFree == nullptr we can take one from here)
  96. public:
  97. /// Return all triangles to the free pool
  98. void Clear()
  99. {
  100. mNextFree = nullptr;
  101. mHighWatermark = 0;
  102. }
  103. /// Allocate a new triangle with 3 indexes
  104. Triangle * CreateTriangle(int inIdx0, int inIdx1, int inIdx2, const Vec3 *inPositions)
  105. {
  106. Triangle *t;
  107. if (mNextFree != nullptr)
  108. {
  109. // Entry available from the free list
  110. t = reinterpret_cast<Triangle *>(&mNextFree->mTriangle);
  111. mNextFree = mNextFree->mNextFree;
  112. }
  113. else
  114. {
  115. // Allocate from never used before triangle store
  116. if (mHighWatermark >= cMaxTriangles)
  117. return nullptr; // Buffer full
  118. t = reinterpret_cast<Triangle *>(&mTriangles[mHighWatermark].mTriangle);
  119. ++mHighWatermark;
  120. }
  121. // Call constructor
  122. new (t) Triangle(inIdx0, inIdx1, inIdx2, inPositions);
  123. return t;
  124. }
  125. /// Free a triangle
  126. void FreeTriangle(Triangle *inT)
  127. {
  128. // Destruct triangle
  129. inT->~Triangle();
  130. #ifdef _DEBUG
  131. memset(inT, 0xcd, sizeof(Triangle));
  132. #endif
  133. // Add triangle to the free list
  134. Block *tu = reinterpret_cast<Block *>(inT);
  135. tu->mNextFree = mNextFree;
  136. mNextFree = tu;
  137. }
  138. };
  139. // Typedefs
  140. using PointsBase = StaticArray<Vec3, cMaxPoints>;
  141. using Triangles = StaticArray<Triangle *, cMaxTriangles>;
  142. /// Specialized points list that allows direct access to the size
  143. class Points : public PointsBase
  144. {
  145. public:
  146. size_type & GetSizeRef()
  147. {
  148. return mSize;
  149. }
  150. };
  151. /// Specialized triangles list that keeps them sorted on closest distance to origin
  152. class TriangleQueue : public Triangles
  153. {
  154. public:
  155. /// Function to sort triangles on closest distance to origin
  156. static bool sTriangleSorter(const Triangle *inT1, const Triangle *inT2)
  157. {
  158. return inT1->mClosestLenSq > inT2->mClosestLenSq;
  159. }
  160. /// Add triangle to the list
  161. void push_back(Triangle *inT)
  162. {
  163. // Add to base
  164. Triangles::push_back(inT);
  165. // Mark in queue
  166. inT->mInQueue = true;
  167. // Resort heap
  168. std::push_heap(begin(), end(), sTriangleSorter);
  169. }
  170. /// Peek the next closest triangle without removing it
  171. Triangle * PeekClosest()
  172. {
  173. return front();
  174. }
  175. /// Get next closest triangle
  176. Triangle * PopClosest()
  177. {
  178. // Move largest to end
  179. std::pop_heap(begin(), end(), sTriangleSorter);
  180. // Remove last triangle
  181. Triangle *t = back();
  182. pop_back();
  183. return t;
  184. }
  185. };
  186. /// Constructor
  187. explicit EPAConvexHullBuilder(const Points &inPositions) :
  188. mPositions(inPositions)
  189. {
  190. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  191. mIteration = 0;
  192. mOffset = RVec3::sZero();
  193. #endif
  194. }
  195. /// Initialize the hull with 3 points
  196. void Initialize(int inIdx1, int inIdx2, int inIdx3)
  197. {
  198. // Release triangles
  199. mFactory.Clear();
  200. // Create triangles (back to back)
  201. Triangle *t1 = CreateTriangle(inIdx1, inIdx2, inIdx3);
  202. Triangle *t2 = CreateTriangle(inIdx1, inIdx3, inIdx2);
  203. // Link triangles edges
  204. sLinkTriangle(t1, 0, t2, 2);
  205. sLinkTriangle(t1, 1, t2, 1);
  206. sLinkTriangle(t1, 2, t2, 0);
  207. // Always add both triangles to the priority queue
  208. mTriangleQueue.push_back(t1);
  209. mTriangleQueue.push_back(t2);
  210. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  211. // Draw current state
  212. DrawState();
  213. // Increment iteration counter
  214. ++mIteration;
  215. #endif
  216. }
  217. /// Check if there's another triangle to process from the queue
  218. bool HasNextTriangle() const
  219. {
  220. return !mTriangleQueue.empty();
  221. }
  222. /// Access to the next closest triangle to the origin (won't remove it from the queue).
  223. Triangle * PeekClosestTriangleInQueue()
  224. {
  225. return mTriangleQueue.PeekClosest();
  226. }
  227. /// Access to the next closest triangle to the origin and remove it from the queue.
  228. Triangle * PopClosestTriangleFromQueue()
  229. {
  230. return mTriangleQueue.PopClosest();
  231. }
  232. /// Find the triangle on which inPosition is the furthest to the front
  233. /// Note this function works as long as all points added have been added with AddPoint(..., FLT_MAX).
  234. Triangle * FindFacingTriangle(Vec3Arg inPosition, float &outBestDistSq)
  235. {
  236. Triangle *best = nullptr;
  237. float best_dist_sq = 0.0f;
  238. for (Triangle *t : mTriangleQueue)
  239. if (!t->mRemoved)
  240. {
  241. float dot = t->mNormal.Dot(inPosition - t->mCentroid);
  242. if (dot > 0.0f)
  243. {
  244. float dist_sq = dot * dot / t->mNormal.LengthSq();
  245. if (dist_sq > best_dist_sq)
  246. {
  247. best = t;
  248. best_dist_sq = dist_sq;
  249. }
  250. }
  251. }
  252. outBestDistSq = best_dist_sq;
  253. return best;
  254. }
  255. /// Add a new point to the convex hull
  256. bool AddPoint(Triangle *inFacingTriangle, int inIdx, float inClosestDistSq, NewTriangles &outTriangles)
  257. {
  258. // Get position
  259. Vec3 pos = mPositions[inIdx];
  260. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  261. // Draw new support point
  262. DrawMarker(pos, Color::sYellow, 1.0f);
  263. #endif
  264. #ifdef JPH_EPA_CONVEX_BUILDER_VALIDATE
  265. // Check if structure is intact
  266. ValidateTriangles();
  267. #endif
  268. // Find edge of convex hull of triangles that are not facing the new vertex w
  269. Edges edges;
  270. if (!FindEdge(inFacingTriangle, pos, edges))
  271. return false;
  272. // Create new triangles
  273. int num_edges = edges.size();
  274. for (int i = 0; i < num_edges; ++i)
  275. {
  276. // Create new triangle
  277. Triangle *nt = CreateTriangle(edges[i].mStartIdx, edges[(i + 1) % num_edges].mStartIdx, inIdx);
  278. if (nt == nullptr)
  279. return false;
  280. outTriangles.push_back(nt);
  281. // Check if we need to put this triangle in the priority queue
  282. if ((nt->mClosestPointInterior && nt->mClosestLenSq < inClosestDistSq) // For the main algorithm
  283. || nt->mClosestLenSq < 0.0f) // For when the origin is not inside the hull yet
  284. mTriangleQueue.push_back(nt);
  285. }
  286. // Link edges
  287. for (int i = 0; i < num_edges; ++i)
  288. {
  289. sLinkTriangle(outTriangles[i], 0, edges[i].mNeighbourTriangle, edges[i].mNeighbourEdge);
  290. sLinkTriangle(outTriangles[i], 1, outTriangles[(i + 1) % num_edges], 2);
  291. }
  292. #ifdef JPH_EPA_CONVEX_BUILDER_VALIDATE
  293. // Check if structure is intact
  294. ValidateTriangles();
  295. #endif
  296. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  297. // Draw state of the hull
  298. DrawState();
  299. // Increment iteration counter
  300. ++mIteration;
  301. #endif
  302. return true;
  303. }
  304. /// Free a triangle
  305. void FreeTriangle(Triangle *inT)
  306. {
  307. #ifdef JPH_ENABLE_ASSERTS
  308. // Make sure that this triangle is not connected
  309. JPH_ASSERT(inT->mRemoved);
  310. for (const Edge &e : inT->mEdge)
  311. JPH_ASSERT(e.mNeighbourTriangle == nullptr);
  312. #endif
  313. #if defined(JPH_EPA_CONVEX_BUILDER_VALIDATE) || defined(JPH_EPA_CONVEX_BUILDER_DRAW)
  314. // Remove from list of all triangles
  315. Triangles::iterator i = std::find(mTriangles.begin(), mTriangles.end(), inT);
  316. JPH_ASSERT(i != mTriangles.end());
  317. mTriangles.erase(i);
  318. #endif
  319. mFactory.FreeTriangle(inT);
  320. }
  321. private:
  322. /// Create a new triangle
  323. Triangle * CreateTriangle(int inIdx1, int inIdx2, int inIdx3)
  324. {
  325. // Call provider to create triangle
  326. Triangle *t = mFactory.CreateTriangle(inIdx1, inIdx2, inIdx3, mPositions.data());
  327. if (t == nullptr)
  328. return nullptr;
  329. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  330. // Remember iteration counter
  331. t->mIteration = mIteration;
  332. #endif
  333. #if defined(JPH_EPA_CONVEX_BUILDER_VALIDATE) || defined(JPH_EPA_CONVEX_BUILDER_DRAW)
  334. // Add to list of triangles for debugging purposes
  335. mTriangles.push_back(t);
  336. #endif
  337. return t;
  338. }
  339. /// Link triangle edge to other triangle edge
  340. static void sLinkTriangle(Triangle *inT1, int inEdge1, Triangle *inT2, int inEdge2)
  341. {
  342. JPH_ASSERT(inEdge1 >= 0 && inEdge1 < 3);
  343. JPH_ASSERT(inEdge2 >= 0 && inEdge2 < 3);
  344. Edge &e1 = inT1->mEdge[inEdge1];
  345. Edge &e2 = inT2->mEdge[inEdge2];
  346. // Check not connected yet
  347. JPH_ASSERT(e1.mNeighbourTriangle == nullptr);
  348. JPH_ASSERT(e2.mNeighbourTriangle == nullptr);
  349. // Check vertices match
  350. JPH_ASSERT(e1.mStartIdx == inT2->GetNextEdge(inEdge2).mStartIdx);
  351. JPH_ASSERT(e2.mStartIdx == inT1->GetNextEdge(inEdge1).mStartIdx);
  352. // Link up
  353. e1.mNeighbourTriangle = inT2;
  354. e1.mNeighbourEdge = inEdge2;
  355. e2.mNeighbourTriangle = inT1;
  356. e2.mNeighbourEdge = inEdge1;
  357. }
  358. /// Unlink this triangle
  359. void UnlinkTriangle(Triangle *inT)
  360. {
  361. // Unlink from neighbours
  362. for (int i = 0; i < 3; ++i)
  363. {
  364. Edge &edge = inT->mEdge[i];
  365. if (edge.mNeighbourTriangle != nullptr)
  366. {
  367. Edge &neighbour_edge = edge.mNeighbourTriangle->mEdge[edge.mNeighbourEdge];
  368. // Validate that neighbour points to us
  369. JPH_ASSERT(neighbour_edge.mNeighbourTriangle == inT);
  370. JPH_ASSERT(neighbour_edge.mNeighbourEdge == i);
  371. // Unlink
  372. neighbour_edge.mNeighbourTriangle = nullptr;
  373. edge.mNeighbourTriangle = nullptr;
  374. }
  375. }
  376. // If this triangle is not in the priority queue, we can delete it now
  377. if (!inT->mInQueue)
  378. FreeTriangle(inT);
  379. }
  380. /// Given one triangle that faces inVertex, find the edges of the triangles that are not facing inVertex.
  381. /// Will flag all those triangles for removal.
  382. bool FindEdge(Triangle *inFacingTriangle, Vec3Arg inVertex, Edges &outEdges)
  383. {
  384. // Assert that we were given an empty array
  385. JPH_ASSERT(outEdges.empty());
  386. // Should start with a facing triangle
  387. JPH_ASSERT(inFacingTriangle->IsFacing(inVertex));
  388. // Flag as removed
  389. inFacingTriangle->mRemoved = true;
  390. // Instead of recursing, we build our own stack with the information we need
  391. struct StackEntry
  392. {
  393. Triangle * mTriangle;
  394. int mEdge;
  395. int mIter;
  396. };
  397. StackEntry stack[cMaxEdgeLength];
  398. int cur_stack_pos = 0;
  399. // Start with the triangle / edge provided
  400. stack[0].mTriangle = inFacingTriangle;
  401. stack[0].mEdge = 0;
  402. stack[0].mIter = -1; // Start with edge 0 (is incremented below before use)
  403. // Next index that we expect to find, if we don't then there are 'islands'
  404. int next_expected_start_idx = -1;
  405. for (;;)
  406. {
  407. StackEntry &cur_entry = stack[cur_stack_pos];
  408. // Next iteration
  409. if (++cur_entry.mIter >= 3)
  410. {
  411. // This triangle needs to be removed, unlink it now
  412. UnlinkTriangle(cur_entry.mTriangle);
  413. // Pop from stack
  414. if (--cur_stack_pos < 0)
  415. break;
  416. }
  417. else
  418. {
  419. // Visit neighbour
  420. Edge &e = cur_entry.mTriangle->mEdge[(cur_entry.mEdge + cur_entry.mIter) % 3];
  421. Triangle *n = e.mNeighbourTriangle;
  422. if (n != nullptr && !n->mRemoved)
  423. {
  424. // Check if vertex is on the front side of this triangle
  425. if (n->IsFacing(inVertex))
  426. {
  427. // Vertex on front, this triangle needs to be removed
  428. n->mRemoved = true;
  429. // Add element to the stack of elements to visit
  430. cur_stack_pos++;
  431. JPH_ASSERT(cur_stack_pos < cMaxEdgeLength);
  432. StackEntry &new_entry = stack[cur_stack_pos];
  433. new_entry.mTriangle = n;
  434. new_entry.mEdge = e.mNeighbourEdge;
  435. new_entry.mIter = 0; // Is incremented before use, we don't need to test this edge again since we came from it
  436. }
  437. else
  438. {
  439. // Detect if edge doesn't connect to previous edge, if this happens we have found and 'island' which means
  440. // the newly added point is so close to the triangles of the hull that we classified some (nearly) coplanar
  441. // triangles as before and some behind the point. At this point we just abort adding the point because
  442. // we've reached numerical precision.
  443. // Note that we do not need to test if the first and last edge connect, since when there are islands
  444. // there should be at least 2 disconnects.
  445. if (e.mStartIdx != next_expected_start_idx && next_expected_start_idx != -1)
  446. return false;
  447. // Next expected index is the start index of our neighbour's edge
  448. next_expected_start_idx = n->mEdge[e.mNeighbourEdge].mStartIdx;
  449. // Vertex behind, keep edge
  450. outEdges.push_back(e);
  451. }
  452. }
  453. }
  454. }
  455. // Assert that we have a fully connected loop
  456. JPH_ASSERT(outEdges.empty() || outEdges[0].mStartIdx == next_expected_start_idx);
  457. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  458. // Draw edge of facing triangles
  459. for (int i = 0; i < (int)outEdges.size(); ++i)
  460. {
  461. RVec3 edge_start = cDrawScale * (mOffset + mPositions[outEdges[i].mStartIdx]);
  462. DebugRenderer::sInstance->DrawArrow(edge_start, cDrawScale * (mOffset + mPositions[outEdges[(i + 1) % outEdges.size()].mStartIdx]), Color::sYellow, 0.01f);
  463. DebugRenderer::sInstance->DrawText3D(edge_start, ConvertToString(outEdges[i].mStartIdx), Color::sWhite);
  464. }
  465. // Draw the state with the facing triangles removed
  466. DrawState();
  467. #endif
  468. // When we start with two triangles facing away from each other and adding a point that is on the plane,
  469. // sometimes we consider the point in front of both causing both triangles to be removed resulting in an empty edge list.
  470. // In this case we fail to add the point which will result in no collision reported (the shapes are contacting in 1 point so there's 0 penetration)
  471. return outEdges.size() >= 3;
  472. }
  473. #ifdef JPH_EPA_CONVEX_BUILDER_VALIDATE
  474. /// Check consistency of 1 triangle
  475. void ValidateTriangle(const Triangle *inT) const
  476. {
  477. if (inT->mRemoved)
  478. {
  479. // Valdiate that removed triangles are not connected to anything
  480. for (const Edge &my_edge : inT->mEdge)
  481. JPH_ASSERT(my_edge.mNeighbourTriangle == nullptr);
  482. }
  483. else
  484. {
  485. for (int i = 0; i < 3; ++i)
  486. {
  487. const Edge &my_edge = inT->mEdge[i];
  488. // Assert that we have a neighbour
  489. const Triangle *nb = my_edge.mNeighbourTriangle;
  490. JPH_ASSERT(nb != nullptr);
  491. if (nb != nullptr)
  492. {
  493. // Assert that our neighbours edge points to us
  494. const Edge &nb_edge = nb->mEdge[my_edge.mNeighbourEdge];
  495. JPH_ASSERT(nb_edge.mNeighbourTriangle == inT);
  496. JPH_ASSERT(nb_edge.mNeighbourEdge == i);
  497. // Assert that the next edge of the neighbour points to the same vertex as this edge's vertex
  498. const Edge &nb_next_edge = nb->GetNextEdge(my_edge.mNeighbourEdge);
  499. JPH_ASSERT(nb_next_edge.mStartIdx == my_edge.mStartIdx);
  500. // Assert that my next edge points to the same vertex as my neighbours vertex
  501. const Edge &my_next_edge = inT->GetNextEdge(i);
  502. JPH_ASSERT(my_next_edge.mStartIdx == nb_edge.mStartIdx);
  503. }
  504. }
  505. }
  506. }
  507. /// Check consistency of all triangles
  508. void ValidateTriangles() const
  509. {
  510. for (const Triangle *t : mTriangles)
  511. ValidateTriangle(t);
  512. }
  513. #endif
  514. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  515. public:
  516. /// Draw state of algorithm
  517. void DrawState()
  518. {
  519. // Draw origin
  520. DebugRenderer::sInstance->DrawCoordinateSystem(RMat44::sTranslation(cDrawScale * mOffset), 1.0f);
  521. // Draw triangles
  522. for (const Triangle *t : mTriangles)
  523. if (!t->mRemoved)
  524. {
  525. // Calculate the triangle vertices
  526. RVec3 p1 = cDrawScale * (mOffset + mPositions[t->mEdge[0].mStartIdx]);
  527. RVec3 p2 = cDrawScale * (mOffset + mPositions[t->mEdge[1].mStartIdx]);
  528. RVec3 p3 = cDrawScale * (mOffset + mPositions[t->mEdge[2].mStartIdx]);
  529. // Draw triangle
  530. DebugRenderer::sInstance->DrawTriangle(p1, p2, p3, Color::sGetDistinctColor(t->mIteration));
  531. DebugRenderer::sInstance->DrawWireTriangle(p1, p2, p3, Color::sGrey);
  532. // Draw normal
  533. RVec3 centroid = cDrawScale * (mOffset + t->mCentroid);
  534. float len = t->mNormal.Length();
  535. if (len > 0.0f)
  536. DebugRenderer::sInstance->DrawArrow(centroid, centroid + t->mNormal / len, Color::sDarkGreen, 0.01f);
  537. }
  538. // Determine max position
  539. float min_x = FLT_MAX;
  540. float max_x = -FLT_MAX;
  541. for (Vec3 p : mPositions)
  542. {
  543. min_x = min(min_x, p.GetX());
  544. max_x = max(max_x, p.GetX());
  545. }
  546. // Offset to the right
  547. mOffset += Vec3(max_x - min_x + 0.5f, 0.0f, 0.0f);
  548. }
  549. /// Draw a label to indicate the next stage in the algorithm
  550. void DrawLabel(const string_view &inText)
  551. {
  552. DebugRenderer::sInstance->DrawText3D(cDrawScale * mOffset, inText, Color::sWhite, 0.1f * cDrawScale);
  553. mOffset += Vec3(5.0f, 0.0f, 0.0f);
  554. }
  555. /// Draw geometry for debugging purposes
  556. void DrawGeometry(const DebugRenderer::GeometryRef &inGeometry, ColorArg inColor)
  557. {
  558. RMat44 origin = RMat44::sScale(Vec3::sReplicate(cDrawScale)) * RMat44::sTranslation(mOffset);
  559. DebugRenderer::sInstance->DrawGeometry(origin, inGeometry->mBounds.Transformed(origin), inGeometry->mBounds.GetExtent().LengthSq(), inColor, inGeometry);
  560. mOffset += Vec3(inGeometry->mBounds.GetSize().GetX(), 0, 0);
  561. }
  562. /// Draw a triangle for debugging purposes
  563. void DrawWireTriangle(const Triangle &inTriangle, ColorArg inColor)
  564. {
  565. RVec3 prev = cDrawScale * (mOffset + mPositions[inTriangle.mEdge[2].mStartIdx]);
  566. for (const Edge &edge : inTriangle.mEdge)
  567. {
  568. RVec3 cur = cDrawScale * (mOffset + mPositions[edge.mStartIdx]);
  569. DebugRenderer::sInstance->DrawArrow(prev, cur, inColor, 0.01f);
  570. prev = cur;
  571. }
  572. }
  573. /// Draw a marker for debugging purposes
  574. void DrawMarker(Vec3Arg inPosition, ColorArg inColor, float inSize)
  575. {
  576. DebugRenderer::sInstance->DrawMarker(cDrawScale * (mOffset + inPosition), inColor, inSize);
  577. }
  578. /// Draw an arrow for debugging purposes
  579. void DrawArrow(Vec3Arg inFrom, Vec3Arg inTo, ColorArg inColor, float inArrowSize)
  580. {
  581. DebugRenderer::sInstance->DrawArrow(cDrawScale * (mOffset + inFrom), cDrawScale * (mOffset + inTo), inColor, inArrowSize);
  582. }
  583. #endif
  584. private:
  585. TriangleFactory mFactory; ///< Factory to create new triangles and remove old ones
  586. const Points & mPositions; ///< List of positions (some of them are part of the hull)
  587. TriangleQueue mTriangleQueue; ///< List of triangles that are part of the hull that still need to be checked (if !mRemoved)
  588. #if defined(JPH_EPA_CONVEX_BUILDER_VALIDATE) || defined(JPH_EPA_CONVEX_BUILDER_DRAW)
  589. Triangles mTriangles; ///< The list of all triangles in this hull (for debug purposes)
  590. #endif
  591. #ifdef JPH_EPA_CONVEX_BUILDER_DRAW
  592. int mIteration; ///< Number of iterations we've had so far (for debug purposes)
  593. RVec3 mOffset; ///< Offset to use for state drawing
  594. #endif
  595. };
  596. // The determinant that is calculated in the Triangle constructor is really sensitive
  597. // to numerical round off, disable the fmadd instructions to maintain precision.
  598. JPH_PRECISE_MATH_ON
  599. EPAConvexHullBuilder::Triangle::Triangle(int inIdx0, int inIdx1, int inIdx2, const Vec3 *inPositions)
  600. {
  601. // Fill in indexes
  602. JPH_ASSERT(inIdx0 != inIdx1 && inIdx0 != inIdx2 && inIdx1 != inIdx2);
  603. mEdge[0].mStartIdx = inIdx0;
  604. mEdge[1].mStartIdx = inIdx1;
  605. mEdge[2].mStartIdx = inIdx2;
  606. // Clear links
  607. mEdge[0].mNeighbourTriangle = nullptr;
  608. mEdge[1].mNeighbourTriangle = nullptr;
  609. mEdge[2].mNeighbourTriangle = nullptr;
  610. // Get vertex positions
  611. Vec3 y0 = inPositions[inIdx0];
  612. Vec3 y1 = inPositions[inIdx1];
  613. Vec3 y2 = inPositions[inIdx2];
  614. // Calculate centroid
  615. mCentroid = (y0 + y1 + y2) / 3.0f;
  616. // Calculate edges
  617. Vec3 y10 = y1 - y0;
  618. Vec3 y20 = y2 - y0;
  619. Vec3 y21 = y2 - y1;
  620. // The most accurate normal is calculated by using the two shortest edges
  621. // See: https://box2d.org/posts/2014/01/troublesome-triangle/
  622. // 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).
  623. // Therefore we can suffice by just picking the shortest from 2 edges and use that with the 3rd edge to calculate the normal.
  624. // We first check which of the edges is shorter.
  625. float y20_dot_y20 = y20.Dot(y20);
  626. float y21_dot_y21 = y21.Dot(y21);
  627. if (y20_dot_y20 < y21_dot_y21)
  628. {
  629. // We select the edges y10 and y20
  630. mNormal = y10.Cross(y20);
  631. // Check if triangle is degenerate
  632. float normal_len_sq = mNormal.LengthSq();
  633. if (normal_len_sq > cMinTriangleArea)
  634. {
  635. // Determine distance between triangle and origin: distance = (centroid - origin) . normal / |normal|
  636. // Note that this way of calculating the closest point is much more accurate than first calculating barycentric coordinates and then calculating the closest
  637. // point based on those coordinates. Note that we preserve the sign of the distance to check on which side the origin is.
  638. float c_dot_n = mCentroid.Dot(mNormal);
  639. mClosestLenSq = abs(c_dot_n) * c_dot_n / normal_len_sq;
  640. // Calculate closest point to origin using barycentric coordinates:
  641. //
  642. // v = y0 + l0 * (y1 - y0) + l1 * (y2 - y0)
  643. // v . (y1 - y0) = 0
  644. // v . (y2 - y0) = 0
  645. //
  646. // Written in matrix form:
  647. //
  648. // | y10.y10 y20.y10 | | l0 | = | -y0.y10 |
  649. // | y10.y20 y20.y20 | | l1 | | -y0.y20 |
  650. //
  651. // (y10 = y1 - y0 etc.)
  652. //
  653. // Cramers rule to invert matrix:
  654. float y10_dot_y10 = y10.LengthSq();
  655. float y10_dot_y20 = y10.Dot(y20);
  656. float determinant = y10_dot_y10 * y20_dot_y20 - y10_dot_y20 * y10_dot_y20;
  657. if (determinant > 0.0f) // If determinant == 0 then the system is linearly dependent and the triangle is degenerate, since y10.10 * y20.y20 > y10.y20^2 it should also be > 0
  658. {
  659. float y0_dot_y10 = y0.Dot(y10);
  660. float y0_dot_y20 = y0.Dot(y20);
  661. float l0 = (y10_dot_y20 * y0_dot_y20 - y20_dot_y20 * y0_dot_y10) / determinant;
  662. float l1 = (y10_dot_y20 * y0_dot_y10 - y10_dot_y10 * y0_dot_y20) / determinant;
  663. mLambda[0] = l0;
  664. mLambda[1] = l1;
  665. mLambdaRelativeTo0 = true;
  666. // Check if closest point is interior to the triangle. For a convex hull which contains the origin each face must contain the origin, but because
  667. // our faces are triangles, we can have multiple coplanar triangles and only 1 will have the origin as an interior point. We want to use this triangle
  668. // to calculate the contact points because it gives the most accurate results, so we will only add these triangles to the priority queue.
  669. if (l0 > -cBarycentricEpsilon && l1 > -cBarycentricEpsilon && l0 + l1 < 1.0f + cBarycentricEpsilon)
  670. mClosestPointInterior = true;
  671. }
  672. }
  673. }
  674. else
  675. {
  676. // We select the edges y10 and y21
  677. mNormal = y10.Cross(y21);
  678. // Check if triangle is degenerate
  679. float normal_len_sq = mNormal.LengthSq();
  680. if (normal_len_sq > cMinTriangleArea)
  681. {
  682. // Again calculate distance between triangle and origin
  683. float c_dot_n = mCentroid.Dot(mNormal);
  684. mClosestLenSq = abs(c_dot_n) * c_dot_n / normal_len_sq;
  685. // Calculate closest point to origin using barycentric coordinates but this time using y1 as the reference vertex
  686. //
  687. // v = y1 + l0 * (y0 - y1) + l1 * (y2 - y1)
  688. // v . (y0 - y1) = 0
  689. // v . (y2 - y1) = 0
  690. //
  691. // Written in matrix form:
  692. //
  693. // | y10.y10 -y21.y10 | | l0 | = | y1.y10 |
  694. // | -y10.y21 y21.y21 | | l1 | | -y1.y21 |
  695. //
  696. // Cramers rule to invert matrix:
  697. float y10_dot_y10 = y10.LengthSq();
  698. float y10_dot_y21 = y10.Dot(y21);
  699. float determinant = y10_dot_y10 * y21_dot_y21 - y10_dot_y21 * y10_dot_y21;
  700. if (determinant > 0.0f)
  701. {
  702. float y1_dot_y10 = y1.Dot(y10);
  703. float y1_dot_y21 = y1.Dot(y21);
  704. float l0 = (y21_dot_y21 * y1_dot_y10 - y10_dot_y21 * y1_dot_y21) / determinant;
  705. float l1 = (y10_dot_y21 * y1_dot_y10 - y10_dot_y10 * y1_dot_y21) / determinant;
  706. mLambda[0] = l0;
  707. mLambda[1] = l1;
  708. mLambdaRelativeTo0 = false;
  709. // Again check if the closest point is inside the triangle
  710. if (l0 > -cBarycentricEpsilon && l1 > -cBarycentricEpsilon && l0 + l1 < 1.0f + cBarycentricEpsilon)
  711. mClosestPointInterior = true;
  712. }
  713. }
  714. }
  715. }
  716. JPH_PRECISE_MATH_OFF
  717. JPH_NAMESPACE_END