InternalEdgeRemovingCollector.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2024 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Core/QuickSort.h>
  6. #include <Jolt/Core/STLLocalAllocator.h>
  7. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  8. //#define JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  9. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  10. #include <Jolt/Renderer/DebugRenderer.h>
  11. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  12. JPH_NAMESPACE_BEGIN
  13. /// Removes internal edges from collision results. Can be used to filter out 'ghost collisions'.
  14. /// Based on: Contact generation for meshes - Pierre Terdiman (https://www.codercorner.com/MeshContacts.pdf)
  15. ///
  16. /// Note that this class requires that CollideSettingsBase::mActiveEdgeMode == EActiveEdgeMode::CollideWithAll
  17. /// and CollideSettingsBase::mCollectFacesMode == ECollectFacesMode::CollectFaces.
  18. class InternalEdgeRemovingCollector : public CollideShapeCollector
  19. {
  20. static constexpr uint cMaxLocalDelayedResults = 32;
  21. static constexpr uint cMaxLocalVoidedFeatures = 128;
  22. /// Check if a vertex is voided
  23. inline bool IsVoided(const SubShapeID &inSubShapeID, Vec3 inV) const
  24. {
  25. for (const Voided &vf : mVoidedFeatures)
  26. if (vf.mSubShapeID == inSubShapeID
  27. && inV.IsClose(Vec3::sLoadFloat3Unsafe(vf.mFeature), 1.0e-8f))
  28. return true;
  29. return false;
  30. }
  31. /// Add all vertices of a face to the voided features
  32. inline void VoidFeatures(const CollideShapeResult &inResult)
  33. {
  34. for (const Vec3 &v : inResult.mShape2Face)
  35. if (!IsVoided(inResult.mSubShapeID1, v))
  36. {
  37. Voided vf;
  38. v.StoreFloat3(&vf.mFeature);
  39. vf.mSubShapeID = inResult.mSubShapeID1;
  40. mVoidedFeatures.push_back(vf);
  41. }
  42. }
  43. /// Call the chained collector
  44. inline void Chain(const CollideShapeResult &inResult)
  45. {
  46. // Make sure the chained collector has the same context as we do
  47. mChainedCollector.SetContext(GetContext());
  48. // Forward the hit
  49. mChainedCollector.AddHit(inResult);
  50. // If our chained collector updated its early out fraction, we need to follow
  51. UpdateEarlyOutFraction(mChainedCollector.GetEarlyOutFraction());
  52. }
  53. /// Call the chained collector and void all features of inResult
  54. inline void ChainAndVoid(const CollideShapeResult &inResult)
  55. {
  56. Chain(inResult);
  57. VoidFeatures(inResult);
  58. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  59. DebugRenderer::sInstance->DrawWirePolygon(RMat44::sTranslation(mBaseOffset), inResult.mShape2Face, Color::sGreen);
  60. DebugRenderer::sInstance->DrawArrow(mBaseOffset + inResult.mContactPointOn2, mBaseOffset + inResult.mContactPointOn2 + inResult.mPenetrationAxis.NormalizedOr(Vec3::sZero()), Color::sGreen, 0.1f);
  61. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  62. }
  63. public:
  64. /// Constructor, configures a collector to be called with all the results that do not hit internal edges
  65. explicit InternalEdgeRemovingCollector(CollideShapeCollector &inChainedCollector
  66. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  67. , RVec3Arg inBaseOffset
  68. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  69. ) :
  70. CollideShapeCollector(inChainedCollector),
  71. mChainedCollector(inChainedCollector)
  72. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  73. , mBaseOffset(inBaseOffset)
  74. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  75. {
  76. // Initialize arrays to full capacity to avoid needless reallocation calls
  77. mVoidedFeatures.reserve(cMaxLocalVoidedFeatures);
  78. mDelayedResults.reserve(cMaxLocalDelayedResults);
  79. }
  80. // See: CollideShapeCollector::Reset
  81. virtual void Reset() override
  82. {
  83. CollideShapeCollector::Reset();
  84. mChainedCollector.Reset();
  85. mVoidedFeatures.clear();
  86. mDelayedResults.clear();
  87. }
  88. // See: CollideShapeCollector::OnBody
  89. virtual void OnBody(const Body &inBody) override
  90. {
  91. // Just forward the call to our chained collector
  92. mChainedCollector.OnBody(inBody);
  93. }
  94. // See: CollideShapeCollector::AddHit
  95. virtual void AddHit(const CollideShapeResult &inResult) override
  96. {
  97. // We only support welding when the shape is a triangle or has more vertices so that we can calculate a normal
  98. if (inResult.mShape2Face.size() < 3)
  99. return ChainAndVoid(inResult);
  100. // Get the triangle normal of shape 2 face
  101. Vec3 triangle_normal = (inResult.mShape2Face[1] - inResult.mShape2Face[0]).Cross(inResult.mShape2Face[2] - inResult.mShape2Face[0]);
  102. float triangle_normal_len = triangle_normal.Length();
  103. if (triangle_normal_len < 1e-6f)
  104. return ChainAndVoid(inResult);
  105. // If the triangle normal matches the contact normal within 1 degree, we can process the contact immediately
  106. // We make the assumption here that if the contact normal and the triangle normal align that the we're dealing with a 'face contact'
  107. Vec3 contact_normal = -inResult.mPenetrationAxis;
  108. float contact_normal_len = inResult.mPenetrationAxis.Length();
  109. if (triangle_normal.Dot(contact_normal) > 0.999848f * contact_normal_len * triangle_normal_len) // cos(1 degree)
  110. return ChainAndVoid(inResult);
  111. // Delayed processing
  112. mDelayedResults.push_back(inResult);
  113. }
  114. /// After all hits have been added, call this function to process the delayed results
  115. void Flush()
  116. {
  117. // Sort on biggest penetration depth first
  118. Array<uint, STLLocalAllocator<uint, cMaxLocalDelayedResults>> sorted_indices;
  119. sorted_indices.resize(mDelayedResults.size());
  120. for (uint i = 0; i < uint(mDelayedResults.size()); ++i)
  121. sorted_indices[i] = i;
  122. QuickSort(sorted_indices.begin(), sorted_indices.end(), [this](uint inLHS, uint inRHS) { return mDelayedResults[inLHS].mPenetrationDepth > mDelayedResults[inRHS].mPenetrationDepth; });
  123. // Loop over all results
  124. for (uint i = 0; i < uint(mDelayedResults.size()); ++i)
  125. {
  126. const CollideShapeResult &r = mDelayedResults[sorted_indices[i]];
  127. // Determine which vertex or which edge is the closest to the contact point
  128. float best_dist_sq = FLT_MAX;
  129. uint best_v1_idx = 0;
  130. uint best_v2_idx = 0;
  131. uint num_v = uint(r.mShape2Face.size());
  132. uint v1_idx = num_v - 1;
  133. Vec3 v1 = r.mShape2Face[v1_idx] - r.mContactPointOn2;
  134. for (uint v2_idx = 0; v2_idx < num_v; ++v2_idx)
  135. {
  136. Vec3 v2 = r.mShape2Face[v2_idx] - r.mContactPointOn2;
  137. Vec3 v1_v2 = v2 - v1;
  138. float denominator = v1_v2.LengthSq();
  139. if (denominator < Square(FLT_EPSILON))
  140. {
  141. // Degenerate, assume v1 is closest, v2 will be tested in a later iteration
  142. float v1_len_sq = v1.LengthSq();
  143. if (v1_len_sq < best_dist_sq)
  144. {
  145. best_dist_sq = v1_len_sq;
  146. best_v1_idx = v1_idx;
  147. best_v2_idx = v1_idx;
  148. }
  149. }
  150. else
  151. {
  152. // Taken from ClosestPoint::GetBaryCentricCoordinates
  153. float fraction = -v1.Dot(v1_v2) / denominator;
  154. if (fraction < 1.0e-6f)
  155. {
  156. // Closest lies on v1
  157. float v1_len_sq = v1.LengthSq();
  158. if (v1_len_sq < best_dist_sq)
  159. {
  160. best_dist_sq = v1_len_sq;
  161. best_v1_idx = v1_idx;
  162. best_v2_idx = v1_idx;
  163. }
  164. }
  165. else if (fraction < 1.0f - 1.0e-6f)
  166. {
  167. // Closest lies on the line segment v1, v2
  168. Vec3 closest = v1 + fraction * v1_v2;
  169. float closest_len_sq = closest.LengthSq();
  170. if (closest_len_sq < best_dist_sq)
  171. {
  172. best_dist_sq = closest_len_sq;
  173. best_v1_idx = v1_idx;
  174. best_v2_idx = v2_idx;
  175. }
  176. }
  177. // else closest is v2, but v2 will be tested in a later iteration
  178. }
  179. v1_idx = v2_idx;
  180. v1 = v2;
  181. }
  182. // Check if this vertex/edge is voided
  183. bool voided = IsVoided(r.mSubShapeID1, r.mShape2Face[best_v1_idx])
  184. && (best_v1_idx == best_v2_idx || IsVoided(r.mSubShapeID1, r.mShape2Face[best_v2_idx]));
  185. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  186. Color color = voided? Color::sRed : Color::sYellow;
  187. DebugRenderer::sInstance->DrawText3D(mBaseOffset + r.mContactPointOn2, StringFormat("%d: %g", i, r.mPenetrationDepth), color, 0.1f);
  188. DebugRenderer::sInstance->DrawWirePolygon(RMat44::sTranslation(mBaseOffset), r.mShape2Face, color);
  189. DebugRenderer::sInstance->DrawArrow(mBaseOffset + r.mContactPointOn2, mBaseOffset + r.mContactPointOn2 + r.mPenetrationAxis.NormalizedOr(Vec3::sZero()), color, 0.1f);
  190. DebugRenderer::sInstance->DrawMarker(mBaseOffset + r.mShape2Face[best_v1_idx], IsVoided(r.mSubShapeID1, r.mShape2Face[best_v1_idx])? Color::sRed : Color::sYellow, 0.1f);
  191. DebugRenderer::sInstance->DrawMarker(mBaseOffset + r.mShape2Face[best_v2_idx], IsVoided(r.mSubShapeID1, r.mShape2Face[best_v2_idx])? Color::sRed : Color::sYellow, 0.1f);
  192. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  193. // No voided features, accept the contact
  194. if (!voided)
  195. Chain(r);
  196. // Void the features of this face
  197. VoidFeatures(r);
  198. }
  199. // All delayed results have been processed
  200. mVoidedFeatures.clear();
  201. mDelayedResults.clear();
  202. }
  203. // See: CollideShapeCollector::OnBodyEnd
  204. virtual void OnBodyEnd() override
  205. {
  206. Flush();
  207. mChainedCollector.OnBodyEnd();
  208. }
  209. /// Version of CollisionDispatch::sCollideShapeVsShape that removes internal edges
  210. static void sCollideShapeVsShape(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter = { }
  211. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  212. , RVec3Arg inBaseOffset = RVec3::sZero()
  213. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  214. )
  215. {
  216. JPH_ASSERT(inCollideShapeSettings.mActiveEdgeMode == EActiveEdgeMode::CollideWithAll); // Won't work without colliding with all edges
  217. JPH_ASSERT(inCollideShapeSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces); // Won't work without collecting faces
  218. InternalEdgeRemovingCollector wrapper(ioCollector
  219. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  220. , inBaseOffset
  221. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  222. );
  223. CollisionDispatch::sCollideShapeVsShape(inShape1, inShape2, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, inCollideShapeSettings, wrapper, inShapeFilter);
  224. wrapper.Flush();
  225. }
  226. private:
  227. // This algorithm tests a convex shape (shape 1) against a set of polygons (shape 2).
  228. // This assumption doesn't hold if the shape we're testing is a compound shape, so we must also
  229. // store the sub shape ID and ignore voided features that belong to another sub shape ID.
  230. struct Voided
  231. {
  232. Float3 mFeature; // Feature that is voided (of shape 2). Read with Vec3::sLoadFloat3Unsafe so must not be the last member.
  233. SubShapeID mSubShapeID; // Sub shape ID of the shape that is colliding against the feature (of shape 1).
  234. };
  235. CollideShapeCollector & mChainedCollector;
  236. Array<Voided, STLLocalAllocator<Voided, cMaxLocalVoidedFeatures>> mVoidedFeatures;
  237. Array<CollideShapeResult, STLLocalAllocator<CollideShapeResult, cMaxLocalDelayedResults>> mDelayedResults;
  238. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  239. RVec3 mBaseOffset; // Base offset for the query, used to draw the results in the right place
  240. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  241. };
  242. JPH_NAMESPACE_END