PhysicsTests.cpp 54 KB

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