InternalEdgeRemovingCollector.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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/Physics/Collision/CollisionDispatch.h>
  7. //#define JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  8. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  9. #include <Jolt/Renderer/DebugRenderer.h>
  10. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  11. JPH_NAMESPACE_BEGIN
  12. /// Removes internal edges from collision results. Can be used to filter out 'ghost collisions'.
  13. /// Based on: Contact generation for meshes - Pierre Terdiman (https://www.codercorner.com/MeshContacts.pdf)
  14. class InternalEdgeRemovingCollector : public CollideShapeCollector
  15. {
  16. static constexpr uint cMaxDelayedResults = 16;
  17. static constexpr uint cMaxVoidedFeatures = 128;
  18. /// Check if a vertex is voided
  19. inline bool IsVoided(Vec3 inV) const
  20. {
  21. for (const Float3 &vf : mVoidedFeatures)
  22. if (inV.IsClose(Vec3::sLoadFloat3Unsafe(vf), 1.0e-8f))
  23. return true;
  24. return false;
  25. }
  26. /// Add all vertices of a face to the voided features
  27. inline void VoidFeatures(const CollideShapeResult &inResult)
  28. {
  29. for (const Vec3 &v : inResult.mShape2Face)
  30. if (!IsVoided(v))
  31. {
  32. if (mVoidedFeatures.size() == cMaxVoidedFeatures)
  33. break;
  34. Float3 f;
  35. v.StoreFloat3(&f);
  36. mVoidedFeatures.push_back(f);
  37. }
  38. }
  39. /// Call the chained collector
  40. inline void Chain(const CollideShapeResult &inResult)
  41. {
  42. // Make sure the chained collector has the same context as we do
  43. mChainedCollector.SetContext(GetContext());
  44. // Forward the hit
  45. mChainedCollector.AddHit(inResult);
  46. // If our chained collector updated its early out fraction, we need to follow
  47. UpdateEarlyOutFraction(mChainedCollector.GetEarlyOutFraction());
  48. }
  49. /// Call the chained collector and void all features of inResult
  50. inline void ChainAndVoid(const CollideShapeResult &inResult)
  51. {
  52. Chain(inResult);
  53. VoidFeatures(inResult);
  54. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  55. DebugRenderer::sInstance->DrawWirePolygon(RMat44::sIdentity(), inResult.mShape2Face, Color::sGreen);
  56. DebugRenderer::sInstance->DrawArrow(RVec3(inResult.mContactPointOn2), RVec3(inResult.mContactPointOn2) + inResult.mPenetrationAxis.NormalizedOr(Vec3::sZero()), Color::sGreen, 0.1f);
  57. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  58. }
  59. public:
  60. /// Constructor, configures a collector to be called with all the results that do not hit internal edges
  61. explicit InternalEdgeRemovingCollector(CollideShapeCollector &inChainedCollector) :
  62. mChainedCollector(inChainedCollector)
  63. {
  64. }
  65. // See: CollideShapeCollector::Reset
  66. virtual void Reset() override
  67. {
  68. CollideShapeCollector::Reset();
  69. mChainedCollector.Reset();
  70. mVoidedFeatures.clear();
  71. mDelayedResults.clear();
  72. }
  73. // See: CollideShapeCollector::OnBody
  74. virtual void OnBody(const Body &inBody) override
  75. {
  76. // Just forward the call to our chained collector
  77. mChainedCollector.OnBody(inBody);
  78. }
  79. // See: CollideShapeCollector::AddHit
  80. virtual void AddHit(const CollideShapeResult &inResult) override
  81. {
  82. // We only support welding when the shape is a triangle or has more vertices so that we can calculate a normal
  83. if (inResult.mShape2Face.size() < 3)
  84. return ChainAndVoid(inResult);
  85. // Get the triangle normal of shape 2 face
  86. Vec3 triangle_normal = (inResult.mShape2Face[1] - inResult.mShape2Face[0]).Cross(inResult.mShape2Face[2] - inResult.mShape2Face[0]);
  87. float triangle_normal_len = triangle_normal.Length();
  88. if (triangle_normal_len < 1e-6f)
  89. return ChainAndVoid(inResult);
  90. // If the triangle normal matches the contact normal within 1 degree, we can process the contact immediately
  91. // We make the assumption here that if the contact normal and the triangle normal align that the we're dealing with a 'face contact'
  92. Vec3 contact_normal = -inResult.mPenetrationAxis;
  93. float contact_normal_len = inResult.mPenetrationAxis.Length();
  94. if (triangle_normal.Dot(contact_normal) > 0.999848f * contact_normal_len * triangle_normal_len) // cos(1 degree)
  95. return ChainAndVoid(inResult);
  96. // Delayed processing
  97. if (mDelayedResults.size() == cMaxDelayedResults)
  98. return ChainAndVoid(inResult);
  99. mDelayedResults.push_back(inResult);
  100. }
  101. /// After all hits have been added, call this function to process the delayed results
  102. void Flush()
  103. {
  104. // Sort on biggest penetration depth first
  105. uint sorted_indices[cMaxDelayedResults];
  106. for (uint i = 0; i < uint(mDelayedResults.size()); ++i)
  107. sorted_indices[i] = i;
  108. QuickSort(sorted_indices, sorted_indices + mDelayedResults.size(), [this](uint inLHS, uint inRHS) { return mDelayedResults[inLHS].mPenetrationDepth > mDelayedResults[inRHS].mPenetrationDepth; });
  109. // Loop over all results
  110. for (uint i = 0; i < uint(mDelayedResults.size()); ++i)
  111. {
  112. const CollideShapeResult &r = mDelayedResults[sorted_indices[i]];
  113. // Determine which vertex or which edge is the closest to the contact point
  114. float best_dist_sq = FLT_MAX;
  115. uint best_v1_idx = 0;
  116. uint best_v2_idx = 0;
  117. uint num_v = uint(r.mShape2Face.size());
  118. uint v1_idx = num_v - 1;
  119. Vec3 v1 = r.mShape2Face[v1_idx] - r.mContactPointOn2;
  120. for (uint v2_idx = 0; v2_idx < num_v; ++v2_idx)
  121. {
  122. Vec3 v2 = r.mShape2Face[v2_idx] - r.mContactPointOn2;
  123. Vec3 v1_v2 = v2 - v1;
  124. float denominator = v1_v2.LengthSq();
  125. if (denominator < Square(FLT_EPSILON))
  126. {
  127. // Degenerate, assume v1 is closest, v2 will be tested in a later iteration
  128. float v1_len_sq = v1.LengthSq();
  129. if (v1_len_sq < best_dist_sq)
  130. {
  131. best_dist_sq = v1_len_sq;
  132. best_v1_idx = v1_idx;
  133. best_v2_idx = v1_idx;
  134. }
  135. }
  136. else
  137. {
  138. // Taken from ClosestPoint::GetBaryCentricCoordinates
  139. float fraction = -v1.Dot(v1_v2) / denominator;
  140. if (fraction < 1.0e-6f)
  141. {
  142. // Closest lies on v1
  143. float v1_len_sq = v1.LengthSq();
  144. if (v1_len_sq < best_dist_sq)
  145. {
  146. best_dist_sq = v1_len_sq;
  147. best_v1_idx = v1_idx;
  148. best_v2_idx = v1_idx;
  149. }
  150. }
  151. else if (fraction < 1.0f - 1.0e-6f)
  152. {
  153. // Closest lies on the line segment v1, v2
  154. Vec3 closest = v1 + fraction * v1_v2;
  155. float closest_len_sq = closest.LengthSq();
  156. if (closest_len_sq < best_dist_sq)
  157. {
  158. best_dist_sq = closest_len_sq;
  159. best_v1_idx = v1_idx;
  160. best_v2_idx = v2_idx;
  161. }
  162. }
  163. // else closest is v2, but v2 will be tested in a later iteration
  164. }
  165. v1_idx = v2_idx;
  166. v1 = v2;
  167. }
  168. // Check if this vertex/edge is voided
  169. bool voided = IsVoided(r.mShape2Face[best_v1_idx])
  170. && (best_v1_idx == best_v2_idx || IsVoided(r.mShape2Face[best_v2_idx]));
  171. #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  172. Color color = voided? Color::sRed : Color::sYellow;
  173. DebugRenderer::sInstance->DrawText3D(RVec3(r.mContactPointOn2), StringFormat("%d: %g", i, r.mPenetrationDepth), color, 0.1f);
  174. DebugRenderer::sInstance->DrawWirePolygon(RMat44::sIdentity(), r.mShape2Face, color);
  175. DebugRenderer::sInstance->DrawArrow(RVec3(r.mContactPointOn2), RVec3(r.mContactPointOn2) + r.mPenetrationAxis.NormalizedOr(Vec3::sZero()), color, 0.1f);
  176. DebugRenderer::sInstance->DrawMarker(RVec3(r.mShape2Face[best_v1_idx]), IsVoided(r.mShape2Face[best_v1_idx])? Color::sRed : Color::sYellow, 0.1f);
  177. DebugRenderer::sInstance->DrawMarker(RVec3(r.mShape2Face[best_v2_idx]), IsVoided(r.mShape2Face[best_v2_idx])? Color::sRed : Color::sYellow, 0.1f);
  178. #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
  179. // No voided features, accept the contact
  180. if (!voided)
  181. Chain(r);
  182. // Void the features of this face
  183. VoidFeatures(r);
  184. }
  185. }
  186. /// Version of CollisionDispatch::sCollideShapeVsShape that removes internal edges
  187. 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 = { })
  188. {
  189. JPH_ASSERT(inCollideShapeSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces); // Won't work without collecting faces
  190. InternalEdgeRemovingCollector wrapper(ioCollector);
  191. CollisionDispatch::sCollideShapeVsShape(inShape1, inShape2, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, inCollideShapeSettings, wrapper, inShapeFilter);
  192. wrapper.Flush();
  193. }
  194. private:
  195. CollideShapeCollector & mChainedCollector;
  196. StaticArray<Float3, cMaxVoidedFeatures> mVoidedFeatures; // Read with Vec3::sLoadFloat3Unsafe so must not be the last member
  197. StaticArray<CollideShapeResult, cMaxDelayedResults> mDelayedResults;
  198. };
  199. JPH_NAMESPACE_END