ActiveEdgesTests.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include "UnitTestFramework.h"
  5. #include "PhysicsTestContext.h"
  6. #include "Layers.h"
  7. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  8. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  9. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  10. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  11. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  12. #include <Jolt/Physics/Collision/Shape/HeightFieldShape.h>
  13. #include <Jolt/Physics/Collision/Shape/ScaledShape.h>
  14. #include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
  15. #include <Jolt/Physics/Collision/CollideShape.h>
  16. #include <Jolt/Physics/Collision/ShapeCast.h>
  17. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  18. TEST_SUITE("ActiveEdgesTest")
  19. {
  20. static const float cCapsuleProbeOffset = 0.1f; // How much to offset the probe from y = 0 in order to avoid hitting a back instead of a front face
  21. static const float cCapsuleRadius = 0.1f;
  22. // Create a capsule as our probe
  23. static Ref<Shape> sCreateProbeCapsule()
  24. {
  25. // Ensure capsule is long enough so that when active edges mode is on, we will always get a horizontal penetration axis rather than a vertical one
  26. CapsuleShapeSettings capsule(1.0f, cCapsuleRadius);
  27. capsule.SetEmbedded();
  28. return capsule.Create().Get();
  29. }
  30. // Create a flat mesh shape consisting of 7 x 7 quads, we know that only the outer edges of this shape are active
  31. static Ref<ShapeSettings> sCreateMeshShape()
  32. {
  33. TriangleList triangles;
  34. for (int z = 0; z < 7; ++z)
  35. for (int x = 0; x < 7; ++x)
  36. {
  37. float fx = (float)x - 3.5f, fz = (float)z - 3.5f;
  38. triangles.push_back(Triangle(Vec3(fx, 0, fz), Vec3(fx, 0, fz + 1), Vec3(fx + 1, 0, fz + 1)));
  39. triangles.push_back(Triangle(Vec3(fx, 0, fz), Vec3(fx + 1, 0, fz + 1), Vec3(fx + 1, 0, fz)));
  40. }
  41. return new MeshShapeSettings(triangles);
  42. }
  43. // Create a flat height field shape that has the same properties as the mesh shape
  44. static Ref<ShapeSettings> sCreateHeightFieldShape()
  45. {
  46. float samples[8*8];
  47. memset(samples, 0, sizeof(samples));
  48. return new HeightFieldShapeSettings(samples, Vec3(-3.5f, 0, -3.5f), Vec3::sOne(), 8);
  49. }
  50. // This struct indicates what we hope to find as hit
  51. struct ExpectedHit
  52. {
  53. Vec3 mPosition;
  54. Vec3 mPenetrationAxis;
  55. };
  56. // Compare expected hits with returned hits
  57. template <class ResultType>
  58. static void sCheckMatch(const Array<ResultType> &inResult, const Array<ExpectedHit> &inExpectedHits, float inAccuracySq)
  59. {
  60. CHECK(inResult.size() == inExpectedHits.size());
  61. for (const ExpectedHit &hit : inExpectedHits)
  62. {
  63. bool found = false;
  64. for (const ResultType &result : inResult)
  65. if (result.mContactPointOn2.IsClose(hit.mPosition, inAccuracySq)
  66. && result.mPenetrationAxis.Normalized().IsClose(hit.mPenetrationAxis, inAccuracySq))
  67. {
  68. found = true;
  69. break;
  70. }
  71. CHECK(found);
  72. }
  73. }
  74. // Collide our probe against the test shape and validate the hit results
  75. static void sTestCollideShape(Shape *inProbeShape, Shape *inTestShape, Vec3Arg inTestShapeScale, const CollideShapeSettings &inSettings, Vec3Arg inProbeShapePos, const Array<ExpectedHit> &inExpectedHits)
  76. {
  77. AllHitCollisionCollector<CollideShapeCollector> collector;
  78. CollisionDispatch::sCollideShapeVsShape(inProbeShape, inTestShape, Vec3::sOne(), inTestShapeScale, Mat44::sTranslation(inProbeShapePos), Mat44::sIdentity(), SubShapeIDCreator(), SubShapeIDCreator(), inSettings, collector);
  79. sCheckMatch(collector.mHits, inExpectedHits, 1.0e-8f);
  80. }
  81. // Collide a probe shape against our test shape in various locations to verify active edge behavior
  82. static void sTestCollideShape(const ShapeSettings *inTestShape, Vec3Arg inTestShapeScale, bool inActiveEdgesOnly)
  83. {
  84. CollideShapeSettings settings;
  85. settings.mActiveEdgeMode = inActiveEdgesOnly? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;
  86. Ref<Shape> test_shape = inTestShape->Create().Get();
  87. Ref<Shape> capsule = sCreateProbeCapsule();
  88. // Test hitting all active edges
  89. sTestCollideShape(capsule, test_shape, inTestShapeScale, settings, Vec3(-3.5f, cCapsuleProbeOffset, 0), { { Vec3(-3.5f, 0, 0), Vec3(1, 0, 0) } });
  90. sTestCollideShape(capsule, test_shape, inTestShapeScale, settings, Vec3(3.5f, cCapsuleProbeOffset, 0), { { Vec3(3.5f, 0, 0), Vec3(-1, 0, 0) } });
  91. sTestCollideShape(capsule, test_shape, inTestShapeScale, settings, Vec3(0, cCapsuleProbeOffset, -3.5f), { { Vec3(0, 0, -3.5f), Vec3(0, 0, 1) } });
  92. sTestCollideShape(capsule, test_shape, inTestShapeScale, settings, Vec3(0, cCapsuleProbeOffset, 3.5f), { { Vec3(0, 0, 3.5f), Vec3(0, 0, -1) } });
  93. // Test hitting internal edges, this should return two hits
  94. sTestCollideShape(capsule, test_shape, inTestShapeScale, settings, Vec3(-2.5f, cCapsuleProbeOffset, 0), { { Vec3(-2.5f, 0, 0), inActiveEdgesOnly? Vec3(0, -1, 0) : Vec3(-1, 0, 0) }, { Vec3(-2.5f, 0, 0), inActiveEdgesOnly? Vec3(0, -1, 0) : Vec3(1, 0, 0) } });
  95. sTestCollideShape(capsule, test_shape, inTestShapeScale, settings, Vec3(0, cCapsuleProbeOffset, -2.5f), { { Vec3(0, 0, -2.5f), inActiveEdgesOnly? Vec3(0, -1, 0) : Vec3(0, 0, -1) }, { Vec3(0, 0, -2.5f), inActiveEdgesOnly? Vec3(0, -1, 0) : Vec3(0, 0, -1) } });
  96. // Test hitting an interior diagonal, this should return two hits
  97. sTestCollideShape(capsule, test_shape, inTestShapeScale, settings, Vec3(-3.0f, cCapsuleProbeOffset, 0), { { Vec3(-3.0f, 0, 0), inActiveEdgesOnly? Vec3(0, -1, 0) : (inTestShapeScale * Vec3(1, 0, -1)).Normalized() }, { Vec3(-3.0f, 0, 0), inActiveEdgesOnly? Vec3(0, -1, 0) : (inTestShapeScale * Vec3(-1, 0, 1)).Normalized() } });
  98. }
  99. TEST_CASE("CollideShapeMesh")
  100. {
  101. Ref<ShapeSettings> shape = sCreateMeshShape();
  102. sTestCollideShape(shape, Vec3::sOne(), false);
  103. sTestCollideShape(shape, Vec3::sOne(), true);
  104. sTestCollideShape(shape, Vec3(-1, 1, 1), false);
  105. sTestCollideShape(shape, Vec3(-1, 1, 1), true);
  106. }
  107. TEST_CASE("CollideShapeHeightField")
  108. {
  109. Ref<ShapeSettings> shape = sCreateHeightFieldShape();
  110. sTestCollideShape(shape, Vec3::sOne(), false);
  111. sTestCollideShape(shape, Vec3::sOne(), true);
  112. sTestCollideShape(shape, Vec3(-1, 1, 1), false);
  113. sTestCollideShape(shape, Vec3(-1, 1, 1), true);
  114. }
  115. // Cast our probe against the test shape and validate the hit results
  116. static void sTestCastShape(Shape *inProbeShape, Shape *inTestShape, Vec3Arg inTestShapeScale, const ShapeCastSettings &inSettings, Vec3Arg inProbeShapePos, Vec3Arg inProbeShapeDirection, const Array<ExpectedHit> &inExpectedHits)
  117. {
  118. AllHitCollisionCollector<CastShapeCollector> collector;
  119. ShapeCast shape_cast(inProbeShape, Vec3::sOne(), Mat44::sTranslation(inProbeShapePos), inProbeShapeDirection);
  120. CollisionDispatch::sCastShapeVsShapeLocalSpace(shape_cast, inSettings, inTestShape, inTestShapeScale, ShapeFilter(), Mat44::sIdentity(), SubShapeIDCreator(), SubShapeIDCreator(), collector);
  121. sCheckMatch(collector.mHits, inExpectedHits, 1.0e-6f);
  122. }
  123. // Cast a probe shape against our test shape in various locations to verify active edge behavior
  124. static void sTestCastShape(const ShapeSettings *inTestShape, Vec3Arg inTestShapeScale, bool inActiveEdgesOnly)
  125. {
  126. ShapeCastSettings settings;
  127. settings.mActiveEdgeMode = inActiveEdgesOnly? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;
  128. settings.mReturnDeepestPoint = true;
  129. Ref<Shape> test_shape = inTestShape->Create().Get();
  130. Ref<Shape> capsule = sCreateProbeCapsule();
  131. // Test hitting all active edges
  132. sTestCastShape(capsule, test_shape, inTestShapeScale, settings, Vec3(-4, cCapsuleProbeOffset, 0), Vec3(0.5f, 0, 0), { { Vec3(-3.5f, 0, 0), Vec3(1, 0, 0) } });
  133. sTestCastShape(capsule, test_shape, inTestShapeScale, settings, Vec3(4, cCapsuleProbeOffset, 0), Vec3(-0.5f, 0, 0), { { Vec3(3.5f, 0, 0), Vec3(-1, 0, 0) } });
  134. sTestCastShape(capsule, test_shape, inTestShapeScale, settings, Vec3(0, cCapsuleProbeOffset, -4), Vec3(0, 0, 0.5f), { { Vec3(0, 0, -3.5f), Vec3(0, 0, 1) } });
  135. sTestCastShape(capsule, test_shape, inTestShapeScale, settings, Vec3(0, cCapsuleProbeOffset, 4), Vec3(0, 0, -0.5f), { { Vec3(0, 0, 3.5f), Vec3(0, 0, -1) } });
  136. // Test hitting internal edges, this should return two hits
  137. sTestCastShape(capsule, test_shape, inTestShapeScale, settings, Vec3(-2.5f - 1.1f * cCapsuleRadius, cCapsuleProbeOffset, 0), Vec3(0.2f * cCapsuleRadius, 0, 0), { { Vec3(-2.5f, 0, 0), inActiveEdgesOnly? Vec3(0, -1, 0) : Vec3(-1, 0, 0) }, { Vec3(-2.5f, 0, 0), inActiveEdgesOnly? Vec3(0, -1, 0) : Vec3(1, 0, 0) } });
  138. sTestCastShape(capsule, test_shape, inTestShapeScale, settings, Vec3(0, cCapsuleProbeOffset, -2.5f - 1.1f * cCapsuleRadius), Vec3(0, 0, 0.2f * cCapsuleRadius), { { Vec3(0, 0, -2.5f), inActiveEdgesOnly? Vec3(0, -1, 0) : Vec3(0, 0, -1) }, { Vec3(0, 0, -2.5f), inActiveEdgesOnly? Vec3(0, -1, 0) : Vec3(0, 0, -1) } });
  139. }
  140. TEST_CASE("CastShapeMesh")
  141. {
  142. Ref<ShapeSettings> shape = sCreateMeshShape();
  143. sTestCastShape(shape, Vec3::sOne(), false);
  144. sTestCastShape(shape, Vec3::sOne(), true);
  145. sTestCastShape(shape, Vec3(-1, 1, 1), false);
  146. sTestCastShape(shape, Vec3(-1, 1, 1), true);
  147. }
  148. TEST_CASE("CastShapeHeightField")
  149. {
  150. Ref<ShapeSettings> shape = sCreateHeightFieldShape();
  151. sTestCastShape(shape, Vec3::sOne(), false);
  152. sTestCastShape(shape, Vec3::sOne(), true);
  153. sTestCastShape(shape, Vec3(-1, 1, 1), false);
  154. sTestCastShape(shape, Vec3(-1, 1, 1), true);
  155. }
  156. // Tests a discrete cube sliding over a mesh / heightfield shape
  157. static void sDiscreteCubeSlide(Ref<ShapeSettings> inShape, bool inCheckActiveEdges)
  158. {
  159. PhysicsTestContext c;
  160. const float cPenetrationSlop = c.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  161. // Set simulation settings
  162. PhysicsSettings settings;
  163. settings.mCheckActiveEdges = inCheckActiveEdges;
  164. c.GetSystem()->SetPhysicsSettings(settings);
  165. // Create frictionless floor
  166. Body &floor = c.CreateBody(inShape, RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, EActivation::DontActivate);
  167. floor.SetFriction(0.0f);
  168. // Create box sliding over the floor
  169. RVec3 initial_position(-3, 0.1f - cPenetrationSlop, 0);
  170. Vec3 initial_velocity(3, 0, 0);
  171. Body &box = c.CreateBox(initial_position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.1f));
  172. box.SetLinearVelocity(initial_velocity);
  173. box.SetFriction(0.0f);
  174. box.GetMotionProperties()->SetLinearDamping(0.0f);
  175. const float cSimulationTime = 2.0f;
  176. c.Simulate(cSimulationTime);
  177. RVec3 expected_position = initial_position + cSimulationTime * initial_velocity;
  178. if (inCheckActiveEdges)
  179. {
  180. // Box should have slided frictionless over the plane without encountering any collisions
  181. CHECK_APPROX_EQUAL(box.GetPosition(), expected_position, 1.0e-3f);
  182. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), initial_velocity, 2.0e-3f);
  183. }
  184. else
  185. {
  186. // Box should have bumped into an internal edge and not reached its target
  187. CHECK(box.GetPosition().GetX() < expected_position.GetX() - 1.0f);
  188. }
  189. }
  190. TEST_CASE("DiscreteCubeSlideMesh")
  191. {
  192. Ref<ShapeSettings> shape = sCreateMeshShape();
  193. sDiscreteCubeSlide(shape, false);
  194. sDiscreteCubeSlide(shape, true);
  195. Ref<ShapeSettings> scaled_shape = new ScaledShapeSettings(shape, Vec3(-1, 1, 1));
  196. sDiscreteCubeSlide(scaled_shape, false);
  197. sDiscreteCubeSlide(scaled_shape, true);
  198. }
  199. TEST_CASE("DiscreteCubeSlideHeightField")
  200. {
  201. Ref<ShapeSettings> shape = sCreateHeightFieldShape();
  202. sDiscreteCubeSlide(shape, false);
  203. sDiscreteCubeSlide(shape, true);
  204. Ref<ShapeSettings> scaled_shape = new ScaledShapeSettings(shape, Vec3(-1, 1, 1));
  205. sDiscreteCubeSlide(scaled_shape, false);
  206. sDiscreteCubeSlide(scaled_shape, true);
  207. }
  208. // Tests a linear cast cube sliding over a mesh / heightfield shape
  209. static void sLinearCastCubeSlide(Ref<ShapeSettings> inShape, bool inCheckActiveEdges)
  210. {
  211. PhysicsTestContext c;
  212. const float cPenetrationSlop = c.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  213. // Set simulation settings
  214. PhysicsSettings settings;
  215. settings.mCheckActiveEdges = inCheckActiveEdges;
  216. c.GetSystem()->SetPhysicsSettings(settings);
  217. // Create frictionless floor
  218. Body &floor = c.CreateBody(inShape, RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, EActivation::DontActivate);
  219. floor.SetFriction(0.0f);
  220. // Create box starting a little bit above the floor and ending 0.5 * cPenetrationSlop below the floor so that if no internal edges are hit the motion should not be stopped
  221. // Note that we need the vertical velocity or else back face culling will ignore the face
  222. RVec3 initial_position(-3, 0.1f + cPenetrationSlop, 0);
  223. Vec3 initial_velocity(6 * 60, -1.5f * cPenetrationSlop * 60, 0);
  224. Body &box = c.CreateBox(initial_position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::LinearCast, Layers::MOVING, Vec3::sReplicate(0.1f));
  225. box.SetLinearVelocity(initial_velocity);
  226. box.SetFriction(0.0f);
  227. box.GetMotionProperties()->SetLinearDamping(0.0f);
  228. // To avoid extra vertical velocity being picked up in 1 step, zero gravity
  229. c.ZeroGravity();
  230. c.SimulateSingleStep();
  231. RVec3 expected_position = initial_position + initial_velocity / 60.0f;
  232. if (inCheckActiveEdges)
  233. {
  234. // Box should stepped in one frame over the plane without encountering any linear cast collisions
  235. CHECK_APPROX_EQUAL(box.GetPosition(), expected_position, 1.0e-4f);
  236. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), initial_velocity, 1.0e-4f);
  237. }
  238. else
  239. {
  240. // Box should have bumped into an internal edge and not reached its target
  241. CHECK(box.GetPosition().GetX() < expected_position.GetX() - 1.0f);
  242. }
  243. }
  244. TEST_CASE("LinearCastCubeSlideMesh")
  245. {
  246. Ref<ShapeSettings> shape = sCreateMeshShape();
  247. sLinearCastCubeSlide(shape, false);
  248. sLinearCastCubeSlide(shape, true);
  249. Ref<ShapeSettings> scaled_shape = new ScaledShapeSettings(shape, Vec3(-1, 1, 1));
  250. sLinearCastCubeSlide(scaled_shape, false);
  251. sLinearCastCubeSlide(scaled_shape, true);
  252. }
  253. TEST_CASE("LinearCastCubeSlideHeightField")
  254. {
  255. Ref<ShapeSettings> shape = sCreateHeightFieldShape();
  256. sLinearCastCubeSlide(shape, false);
  257. sLinearCastCubeSlide(shape, true);
  258. Ref<ShapeSettings> scaled_shape = new ScaledShapeSettings(shape, Vec3(-1, 1, 1));
  259. sLinearCastCubeSlide(scaled_shape, false);
  260. sLinearCastCubeSlide(scaled_shape, true);
  261. }
  262. TEST_CASE("TestNonManifoldMesh")
  263. {
  264. // Test 3 triangles in a plane that all share the same edge
  265. // Normally the shared edge would not be active, but since the mesh is non-manifold we expect all of them to be active
  266. TriangleList triangles;
  267. triangles.push_back(Triangle(Float3(0, 0, -1), Float3(0, 0, 1), Float3(1, 0, 0), 0));
  268. triangles.push_back(Triangle(Float3(0, 0, 1), Float3(0, 0, -1), Float3(-1, 0, 0), 0));
  269. triangles.push_back(Triangle(Float3(0, 0, 1), Float3(0, 0, -1), Float3(-0.5f, 0, 0), 0));
  270. ShapeRefC shape = MeshShapeSettings(triangles).Create().Get();
  271. ShapeRefC sphere = new SphereShape(0.1f);
  272. CollideShapeSettings settings;
  273. settings.mActiveEdgeMode = EActiveEdgeMode::CollideOnlyWithActive;
  274. // Collide a sphere on both sides of the active edge so that a 45 degree normal will be found then the edge is active.
  275. // An inactive edge will return a normal that is perpendicular to the plane.
  276. {
  277. AllHitCollisionCollector<CollideShapeCollector> collector;
  278. CollisionDispatch::sCollideShapeVsShape(sphere, shape, Vec3::sOne(), Vec3::sOne(), Mat44::sTranslation(Vec3(0.05f, 0.05f, 0)), Mat44::sIdentity(), SubShapeIDCreator(), SubShapeIDCreator(), settings, collector);
  279. CHECK(collector.mHits.size() == 3);
  280. // We expect one interior hit because the sphere is above the triangle and 2 active edge hits that provide a normal pointing towards the sphere
  281. int num_interior = 0, num_on_shared_edge = 0;
  282. for (const CollideShapeResult &r : collector.mHits)
  283. if (r.mContactPointOn2.IsClose(Vec3(0.05f, 0.0f, 0.0f)))
  284. {
  285. CHECK_APPROX_EQUAL(r.mPenetrationAxis.Normalized(), Vec3(0, -1, 0));
  286. ++num_interior;
  287. }
  288. else if (r.mContactPointOn2.IsNearZero())
  289. {
  290. CHECK_APPROX_EQUAL(r.mPenetrationAxis.Normalized(), Vec3(-1, -1, 0).Normalized(), 1.0e-5f);
  291. ++num_on_shared_edge;
  292. }
  293. CHECK(num_interior == 1);
  294. CHECK(num_on_shared_edge == 2);
  295. }
  296. {
  297. AllHitCollisionCollector<CollideShapeCollector> collector;
  298. CollisionDispatch::sCollideShapeVsShape(sphere, shape, Vec3::sOne(), Vec3::sOne(), Mat44::sTranslation(Vec3(-0.05f, 0.05f, 0)), Mat44::sIdentity(), SubShapeIDCreator(), SubShapeIDCreator(), settings, collector);
  299. CHECK(collector.mHits.size() == 3);
  300. // We expect 2 interior hits because the sphere is above the triangle and 1 active edge hit that provide a normal pointing towards the sphere
  301. int num_interior = 0, num_on_shared_edge = 0;
  302. for (const CollideShapeResult &r : collector.mHits)
  303. if (r.mContactPointOn2.IsClose(Vec3(-0.05f, 0.0f, 0.0f)))
  304. {
  305. CHECK_APPROX_EQUAL(r.mPenetrationAxis.Normalized(), Vec3(0, -1, 0));
  306. ++num_interior;
  307. }
  308. else if (r.mContactPointOn2.IsNearZero())
  309. {
  310. CHECK_APPROX_EQUAL(r.mPenetrationAxis.Normalized(), Vec3(1, -1, 0).Normalized(), 1.0e-5f);
  311. ++num_on_shared_edge;
  312. }
  313. CHECK(num_interior == 2);
  314. CHECK(num_on_shared_edge == 1);
  315. }
  316. }
  317. }