PhysicsTests.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797
  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/SphereShape.h>
  11. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  12. #include <Jolt/Physics/Collision/Shape/StaticCompoundShape.h>
  13. #include <Jolt/Physics/Body/BodyLockMulti.h>
  14. #include <Jolt/Physics/Constraints/PointConstraint.h>
  15. #include <Jolt/Physics/StateRecorderImpl.h>
  16. TEST_SUITE("PhysicsTests")
  17. {
  18. // Gravity vector
  19. const Vec3 cGravity = Vec3(0.0f, -9.81f, 0.0f);
  20. // Test the test framework's helper functions
  21. TEST_CASE("TestPhysicsTestContext")
  22. {
  23. // Test that the Symplectic Euler integrator is close enough to the real value
  24. const float cSimulationTime = 2.0f;
  25. // For position: x = x0 + v0 * t + 1/2 * a * t^2
  26. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  27. PhysicsTestContext c;
  28. RVec3 simulated_pos = c.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  29. RVec3 integrated_position = cInitialPos + 0.5f * cGravity * Square(cSimulationTime);
  30. CHECK_APPROX_EQUAL(integrated_position, simulated_pos, 0.2f);
  31. // For rotation
  32. const Quat cInitialRot(Quat::sRotation(Vec3::sAxisY(), 0.1f));
  33. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  34. Quat simulated_rot = c.PredictOrientation(cInitialRot, Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  35. Vec3 integrated_acceleration = 0.5f * cAngularAcceleration * Square(cSimulationTime);
  36. float integrated_acceleration_len = integrated_acceleration.Length();
  37. Quat integrated_rot = Quat::sRotation(integrated_acceleration / integrated_acceleration_len, integrated_acceleration_len) * cInitialRot;
  38. CHECK_APPROX_EQUAL(integrated_rot, simulated_rot, 0.02f);
  39. }
  40. TEST_CASE("TestPhysicsBodyLock")
  41. {
  42. PhysicsTestContext c;
  43. // Check that we cannot lock the invalid body ID
  44. {
  45. BodyLockRead lock(c.GetSystem()->GetBodyLockInterface(), BodyID());
  46. CHECK_FALSE(lock.Succeeded());
  47. CHECK_FALSE(lock.SucceededAndIsInBroadPhase());
  48. }
  49. BodyID body1_id;
  50. {
  51. // Create a box
  52. Body &body1 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  53. body1_id = body1.GetID();
  54. CHECK(body1_id.GetIndex() == 0);
  55. CHECK(body1_id.GetSequenceNumber() == 1);
  56. // Create another box
  57. Body &body2 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  58. BodyID body2_id = body2.GetID();
  59. CHECK(body2_id.GetIndex() == 1);
  60. CHECK(body2_id.GetSequenceNumber() == 1);
  61. // Check that we can lock the first box
  62. {
  63. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  64. CHECK(lock1.Succeeded());
  65. CHECK(lock1.SucceededAndIsInBroadPhase());
  66. }
  67. // Remove the first box
  68. c.GetSystem()->GetBodyInterface().RemoveBody(body1_id);
  69. // Check that we can lock the first box
  70. {
  71. BodyLockWrite lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  72. CHECK(lock1.Succeeded());
  73. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  74. }
  75. // Destroy the first box
  76. c.GetSystem()->GetBodyInterface().DestroyBody(body1_id);
  77. // Check that we can not lock the body anymore
  78. {
  79. BodyLockWrite lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  80. CHECK_FALSE(lock1.Succeeded());
  81. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  82. }
  83. }
  84. // Create another box
  85. Body &body3 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  86. BodyID body3_id = body3.GetID();
  87. CHECK(body3_id.GetIndex() == 0); // Check index reused
  88. CHECK(body3_id.GetSequenceNumber() == 2); // Check sequence number changed
  89. // Check that we can lock it
  90. {
  91. BodyLockRead lock3(c.GetSystem()->GetBodyLockInterface(), body3_id);
  92. CHECK(lock3.Succeeded());
  93. CHECK(lock3.SucceededAndIsInBroadPhase());
  94. }
  95. // Check that we can't lock the old body with the same body index anymore
  96. {
  97. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  98. CHECK_FALSE(lock1.Succeeded());
  99. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  100. }
  101. }
  102. TEST_CASE("TestPhysicsBodyLockMulti")
  103. {
  104. PhysicsTestContext c;
  105. // Check that we cannot lock the invalid body ID
  106. {
  107. BodyID bodies[] = { BodyID(), BodyID() };
  108. BodyLockMultiRead lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  109. CHECK(lock.GetBody(0) == nullptr);
  110. CHECK(lock.GetBody(1) == nullptr);
  111. }
  112. {
  113. // Create two bodies
  114. Body &body1 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  115. Body &body2 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sReplicate(1.0f));
  116. BodyID bodies[] = { body1.GetID(), body2.GetID() };
  117. {
  118. // Lock the bodies
  119. BodyLockMultiWrite lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  120. CHECK(lock.GetBody(0) == &body1);
  121. CHECK(lock.GetBody(1) == &body2);
  122. }
  123. // Destroy body 1
  124. c.GetSystem()->GetBodyInterface().RemoveBody(bodies[0]);
  125. c.GetSystem()->GetBodyInterface().DestroyBody(bodies[0]);
  126. {
  127. // Lock the bodies
  128. BodyLockMultiRead lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  129. CHECK(lock.GetBody(0) == nullptr);
  130. CHECK(lock.GetBody(1) == &body2);
  131. }
  132. }
  133. }
  134. TEST_CASE("TestPhysicsBodyID")
  135. {
  136. {
  137. BodyID body_id(0);
  138. CHECK(body_id.GetIndex() == 0);
  139. CHECK(body_id.GetSequenceNumber() == 0);
  140. }
  141. {
  142. BodyID body_id(~BodyID::cBroadPhaseBit);
  143. CHECK(body_id.GetIndex() == BodyID::cMaxBodyIndex);
  144. CHECK(body_id.GetSequenceNumber() == BodyID::cMaxSequenceNumber);
  145. }
  146. }
  147. TEST_CASE("TestPhysicsBodyIDSequenceNumber")
  148. {
  149. PhysicsTestContext c;
  150. BodyInterface &bi = c.GetBodyInterface();
  151. // Create a body and check it's id
  152. BodyID body0_id = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1)).GetID();
  153. CHECK(body0_id == BodyID(0, 1)); // Body 0, sequence number 1
  154. // Check that the sequence numbers aren't reused until after 256 iterations
  155. for (int seq_no = 1; seq_no < 258; ++seq_no)
  156. {
  157. BodyID body1_id = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1)).GetID();
  158. CHECK(body1_id == BodyID(1, uint8(seq_no))); // Body 1
  159. bi.RemoveBody(body1_id);
  160. bi.DestroyBody(body1_id);
  161. }
  162. bi.RemoveBody(body0_id);
  163. bi.DestroyBody(body0_id);
  164. }
  165. TEST_CASE("TestPhysicsBodyIDOverride")
  166. {
  167. PhysicsTestContext c;
  168. BodyInterface &bi = c.GetBodyInterface();
  169. // Dummy creation settings
  170. BodyCreationSettings bc(new BoxShape(Vec3::sReplicate(1.0f)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  171. // Create a body
  172. Body *b1 = bi.CreateBody(bc);
  173. CHECK(b1->GetID() == BodyID(0, 1));
  174. // Create body with same ID and same sequence number
  175. Body *b2 = bi.CreateBodyWithID(BodyID(0, 1), bc);
  176. CHECK(b2 == nullptr);
  177. // Create body with same ID and different sequence number
  178. b2 = bi.CreateBodyWithID(BodyID(0, 2), bc);
  179. CHECK(b2 == nullptr);
  180. // Create body with different ID (leave 1 open slot)
  181. b2 = bi.CreateBodyWithoutID(bc); // Using syntax that allows separation of allocation and assigning an ID
  182. CHECK(b2 != nullptr);
  183. CHECK(b2->GetID().IsInvalid());
  184. bi.AssignBodyID(b2, BodyID(2, 1));
  185. CHECK(b2->GetID() == BodyID(2, 1));
  186. // Create another body and check that the open slot is returned
  187. Body *b3 = bi.CreateBody(bc);
  188. CHECK(b3->GetID() == BodyID(1, 1));
  189. // Create another body and check that we do not hand out the body with specified ID
  190. Body *b4 = bi.CreateBody(bc);
  191. CHECK(b4->GetID() == BodyID(3, 1));
  192. // Delete and recreate body 4
  193. CHECK(bi.CreateBodyWithID(BodyID(3, 1), bc) == nullptr);
  194. bi.DestroyBody(b4->GetID());
  195. b4 = bi.CreateBodyWithID(BodyID(3, 1), bc);
  196. CHECK(b4 != nullptr);
  197. CHECK(b4->GetID() == BodyID(3, 1));
  198. // Destroy 1st body
  199. CHECK(bi.UnassignBodyID(b1->GetID()) == b1); // Use syntax that allows separation of unassigning and deallocation
  200. CHECK(b1->GetID().IsInvalid());
  201. bi.DestroyBodyWithoutID(b1);
  202. // Clean up remaining bodies
  203. bi.DestroyBody(b2->GetID());
  204. bi.DestroyBody(b3->GetID());
  205. bi.DestroyBody(b4->GetID());
  206. // Recreate body 1
  207. b1 = bi.CreateBodyWithID(BodyID(0, 1), bc);
  208. CHECK(b1 != nullptr);
  209. CHECK(b1->GetID() == BodyID(0, 1));
  210. // Destroy last body
  211. bi.DestroyBody(b1->GetID());
  212. }
  213. TEST_CASE("TestPhysicsBodyUserData")
  214. {
  215. PhysicsTestContext c;
  216. BodyInterface &bi = c.GetBodyInterface();
  217. // Create a body and pass user data through the creation settings
  218. BodyCreationSettings body_settings(new BoxShape(Vec3::sReplicate(1.0f)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  219. body_settings.mUserData = 0x1234567887654321;
  220. Body *body = bi.CreateBody(body_settings);
  221. CHECK(body->GetUserData() == 0x1234567887654321);
  222. // Change the user data
  223. body->SetUserData(0x5678123443218765);
  224. CHECK(body->GetUserData() == 0x5678123443218765);
  225. // Convert back to body settings
  226. BodyCreationSettings body_settings2 = body->GetBodyCreationSettings();
  227. CHECK(body_settings2.mUserData == 0x5678123443218765);
  228. }
  229. TEST_CASE("TestPhysicsConstraintUserData")
  230. {
  231. PhysicsTestContext c;
  232. // Create a body
  233. Body &body = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f));
  234. // Create constraint with user data
  235. PointConstraintSettings constraint_settings;
  236. constraint_settings.mUserData = 0x1234567887654321;
  237. Ref<Constraint> constraint = constraint_settings.Create(body, Body::sFixedToWorld);
  238. CHECK(constraint->GetUserData() == 0x1234567887654321);
  239. // Change the user data
  240. constraint->SetUserData(0x5678123443218765);
  241. CHECK(constraint->GetUserData() == 0x5678123443218765);
  242. // Convert back to constraint settings
  243. Ref<ConstraintSettings> constraint_settings2 = constraint->GetConstraintSettings();
  244. CHECK(constraint_settings2->mUserData == 0x5678123443218765);
  245. }
  246. TEST_CASE("TestPhysicsPosition")
  247. {
  248. PhysicsTestContext c;
  249. BodyInterface &bi = c.GetBodyInterface();
  250. // Translate / rotate the box
  251. Vec3 box_pos(1, 2, 3);
  252. Quat box_rotation = Quat::sRotation(Vec3::sAxisX(), 0.25f * JPH_PI);
  253. // Translate / rotate the body
  254. RVec3 body_pos(4, 5, 6);
  255. Quat body_rotation = Quat::sRotation(Vec3::sAxisY(), 0.3f * JPH_PI);
  256. RMat44 body_transform = RMat44::sRotationTranslation(body_rotation, body_pos);
  257. RMat44 com_transform = body_transform * Mat44::sTranslation(box_pos);
  258. // Create body
  259. BodyCreationSettings body_settings(new RotatedTranslatedShapeSettings(box_pos, box_rotation, new BoxShape(Vec3::sReplicate(1.0f))), body_pos, body_rotation, EMotionType::Static, Layers::NON_MOVING);
  260. Body *body = bi.CreateBody(body_settings);
  261. // Check that the correct positions / rotations are reported
  262. CHECK_APPROX_EQUAL(body->GetPosition(), body_pos);
  263. CHECK_APPROX_EQUAL(body->GetRotation(), body_rotation);
  264. CHECK_APPROX_EQUAL(body->GetWorldTransform(), body_transform);
  265. CHECK_APPROX_EQUAL(body->GetCenterOfMassPosition(), com_transform.GetTranslation());
  266. CHECK_APPROX_EQUAL(body->GetCenterOfMassTransform(), com_transform);
  267. CHECK_APPROX_EQUAL(body->GetInverseCenterOfMassTransform(), com_transform.InversedRotationTranslation(), 1.0e-5f);
  268. }
  269. TEST_CASE("TestPhysicsOverrideMassAndInertia")
  270. {
  271. PhysicsTestContext c;
  272. BodyInterface &bi = c.GetBodyInterface();
  273. const float cDensity = 1234.0f;
  274. const Vec3 cBoxExtent(2.0f, 4.0f, 6.0f);
  275. const float cExpectedMass = cBoxExtent.GetX() * cBoxExtent.GetY() * cBoxExtent.GetZ() * cDensity;
  276. // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  277. const Vec3 cSquaredExtents = Vec3(Square(cBoxExtent.GetY()) + Square(cBoxExtent.GetZ()), Square(cBoxExtent.GetX()) + Square(cBoxExtent.GetZ()), Square(cBoxExtent.GetX()) + Square(cBoxExtent.GetY()));
  278. const Vec3 cExpectedInertiaDiagonal = cExpectedMass / 12.0f * cSquaredExtents;
  279. Ref<BoxShapeSettings> shape_settings = new BoxShapeSettings(0.5f * cBoxExtent);
  280. shape_settings->SetDensity(cDensity);
  281. BodyCreationSettings body_settings(shape_settings, RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  282. // Create body as is
  283. Body &b1 = *bi.CreateBody(body_settings);
  284. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseMass(), 1.0f / cExpectedMass);
  285. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  286. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseInertiaDiagonal(), cExpectedInertiaDiagonal.Reciprocal());
  287. // Override only the mass
  288. const float cOverriddenMass = 13.0f;
  289. const Vec3 cOverriddenMassInertiaDiagonal = cOverriddenMass / 12.0f * cSquaredExtents;
  290. body_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  291. body_settings.mMassPropertiesOverride.mMass = cOverriddenMass;
  292. Body &b2 = *bi.CreateBody(body_settings);
  293. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  294. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  295. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenMassInertiaDiagonal.Reciprocal());
  296. // Override both the mass and inertia
  297. 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
  298. const Quat cOverriddenInertiaRotation = Quat::sRotation(Vec3(1, 1, 1).Normalized(), 0.1f * JPH_PI);
  299. body_settings.mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
  300. body_settings.mMassPropertiesOverride.mInertia = Mat44::sRotation(cOverriddenInertiaRotation) * Mat44::sScale(cOverriddenInertiaDiagonal) * Mat44::sRotation(cOverriddenInertiaRotation.Inversed());
  301. Body &b3 = *bi.CreateBody(body_settings);
  302. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  303. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInertiaRotation(), cOverriddenInertiaRotation);
  304. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenInertiaDiagonal.Reciprocal());
  305. }
  306. // Test a box free falling under gravity
  307. static void TestPhysicsFreeFall(PhysicsTestContext &ioContext)
  308. {
  309. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  310. const float cSimulationTime = 2.0f;
  311. // Create box
  312. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  313. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  314. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  315. ioContext.Simulate(cSimulationTime);
  316. // Test resulting velocity (due to gravity)
  317. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  318. // Test resulting position
  319. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  320. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  321. }
  322. TEST_CASE("TestPhysicsFreeFall")
  323. {
  324. PhysicsTestContext c;
  325. TestPhysicsFreeFall(c);
  326. }
  327. TEST_CASE("TestPhysicsFreeFallStep")
  328. {
  329. PhysicsTestContext c1(2.0f / 60.0f, 2);
  330. TestPhysicsFreeFall(c1);
  331. PhysicsTestContext c2(4.0f / 60.0f, 4);
  332. TestPhysicsFreeFall(c2);
  333. }
  334. // Test acceleration of a box with force applied
  335. static void TestPhysicsApplyForce(PhysicsTestContext &ioContext)
  336. {
  337. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  338. const Vec3 cAcceleration(2.0f, 0.0f, 0.0f);
  339. const float cSimulationTime = 2.0f;
  340. // Create box
  341. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  342. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  343. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  344. // Validate mass
  345. float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  346. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  347. // Simulate while applying force
  348. ioContext.Simulate(cSimulationTime, [&]() { body.AddForce(mass * cAcceleration); });
  349. // Test resulting velocity (due to gravity and applied force)
  350. CHECK_APPROX_EQUAL(cSimulationTime * (cGravity + cAcceleration), body.GetLinearVelocity(), 1.0e-4f);
  351. // Test resulting position
  352. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity + cAcceleration, cSimulationTime);
  353. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  354. }
  355. TEST_CASE("TestPhysicsApplyForce")
  356. {
  357. PhysicsTestContext c;
  358. TestPhysicsApplyForce(c);
  359. }
  360. TEST_CASE("TestPhysicsApplyForceStep")
  361. {
  362. PhysicsTestContext c1(2.0f / 60.0f, 2);
  363. TestPhysicsApplyForce(c1);
  364. PhysicsTestContext c2(4.0f / 60.0f, 4);
  365. TestPhysicsApplyForce(c2);
  366. }
  367. // Test angular accelartion for a box by applying torque every frame
  368. static void TestPhysicsApplyTorque(PhysicsTestContext &ioContext)
  369. {
  370. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  371. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  372. const float cSimulationTime = 2.0f;
  373. // Create box
  374. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  375. CHECK_APPROX_EQUAL(Quat::sIdentity(), body.GetRotation());
  376. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  377. // Validate mass and inertia
  378. constexpr float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  379. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  380. constexpr float inertia = mass * 8.0f / 12.0f; // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  381. CHECK_APPROX_EQUAL(Mat44::sScale(1.0f / inertia), body.GetMotionProperties()->GetLocalSpaceInverseInertia());
  382. // Simulate while applying torque
  383. ioContext.Simulate(cSimulationTime, [&]() { body.AddTorque(inertia * cAngularAcceleration); });
  384. // Get resulting angular velocity
  385. CHECK_APPROX_EQUAL(cSimulationTime * cAngularAcceleration, body.GetAngularVelocity(), 1.0e-4f);
  386. // Test resulting rotation
  387. Quat expected_rot = ioContext.PredictOrientation(Quat::sIdentity(), Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  388. CHECK_APPROX_EQUAL(expected_rot, body.GetRotation(), 1.0e-4f);
  389. }
  390. TEST_CASE("TestPhysicsApplyTorque")
  391. {
  392. PhysicsTestContext c;
  393. TestPhysicsApplyTorque(c);
  394. }
  395. TEST_CASE("TestPhysicsApplyTorqueStep")
  396. {
  397. PhysicsTestContext c1(2.0f / 60.0f, 2);
  398. TestPhysicsApplyTorque(c1);
  399. PhysicsTestContext c2(4.0f / 60.0f, 4);
  400. TestPhysicsApplyTorque(c2);
  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 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.GetStepDeltaTime();
  426. float remaining_step_time = ioContext.GetDeltaTime() - ioContext.GetStepDeltaTime();
  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;
  444. TestPhysicsCollisionElastic(c);
  445. }
  446. TEST_CASE("TestPhysicsCollisionElasticStep")
  447. {
  448. PhysicsTestContext c1(2.0f / 60.0f, 2);
  449. TestPhysicsCollisionElastic(c1);
  450. PhysicsTestContext c2(4.0f / 60.0f, 4);
  451. TestPhysicsCollisionElastic(c2);
  452. }
  453. // Let a sphere bounce on the floor with restitution = 0
  454. static void TestPhysicsCollisionInelastic(PhysicsTestContext &ioContext)
  455. {
  456. const float cSimulationTime = 1.0f;
  457. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  458. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  459. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  460. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  461. // Create sphere
  462. ioContext.CreateFloor();
  463. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  464. body.SetRestitution(0.0f);
  465. // Simulate until at floor
  466. ioContext.Simulate(cSimulationTime);
  467. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  468. // Assert collision not yet processed
  469. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  470. // Simulate one more step to process the collision
  471. ioContext.Simulate(ioContext.GetDeltaTime());
  472. // Assert that all velocity was lost in the collision
  473. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  474. // Assert that we're on the floor
  475. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  476. // Simulate some more to validate that we remain on the floor
  477. ioContext.Simulate(cSimulationTime);
  478. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  479. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  480. }
  481. TEST_CASE("TestPhysicsCollisionInelastic")
  482. {
  483. PhysicsTestContext c;
  484. TestPhysicsCollisionInelastic(c);
  485. }
  486. TEST_CASE("TestPhysicsCollisionInelasticStep")
  487. {
  488. PhysicsTestContext c1(2.0f / 60.0f, 2);
  489. TestPhysicsCollisionInelastic(c1);
  490. PhysicsTestContext c2(4.0f / 60.0f, 4);
  491. TestPhysicsCollisionInelastic(c2);
  492. }
  493. // Let box intersect with floor by cPenetrationSlop. It should not move, this is the maximum penetration allowed.
  494. static void TestPhysicsPenetrationSlop1(PhysicsTestContext &ioContext)
  495. {
  496. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  497. const float cSimulationTime = 1.0f;
  498. const RVec3 cInitialPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  499. // Create box, penetrating with floor
  500. ioContext.CreateFloor();
  501. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  502. // Simulate
  503. ioContext.Simulate(cSimulationTime);
  504. // Test slop not resolved
  505. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  506. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  507. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  508. }
  509. TEST_CASE("TestPhysicsPenetrationSlop1")
  510. {
  511. PhysicsTestContext c;
  512. TestPhysicsPenetrationSlop1(c);
  513. }
  514. TEST_CASE("TestPhysicsPenetrationSlop1Step")
  515. {
  516. PhysicsTestContext c(2.0f / 60.0f, 2);
  517. TestPhysicsPenetrationSlop1(c);
  518. PhysicsTestContext c2(4.0f / 60.0f, 4);
  519. TestPhysicsPenetrationSlop1(c2);
  520. }
  521. // Let box intersect with floor with more than cPenetrationSlop. It should be resolved by SolvePositionConstraint until interpenetration is cPenetrationSlop.
  522. static void TestPhysicsPenetrationSlop2(PhysicsTestContext &ioContext)
  523. {
  524. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  525. const float cSimulationTime = 1.0f;
  526. const RVec3 cInitialPos(0.0f, 1.0f - 2.0f * cPenetrationSlop, 0.0f);
  527. const RVec3 cFinalPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  528. // Create box, penetrating with floor
  529. ioContext.CreateFloor();
  530. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  531. // Simulate
  532. ioContext.Simulate(cSimulationTime);
  533. // Test resolved until slop
  534. CHECK_APPROX_EQUAL(cFinalPos, body.GetPosition(), 1.0e-5f);
  535. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  536. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  537. }
  538. TEST_CASE("TestPhysicsPenetrationSlop2")
  539. {
  540. PhysicsTestContext c;
  541. TestPhysicsPenetrationSlop2(c);
  542. }
  543. TEST_CASE("TestPhysicsPenetrationSlop2Step")
  544. {
  545. PhysicsTestContext c(2.0f / 60.0f, 2);
  546. TestPhysicsPenetrationSlop2(c);
  547. PhysicsTestContext c2(4.0f / 60.0f, 4);
  548. TestPhysicsPenetrationSlop2(c2);
  549. }
  550. // Let box intersect with floor with less than cPenetrationSlop. Body should not move because SolveVelocityConstraint should reset velocity.
  551. static void TestPhysicsPenetrationSlop3(PhysicsTestContext &ioContext)
  552. {
  553. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  554. const float cSimulationTime = 1.0f;
  555. const RVec3 cInitialPos(0.0f, 1.0f - 0.1f * cPenetrationSlop, 0.0f);
  556. // Create box, penetrating with floor
  557. ioContext.CreateFloor();
  558. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  559. // Simulate
  560. ioContext.Simulate(cSimulationTime);
  561. // Test body remained static
  562. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  563. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  564. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  565. }
  566. TEST_CASE("TestPhysicsPenetrationSlop3")
  567. {
  568. PhysicsTestContext c;
  569. TestPhysicsPenetrationSlop3(c);
  570. }
  571. TEST_CASE("TestPhysicsPenetrationSlop3Step")
  572. {
  573. PhysicsTestContext c(2.0f / 60.0f, 2);
  574. TestPhysicsPenetrationSlop3(c);
  575. PhysicsTestContext c2(4.0f / 60.0f, 4);
  576. TestPhysicsPenetrationSlop3(c2);
  577. }
  578. TEST_CASE("TestPhysicsOutsideOfSpeculativeContactDistance")
  579. {
  580. PhysicsTestContext c;
  581. Body &floor = c.CreateFloor();
  582. c.ZeroGravity();
  583. LoggingContactListener contact_listener;
  584. c.GetSystem()->SetContactListener(&contact_listener);
  585. // Create a box and a sphere just outside the speculative contact distance
  586. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  587. const float cDistanceAboveFloor = 1.1f * cSpeculativeContactDistance;
  588. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  589. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  590. // Make it move 1 m per step down
  591. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  592. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  593. box.SetLinearVelocity(cVelocity);
  594. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  595. sphere.SetLinearVelocity(cVelocity);
  596. // Simulate a step
  597. c.SimulateSingleStep();
  598. // 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)
  599. CHECK(contact_listener.GetEntryCount() == 0);
  600. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  601. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  602. // Simulate a step
  603. c.SimulateSingleStep();
  604. // Check that the contacts are detected now
  605. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  606. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  607. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  608. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  609. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  610. }
  611. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoRestitution")
  612. {
  613. PhysicsTestContext c;
  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 inside the speculative contact distance
  619. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  620. const float cDistanceAboveFloor = 0.9f * 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 on the floor and that 2 collisions have been detected
  632. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  633. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  634. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  635. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  636. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  637. contact_listener.Clear();
  638. // Velocity should have been reduced to exactly hit the floor in this step
  639. const Vec3 cExpectedVelocity(0, -cDistanceAboveFloor / c.GetDeltaTime(), 0);
  640. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  641. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  642. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cExpectedVelocity, 0.05f);
  643. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  644. // Sphere has only 1 contact point so is much more accurate
  645. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0));
  646. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cExpectedVelocity, 1.0e-4f);
  647. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  648. // Simulate a step
  649. c.SimulateSingleStep();
  650. // Check that the contacts persisted
  651. CHECK(contact_listener.GetEntryCount() >= 2); // 2 persist and possibly 2 validates depending on if the cache got reused
  652. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, box.GetID(), floor.GetID()));
  653. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  654. // Box should have come to rest
  655. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  656. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero(), 0.05f);
  657. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  658. // Sphere should have come to rest
  659. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0), 1.0e-4f);
  660. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), Vec3::sZero(), 1.0e-4f);
  661. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  662. }
  663. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceWithRestitution")
  664. {
  665. PhysicsTestContext c;
  666. Body &floor = c.CreateFloor();
  667. c.ZeroGravity();
  668. LoggingContactListener contact_listener;
  669. c.GetSystem()->SetContactListener(&contact_listener);
  670. // Create a box and a sphere just inside the speculative contact distance
  671. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  672. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  673. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  674. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  675. // Make it move 1 m per step down
  676. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  677. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  678. box.SetLinearVelocity(cVelocity);
  679. box.SetRestitution(1.0f);
  680. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  681. sphere.SetLinearVelocity(cVelocity);
  682. sphere.SetRestitution(1.0f);
  683. // Simulate a step
  684. c.SimulateSingleStep();
  685. // 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)
  686. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  687. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  688. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  689. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  690. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  691. contact_listener.Clear();
  692. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  693. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox - cVelocity * c.GetDeltaTime(), 0.01f);
  694. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), -cVelocity, 0.1f);
  695. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 0.02f);
  696. // Sphere has only 1 contact point so is much more accurate
  697. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere - cVelocity * c.GetDeltaTime(), 1.0e-5f);
  698. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), -cVelocity, 2.0e-4f);
  699. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 2.0e-4f);
  700. // Simulate a step
  701. c.SimulateSingleStep();
  702. // Check that all contact points are removed
  703. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  704. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  705. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  706. }
  707. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoHit")
  708. {
  709. PhysicsTestContext c;
  710. Body &floor = c.CreateFloor();
  711. floor.SetRestitution(1.0f);
  712. c.ZeroGravity();
  713. // Turn off the minimum velocity for restitution, our velocity is lower than the default
  714. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  715. settings.mMinVelocityForRestitution = 0.0f;
  716. c.GetSystem()->SetPhysicsSettings(settings);
  717. LoggingContactListener contact_listener;
  718. c.GetSystem()->SetContactListener(&contact_listener);
  719. // Create a sphere inside speculative contact distance from the ground
  720. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  721. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  722. const RVec3 cInitialPosSphere(0, 1.0f + cDistanceAboveFloor, 0.0f);
  723. // Make it move slow enough so that it will not touch the floor in 1 time step
  724. const Vec3 cVelocity(0, -0.9f * cDistanceAboveFloor / c.GetDeltaTime(), 0);
  725. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  726. sphere.SetLinearVelocity(cVelocity);
  727. sphere.SetRestitution(1.0f);
  728. sphere.GetMotionProperties()->SetLinearDamping(0.0f);
  729. // Simulate a step
  730. c.SimulateSingleStep();
  731. // Check that it has triggered contact points from the speculative contacts
  732. CHECK(contact_listener.GetEntryCount() == 2);
  733. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  734. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  735. contact_listener.Clear();
  736. // Check that sphere didn't actually change velocity (it hasn't actually interacted with the floor, the speculative contact was not an actual contact)
  737. CHECK(sphere.GetLinearVelocity() == cVelocity);
  738. // Simulate a step
  739. c.SimulateSingleStep();
  740. // Check again that it triggered contact points
  741. CHECK(contact_listener.GetEntryCount() == 2);
  742. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  743. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  744. contact_listener.Clear();
  745. // It should have bounced back up and inverted velocity due to restitution being 1
  746. CHECK_APPROX_EQUAL(-sphere.GetLinearVelocity(), cVelocity);
  747. }
  748. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceSensor")
  749. {
  750. PhysicsTestContext c;
  751. Body &floor = c.CreateFloor();
  752. c.ZeroGravity();
  753. LoggingContactListener contact_listener;
  754. c.GetSystem()->SetContactListener(&contact_listener);
  755. // Create a sphere sensor just inside the speculative contact distance
  756. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  757. const float cRadius = 1.0f;
  758. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  759. const RVec3 cInitialPosSphere(5, cRadius + cDistanceAboveFloor, 0);
  760. // Make it move 1 m per step down
  761. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  762. Body &sphere = c.CreateSphere(cInitialPosSphere, cRadius, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  763. sphere.SetIsSensor(true);
  764. sphere.SetLinearVelocity(cVelocity);
  765. // Simulate a step
  766. c.SimulateSingleStep();
  767. CHECK(contact_listener.GetEntryCount() == 0); // We're inside the speculative contact distance but we're a sensor so we shouldn't trigger any contacts
  768. // Simulate a step
  769. c.SimulateSingleStep();
  770. // Check that we're now actually intersecting
  771. CHECK(contact_listener.GetEntryCount() == 2); // 1 validates and 1 contact
  772. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  773. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  774. contact_listener.Clear();
  775. // Sensor should not be affected by the floor
  776. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + 2.0f * c.GetDeltaTime() * cVelocity);
  777. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  778. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  779. }
  780. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceMovingAway")
  781. {
  782. PhysicsTestContext c;
  783. Body &floor = c.CreateFloor();
  784. c.ZeroGravity();
  785. LoggingContactListener contact_listener;
  786. c.GetSystem()->SetContactListener(&contact_listener);
  787. // Create a box and a sphere just inside the speculative contact distance
  788. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  789. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  790. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  791. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  792. // Make it move 1 m per step up
  793. const Vec3 cVelocity(0, 1.0f / c.GetDeltaTime(), 0);
  794. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  795. box.SetLinearVelocity(cVelocity);
  796. box.SetRestitution(1.0f);
  797. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  798. sphere.SetLinearVelocity(cVelocity);
  799. sphere.SetRestitution(1.0f);
  800. // Simulate a step
  801. c.SimulateSingleStep();
  802. // 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)
  803. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  804. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  805. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  806. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  807. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  808. contact_listener.Clear();
  809. // Box should have moved unimpeded
  810. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  811. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cVelocity);
  812. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  813. // Sphere should have moved unimpeded
  814. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  815. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  816. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  817. // Simulate a step
  818. c.SimulateSingleStep();
  819. // Check that all contact points are removed
  820. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  821. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  822. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  823. }
  824. static void TestPhysicsActivationDeactivation(PhysicsTestContext &ioContext)
  825. {
  826. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  827. // Install activation listener
  828. LoggingBodyActivationListener activation_listener;
  829. ioContext.GetSystem()->SetBodyActivationListener(&activation_listener);
  830. // Create floor
  831. Body &floor = ioContext.CreateBox(RVec3(0, -1, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100, 1, 100));
  832. CHECK(!floor.IsActive());
  833. // Create inactive box
  834. Body &box = ioContext.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::DontActivate);
  835. CHECK(!box.IsActive());
  836. CHECK(activation_listener.GetEntryCount() == 0);
  837. // Box should not activate by itself
  838. ioContext.Simulate(1.0f);
  839. CHECK(box.GetPosition() == RVec3(0, 5, 0));
  840. CHECK(!box.IsActive());
  841. CHECK(activation_listener.GetEntryCount() == 0);
  842. // Activate the body and validate it is active now
  843. ioContext.GetBodyInterface().ActivateBody(box.GetID());
  844. CHECK(box.IsActive());
  845. CHECK(box.GetLinearVelocity().IsNearZero());
  846. CHECK(activation_listener.GetEntryCount() == 1);
  847. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, box.GetID()));
  848. activation_listener.Clear();
  849. // Do a single step and check that the body is still active and has gained some velocity
  850. ioContext.SimulateSingleStep();
  851. CHECK(box.IsActive());
  852. CHECK(activation_listener.GetEntryCount() == 0);
  853. CHECK(!box.GetLinearVelocity().IsNearZero());
  854. // Simulate 5 seconds and check it has settled on the floor and is no longer active
  855. ioContext.Simulate(5.0f);
  856. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 0.5f, 0), 1.1f * cPenetrationSlop);
  857. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero());
  858. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  859. CHECK(!box.IsActive());
  860. CHECK(activation_listener.GetEntryCount() == 1);
  861. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Deactivated, box.GetID()));
  862. }
  863. TEST_CASE("TestPhysicsActivationDeactivation")
  864. {
  865. PhysicsTestContext c1(1.0f / 60.0f, 1);
  866. TestPhysicsActivationDeactivation(c1);
  867. PhysicsTestContext c2(2.0f / 60.0f, 2);
  868. TestPhysicsActivationDeactivation(c2);
  869. PhysicsTestContext c3(4.0f / 60.0f, 4);
  870. TestPhysicsActivationDeactivation(c3);
  871. }
  872. // 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
  873. static void TestPhysicsActivateDuringStep(PhysicsTestContext &ioContext, bool inReverseCreate)
  874. {
  875. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  876. const int cNumBodies = 10;
  877. const float cBoxExtent = 0.5f;
  878. PhysicsSystem *system = ioContext.GetSystem();
  879. BodyInterface &bi = ioContext.GetBodyInterface();
  880. LoggingBodyActivationListener activation_listener;
  881. system->SetBodyActivationListener(&activation_listener);
  882. LoggingContactListener contact_listener;
  883. system->SetContactListener(&contact_listener);
  884. // 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
  885. BodyIDVector body_ids;
  886. if (inReverseCreate)
  887. for (int i = cNumBodies - 1; i >= 0; --i)
  888. 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());
  889. else
  890. for (int i = 0; i < cNumBodies; ++i)
  891. 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());
  892. // Test that nothing is active yet
  893. CHECK(activation_listener.GetEntryCount() == 0);
  894. CHECK(contact_listener.GetEntryCount() == 0);
  895. for (BodyID id : body_ids)
  896. CHECK(!bi.IsActive(id));
  897. // 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
  898. bi.SetLinearVelocity(body_ids.front(), Vec3(500, 0, 0));
  899. // Test that only the left most box is active
  900. CHECK(activation_listener.GetEntryCount() == 1);
  901. CHECK(contact_listener.GetEntryCount() == 0);
  902. CHECK(bi.IsActive(body_ids.front()));
  903. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, body_ids.front()));
  904. for (int i = 1; i < cNumBodies; ++i)
  905. CHECK(!bi.IsActive(body_ids[i]));
  906. activation_listener.Clear();
  907. // Step the world
  908. ioContext.SimulateSingleStep();
  909. // Other bodies should now be awake and each body should only collide with its neighbour
  910. CHECK(activation_listener.GetEntryCount() == cNumBodies - 1);
  911. CHECK(contact_listener.GetEntryCount() == 2 * (cNumBodies - 1));
  912. for (int i = 0; i < cNumBodies; ++i)
  913. {
  914. BodyID id = body_ids[i];
  915. // Check body is active
  916. CHECK(bi.IsActive(id));
  917. // Check that body moved to the right
  918. CHECK(bi.GetPosition(id).GetX() > i * (2.0f * cBoxExtent - cPenetrationSlop));
  919. }
  920. for (int i = 1; i < cNumBodies; ++i)
  921. {
  922. BodyID id1 = body_ids[i - 1];
  923. BodyID id2 = body_ids[i];
  924. // Check that we received activation events for each body
  925. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, id2));
  926. // Check that we received a validate and an add for each body pair
  927. int validate = contact_listener.Find(LoggingContactListener::EType::Validate, id1, id2);
  928. CHECK(validate >= 0);
  929. int add = contact_listener.Find(LoggingContactListener::EType::Add, id1, id2);
  930. CHECK(add >= 0);
  931. CHECK(add > validate);
  932. // Check that bodies did not tunnel through each other
  933. CHECK(bi.GetPosition(id1).GetX() < bi.GetPosition(id2).GetX());
  934. }
  935. }
  936. TEST_CASE("TestPhysicsActivateDuringStep")
  937. {
  938. PhysicsTestContext c;
  939. TestPhysicsActivateDuringStep(c, false);
  940. PhysicsTestContext c2;
  941. TestPhysicsActivateDuringStep(c2, true);
  942. }
  943. TEST_CASE("TestPhysicsBroadPhaseLayers")
  944. {
  945. PhysicsTestContext c;
  946. BodyInterface &bi = c.GetBodyInterface();
  947. // Reduce slop
  948. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  949. settings.mPenetrationSlop = 0.0f;
  950. c.GetSystem()->SetPhysicsSettings(settings);
  951. // Create static floor
  952. c.CreateFloor();
  953. // Create MOVING boxes
  954. Body &moving1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  955. Body &moving2 = c.CreateBox(RVec3(0, 2, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  956. // Create HQ_DEBRIS boxes
  957. Body &hq_debris1 = c.CreateBox(RVec3(0, 3, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  958. Body &hq_debris2 = c.CreateBox(RVec3(0, 4, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  959. // Create LQ_DEBRIS boxes
  960. Body &lq_debris1 = c.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  961. Body &lq_debris2 = c.CreateBox(RVec3(0, 6, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  962. // Check layers
  963. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  964. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  965. CHECK(hq_debris1.GetObjectLayer() == Layers::HQ_DEBRIS);
  966. CHECK(hq_debris2.GetObjectLayer() == Layers::HQ_DEBRIS);
  967. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  968. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  969. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  970. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  971. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  972. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  973. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  974. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  975. // Simulate the boxes falling
  976. c.Simulate(5.0f);
  977. // Everything should sleep
  978. CHECK_FALSE(moving1.IsActive());
  979. CHECK_FALSE(moving2.IsActive());
  980. CHECK_FALSE(hq_debris1.IsActive());
  981. CHECK_FALSE(hq_debris2.IsActive());
  982. CHECK_FALSE(lq_debris1.IsActive());
  983. CHECK_FALSE(lq_debris2.IsActive());
  984. // MOVING boxes should have stacked
  985. float slop = 0.02f;
  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 boxes should have stacked on MOVING boxes but don't collide with each other
  989. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 2.5f, 0), slop);
  990. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 2.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 HQ_DEBRIS to LQ_DEBRIS
  995. bi.SetObjectLayer(hq_debris1.GetID(), Layers::LQ_DEBRIS);
  996. bi.SetObjectLayer(hq_debris2.GetID(), Layers::LQ_DEBRIS);
  997. bi.ActivateBody(hq_debris1.GetID());
  998. bi.ActivateBody(hq_debris2.GetID());
  999. // Check layers
  1000. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  1001. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  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);
  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 should have stacked
  1022. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1023. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.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. // Now change MOVING to HQ_DEBRIS (this doesn't change the broadphase layer so avoids adding/removing bodies)
  1031. bi.SetObjectLayer(moving1.GetID(), Layers::HQ_DEBRIS);
  1032. bi.SetObjectLayer(moving2.GetID(), Layers::HQ_DEBRIS);
  1033. bi.ActivateBody(moving1.GetID());
  1034. bi.ActivateBody(moving2.GetID());
  1035. // Check layers
  1036. CHECK(moving1.GetObjectLayer() == Layers::HQ_DEBRIS);
  1037. CHECK(moving2.GetObjectLayer() == Layers::HQ_DEBRIS);
  1038. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1039. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1040. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1041. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1042. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING); // Broadphase layer didn't change
  1043. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1044. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1045. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1046. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1047. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1048. // Simulate again
  1049. c.Simulate(5.0f);
  1050. // Everything should sleep
  1051. CHECK_FALSE(moving1.IsActive());
  1052. CHECK_FALSE(moving2.IsActive());
  1053. CHECK_FALSE(hq_debris1.IsActive());
  1054. CHECK_FALSE(hq_debris2.IsActive());
  1055. CHECK_FALSE(lq_debris1.IsActive());
  1056. CHECK_FALSE(lq_debris2.IsActive());
  1057. // MOVING boxes now also fall through
  1058. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1059. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1060. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1061. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1062. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1063. // LQ_DEBRIS should have fallen through all but the floor
  1064. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1065. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1066. }
  1067. TEST_CASE("TestMultiplePhysicsSystems")
  1068. {
  1069. PhysicsTestContext c1;
  1070. c1.ZeroGravity();
  1071. PhysicsTestContext c2;
  1072. c2.ZeroGravity();
  1073. const RVec3 cBox1Position(1.0f, 2.0f, 3.0f);
  1074. Body &box1 = c1.CreateBox(cBox1Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1075. const RVec3 cBox2Position(4.0f, 5.0f, 6.0f);
  1076. Body& box2 = c2.CreateBox(cBox2Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1077. const Vec3 cBox1Velocity(1.0f, 0, 0);
  1078. const Vec3 cBox2Velocity(2.0f, 0, 0);
  1079. {
  1080. // 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)
  1081. BodyLockWrite lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1082. BodyLockWrite lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1083. CHECK(lock1.GetBody().GetPosition() == cBox1Position);
  1084. CHECK(lock2.GetBody().GetPosition() == cBox2Position);
  1085. lock1.GetBody().SetLinearVelocity(cBox1Velocity);
  1086. lock2.GetBody().SetLinearVelocity(cBox2Velocity);
  1087. }
  1088. const float cTime = 1.0f;
  1089. c1.Simulate(cTime);
  1090. c2.Simulate(cTime);
  1091. {
  1092. BodyLockRead lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1093. BodyLockRead lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1094. // Check that the bodies in the different systems updated correctly
  1095. CHECK_APPROX_EQUAL(lock1.GetBody().GetPosition(), cBox1Position + cBox1Velocity * cTime, 1.0e-5f);
  1096. CHECK_APPROX_EQUAL(lock2.GetBody().GetPosition(), cBox2Position + cBox2Velocity * cTime, 1.0e-5f);
  1097. }
  1098. }
  1099. TEST_CASE("TestOutOfBodies")
  1100. {
  1101. // Create a context with space for a single body
  1102. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1);
  1103. BodyInterface& bi = c.GetBodyInterface();
  1104. // First body
  1105. Body *b1 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1106. CHECK(b1 != nullptr);
  1107. // Second body should fail
  1108. Body *b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1109. CHECK(b2 == nullptr);
  1110. // Free first body
  1111. bi.DestroyBody(b1->GetID());
  1112. // Second body creation should succeed
  1113. b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1114. CHECK(b2 != nullptr);
  1115. // Clean up
  1116. bi.DestroyBody(b2->GetID());
  1117. }
  1118. TEST_CASE("TestOutOfContactConstraints")
  1119. {
  1120. // Create a context with space for 8 constraints
  1121. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1122. c.CreateFloor();
  1123. // The first 8 boxes should be fine
  1124. for (int i = 0; i < 8; ++i)
  1125. c.CreateBox(RVec3(3.0_r * i, 0.9_r, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1126. // Step
  1127. EPhysicsUpdateError errors = c.SimulateSingleStep();
  1128. CHECK(errors == EPhysicsUpdateError::None);
  1129. // Adding one more box should introduce an error
  1130. c.CreateBox(RVec3(24.0_r, 0.9_r, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1131. // Step
  1132. {
  1133. JPH_IF_ENABLE_ASSERTS(ExpectAssert expect_assert(1);)
  1134. errors = c.SimulateSingleStep();
  1135. }
  1136. CHECK((errors & EPhysicsUpdateError::ContactConstraintsFull) != EPhysicsUpdateError::None);
  1137. }
  1138. TEST_CASE("TestFriction")
  1139. {
  1140. const float friction_floor = 0.9f;
  1141. const float friction_box = 0.8f;
  1142. const float combined_friction = sqrt(friction_floor * friction_box);
  1143. for (float angle = 0; angle < 360.0f; angle += 30.0f)
  1144. {
  1145. // Create a context with space for 8 constraints
  1146. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1147. // Create floor
  1148. Body &floor = c.CreateFloor();
  1149. floor.SetFriction(friction_floor);
  1150. // Create box with a velocity that will make it slide over the floor (making sure it intersects a little bit initially)
  1151. BodyCreationSettings box_settings(new BoxShape(Vec3::sReplicate(1.0f)), RVec3(0, 0.999_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1152. box_settings.mFriction = friction_box;
  1153. box_settings.mLinearDamping = 0;
  1154. box_settings.mLinearVelocity = Vec3(Sin(DegreesToRadians(angle)), 0, Cos(DegreesToRadians(angle))) * 20.0f;
  1155. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1156. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1157. // We know that the friction force equals the normal force times the friction coefficient
  1158. float friction_acceleration = combined_friction * c.GetSystem()->GetGravity().Length();
  1159. // Simulate
  1160. Vec3 velocity = box_settings.mLinearVelocity;
  1161. RVec3 position = box_settings.mPosition;
  1162. for (int i = 0; i < 60; ++i)
  1163. {
  1164. c.SimulateSingleStep();
  1165. // Integrate our own simulation
  1166. velocity -= velocity.Normalized() * friction_acceleration * c.GetDeltaTime();
  1167. position += velocity * c.GetDeltaTime();
  1168. }
  1169. // Note that the result is not very accurate so we need quite a high tolerance
  1170. CHECK_APPROX_EQUAL(box.GetCenterOfMassPosition(), position, 1.0e-2f);
  1171. CHECK_APPROX_EQUAL(box.GetRotation(), box_settings.mRotation, 1.0e-2f);
  1172. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), velocity, 2.0e-2f);
  1173. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  1174. }
  1175. }
  1176. TEST_CASE("TestAllowedDOFs")
  1177. {
  1178. for (uint allowed_dofs = 1; allowed_dofs <= 0b111111; ++allowed_dofs)
  1179. {
  1180. // Create a context
  1181. PhysicsTestContext c;
  1182. c.ZeroGravity();
  1183. // Create box
  1184. RVec3 initial_position(1, 2, 3);
  1185. Quat initial_rotation = Quat::sRotation(Vec3::sReplicate(sqrt(1.0f / 3.0f)), DegreesToRadians(20.0f));
  1186. ShapeRefC box_shape = new BoxShape(Vec3(0.3f, 0.5f, 0.7f));
  1187. BodyCreationSettings box_settings(box_shape, initial_position, initial_rotation, EMotionType::Dynamic, Layers::MOVING);
  1188. box_settings.mLinearDamping = 0;
  1189. box_settings.mAngularDamping = 0;
  1190. box_settings.mAllowedDOFs = (EAllowedDOFs)allowed_dofs;
  1191. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1192. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1193. // Apply a force and torque in 3D
  1194. Vec3 force(100000, 110000, 120000);
  1195. box.AddForce(force);
  1196. Vec3 local_torque(13000, 14000, 15000);
  1197. box.AddTorque(initial_rotation * local_torque);
  1198. // Simulate
  1199. c.SimulateSingleStep();
  1200. // Cancel components that should not be allowed by the allowed DOFs
  1201. for (uint axis = 0; axis < 3; ++axis)
  1202. {
  1203. if ((allowed_dofs & (1 << axis)) == 0)
  1204. force.SetComponent(axis, 0.0f);
  1205. if ((allowed_dofs & (0b1000 << axis)) == 0)
  1206. local_torque.SetComponent(axis, 0.0f);
  1207. }
  1208. // Check resulting linear velocity
  1209. MassProperties mp = box_shape->GetMassProperties();
  1210. Vec3 expected_linear_velocity = force / mp.mMass * c.GetDeltaTime();
  1211. CHECK((force == Vec3::sZero() || expected_linear_velocity.Length() > 1.0f)); // Just to check that we applied a high enough force
  1212. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), expected_linear_velocity);
  1213. RVec3 expected_position = initial_position + expected_linear_velocity * c.GetDeltaTime();
  1214. CHECK_APPROX_EQUAL(box.GetPosition(), expected_position);
  1215. // Check resulting angular velocity
  1216. Vec3 expected_angular_velocity = initial_rotation * (mp.mInertia.Inversed3x3() * local_torque) * c.GetDeltaTime();
  1217. CHECK((local_torque == Vec3::sZero() || expected_angular_velocity.Length() > 1.0f)); // Just to check that we applied a high enough torque
  1218. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), expected_angular_velocity);
  1219. float expected_angular_velocity_len = expected_angular_velocity.Length();
  1220. Quat expected_rotation = expected_angular_velocity_len > 0.0f? Quat::sRotation(expected_angular_velocity / expected_angular_velocity_len, expected_angular_velocity_len * c.GetDeltaTime()) * initial_rotation : initial_rotation;
  1221. CHECK_APPROX_EQUAL(box.GetRotation(), expected_rotation);
  1222. }
  1223. }
  1224. TEST_CASE("TestSelectiveStateSaveAndRestore")
  1225. {
  1226. class MyFilter : public StateRecorderFilter
  1227. {
  1228. public:
  1229. bool ShouldSaveBody(const BodyID &inBodyID) const
  1230. {
  1231. return find(mIgnoreBodies.cbegin(), mIgnoreBodies.cend(), inBodyID) == mIgnoreBodies.cend();
  1232. }
  1233. virtual bool ShouldSaveBody(const Body &inBody) const override
  1234. {
  1235. return ShouldSaveBody(inBody.GetID());
  1236. }
  1237. virtual bool ShouldSaveContact(const BodyID &inBody1, const BodyID &inBody2) const override
  1238. {
  1239. return ShouldSaveBody(inBody1) && ShouldSaveBody(inBody2);
  1240. }
  1241. Array<BodyID> mIgnoreBodies;
  1242. };
  1243. for (int mode = 0; mode < 2; mode++)
  1244. {
  1245. PhysicsTestContext c;
  1246. Vec3 gravity = c.GetSystem()->GetGravity();
  1247. Vec3 upside_down_gravity = -gravity;
  1248. // Create the ground.
  1249. Body &ground = c.CreateFloor();
  1250. // Create two sets of bodies that each overlap
  1251. Body &box1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1252. Body &sphere1 = c.CreateSphere(RVec3(0, 1, 0.1f), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate);
  1253. Body &box2 = c.CreateBox(RVec3(5, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(1.0f), EActivation::Activate);
  1254. Body &sphere2 = c.CreateSphere(RVec3(5, 1, 0.1f), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate);
  1255. // Store the absolute initial state, that will be used for the final test.
  1256. StateRecorderImpl absolute_initial_state;
  1257. c.GetSystem()->SaveState(absolute_initial_state);
  1258. EStateRecorderState state_to_save = EStateRecorderState::All;
  1259. MyFilter filter;
  1260. if (mode == 1)
  1261. {
  1262. // Don't save the global state
  1263. state_to_save = EStateRecorderState(uint(EStateRecorderState::All) ^ uint(EStateRecorderState::Global));
  1264. // Don't save some bodies
  1265. filter.mIgnoreBodies.push_back(ground.GetID());
  1266. filter.mIgnoreBodies.push_back(box2.GetID());
  1267. filter.mIgnoreBodies.push_back(sphere2.GetID());
  1268. }
  1269. // Store the initial transform.
  1270. const RMat44 initial_box1_transform = box1.GetWorldTransform();
  1271. const RMat44 initial_sphere1_transform = sphere1.GetWorldTransform();
  1272. const RMat44 initial_box2_transform = box2.GetWorldTransform();
  1273. const RMat44 initial_sphere2_transform = sphere2.GetWorldTransform();
  1274. // Save partial state
  1275. StateRecorderImpl initial_state;
  1276. c.GetSystem()->SaveState(initial_state, state_to_save, &filter);
  1277. // Simulate for 2 seconds
  1278. c.Simulate(2.0f);
  1279. // The bodies should have moved and come to rest
  1280. const RMat44 intermediate_box1_transform = box1.GetWorldTransform();
  1281. const RMat44 intermediate_sphere1_transform = sphere1.GetWorldTransform();
  1282. const RMat44 intermediate_box2_transform = box2.GetWorldTransform();
  1283. const RMat44 intermediate_sphere2_transform = sphere2.GetWorldTransform();
  1284. CHECK(intermediate_box1_transform != initial_box1_transform);
  1285. CHECK(intermediate_sphere1_transform != initial_sphere1_transform);
  1286. CHECK(intermediate_box2_transform != initial_box2_transform);
  1287. CHECK(intermediate_sphere2_transform != initial_sphere2_transform);
  1288. CHECK(!box1.IsActive());
  1289. CHECK(!sphere1.IsActive());
  1290. CHECK(!box2.IsActive());
  1291. CHECK(!sphere2.IsActive());
  1292. // Save the intermediate state.
  1293. StateRecorderImpl intermediate_state;
  1294. c.GetSystem()->SaveState(intermediate_state, state_to_save, &filter);
  1295. // Change the gravity.
  1296. c.GetSystem()->SetGravity(upside_down_gravity);
  1297. // Restore the initial state.
  1298. c.GetSystem()->RestoreState(initial_state);
  1299. // Make sure the state is properly set back to the initial state.
  1300. CHECK(box1.GetWorldTransform() == initial_box1_transform);
  1301. CHECK(sphere1.GetWorldTransform() == initial_sphere1_transform);
  1302. CHECK(box1.IsActive());
  1303. CHECK(sphere1.IsActive());
  1304. if (mode == 0)
  1305. {
  1306. // Make sure the gravity is restored.
  1307. CHECK(c.GetSystem()->GetGravity() == gravity);
  1308. // The second set of bodies should have been restored as well
  1309. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1310. CHECK(sphere2.GetWorldTransform() == initial_sphere2_transform);
  1311. CHECK(box2.IsActive());
  1312. CHECK(sphere2.IsActive());
  1313. }
  1314. else
  1315. {
  1316. // Make sure the gravity is NOT restored.
  1317. CHECK(c.GetSystem()->GetGravity() == upside_down_gravity);
  1318. c.GetSystem()->SetGravity(gravity);
  1319. // The second set of bodies should NOT have been restored
  1320. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1321. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1322. CHECK(!box2.IsActive());
  1323. CHECK(!sphere2.IsActive());
  1324. // Apply a velocity to the second set of bodies to make sure they are active again
  1325. c.GetBodyInterface().SetLinearVelocity(box2.GetID(), Vec3(0, 0, 0.1f));
  1326. c.GetBodyInterface().SetLinearVelocity(sphere2.GetID(), Vec3(0, 0, 0.1f));
  1327. }
  1328. // Simulate for 2 seconds - again
  1329. c.Simulate(2.0f);
  1330. // The first set of bodies have been saved and should have returned to the same positions again
  1331. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1332. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1333. CHECK(!box1.IsActive());
  1334. CHECK(!sphere1.IsActive());
  1335. if (mode == 0)
  1336. {
  1337. // The second set of bodies have been saved and should have returned to the same positions again
  1338. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1339. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1340. CHECK(!box2.IsActive());
  1341. CHECK(!sphere2.IsActive());
  1342. }
  1343. else
  1344. {
  1345. // The second set of bodies have not been saved and should have moved on
  1346. CHECK(box2.GetWorldTransform() != intermediate_box2_transform);
  1347. CHECK(sphere2.GetWorldTransform() != intermediate_sphere2_transform);
  1348. CHECK(!box2.IsActive());
  1349. CHECK(sphere2.IsActive()); // The sphere keeps rolling
  1350. }
  1351. // Save the final state
  1352. StateRecorderImpl final_state;
  1353. c.GetSystem()->SaveState(final_state, state_to_save, &filter);
  1354. // Compare the states to make sure they are the same
  1355. CHECK(final_state.IsEqual(intermediate_state));
  1356. // Now restore the absolute initial state and make sure all the
  1357. // bodies are being active and ready to be processed again
  1358. c.GetSystem()->RestoreState(absolute_initial_state);
  1359. CHECK(box1.GetWorldTransform() == initial_box1_transform);
  1360. CHECK(sphere1.GetWorldTransform() == initial_sphere1_transform);
  1361. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1362. CHECK(sphere2.GetWorldTransform() == initial_sphere2_transform);
  1363. CHECK(box1.IsActive());
  1364. CHECK(sphere1.IsActive());
  1365. CHECK(box2.IsActive());
  1366. CHECK(sphere2.IsActive());
  1367. // Save the state of a single body
  1368. StateRecorderImpl single_body;
  1369. c.GetSystem()->SaveBodyState(box2, single_body);
  1370. // Simulate for 2 seconds - again
  1371. c.Simulate(2.0f);
  1372. // We should have reached the same state as before
  1373. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1374. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1375. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1376. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1377. CHECK(!box1.IsActive());
  1378. CHECK(!sphere1.IsActive());
  1379. CHECK(!box2.IsActive());
  1380. CHECK(!sphere2.IsActive());
  1381. // Restore the single body
  1382. c.GetSystem()->RestoreBodyState(box2, single_body);
  1383. // Only that body should have been restored
  1384. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1385. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1386. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1387. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1388. CHECK(!box1.IsActive());
  1389. CHECK(!sphere1.IsActive());
  1390. CHECK(box2.IsActive());
  1391. CHECK(!sphere2.IsActive());
  1392. }
  1393. }
  1394. // This tests that when switching UseManifoldReduction on/off we get the correct contact callbacks
  1395. TEST_CASE("TestSwitchUseManifoldReduction")
  1396. {
  1397. PhysicsTestContext c;
  1398. // Install listener
  1399. LoggingContactListener contact_listener;
  1400. c.GetSystem()->SetContactListener(&contact_listener);
  1401. // Create floor
  1402. Body &floor = c.CreateFloor();
  1403. // Create a compound with 4 boxes
  1404. Ref<BoxShape> box_shape = new BoxShape(Vec3::sReplicate(2));
  1405. Ref<StaticCompoundShapeSettings> shape_settings = new StaticCompoundShapeSettings();
  1406. shape_settings->AddShape(Vec3(5, 0, 0), Quat::sIdentity(), box_shape);
  1407. shape_settings->AddShape(Vec3(-5, 0, 0), Quat::sIdentity(), box_shape);
  1408. shape_settings->AddShape(Vec3(0, 0, 5), Quat::sIdentity(), box_shape);
  1409. shape_settings->AddShape(Vec3(0, 0, -5), Quat::sIdentity(), box_shape);
  1410. RefConst<StaticCompoundShape> compound_shape = static_cast<const StaticCompoundShape *>(shape_settings->Create().Get().GetPtr());
  1411. SubShapeID sub_shape_ids[] = {
  1412. compound_shape->GetSubShapeIDFromIndex(0, SubShapeIDCreator()).GetID(),
  1413. compound_shape->GetSubShapeIDFromIndex(1, SubShapeIDCreator()).GetID(),
  1414. compound_shape->GetSubShapeIDFromIndex(2, SubShapeIDCreator()).GetID(),
  1415. compound_shape->GetSubShapeIDFromIndex(3, SubShapeIDCreator()).GetID()
  1416. };
  1417. // Embed body a little bit into the floor so we immediately get contact callbacks
  1418. BodyCreationSettings body_settings(compound_shape, RVec3(0, 1.99_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1419. body_settings.mUseManifoldReduction = true;
  1420. BodyID body_id = c.GetBodyInterface().CreateAndAddBody(body_settings, EActivation::Activate);
  1421. // Trigger contact callbacks
  1422. c.SimulateSingleStep();
  1423. // Since manifold reduction is on and the contacts will be coplanar we should only get 1 contact with the floor
  1424. // Note that which sub shape ID we get is deterministic but not guaranteed to be a particular value, sub_shape_ids[3] is the one it currently returns!!
  1425. CHECK(contact_listener.GetEntryCount() == 5); // 4x validate + 1x add
  1426. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1427. contact_listener.Clear();
  1428. // Now disable manifold reduction
  1429. c.GetBodyInterface().SetUseManifoldReduction(body_id, false);
  1430. // Trigger contact callbacks
  1431. c.SimulateSingleStep();
  1432. // Now manifold reduction is off so we should get collisions with each of the sub shapes
  1433. CHECK(contact_listener.GetEntryCount() == 8); // 4x validate + 1x persist + 3x add
  1434. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1435. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[0]));
  1436. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[1]));
  1437. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[2]));
  1438. contact_listener.Clear();
  1439. // Now enable manifold reduction again
  1440. c.GetBodyInterface().SetUseManifoldReduction(body_id, true);
  1441. // Trigger contact callbacks
  1442. c.SimulateSingleStep();
  1443. // We should be back to the first state now where we only have 1 contact
  1444. CHECK(contact_listener.GetEntryCount() == 8); // 4x validate + 1x persist + 3x remove
  1445. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1446. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[0]));
  1447. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[1]));
  1448. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[2]));
  1449. }
  1450. }