PhysicsTests.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include "UnitTestFramework.h"
  4. #include "PhysicsTestContext.h"
  5. #include "Layers.h"
  6. #include "LoggingBodyActivationListener.h"
  7. #include "LoggingContactListener.h"
  8. #include <Physics/Collision/Shape/BoxShape.h>
  9. #include <Physics/Body/BodyLockMulti.h>
  10. TEST_SUITE("PhysicsTests")
  11. {
  12. // Gravity vector
  13. const Vec3 cGravity = Vec3(0.0f, -9.81f, 0.0f);
  14. // Test the test framework's helper functions
  15. TEST_CASE("TestPhysicsTestContext")
  16. {
  17. // Test that the Symplectic Euler integrator is close enough to the real value
  18. const float cSimulationTime = 2.0f;
  19. // For position: x = x0 + v0 * t + 1/2 * a * t^2
  20. const Vec3 cInitialPos(0.0f, 10.0f, 0.0f);
  21. PhysicsTestContext c;
  22. Vec3 simulated_pos = c.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  23. Vec3 integrated_position = cInitialPos + 0.5f * cGravity * Square(cSimulationTime);
  24. CHECK_APPROX_EQUAL(integrated_position, simulated_pos, 0.2f);
  25. // For rotation
  26. const Quat cInitialRot(Quat::sRotation(Vec3::sAxisY(), 0.1f));
  27. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  28. Quat simulated_rot = c.PredictOrientation(cInitialRot, Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  29. Vec3 integrated_acceleration = 0.5f * cAngularAcceleration * Square(cSimulationTime);
  30. float integrated_acceleration_len = integrated_acceleration.Length();
  31. Quat integrated_rot = Quat::sRotation(integrated_acceleration / integrated_acceleration_len, integrated_acceleration_len) * cInitialRot;
  32. CHECK_APPROX_EQUAL(integrated_rot, simulated_rot, 0.02f);
  33. }
  34. TEST_CASE("TestPhysicsBodyLock")
  35. {
  36. PhysicsTestContext c;
  37. // Check that we cannot lock the invalid body ID
  38. {
  39. BodyLockRead lock(c.GetSystem()->GetBodyLockInterface(), BodyID());
  40. CHECK_FALSE(lock.Succeeded());
  41. CHECK_FALSE(lock.SucceededAndIsInBroadPhase());
  42. }
  43. BodyID body1_id;
  44. {
  45. // Create a box
  46. Body &body1 = c.CreateBox(Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  47. body1_id = body1.GetID();
  48. CHECK(body1_id.GetIndex() == 0);
  49. CHECK(body1_id.GetSequenceNumber() == 1);
  50. // Create another box
  51. Body &body2 = c.CreateBox(Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  52. BodyID body2_id = body2.GetID();
  53. CHECK(body2_id.GetIndex() == 1);
  54. CHECK(body2_id.GetSequenceNumber() == 1);
  55. // Check that we can lock the first box
  56. {
  57. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  58. CHECK(lock1.Succeeded());
  59. CHECK(lock1.SucceededAndIsInBroadPhase());
  60. }
  61. // Remove the first box
  62. c.GetSystem()->GetBodyInterface().RemoveBody(body1_id);
  63. // Check that we can lock the first box
  64. {
  65. BodyLockWrite lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  66. CHECK(lock1.Succeeded());
  67. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  68. }
  69. // Destroy the first box
  70. c.GetSystem()->GetBodyInterface().DestroyBody(body1_id);
  71. // Check that we can not lock the body anymore
  72. {
  73. BodyLockWrite lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  74. CHECK_FALSE(lock1.Succeeded());
  75. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  76. }
  77. }
  78. // Create another box
  79. Body &body3 = c.CreateBox(Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  80. BodyID body3_id = body3.GetID();
  81. CHECK(body3_id.GetIndex() == 0); // Check index reused
  82. CHECK(body3_id.GetSequenceNumber() == 2); // Check sequence number changed
  83. // Check that we can lock it
  84. {
  85. BodyLockRead lock3(c.GetSystem()->GetBodyLockInterface(), body3_id);
  86. CHECK(lock3.Succeeded());
  87. CHECK(lock3.SucceededAndIsInBroadPhase());
  88. }
  89. // Check that we can't lock the old body with the same body index anymore
  90. {
  91. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  92. CHECK_FALSE(lock1.Succeeded());
  93. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  94. }
  95. }
  96. TEST_CASE("TestPhysicsBodyLockMulti")
  97. {
  98. PhysicsTestContext c;
  99. // Check that we cannot lock the invalid body ID
  100. {
  101. BodyID bodies[] = { BodyID(), BodyID() };
  102. BodyLockMultiRead lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  103. CHECK(lock.GetBody(0) == nullptr);
  104. CHECK(lock.GetBody(1) == nullptr);
  105. }
  106. {
  107. // Create two bodies
  108. Body &body1 = c.CreateBox(Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  109. Body &body2 = c.CreateBox(Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  110. BodyID bodies[] = { body1.GetID(), body2.GetID() };
  111. {
  112. // Lock the bodies
  113. BodyLockMultiWrite lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  114. CHECK(lock.GetBody(0) == &body1);
  115. CHECK(lock.GetBody(1) == &body2);
  116. }
  117. // Destroy body 1
  118. c.GetSystem()->GetBodyInterface().RemoveBody(bodies[0]);
  119. c.GetSystem()->GetBodyInterface().DestroyBody(bodies[0]);
  120. {
  121. // Lock the bodies
  122. BodyLockMultiRead lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  123. CHECK(lock.GetBody(0) == nullptr);
  124. CHECK(lock.GetBody(1) == &body2);
  125. }
  126. }
  127. }
  128. TEST_CASE("TestPhysicsBodyID")
  129. {
  130. {
  131. BodyID body_id(0);
  132. CHECK(body_id.GetIndex() == 0);
  133. CHECK(body_id.GetSequenceNumber() == 0);
  134. }
  135. {
  136. BodyID body_id(~BodyID::cBroadPhaseBit);
  137. CHECK(body_id.GetIndex() == BodyID::cMaxBodyIndex);
  138. CHECK(body_id.GetSequenceNumber() == BodyID::cMaxSequenceNumber);
  139. }
  140. }
  141. TEST_CASE("TestPhysicsBodyIDSequenceNumber")
  142. {
  143. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  144. BodyInterface &bi = c.GetBodyInterface();
  145. // Create a body and check it's id
  146. BodyID body0_id = c.CreateBox(Vec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1)).GetID();
  147. CHECK(body0_id == BodyID(0, 1)); // Body 0, sequence number 1
  148. // Check that the sequence numbers aren't reused until after 256 iterations
  149. for (int seq_no = 1; seq_no < 258; ++seq_no)
  150. {
  151. BodyID body1_id = c.CreateBox(Vec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1)).GetID();
  152. CHECK(body1_id == BodyID(1, uint8(seq_no))); // Body 1
  153. bi.RemoveBody(body1_id);
  154. bi.DestroyBody(body1_id);
  155. }
  156. bi.RemoveBody(body0_id);
  157. bi.DestroyBody(body0_id);
  158. }
  159. TEST_CASE("TestPhysicsBodyUserData")
  160. {
  161. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  162. BodyInterface &bi = c.GetBodyInterface();
  163. // Create a body and pass user data through the creation settings
  164. BodyCreationSettings body_settings(new BoxShape(Vec3::sReplicate(1.0f)), Vec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  165. body_settings.mUserData = 0x1234567887654321;
  166. Body *body = bi.CreateBody(body_settings);
  167. CHECK(body->GetUserData() == 0x1234567887654321);
  168. // Change the user data
  169. body->SetUserData(0x5678123443218765);
  170. CHECK(body->GetUserData() == 0x5678123443218765);
  171. }
  172. TEST_CASE("TestPhysicsOverrideMassAndInertia")
  173. {
  174. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  175. BodyInterface &bi = c.GetBodyInterface();
  176. const float cDensity = 1234.0f;
  177. const Vec3 cBoxExtent(2.0f, 4.0f, 6.0f);
  178. const float cExpectedMass = cBoxExtent.GetX() * cBoxExtent.GetY() * cBoxExtent.GetZ() * cDensity;
  179. // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  180. const Vec3 cSquaredExtents = Vec3(Square(cBoxExtent.GetY()) + Square(cBoxExtent.GetZ()), Square(cBoxExtent.GetX()) + Square(cBoxExtent.GetZ()), Square(cBoxExtent.GetX()) + Square(cBoxExtent.GetY()));
  181. const Vec3 cExpectedInertiaDiagonal = cExpectedMass / 12.0f * cSquaredExtents;
  182. Ref<BoxShapeSettings> shape_settings = new BoxShapeSettings(0.5f * cBoxExtent);
  183. shape_settings->SetDensity(cDensity);
  184. BodyCreationSettings body_settings(shape_settings, Vec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  185. // Create body as is
  186. Body &b1 = *bi.CreateBody(body_settings);
  187. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseMass(), 1.0f / cExpectedMass);
  188. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  189. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseInertiaDiagonal(), cExpectedInertiaDiagonal.Reciprocal());
  190. // Override only the mass
  191. const float cOverriddenMass = 13.0f;
  192. const Vec3 cOverriddenMassInertiaDiagonal = cOverriddenMass / 12.0f * cSquaredExtents;
  193. body_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  194. body_settings.mMassPropertiesOverride.mMass = cOverriddenMass;
  195. Body &b2 = *bi.CreateBody(body_settings);
  196. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  197. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  198. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenMassInertiaDiagonal.Reciprocal());
  199. // Override both the mass and inertia
  200. const Vec3 cOverriddenInertiaDiagonal(3.0f, 2.0f, 1.0f); // From big to small so that MassProperties::DecomposePrincipalMomentsOfInertia returns the same rotation as we put in
  201. const Quat cOverriddenInertiaRotation = Quat::sRotation(Vec3(1, 1, 1).Normalized(), 0.1f * JPH_PI);
  202. body_settings.mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
  203. body_settings.mMassPropertiesOverride.mInertia = Mat44::sRotation(cOverriddenInertiaRotation) * Mat44::sScale(cOverriddenInertiaDiagonal) * Mat44::sRotation(cOverriddenInertiaRotation.Inversed());
  204. Body &b3 = *bi.CreateBody(body_settings);
  205. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  206. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInertiaRotation(), cOverriddenInertiaRotation);
  207. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenInertiaDiagonal.Reciprocal());
  208. }
  209. // Test a box free falling under gravity
  210. static void TestPhysicsFreeFall(PhysicsTestContext &ioContext)
  211. {
  212. const Vec3 cInitialPos(0.0f, 10.0f, 0.0f);
  213. const float cSimulationTime = 2.0f;
  214. // Create box
  215. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  216. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  217. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  218. ioContext.Simulate(cSimulationTime);
  219. // Test resulting velocity (due to gravity)
  220. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  221. // Test resulting position
  222. Vec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  223. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  224. }
  225. TEST_CASE("TestPhysicsFreeFall")
  226. {
  227. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  228. TestPhysicsFreeFall(c);
  229. }
  230. TEST_CASE("TestPhysicsFreeFallSubStep")
  231. {
  232. PhysicsTestContext c1(2.0f / 60.0f, 1, 2);
  233. TestPhysicsFreeFall(c1);
  234. PhysicsTestContext c2(4.0f / 60.0f, 1, 4);
  235. TestPhysicsFreeFall(c2);
  236. PhysicsTestContext c3(4.0f / 60.0f, 2, 2);
  237. TestPhysicsFreeFall(c3);
  238. PhysicsTestContext c4(2.0f / 60.0f, 2, 1);
  239. TestPhysicsFreeFall(c4);
  240. PhysicsTestContext c5(8.0f / 60.0f, 4, 2);
  241. TestPhysicsFreeFall(c5);
  242. PhysicsTestContext c6(4.0f / 60.0f, 4, 1);
  243. TestPhysicsFreeFall(c6);
  244. }
  245. // Test acceleration of a box with force applied
  246. static void TestPhysicsApplyForce(PhysicsTestContext &ioContext)
  247. {
  248. const Vec3 cInitialPos(0.0f, 10.0f, 0.0f);
  249. const Vec3 cAcceleration(2.0f, 0.0f, 0.0f);
  250. const float cSimulationTime = 2.0f;
  251. // Create box
  252. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  253. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  254. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  255. // Validate mass
  256. float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  257. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  258. // Simulate while applying force
  259. ioContext.Simulate(cSimulationTime, [&]() { body.AddForce(mass * cAcceleration); });
  260. // Test resulting velocity (due to gravity and applied force)
  261. CHECK_APPROX_EQUAL(cSimulationTime * (cGravity + cAcceleration), body.GetLinearVelocity(), 1.0e-4f);
  262. // Test resulting position
  263. Vec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity + cAcceleration, cSimulationTime);
  264. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  265. }
  266. TEST_CASE("TestPhysicsApplyForce")
  267. {
  268. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  269. TestPhysicsApplyForce(c);
  270. }
  271. TEST_CASE("TestPhysicsApplyForceSubStep")
  272. {
  273. PhysicsTestContext c1(2.0f / 60.0f, 1, 2);
  274. TestPhysicsApplyForce(c1);
  275. PhysicsTestContext c2(4.0f / 60.0f, 1, 4);
  276. TestPhysicsApplyForce(c2);
  277. PhysicsTestContext c3(4.0f / 60.0f, 2, 2);
  278. TestPhysicsApplyForce(c3);
  279. PhysicsTestContext c4(2.0f / 60.0f, 2, 1);
  280. TestPhysicsApplyForce(c4);
  281. PhysicsTestContext c5(8.0f / 60.0f, 4, 2);
  282. TestPhysicsApplyForce(c5);
  283. PhysicsTestContext c6(4.0f / 60.0f, 4, 1);
  284. TestPhysicsApplyForce(c6);
  285. }
  286. // Test angular accelartion for a box by applying torque every frame
  287. static void TestPhysicsApplyTorque(PhysicsTestContext &ioContext)
  288. {
  289. const Vec3 cInitialPos(0.0f, 10.0f, 0.0f);
  290. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  291. const float cSimulationTime = 2.0f;
  292. // Create box
  293. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  294. CHECK_APPROX_EQUAL(Quat::sIdentity(), body.GetRotation());
  295. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  296. // Validate mass and inertia
  297. constexpr float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  298. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  299. constexpr float inertia = mass * 8.0f / 12.0f; // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  300. CHECK_APPROX_EQUAL(Mat44::sScale(1.0f / inertia), body.GetMotionProperties()->GetLocalSpaceInverseInertia());
  301. // Simulate while applying torque
  302. ioContext.Simulate(cSimulationTime, [&]() { body.AddTorque(inertia * cAngularAcceleration); });
  303. // Get resulting angular velocity
  304. CHECK_APPROX_EQUAL(cSimulationTime * cAngularAcceleration, body.GetAngularVelocity(), 1.0e-4f);
  305. // Test resulting rotation
  306. Quat expected_rot = ioContext.PredictOrientation(Quat::sIdentity(), Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  307. CHECK_APPROX_EQUAL(expected_rot, body.GetRotation(), 1.0e-4f);
  308. }
  309. TEST_CASE("TestPhysicsApplyTorque")
  310. {
  311. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  312. TestPhysicsApplyTorque(c);
  313. }
  314. TEST_CASE("TestPhysicsApplyTorqueSubStep")
  315. {
  316. PhysicsTestContext c1(2.0f / 60.0f, 1, 2);
  317. TestPhysicsApplyTorque(c1);
  318. PhysicsTestContext c2(4.0f / 60.0f, 1, 4);
  319. TestPhysicsApplyTorque(c2);
  320. PhysicsTestContext c3(4.0f / 60.0f, 2, 2);
  321. TestPhysicsApplyTorque(c3);
  322. PhysicsTestContext c4(2.0f / 60.0f, 2, 1);
  323. TestPhysicsApplyTorque(c4);
  324. PhysicsTestContext c5(8.0f / 60.0f, 4, 2);
  325. TestPhysicsApplyTorque(c5);
  326. PhysicsTestContext c6(4.0f / 60.0f, 4, 1);
  327. TestPhysicsApplyTorque(c6);
  328. }
  329. // Let a sphere bounce on the floor with restition = 1
  330. static void TestPhysicsCollisionElastic(PhysicsTestContext &ioContext)
  331. {
  332. const float cSimulationTime = 1.0f;
  333. const Vec3 cDistanceTraveled = ioContext.PredictPosition(Vec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  334. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  335. const Vec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  336. const Vec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  337. // Create sphere
  338. ioContext.CreateFloor();
  339. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  340. body.SetRestitution(1.0f);
  341. // Simulate until at floor
  342. ioContext.Simulate(cSimulationTime);
  343. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  344. // Assert collision not yet processed
  345. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  346. // Simulate one more step to process the collision
  347. ioContext.Simulate(ioContext.GetDeltaTime());
  348. // Assert that collision is processed and velocity is reversed (which is required for a fully elastic collision).
  349. // Note that the physics engine will first apply gravity for the time step and then do collision detection,
  350. // hence the reflected velocity is actually 1 sub-step times gravity bigger than it would be in reality
  351. // For the remainder of cDeltaTime normal gravity will be applied
  352. float sub_step_delta_time = ioContext.GetSubStepDeltaTime();
  353. float remaining_step_time = ioContext.GetDeltaTime() - ioContext.GetSubStepDeltaTime();
  354. Vec3 reflected_velocity_after_sub_step = -(cSimulationTime + sub_step_delta_time) * cGravity;
  355. Vec3 reflected_velocity_after_full_step = reflected_velocity_after_sub_step + remaining_step_time * cGravity;
  356. CHECK_APPROX_EQUAL(reflected_velocity_after_full_step, body.GetLinearVelocity(), 1.0e-4f);
  357. // Body should have bounced back
  358. Vec3 pos_after_bounce_sub_step = cFloorHitPos + reflected_velocity_after_sub_step * sub_step_delta_time;
  359. Vec3 pos_after_bounce_full_step = ioContext.PredictPosition(pos_after_bounce_sub_step, reflected_velocity_after_sub_step, cGravity, remaining_step_time);
  360. CHECK_APPROX_EQUAL(pos_after_bounce_full_step, body.GetPosition());
  361. // Simulate same time, with a fully elastic body we should reach the initial position again
  362. // In our physics engine because of the velocity being too big we actually end up a bit higher than our initial position
  363. Vec3 expected_pos = ioContext.PredictPosition(pos_after_bounce_full_step, reflected_velocity_after_full_step, cGravity, cSimulationTime);
  364. ioContext.Simulate(cSimulationTime);
  365. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition(), 1.0e-4f);
  366. CHECK(expected_pos.GetY() >= cInitialPos.GetY());
  367. }
  368. TEST_CASE("TestPhysicsCollisionElastic")
  369. {
  370. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  371. TestPhysicsCollisionElastic(c);
  372. }
  373. TEST_CASE("TestPhysicsCollisionElasticSubStep")
  374. {
  375. PhysicsTestContext c1(2.0f / 60.0f, 1, 2);
  376. TestPhysicsCollisionElastic(c1);
  377. PhysicsTestContext c2(4.0f / 60.0f, 1, 4);
  378. TestPhysicsCollisionElastic(c2);
  379. PhysicsTestContext c3(4.0f / 60.0f, 2, 2);
  380. TestPhysicsCollisionElastic(c3);
  381. PhysicsTestContext c4(2.0f / 60.0f, 2, 1);
  382. TestPhysicsCollisionElastic(c4);
  383. PhysicsTestContext c5(4.0f / 60.0f, 4, 1);
  384. TestPhysicsCollisionElastic(c5);
  385. }
  386. // Let a sphere bounce on the floor with restitution = 0
  387. static void TestPhysicsCollisionInelastic(PhysicsTestContext &ioContext)
  388. {
  389. const float cSimulationTime = 1.0f;
  390. const Vec3 cDistanceTraveled = ioContext.PredictPosition(Vec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  391. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  392. const Vec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  393. const Vec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  394. // Create sphere
  395. ioContext.CreateFloor();
  396. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  397. body.SetRestitution(0.0f);
  398. // Simulate until at floor
  399. ioContext.Simulate(cSimulationTime);
  400. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  401. // Assert collision not yet processed
  402. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  403. // Simulate one more step to process the collision
  404. ioContext.Simulate(ioContext.GetDeltaTime());
  405. // Assert that all velocity was lost in the collision
  406. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  407. // Assert that we're on the floor
  408. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  409. // Simulate some more to validate that we remain on the floor
  410. ioContext.Simulate(cSimulationTime);
  411. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  412. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  413. }
  414. TEST_CASE("TestPhysicsCollisionInelastic")
  415. {
  416. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  417. TestPhysicsCollisionInelastic(c);
  418. }
  419. TEST_CASE("TestPhysicsCollisionInelasticSubStep")
  420. {
  421. PhysicsTestContext c1(2.0f / 60.0f, 1, 2);
  422. TestPhysicsCollisionInelastic(c1);
  423. PhysicsTestContext c2(4.0f / 60.0f, 1, 4);
  424. TestPhysicsCollisionInelastic(c2);
  425. PhysicsTestContext c3(4.0f / 60.0f, 2, 2);
  426. TestPhysicsCollisionInelastic(c3);
  427. PhysicsTestContext c4(2.0f / 60.0f, 2, 1);
  428. TestPhysicsCollisionInelastic(c4);
  429. PhysicsTestContext c5(4.0f / 60.0f, 4, 1);
  430. TestPhysicsCollisionInelastic(c5);
  431. }
  432. // Let box intersect with floor by cPenetrationSlop. It should not move, this is the maximum penetration allowed.
  433. static void TestPhysicsPenetrationSlop1(PhysicsTestContext &ioContext)
  434. {
  435. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  436. const float cSimulationTime = 1.0f;
  437. const Vec3 cInitialPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  438. // Create box, penetrating with floor
  439. ioContext.CreateFloor();
  440. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  441. // Simulate
  442. ioContext.Simulate(cSimulationTime);
  443. // Test slop not resolved
  444. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  445. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  446. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  447. }
  448. TEST_CASE("TestPhysicsPenetrationSlop1")
  449. {
  450. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  451. TestPhysicsPenetrationSlop1(c);
  452. }
  453. TEST_CASE("TestPhysicsPenetrationSlop1SubStep")
  454. {
  455. PhysicsTestContext c(1.0f / 30.0f, 1, 2);
  456. TestPhysicsPenetrationSlop1(c);
  457. PhysicsTestContext c2(1.0f / 30.0f, 2, 1);
  458. TestPhysicsPenetrationSlop1(c2);
  459. }
  460. // Let box intersect with floor with more than cPenetrationSlop. It should be resolved by SolvePositionConstraint until interpenetration is cPenetrationSlop.
  461. static void TestPhysicsPenetrationSlop2(PhysicsTestContext &ioContext)
  462. {
  463. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  464. const float cSimulationTime = 1.0f;
  465. const Vec3 cInitialPos(0.0f, 1.0f - 2.0f * cPenetrationSlop, 0.0f);
  466. const Vec3 cFinalPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  467. // Create box, penetrating with floor
  468. ioContext.CreateFloor();
  469. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  470. // Simulate
  471. ioContext.Simulate(cSimulationTime);
  472. // Test resolved until slop
  473. CHECK_APPROX_EQUAL(cFinalPos, body.GetPosition(), 1.0e-5f);
  474. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  475. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  476. }
  477. TEST_CASE("TestPhysicsPenetrationSlop2")
  478. {
  479. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  480. TestPhysicsPenetrationSlop2(c);
  481. }
  482. TEST_CASE("TestPhysicsPenetrationSlop2SubStep")
  483. {
  484. PhysicsTestContext c(1.0f / 30.0f, 1, 2);
  485. TestPhysicsPenetrationSlop2(c);
  486. PhysicsTestContext c2(1.0f / 30.0f, 2, 1);
  487. TestPhysicsPenetrationSlop2(c2);
  488. }
  489. // Let box intersect with floor with less than cPenetrationSlop. Body should not move because SolveVelocityConstraint should reset velocity.
  490. static void TestPhysicsPenetrationSlop3(PhysicsTestContext &ioContext)
  491. {
  492. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  493. const float cSimulationTime = 1.0f;
  494. const Vec3 cInitialPos(0.0f, 1.0f - 0.1f * cPenetrationSlop, 0.0f);
  495. // Create box, penetrating with floor
  496. ioContext.CreateFloor();
  497. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  498. // Simulate
  499. ioContext.Simulate(cSimulationTime);
  500. // Test body remained static
  501. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  502. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  503. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  504. }
  505. TEST_CASE("TestPhysicsPenetrationSlop3")
  506. {
  507. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  508. TestPhysicsPenetrationSlop3(c);
  509. }
  510. TEST_CASE("TestPhysicsPenetrationSlop3SubStep")
  511. {
  512. PhysicsTestContext c(1.0f / 30.0f, 1, 2);
  513. TestPhysicsPenetrationSlop3(c);
  514. PhysicsTestContext c2(1.0f / 30.0f, 2, 1);
  515. TestPhysicsPenetrationSlop3(c2);
  516. }
  517. TEST_CASE("TestPhysicsOutsideOfSpeculativeContactDistance")
  518. {
  519. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  520. Body &floor = c.CreateFloor();
  521. c.ZeroGravity();
  522. LoggingContactListener contact_listener;
  523. c.GetSystem()->SetContactListener(&contact_listener);
  524. // Create a box and a sphere just outside the speculative contact distance
  525. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  526. const float cDistanceAboveFloor = 1.1f * cSpeculativeContactDistance;
  527. const Vec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  528. const Vec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  529. // Make it move 1 m per step down
  530. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  531. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  532. box.SetLinearVelocity(cVelocity);
  533. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  534. sphere.SetLinearVelocity(cVelocity);
  535. // Simulate a step
  536. c.SimulateSingleStep();
  537. // Check that it is now penetrating the floor (collision should not have been detected as it is a discrete body and there was no collision initially)
  538. CHECK(contact_listener.GetEntryCount() == 0);
  539. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  540. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  541. // Simulate a step
  542. c.SimulateSingleStep();
  543. // Check that the contacts are detected now
  544. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  545. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  546. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  547. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  548. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  549. }
  550. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoRestitution")
  551. {
  552. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  553. Body &floor = c.CreateFloor();
  554. c.ZeroGravity();
  555. LoggingContactListener contact_listener;
  556. c.GetSystem()->SetContactListener(&contact_listener);
  557. // Create a box and a sphere just inside the speculative contact distance
  558. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  559. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  560. const Vec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  561. const Vec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  562. // Make it move 1 m per step down
  563. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  564. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  565. box.SetLinearVelocity(cVelocity);
  566. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  567. sphere.SetLinearVelocity(cVelocity);
  568. // Simulate a step
  569. c.SimulateSingleStep();
  570. // Check that it is now on the floor and that 2 collisions have been detected
  571. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  572. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  573. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  574. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  575. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  576. contact_listener.Clear();
  577. // Velocity should have been reduced to exactly hit the floor in this step
  578. const Vec3 cExpectedVelocity(0, -cDistanceAboveFloor / c.GetDeltaTime(), 0);
  579. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  580. CHECK_APPROX_EQUAL(box.GetPosition(), Vec3(0, 1, 0), 1.0e-3f);
  581. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cExpectedVelocity, 0.05f);
  582. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  583. // Sphere has only 1 contact point so is much more accurate
  584. CHECK_APPROX_EQUAL(sphere.GetPosition(), Vec3(5, 1, 0));
  585. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cExpectedVelocity, 1.0e-4f);
  586. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  587. // Simulate a step
  588. c.SimulateSingleStep();
  589. // Check that the contacts persisted
  590. CHECK(contact_listener.GetEntryCount() >= 2); // 2 persist and possibly 2 validates depending on if the cache got reused
  591. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, box.GetID(), floor.GetID()));
  592. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  593. // Box should have come to rest
  594. CHECK_APPROX_EQUAL(box.GetPosition(), Vec3(0, 1, 0), 1.0e-3f);
  595. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero(), 0.05f);
  596. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  597. // Sphere should have come to rest
  598. CHECK_APPROX_EQUAL(sphere.GetPosition(), Vec3(5, 1, 0), 1.0e-4f);
  599. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), Vec3::sZero(), 1.0e-4f);
  600. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  601. }
  602. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceWithRestitution")
  603. {
  604. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  605. Body &floor = c.CreateFloor();
  606. c.ZeroGravity();
  607. LoggingContactListener contact_listener;
  608. c.GetSystem()->SetContactListener(&contact_listener);
  609. // Create a box and a sphere just inside the speculative contact distance
  610. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  611. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  612. const Vec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  613. const Vec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  614. // Make it move 1 m per step down
  615. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  616. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  617. box.SetLinearVelocity(cVelocity);
  618. box.SetRestitution(1.0f);
  619. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  620. sphere.SetLinearVelocity(cVelocity);
  621. sphere.SetRestitution(1.0f);
  622. // Simulate a step
  623. c.SimulateSingleStep();
  624. // Check that it has triggered contact points and has bounced from it's initial position (effectively travelling the extra distance to the floor and back for free)
  625. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  626. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  627. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  628. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  629. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  630. contact_listener.Clear();
  631. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  632. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox - cVelocity * c.GetDeltaTime(), 0.01f);
  633. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), -cVelocity, 0.1f);
  634. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 0.02f);
  635. // Sphere has only 1 contact point so is much more accurate
  636. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere - cVelocity * c.GetDeltaTime(), 1.0e-5f);
  637. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), -cVelocity, 2.0e-4f);
  638. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 2.0e-4f);
  639. // Simulate a step
  640. c.SimulateSingleStep();
  641. // Check that all contact points are removed
  642. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  643. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  644. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  645. }
  646. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceMovingAway")
  647. {
  648. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  649. Body &floor = c.CreateFloor();
  650. c.ZeroGravity();
  651. LoggingContactListener contact_listener;
  652. c.GetSystem()->SetContactListener(&contact_listener);
  653. // Create a box and a sphere just inside the speculative contact distance
  654. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  655. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  656. const Vec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  657. const Vec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  658. // Make it move 1 m per step up
  659. const Vec3 cVelocity(0, 1.0f / c.GetDeltaTime(), 0);
  660. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  661. box.SetLinearVelocity(cVelocity);
  662. box.SetRestitution(1.0f);
  663. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  664. sphere.SetLinearVelocity(cVelocity);
  665. sphere.SetRestitution(1.0f);
  666. // Simulate a step
  667. c.SimulateSingleStep();
  668. // Check that it has triggered contact points (note that this is wrong since the object never touched the floor but that's the downside of the speculative contacts -> you'll get an incorrect collision callback)
  669. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  670. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  671. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  672. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  673. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  674. contact_listener.Clear();
  675. // Box should have moved unimpeded
  676. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  677. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cVelocity);
  678. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  679. // Sphere should have moved unimpeded
  680. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  681. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  682. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  683. // Simulate a step
  684. c.SimulateSingleStep();
  685. // Check that all contact points are removed
  686. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  687. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  688. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  689. }
  690. static void TestPhysicsActivationDeactivation(PhysicsTestContext &ioContext)
  691. {
  692. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  693. // Install activation listener
  694. LoggingBodyActivationListener activation_listener;
  695. ioContext.GetSystem()->SetBodyActivationListener(&activation_listener);
  696. // Create floor
  697. Body &floor = ioContext.CreateBox(Vec3(0, -1, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100, 1, 100));
  698. CHECK(!floor.IsActive());
  699. // Create inactive box
  700. Body &box = ioContext.CreateBox(Vec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::DontActivate);
  701. CHECK(!box.IsActive());
  702. CHECK(activation_listener.GetEntryCount() == 0);
  703. // Box should not activate by itself
  704. ioContext.Simulate(1.0f);
  705. CHECK(box.GetPosition() == Vec3(0, 5, 0));
  706. CHECK(!box.IsActive());
  707. CHECK(activation_listener.GetEntryCount() == 0);
  708. // Activate the body and validate it is active now
  709. ioContext.GetBodyInterface().ActivateBody(box.GetID());
  710. CHECK(box.IsActive());
  711. CHECK(box.GetLinearVelocity().IsNearZero());
  712. CHECK(activation_listener.GetEntryCount() == 1);
  713. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, box.GetID()));
  714. activation_listener.Clear();
  715. // Do a single step and check that the body is still active and has gained some velocity
  716. ioContext.SimulateSingleStep();
  717. CHECK(box.IsActive());
  718. CHECK(activation_listener.GetEntryCount() == 0);
  719. CHECK(!box.GetLinearVelocity().IsNearZero());
  720. // Simulate 5 seconds and check it has settled on the floor and is no longer active
  721. ioContext.Simulate(5.0f);
  722. CHECK_APPROX_EQUAL(box.GetPosition(), Vec3(0, 0.5f, 0), 1.1f * cPenetrationSlop);
  723. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero());
  724. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  725. CHECK(!box.IsActive());
  726. CHECK(activation_listener.GetEntryCount() == 1);
  727. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Deactivated, box.GetID()));
  728. }
  729. TEST_CASE("TestPhysicsActivationDeactivation")
  730. {
  731. PhysicsTestContext c1(1.0f / 60.0f, 1, 1);
  732. TestPhysicsActivationDeactivation(c1);
  733. PhysicsTestContext c2(2.0f / 60.0f, 1, 2);
  734. TestPhysicsActivationDeactivation(c2);
  735. PhysicsTestContext c3(2.0f / 60.0f, 2, 1);
  736. TestPhysicsActivationDeactivation(c3);
  737. PhysicsTestContext c4(4.0f / 60.0f, 4, 1);
  738. TestPhysicsActivationDeactivation(c4);
  739. PhysicsTestContext c5(8.0f / 60.0f, 4, 2);
  740. TestPhysicsActivationDeactivation(c5);
  741. }
  742. // A test that checks that a row of penetrating boxes will all activate and handle collision in 1 frame so that active bodies cannot tunnel through inactive bodies
  743. static void TestPhysicsActivateDuringStep(PhysicsTestContext &ioContext, bool inReverseCreate)
  744. {
  745. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  746. const int cNumBodies = 10;
  747. const float cBoxExtent = 0.5f;
  748. PhysicsSystem *system = ioContext.GetSystem();
  749. BodyInterface &bi = ioContext.GetBodyInterface();
  750. LoggingBodyActivationListener activation_listener;
  751. system->SetBodyActivationListener(&activation_listener);
  752. LoggingContactListener contact_listener;
  753. system->SetContactListener(&contact_listener);
  754. // Create a row of penetrating boxes. Since some of the algorithms rely on body index, we create them normally and reversed to test both cases
  755. BodyIDVector body_ids;
  756. if (inReverseCreate)
  757. for (int i = cNumBodies - 1; i >= 0; --i)
  758. body_ids.insert(body_ids.begin(), ioContext.CreateBox(Vec3(i * (2.0f * cBoxExtent - cPenetrationSlop), 0, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(cBoxExtent), EActivation::DontActivate).GetID());
  759. else
  760. for (int i = 0; i < cNumBodies; ++i)
  761. body_ids.push_back(ioContext.CreateBox(Vec3(i * (2.0f * cBoxExtent - cPenetrationSlop), 0, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::DontActivate).GetID());
  762. // Test that nothing is active yet
  763. CHECK(activation_listener.GetEntryCount() == 0);
  764. CHECK(contact_listener.GetEntryCount() == 0);
  765. for (BodyID id : body_ids)
  766. CHECK(!bi.IsActive(id));
  767. // Activate the left most box and give it a velocity that is high enough to make it tunnel through the second box in a single step
  768. bi.SetLinearVelocity(body_ids.front(), Vec3(500, 0, 0));
  769. // Test that only the left most box is active
  770. CHECK(activation_listener.GetEntryCount() == 1);
  771. CHECK(contact_listener.GetEntryCount() == 0);
  772. CHECK(bi.IsActive(body_ids.front()));
  773. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, body_ids.front()));
  774. for (int i = 1; i < cNumBodies; ++i)
  775. CHECK(!bi.IsActive(body_ids[i]));
  776. activation_listener.Clear();
  777. // Step the world
  778. ioContext.SimulateSingleStep();
  779. // Other bodies should now be awake and each body should only collide with its neighbour
  780. CHECK(activation_listener.GetEntryCount() == cNumBodies - 1);
  781. CHECK(contact_listener.GetEntryCount() == 2 * (cNumBodies - 1));
  782. for (int i = 0; i < cNumBodies; ++i)
  783. {
  784. BodyID id = body_ids[i];
  785. // Check body is active
  786. CHECK(bi.IsActive(id));
  787. // Check that body moved to the right
  788. CHECK(bi.GetPosition(id).GetX() > i * (2.0f * cBoxExtent - cPenetrationSlop));
  789. }
  790. for (int i = 1; i < cNumBodies; ++i)
  791. {
  792. BodyID id1 = body_ids[i - 1];
  793. BodyID id2 = body_ids[i];
  794. // Check that we received activation events for each body
  795. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, id2));
  796. // Check that we received a validate and an add for each body pair
  797. int validate = contact_listener.Find(LoggingContactListener::EType::Validate, id1, id2);
  798. CHECK(validate >= 0);
  799. int add = contact_listener.Find(LoggingContactListener::EType::Add, id1, id2);
  800. CHECK(add >= 0);
  801. CHECK(add > validate);
  802. // Check that bodies did not tunnel through each other
  803. CHECK(bi.GetPosition(id1).GetX() < bi.GetPosition(id2).GetX());
  804. }
  805. }
  806. TEST_CASE("TestPhysicsActivateDuringStep")
  807. {
  808. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  809. TestPhysicsActivateDuringStep(c, false);
  810. PhysicsTestContext c2(1.0f / 60.0f, 1, 1);
  811. TestPhysicsActivateDuringStep(c2, true);
  812. }
  813. TEST_CASE("TestPhysicsBroadPhaseLayers")
  814. {
  815. PhysicsTestContext c(1.0f / 60.0f, 1, 1);
  816. BodyInterface &bi = c.GetBodyInterface();
  817. // Reduce slop
  818. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  819. settings.mPenetrationSlop = 0.0f;
  820. c.GetSystem()->SetPhysicsSettings(settings);
  821. // Create static floor
  822. c.CreateFloor();
  823. // Create MOVING boxes
  824. Body &moving1 = c.CreateBox(Vec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  825. Body &moving2 = c.CreateBox(Vec3(0, 2, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  826. // Create HQ_DEBRIS boxes
  827. Body &hq_debris1 = c.CreateBox(Vec3(0, 3, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  828. Body &hq_debris2 = c.CreateBox(Vec3(0, 4, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  829. // Create LQ_DEBRIS boxes
  830. Body &lq_debris1 = c.CreateBox(Vec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  831. Body &lq_debris2 = c.CreateBox(Vec3(0, 6, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  832. // Check layers
  833. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  834. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  835. CHECK(hq_debris1.GetObjectLayer() == Layers::HQ_DEBRIS);
  836. CHECK(hq_debris2.GetObjectLayer() == Layers::HQ_DEBRIS);
  837. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  838. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  839. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  840. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  841. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  842. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  843. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  844. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  845. // Simulate the boxes falling
  846. c.Simulate(5.0f);
  847. // Everything should sleep
  848. CHECK_FALSE(moving1.IsActive());
  849. CHECK_FALSE(moving2.IsActive());
  850. CHECK_FALSE(hq_debris1.IsActive());
  851. CHECK_FALSE(hq_debris2.IsActive());
  852. CHECK_FALSE(lq_debris1.IsActive());
  853. CHECK_FALSE(lq_debris2.IsActive());
  854. // MOVING boxes should have stacked
  855. float slop = 0.02f;
  856. CHECK_APPROX_EQUAL(moving1.GetPosition(), Vec3(0, 0.5f, 0), slop);
  857. CHECK_APPROX_EQUAL(moving2.GetPosition(), Vec3(0, 1.5f, 0), slop);
  858. // HQ_DEBRIS boxes should have stacked on MOVING boxes but don't collide with each other
  859. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), Vec3(0, 2.5f, 0), slop);
  860. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), Vec3(0, 2.5f, 0), slop);
  861. // LQ_DEBRIS should have fallen through all but the floor
  862. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), Vec3(0, 0.5f, 0), slop);
  863. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), Vec3(0, 0.5f, 0), slop);
  864. // Now change HQ_DEBRIS to LQ_DEBRIS
  865. bi.SetObjectLayer(hq_debris1.GetID(), Layers::LQ_DEBRIS);
  866. bi.SetObjectLayer(hq_debris2.GetID(), Layers::LQ_DEBRIS);
  867. bi.ActivateBody(hq_debris1.GetID());
  868. bi.ActivateBody(hq_debris2.GetID());
  869. // Check layers
  870. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  871. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  872. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  873. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  874. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  875. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  876. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  877. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  878. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  879. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  880. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  881. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  882. // Simulate again
  883. c.Simulate(5.0f);
  884. // Everything should sleep
  885. CHECK_FALSE(moving1.IsActive());
  886. CHECK_FALSE(moving2.IsActive());
  887. CHECK_FALSE(hq_debris1.IsActive());
  888. CHECK_FALSE(hq_debris2.IsActive());
  889. CHECK_FALSE(lq_debris1.IsActive());
  890. CHECK_FALSE(lq_debris2.IsActive());
  891. // MOVING boxes should have stacked
  892. CHECK_APPROX_EQUAL(moving1.GetPosition(), Vec3(0, 0.5f, 0), slop);
  893. CHECK_APPROX_EQUAL(moving2.GetPosition(), Vec3(0, 1.5f, 0), slop);
  894. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  895. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), Vec3(0, 0.5f, 0), slop);
  896. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), Vec3(0, 0.5f, 0), slop);
  897. // LQ_DEBRIS should have fallen through all but the floor
  898. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), Vec3(0, 0.5f, 0), slop);
  899. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), Vec3(0, 0.5f, 0), slop);
  900. // Now change MOVING to HQ_DEBRIS (this doesn't change the broadphase layer so avoids adding/removing bodies)
  901. bi.SetObjectLayer(moving1.GetID(), Layers::HQ_DEBRIS);
  902. bi.SetObjectLayer(moving2.GetID(), Layers::HQ_DEBRIS);
  903. bi.ActivateBody(moving1.GetID());
  904. bi.ActivateBody(moving2.GetID());
  905. // Check layers
  906. CHECK(moving1.GetObjectLayer() == Layers::HQ_DEBRIS);
  907. CHECK(moving2.GetObjectLayer() == Layers::HQ_DEBRIS);
  908. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  909. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  910. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  911. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  912. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING); // Broadphase layer didn't change
  913. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  914. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  915. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  916. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  917. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  918. // Simulate again
  919. c.Simulate(5.0f);
  920. // Everything should sleep
  921. CHECK_FALSE(moving1.IsActive());
  922. CHECK_FALSE(moving2.IsActive());
  923. CHECK_FALSE(hq_debris1.IsActive());
  924. CHECK_FALSE(hq_debris2.IsActive());
  925. CHECK_FALSE(lq_debris1.IsActive());
  926. CHECK_FALSE(lq_debris2.IsActive());
  927. // MOVING boxes now also fall through
  928. CHECK_APPROX_EQUAL(moving1.GetPosition(), Vec3(0, 0.5f, 0), slop);
  929. CHECK_APPROX_EQUAL(moving2.GetPosition(), Vec3(0, 0.5f, 0), slop);
  930. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  931. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), Vec3(0, 0.5f, 0), slop);
  932. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), Vec3(0, 0.5f, 0), slop);
  933. // LQ_DEBRIS should have fallen through all but the floor
  934. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), Vec3(0, 0.5f, 0), slop);
  935. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), Vec3(0, 0.5f, 0), slop);
  936. }
  937. }