ConvexHullBuilder.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. //#define JPH_CONVEX_BUILDER_DEBUG
  5. //#define JPH_CONVEX_BUILDER_DUMP_SHAPE
  6. #ifdef JPH_CONVEX_BUILDER_DEBUG
  7. #include <Jolt/Core/Color.h>
  8. #endif
  9. #include <Jolt/Core/StaticArray.h>
  10. #include <Jolt/Core/NonCopyable.h>
  11. JPH_NAMESPACE_BEGIN
  12. /// A convex hull builder that tries to create hulls as accurately as possible. Used for offline processing.
  13. class ConvexHullBuilder : public NonCopyable
  14. {
  15. public:
  16. // Forward declare
  17. class Face;
  18. /// Class that holds the information of an edge
  19. class Edge : public NonCopyable
  20. {
  21. public:
  22. JPH_OVERRIDE_NEW_DELETE
  23. /// Constructor
  24. Edge(Face *inFace, int inStartIdx) : mFace(inFace), mStartIdx(inStartIdx) { }
  25. /// Get the previous edge
  26. inline Edge * GetPreviousEdge()
  27. {
  28. Edge *prev_edge = this;
  29. while (prev_edge->mNextEdge != this)
  30. prev_edge = prev_edge->mNextEdge;
  31. return prev_edge;
  32. }
  33. Face * mFace; ///< Face that this edge belongs to
  34. Edge * mNextEdge = nullptr; ///< Next edge of this face
  35. Edge * mNeighbourEdge = nullptr; ///< Edge that this edge is connected to
  36. int mStartIdx; ///< Vertex index in mPositions that indicates the start vertex of this edge
  37. };
  38. using ConflictList = Array<int>;
  39. /// Class that holds the information of one face
  40. class Face : public NonCopyable
  41. {
  42. public:
  43. JPH_OVERRIDE_NEW_DELETE
  44. /// Destructor
  45. ~Face();
  46. /// Initialize a face with three indices
  47. void Initialize(int inIdx0, int inIdx1, int inIdx2, const Vec3 *inPositions);
  48. /// Calculates the centroid and normal for this face
  49. void CalculateNormalAndCentroid(const Vec3 *inPositions);
  50. /// Check if face inFace is facing inPosition
  51. inline bool IsFacing(Vec3Arg inPosition) const
  52. {
  53. JPH_ASSERT(!mRemoved);
  54. return mNormal.Dot(inPosition - mCentroid) > 0.0f;
  55. }
  56. Vec3 mNormal; ///< Normal of this face, length is 2 times area of face
  57. Vec3 mCentroid; ///< Center of the face
  58. ConflictList mConflictList; ///< Positions associated with this edge (that are closest to this edge). The last position in the list is the point that is furthest away from the face.
  59. Edge * mFirstEdge = nullptr; ///< First edge of this face
  60. float mFurthestPointDistanceSq = 0.0f; ///< Squared distance of furtest point from the conflict list to the face
  61. bool mRemoved = false; ///< Flag that indicates that face has been removed (face will be freed later)
  62. #ifdef JPH_CONVEX_BUILDER_DEBUG
  63. int mIteration; ///< Iteration that this face was created
  64. #endif
  65. };
  66. // Typedefs
  67. using Positions = Array<Vec3>;
  68. using Faces = Array<Face *>;
  69. /// Constructor
  70. explicit ConvexHullBuilder(const Positions &inPositions);
  71. /// Destructor
  72. ~ConvexHullBuilder() { FreeFaces(); }
  73. /// Result enum that indicates how the hull got created
  74. enum class EResult
  75. {
  76. Success, ///< Hull building finished successfully
  77. MaxVerticesReached, ///< Hull building finished successfully, but the desired accuracy was not reached because the max vertices limit was reached
  78. TooFewPoints, ///< Too few points to create a hull
  79. TooFewFaces, ///< Too few faces in the created hull (signifies precision errors during building)
  80. Degenerate, ///< Degenerate hull detected
  81. };
  82. /// Takes all positions as provided by the constructor and use them to build a hull
  83. /// Any points that are closer to the hull than inTolerance will be discarded
  84. /// @param inMaxVertices Max vertices to allow in the hull. Specify INT_MAX if there is no limit.
  85. /// @param inTolerance Max distance that a point is allowed to be outside of the hull
  86. /// @param outError Error message when building fails
  87. /// @return Status code that reports if the hull was created or not
  88. EResult Initialize(int inMaxVertices, float inTolerance, const char *&outError);
  89. /// Returns the amount of vertices that are currently used by the hull
  90. int GetNumVerticesUsed() const;
  91. /// Returns true if the hull contains a polygon with inIndices (counter clockwise indices in mPositions)
  92. bool ContainsFace(const Array<int> &inIndices) const;
  93. /// Calculate the center of mass and the volume of the current convex hull
  94. void GetCenterOfMassAndVolume(Vec3 &outCenterOfMass, float &outVolume) const;
  95. /// Determines the point that is furthest outside of the hull and reports how far it is outside of the hull (which indicates a failure during hull building)
  96. /// @param outFaceWithMaxError The face that caused the error
  97. /// @param outMaxError The maximum distance of a point to the hull
  98. /// @param outMaxErrorPositionIdx The index of the point that had this distance
  99. /// @param outCoplanarDistance Points that are less than this distance from the hull are considered on the hull. This should be used as a lowerbound for the allowed error.
  100. void DetermineMaxError(Face *&outFaceWithMaxError, float &outMaxError, int &outMaxErrorPositionIdx, float &outCoplanarDistance) const;
  101. /// Access to the created faces. Memory is owned by the convex hull builder.
  102. const Faces & GetFaces() const { return mFaces; }
  103. private:
  104. /// Minimal square area of a triangle (used for merging and checking if a triangle is degenerate)
  105. static constexpr float cMinTriangleAreaSq = 1.0e-12f;
  106. #ifdef JPH_CONVEX_BUILDER_DEBUG
  107. /// Factor to scale convex hull when debug drawing the construction process
  108. static constexpr float cDrawScale = 10.0f;
  109. #endif
  110. /// Class that holds an edge including start and end index
  111. class FullEdge
  112. {
  113. public:
  114. Edge * mNeighbourEdge; ///< Edge that this edge is connected to
  115. int mStartIdx; ///< Vertex index in mPositions that indicates the start vertex of this edge
  116. int mEndIdx; ///< Vertex index in mPosition that indicats the end vertex of this edge
  117. };
  118. // Private typedefs
  119. using FullEdges = Array<FullEdge>;
  120. // Determine a suitable tolerance for detecting that points are coplanar
  121. float DetermineCoplanarDistance() const;
  122. /// Find the face for which inPoint is furthest to the front
  123. /// @param inPoint Point to test
  124. /// @param inFaces List of faces to test
  125. /// @param outFace Returns the best face
  126. /// @param outDistSq Returns the squared distance how much inPoint is in front of the plane of the face
  127. void GetFaceForPoint(Vec3Arg inPoint, const Faces &inFaces, Face *&outFace, float &outDistSq) const;
  128. /// @brief Calculates the distance between inPoint and inFace
  129. /// @param inFace Face to test
  130. /// @param inPoint Point to test
  131. /// @return If the projection of the point on the plane is interior to the face 0, otherwise the squared distance to the closest edge
  132. float GetDistanceToEdgeSq(Vec3Arg inPoint, const Face *inFace) const;
  133. /// Assigns a position to one of the supplied faces based on which face is closest.
  134. /// @param inPositionIdx Index of the position to add
  135. /// @param inFaces List of faces to consider
  136. /// @param inToleranceSq Tolerance of the hull, if the point is closer to the face than this, we ignore it
  137. /// @return True if point was assigned, false if it was discarded or added to the coplanar list
  138. bool AssignPointToFace(int inPositionIdx, const Faces &inFaces, float inToleranceSq);
  139. /// Add a new point to the convex hull
  140. void AddPoint(Face *inFacingFace, int inIdx, float inToleranceSq, Faces &outNewFaces);
  141. /// Remove all faces that have been marked 'removed' from mFaces list
  142. void GarbageCollectFaces();
  143. /// Create a new face
  144. Face * CreateFace();
  145. /// Create a new triangle
  146. Face * CreateTriangle(int inIdx1, int inIdx2, int inIdx3);
  147. /// Delete a face (checking that it is not connected to any other faces)
  148. void FreeFace(Face *inFace);
  149. /// Release all faces and edges
  150. void FreeFaces();
  151. /// Link face edge to other face edge
  152. static void sLinkFace(Edge *inEdge1, Edge *inEdge2);
  153. /// Unlink this face from all of its neighbours
  154. static void sUnlinkFace(Face *inFace);
  155. /// Given one face that faces inVertex, find the edges of the faces that are not facing inVertex.
  156. /// Will flag all those faces for removal.
  157. void FindEdge(Face *inFacingFace, Vec3Arg inVertex, FullEdges &outEdges) const;
  158. /// Merges the two faces that share inEdge into the face inEdge->mFace
  159. void MergeFaces(Edge *inEdge);
  160. /// Merges inFace with a neighbour if it is degenerate (a sliver)
  161. void MergeDegenerateFace(Face *inFace, Faces &ioAffectedFaces);
  162. /// Merges any coplanar as well as neighbours that form a non-convex edge into inFace.
  163. /// Faces are considered coplanar if the distance^2 of the other face's centroid is smaller than inToleranceSq.
  164. void MergeCoplanarOrConcaveFaces(Face *inFace, float inToleranceSq, Faces &ioAffectedFaces);
  165. /// Mark face as affected if it is not already in the list
  166. static void sMarkAffected(Face *inFace, Faces &ioAffectedFaces);
  167. /// Removes all invalid edges.
  168. /// 1. Merges inFace with faces that share two edges with it since this means inFace or the other face cannot be convex or the edge is colinear.
  169. /// 2. Removes edges that are interior to inFace (that have inFace on both sides)
  170. /// Any faces that need to be checked for validity will be added to ioAffectedFaces.
  171. void RemoveInvalidEdges(Face *inFace, Faces &ioAffectedFaces);
  172. /// Removes inFace if it consists of only 2 edges, linking its neighbouring faces together
  173. /// Any faces that need to be checked for validity will be added to ioAffectedFaces.
  174. /// @return True if face was removed.
  175. bool RemoveTwoEdgeFace(Face *inFace, Faces &ioAffectedFaces) const;
  176. #ifdef JPH_ENABLE_ASSERTS
  177. /// Dumps the text representation of a face to the TTY
  178. void DumpFace(const Face *inFace) const;
  179. /// Dumps the text representation of all faces to the TTY
  180. void DumpFaces() const;
  181. /// Check consistency of 1 face
  182. void ValidateFace(const Face *inFace) const;
  183. /// Check consistency of all faces
  184. void ValidateFaces() const;
  185. #endif
  186. #ifdef JPH_CONVEX_BUILDER_DEBUG
  187. /// Draw state of algorithm
  188. void DrawState(bool inDrawConflictList = false) const;
  189. /// Draw a face for debugging purposes
  190. void DrawWireFace(const Face *inFace, ColorArg inColor) const;
  191. /// Draw an edge for debugging purposes
  192. void DrawEdge(const Edge *inEdge, ColorArg inColor) const;
  193. #endif
  194. #ifdef JPH_CONVEX_BUILDER_DUMP_SHAPE
  195. void DumpShape() const;
  196. #endif
  197. const Positions & mPositions; ///< List of positions (some of them are part of the hull)
  198. Faces mFaces; ///< List of faces that are part of the hull (if !mRemoved)
  199. struct Coplanar
  200. {
  201. int mPositionIdx; ///< Index in mPositions
  202. float mDistanceSq; ///< Distance to the edge of closest face (should be > 0)
  203. };
  204. using CoplanarList = Array<Coplanar>;
  205. CoplanarList mCoplanarList; ///< List of positions that are coplanar to a face but outside of the face, these are added to the hull at the end
  206. #ifdef JPH_CONVEX_BUILDER_DEBUG
  207. int mIteration; ///< Number of iterations we've had so far (for debug purposes)
  208. mutable Vec3 mOffset; ///< Offset to use for state drawing
  209. Vec3 mDelta; ///< Delta offset between next states
  210. #endif
  211. };
  212. JPH_NAMESPACE_END