CollideConvexVsTriangles.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>
  6. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  7. #include <Jolt/Physics/Collision/CollideShape.h>
  8. #include <Jolt/Physics/Collision/TransformedShape.h>
  9. #include <Jolt/Physics/Collision/ActiveEdges.h>
  10. #include <Jolt/Physics/Collision/NarrowPhaseStats.h>
  11. #include <Jolt/Geometry/EPAPenetrationDepth.h>
  12. #include <Jolt/Geometry/Plane.h>
  13. JPH_NAMESPACE_BEGIN
  14. CollideConvexVsTriangles::CollideConvexVsTriangles(const ConvexShape *inShape1, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeID &inSubShapeID1, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector) :
  15. mCollideShapeSettings(inCollideShapeSettings),
  16. mCollector(ioCollector),
  17. mShape1(inShape1),
  18. mScale1(inScale1),
  19. mScale2(inScale2),
  20. mTransform1(inCenterOfMassTransform1),
  21. mSubShapeID1(inSubShapeID1)
  22. {
  23. // Get transforms
  24. Mat44 inverse_transform2 = inCenterOfMassTransform2.InversedRotationTranslation();
  25. Mat44 transform1_to_2 = inverse_transform2 * inCenterOfMassTransform1;
  26. mTransform2To1 = transform1_to_2.InversedRotationTranslation();
  27. // Calculate bounds
  28. mBoundsOf1 = inShape1->GetLocalBounds().Scaled(inScale1);
  29. mBoundsOf1.ExpandBy(Vec3::sReplicate(inCollideShapeSettings.mMaxSeparationDistance));
  30. mBoundsOf1InSpaceOf2 = mBoundsOf1.Transformed(transform1_to_2); // Convert bounding box of 1 into space of 2
  31. // Determine if shape 2 is inside out or not
  32. mScaleSign2 = ScaleHelpers::IsInsideOut(inScale2)? -1.0f : 1.0f;
  33. }
  34. void CollideConvexVsTriangles::Collide(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, const SubShapeID &inSubShapeID2)
  35. {
  36. // Scale triangle and transform it to the space of 1
  37. Vec3 v0 = mTransform2To1 * (mScale2 * inV0);
  38. Vec3 v1 = mTransform2To1 * (mScale2 * inV1);
  39. Vec3 v2 = mTransform2To1 * (mScale2 * inV2);
  40. // Calculate triangle normal
  41. Vec3 triangle_normal = mScaleSign2 * (v1 - v0).Cross(v2 - v0);
  42. // Backface check
  43. bool back_facing = triangle_normal.Dot(v0) > 0.0f;
  44. if (mCollideShapeSettings.mBackFaceMode == EBackFaceMode::IgnoreBackFaces && back_facing)
  45. return;
  46. // Get bounding box for triangle
  47. AABox triangle_bbox = AABox::sFromTwoPoints(v0, v1);
  48. triangle_bbox.Encapsulate(v2);
  49. // Get intersection between triangle and shape box, if there is none, we're done
  50. if (!triangle_bbox.Overlaps(mBoundsOf1))
  51. return;
  52. // Create triangle support function
  53. TriangleConvexSupport triangle(v0, v1, v2);
  54. // Perform collision detection
  55. // Note: As we don't remember the penetration axis from the last iteration, and it is likely that the shape (A) we're colliding the triangle (B) against is in front of the triangle,
  56. // and the penetration axis is the shortest distance along to push B out of collision, we use the inverse of the triangle normal as an initial penetration axis. This has been seen
  57. // to improve performance by approx. 5% over using a fixed axis like (1, 0, 0).
  58. Vec3 penetration_axis = -triangle_normal, point1, point2;
  59. EPAPenetrationDepth pen_depth;
  60. EPAPenetrationDepth::EStatus status;
  61. // Get the support function
  62. if (mShape1ExCvxRadius == nullptr)
  63. mShape1ExCvxRadius = mShape1->GetSupportFunction(ConvexShape::ESupportMode::ExcludeConvexRadius, mBufferExCvxRadius, mScale1);
  64. // Perform GJK step
  65. float max_separation_distance = mCollideShapeSettings.mMaxSeparationDistance;
  66. status = pen_depth.GetPenetrationDepthStepGJK(*mShape1ExCvxRadius, mShape1ExCvxRadius->GetConvexRadius() + max_separation_distance, triangle, 0.0f, mCollideShapeSettings.mCollisionTolerance, penetration_axis, point1, point2);
  67. // Check result of collision detection
  68. if (status == EPAPenetrationDepth::EStatus::NotColliding)
  69. return;
  70. else if (status == EPAPenetrationDepth::EStatus::Indeterminate)
  71. {
  72. // Need to run expensive EPA algorithm
  73. // We know we're overlapping at this point, so we can set the max separation distance to 0.
  74. // Numerically it is possible that GJK finds that the shapes are overlapping but EPA finds that they're separated.
  75. // In order to avoid this, we clamp the max separation distance to 1 so that we don't excessively inflate the shape,
  76. // but we still inflate it enough to avoid the case where EPA misses the collision.
  77. max_separation_distance = min(max_separation_distance, 1.0f);
  78. // Get the support function
  79. if (mShape1IncCvxRadius == nullptr)
  80. mShape1IncCvxRadius = mShape1->GetSupportFunction(ConvexShape::ESupportMode::IncludeConvexRadius, mBufferIncCvxRadius, mScale1);
  81. // Add convex radius
  82. AddConvexRadius shape1_add_max_separation_distance(*mShape1IncCvxRadius, max_separation_distance);
  83. // Perform EPA step
  84. if (!pen_depth.GetPenetrationDepthStepEPA(shape1_add_max_separation_distance, triangle, mCollideShapeSettings.mPenetrationTolerance, penetration_axis, point1, point2))
  85. return;
  86. }
  87. // Check if the penetration is bigger than the early out fraction
  88. float penetration_depth = (point2 - point1).Length() - max_separation_distance;
  89. if (-penetration_depth >= mCollector.GetEarlyOutFraction())
  90. return;
  91. // Correct point1 for the added separation distance
  92. float penetration_axis_len = penetration_axis.Length();
  93. if (penetration_axis_len > 0.0f)
  94. point1 -= penetration_axis * (max_separation_distance / penetration_axis_len);
  95. // Check if we have enabled active edge detection
  96. if (mCollideShapeSettings.mActiveEdgeMode == EActiveEdgeMode::CollideOnlyWithActive && inActiveEdges != 0b111)
  97. {
  98. // Convert the active edge velocity hint to local space
  99. Vec3 active_edge_movement_direction = mTransform1.Multiply3x3Transposed(mCollideShapeSettings.mActiveEdgeMovementDirection);
  100. // Update the penetration axis to account for active edges
  101. // Note that we flip the triangle normal as the penetration axis is pointing towards the triangle instead of away
  102. penetration_axis = ActiveEdges::FixNormal(v0, v1, v2, back_facing? triangle_normal : -triangle_normal, inActiveEdges, point2, penetration_axis, active_edge_movement_direction);
  103. }
  104. // Convert to world space
  105. point1 = mTransform1 * point1;
  106. point2 = mTransform1 * point2;
  107. Vec3 penetration_axis_world = mTransform1.Multiply3x3(penetration_axis);
  108. // Create collision result
  109. CollideShapeResult result(point1, point2, penetration_axis_world, penetration_depth, mSubShapeID1, inSubShapeID2, TransformedShape::sGetBodyID(mCollector.GetContext()));
  110. // Gather faces
  111. if (mCollideShapeSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces)
  112. {
  113. // Get supporting face of shape 1
  114. mShape1->GetSupportingFace(SubShapeID(), -penetration_axis, mScale1, mTransform1, result.mShape1Face);
  115. // Get face of the triangle
  116. result.mShape2Face.resize(3);
  117. result.mShape2Face[0] = mTransform1 * v0;
  118. result.mShape2Face[1] = mTransform1 * v1;
  119. result.mShape2Face[2] = mTransform1 * v2;
  120. }
  121. // Notify the collector
  122. JPH_IF_TRACK_NARROWPHASE_STATS(TrackNarrowPhaseCollector track;)
  123. mCollector.AddHit(result);
  124. }
  125. JPH_NAMESPACE_END