PhysicsTests.cpp 55 KB

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