PhysicsTests.cpp 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184
  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/Collision/CollisionCollectorImpl.h>
  14. #include <Jolt/Physics/Collision/RayCast.h>
  15. #include <Jolt/Physics/Collision/CastResult.h>
  16. #include <Jolt/Physics/Collision/BroadPhase/BroadPhase.h>
  17. #include <Jolt/Physics/Body/BodyLockMulti.h>
  18. #include <Jolt/Physics/Constraints/PointConstraint.h>
  19. #include <Jolt/Physics/StateRecorderImpl.h>
  20. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  21. #include <cstring>
  22. JPH_SUPPRESS_WARNINGS_STD_END
  23. TEST_SUITE("PhysicsTests")
  24. {
  25. // Gravity vector
  26. const Vec3 cGravity = Vec3(0.0f, -9.81f, 0.0f);
  27. // Test the test framework's helper functions
  28. TEST_CASE("TestPhysicsTestContext")
  29. {
  30. // Test that the Symplectic Euler integrator is close enough to the real value
  31. const float cSimulationTime = 2.0f;
  32. // For position: x = x0 + v0 * t + 1/2 * a * t^2
  33. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  34. PhysicsTestContext c;
  35. RVec3 simulated_pos = c.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  36. RVec3 integrated_position = cInitialPos + 0.5f * cGravity * Square(cSimulationTime);
  37. CHECK_APPROX_EQUAL(integrated_position, simulated_pos, 0.2f);
  38. // For rotation
  39. const Quat cInitialRot(Quat::sRotation(Vec3::sAxisY(), 0.1f));
  40. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  41. Quat simulated_rot = c.PredictOrientation(cInitialRot, Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  42. Vec3 integrated_acceleration = 0.5f * cAngularAcceleration * Square(cSimulationTime);
  43. float integrated_acceleration_len = integrated_acceleration.Length();
  44. Quat integrated_rot = Quat::sRotation(integrated_acceleration / integrated_acceleration_len, integrated_acceleration_len) * cInitialRot;
  45. CHECK_APPROX_EQUAL(integrated_rot, simulated_rot, 0.02f);
  46. }
  47. TEST_CASE("TestPhysicsBodyLock")
  48. {
  49. PhysicsTestContext c;
  50. // Check that we cannot lock the invalid body ID
  51. {
  52. BodyLockRead lock(c.GetSystem()->GetBodyLockInterface(), BodyID());
  53. CHECK_FALSE(lock.Succeeded());
  54. CHECK_FALSE(lock.SucceededAndIsInBroadPhase());
  55. }
  56. BodyID body1_id;
  57. {
  58. // Create a box
  59. Body &body1 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sOne());
  60. body1_id = body1.GetID();
  61. CHECK(body1_id.GetIndex() == 0);
  62. CHECK(body1_id.GetSequenceNumber() == 1);
  63. // Create another box
  64. Body &body2 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sOne());
  65. BodyID body2_id = body2.GetID();
  66. CHECK(body2_id.GetIndex() == 1);
  67. CHECK(body2_id.GetSequenceNumber() == 1);
  68. // Check that we can lock the first box
  69. {
  70. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  71. CHECK(lock1.Succeeded());
  72. CHECK(lock1.SucceededAndIsInBroadPhase());
  73. // Unlock automatically on going out of scope
  74. }
  75. // Check that we can lock the first box
  76. {
  77. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  78. CHECK(lock1.Succeeded());
  79. CHECK(lock1.SucceededAndIsInBroadPhase());
  80. // Release the lock early
  81. lock1.ReleaseLock();
  82. CHECK(!lock1.Succeeded());
  83. CHECK(!lock1.SucceededAndIsInBroadPhase());
  84. }
  85. // Remove the first box
  86. c.GetSystem()->GetBodyInterface().RemoveBody(body1_id);
  87. // Check that we can lock the first box
  88. {
  89. BodyLockWrite lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  90. CHECK(lock1.Succeeded());
  91. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  92. }
  93. // Destroy the first box
  94. c.GetSystem()->GetBodyInterface().DestroyBody(body1_id);
  95. // Check that we can not lock the body anymore
  96. {
  97. BodyLockWrite lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  98. CHECK_FALSE(lock1.Succeeded());
  99. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  100. }
  101. }
  102. // Create another box
  103. Body &body3 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sOne());
  104. BodyID body3_id = body3.GetID();
  105. CHECK(body3_id.GetIndex() == 0); // Check index reused
  106. CHECK(body3_id.GetSequenceNumber() == 2); // Check sequence number changed
  107. // Check that we can lock it
  108. {
  109. BodyLockRead lock3(c.GetSystem()->GetBodyLockInterface(), body3_id);
  110. CHECK(lock3.Succeeded());
  111. CHECK(lock3.SucceededAndIsInBroadPhase());
  112. }
  113. // Check that we can't lock the old body with the same body index anymore
  114. {
  115. BodyLockRead lock1(c.GetSystem()->GetBodyLockInterface(), body1_id);
  116. CHECK_FALSE(lock1.Succeeded());
  117. CHECK_FALSE(lock1.SucceededAndIsInBroadPhase());
  118. }
  119. }
  120. TEST_CASE("TestPhysicsBodyLockMulti")
  121. {
  122. PhysicsTestContext c;
  123. // Check that we cannot lock the invalid body ID
  124. {
  125. BodyID bodies[] = { BodyID(), BodyID() };
  126. BodyLockMultiRead lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  127. CHECK(lock.GetBody(0) == nullptr);
  128. CHECK(lock.GetBody(1) == nullptr);
  129. }
  130. {
  131. // Create two bodies
  132. Body &body1 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sOne());
  133. Body &body2 = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, 0, Vec3::sOne());
  134. BodyID bodies[] = { body1.GetID(), body2.GetID() };
  135. {
  136. // Lock the bodies
  137. BodyLockMultiWrite lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  138. CHECK(lock.GetBody(0) == &body1);
  139. CHECK(lock.GetBody(1) == &body2);
  140. // Unlock automatically on going out of scope
  141. }
  142. {
  143. // Lock the bodies
  144. BodyLockMultiWrite lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  145. CHECK(lock.GetNumBodies() == 2);
  146. CHECK(lock.GetBody(0) == &body1);
  147. CHECK(lock.GetBody(1) == &body2);
  148. // Release the locks early
  149. lock.ReleaseLocks();
  150. CHECK(lock.GetNumBodies() == 0);
  151. }
  152. // Destroy body 1
  153. c.GetSystem()->GetBodyInterface().RemoveBody(bodies[0]);
  154. c.GetSystem()->GetBodyInterface().DestroyBody(bodies[0]);
  155. {
  156. // Lock the bodies
  157. BodyLockMultiRead lock(c.GetSystem()->GetBodyLockInterface(), bodies, 2);
  158. CHECK(lock.GetBody(0) == nullptr);
  159. CHECK(lock.GetBody(1) == &body2);
  160. }
  161. }
  162. }
  163. TEST_CASE("TestPhysicsBodyID")
  164. {
  165. {
  166. BodyID body_id(0);
  167. CHECK(body_id.GetIndex() == 0);
  168. CHECK(body_id.GetSequenceNumber() == 0);
  169. }
  170. {
  171. BodyID body_id(~BodyID::cBroadPhaseBit);
  172. CHECK(body_id.GetIndex() == BodyID::cMaxBodyIndex);
  173. CHECK(body_id.GetSequenceNumber() == BodyID::cMaxSequenceNumber);
  174. }
  175. }
  176. TEST_CASE("TestPhysicsBodyIDSequenceNumber")
  177. {
  178. PhysicsTestContext c;
  179. BodyInterface &bi = c.GetBodyInterface();
  180. // Create a body and check it's id
  181. BodyID body0_id = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1)).GetID();
  182. CHECK(body0_id == BodyID(0, 1)); // Body 0, sequence number 1
  183. // Check that the sequence numbers aren't reused until after 256 iterations
  184. for (int seq_no = 1; seq_no < 258; ++seq_no)
  185. {
  186. BodyID body1_id = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1)).GetID();
  187. CHECK(body1_id == BodyID(1, uint8(seq_no))); // Body 1
  188. bi.RemoveBody(body1_id);
  189. bi.DestroyBody(body1_id);
  190. }
  191. bi.RemoveBody(body0_id);
  192. bi.DestroyBody(body0_id);
  193. }
  194. TEST_CASE("TestPhysicsBodyIDOverride")
  195. {
  196. PhysicsTestContext c;
  197. BodyInterface &bi = c.GetBodyInterface();
  198. // Dummy creation settings
  199. BodyCreationSettings bc(new BoxShape(Vec3::sOne()), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  200. // Create a body
  201. Body *b1 = bi.CreateBody(bc);
  202. CHECK(b1->GetID() == BodyID(0, 1));
  203. // Create body with same ID and same sequence number
  204. Body *b2 = bi.CreateBodyWithID(BodyID(0, 1), bc);
  205. CHECK(b2 == nullptr);
  206. // Create body with same ID and different sequence number
  207. b2 = bi.CreateBodyWithID(BodyID(0, 2), bc);
  208. CHECK(b2 == nullptr);
  209. // Create body with different ID (leave 1 open slot)
  210. b2 = bi.CreateBodyWithoutID(bc); // Using syntax that allows separation of allocation and assigning an ID
  211. CHECK(b2 != nullptr);
  212. CHECK(b2->GetID().IsInvalid());
  213. bi.AssignBodyID(b2, BodyID(2, 1));
  214. CHECK(b2->GetID() == BodyID(2, 1));
  215. // Create another body and check that the open slot is returned
  216. Body *b3 = bi.CreateBody(bc);
  217. CHECK(b3->GetID() == BodyID(1, 1));
  218. // Create another body and check that we do not hand out the body with specified ID
  219. Body *b4 = bi.CreateBody(bc);
  220. CHECK(b4->GetID() == BodyID(3, 1));
  221. // Delete and recreate body 4
  222. CHECK(bi.CreateBodyWithID(BodyID(3, 1), bc) == nullptr);
  223. bi.DestroyBody(b4->GetID());
  224. b4 = bi.CreateBodyWithID(BodyID(3, 1), bc);
  225. CHECK(b4 != nullptr);
  226. CHECK(b4->GetID() == BodyID(3, 1));
  227. // Destroy 1st body
  228. CHECK(bi.UnassignBodyID(b1->GetID()) == b1); // Use syntax that allows separation of unassigning and deallocation
  229. CHECK(b1->GetID().IsInvalid());
  230. bi.DestroyBodyWithoutID(b1);
  231. // Clean up remaining bodies
  232. bi.DestroyBody(b2->GetID());
  233. bi.DestroyBody(b3->GetID());
  234. bi.DestroyBody(b4->GetID());
  235. // Recreate body 1
  236. b1 = bi.CreateBodyWithID(BodyID(0, 1), bc);
  237. CHECK(b1 != nullptr);
  238. CHECK(b1->GetID() == BodyID(0, 1));
  239. // Destroy last body
  240. bi.DestroyBody(b1->GetID());
  241. }
  242. TEST_CASE("TestPhysicsBodyUserData")
  243. {
  244. PhysicsTestContext c;
  245. BodyInterface &bi = c.GetBodyInterface();
  246. // Create a body and pass user data through the creation settings
  247. BodyCreationSettings body_settings(new BoxShape(Vec3::sOne()), RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  248. body_settings.mUserData = 0x1234567887654321;
  249. Body *body = bi.CreateBody(body_settings);
  250. CHECK(body->GetUserData() == 0x1234567887654321);
  251. // Change the user data
  252. body->SetUserData(0x5678123443218765);
  253. CHECK(body->GetUserData() == 0x5678123443218765);
  254. // Convert back to body settings
  255. BodyCreationSettings body_settings2 = body->GetBodyCreationSettings();
  256. CHECK(body_settings2.mUserData == 0x5678123443218765);
  257. }
  258. TEST_CASE("TestPhysicsConstraintUserData")
  259. {
  260. PhysicsTestContext c;
  261. // Create a body
  262. Body &body = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sOne());
  263. // Create constraint with user data
  264. PointConstraintSettings constraint_settings;
  265. constraint_settings.mUserData = 0x1234567887654321;
  266. Ref<Constraint> constraint = constraint_settings.Create(body, Body::sFixedToWorld);
  267. CHECK(constraint->GetUserData() == 0x1234567887654321);
  268. // Change the user data
  269. constraint->SetUserData(0x5678123443218765);
  270. CHECK(constraint->GetUserData() == 0x5678123443218765);
  271. // Convert back to constraint settings
  272. Ref<ConstraintSettings> constraint_settings2 = constraint->GetConstraintSettings();
  273. CHECK(constraint_settings2->mUserData == 0x5678123443218765);
  274. }
  275. TEST_CASE("TestPhysicsPosition")
  276. {
  277. PhysicsTestContext c;
  278. BodyInterface &bi = c.GetBodyInterface();
  279. // Translate / rotate the box
  280. Vec3 box_pos(1, 2, 3);
  281. Quat box_rotation = Quat::sRotation(Vec3::sAxisX(), 0.25f * JPH_PI);
  282. // Translate / rotate the body
  283. RVec3 body_pos(4, 5, 6);
  284. Quat body_rotation = Quat::sRotation(Vec3::sAxisY(), 0.3f * JPH_PI);
  285. RMat44 body_transform = RMat44::sRotationTranslation(body_rotation, body_pos);
  286. RMat44 com_transform = body_transform * Mat44::sTranslation(box_pos);
  287. // Create body
  288. BodyCreationSettings body_settings(new RotatedTranslatedShapeSettings(box_pos, box_rotation, new BoxShape(Vec3::sOne())), body_pos, body_rotation, EMotionType::Static, Layers::NON_MOVING);
  289. Body *body = bi.CreateBody(body_settings);
  290. // Check that the correct positions / rotations are reported
  291. CHECK_APPROX_EQUAL(body->GetPosition(), body_pos);
  292. CHECK_APPROX_EQUAL(body->GetRotation(), body_rotation);
  293. CHECK_APPROX_EQUAL(body->GetWorldTransform(), body_transform);
  294. CHECK_APPROX_EQUAL(body->GetCenterOfMassPosition(), com_transform.GetTranslation());
  295. CHECK_APPROX_EQUAL(body->GetCenterOfMassTransform(), com_transform);
  296. CHECK_APPROX_EQUAL(body->GetInverseCenterOfMassTransform(), com_transform.InversedRotationTranslation(), 1.0e-5f);
  297. }
  298. TEST_CASE("TestPhysicsOverrideMassAndInertia")
  299. {
  300. PhysicsTestContext c;
  301. BodyInterface &bi = c.GetBodyInterface();
  302. const float cDensity = 1234.0f;
  303. const Vec3 cBoxExtent(2.0f, 4.0f, 6.0f);
  304. const float cExpectedMass = cBoxExtent.GetX() * cBoxExtent.GetY() * cBoxExtent.GetZ() * cDensity;
  305. // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  306. const Vec3 cSquaredExtents = Vec3(Square(cBoxExtent.GetY()) + Square(cBoxExtent.GetZ()), Square(cBoxExtent.GetX()) + Square(cBoxExtent.GetZ()), Square(cBoxExtent.GetX()) + Square(cBoxExtent.GetY()));
  307. const Vec3 cExpectedInertiaDiagonal = cExpectedMass / 12.0f * cSquaredExtents;
  308. Ref<BoxShapeSettings> shape_settings = new BoxShapeSettings(0.5f * cBoxExtent);
  309. shape_settings->SetDensity(cDensity);
  310. BodyCreationSettings body_settings(shape_settings, RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  311. // Create body as is
  312. Body &b1 = *bi.CreateBody(body_settings);
  313. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseMass(), 1.0f / cExpectedMass);
  314. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  315. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseInertiaDiagonal(), cExpectedInertiaDiagonal.Reciprocal());
  316. // Scale the mass and check that the mass and inertia are correct
  317. const float cNewMass = 2.0f;
  318. b1.GetMotionProperties()->ScaleToMass(cNewMass);
  319. const Vec3 cNewExpectedInertiaDiagonal = cNewMass / 12.0f * cSquaredExtents;
  320. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseMass(), 1.0f / cNewMass);
  321. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  322. CHECK_APPROX_EQUAL(b1.GetMotionProperties()->GetInverseInertiaDiagonal(), cNewExpectedInertiaDiagonal.Reciprocal());
  323. // Override only the mass
  324. const float cOverriddenMass = 13.0f;
  325. const Vec3 cOverriddenMassInertiaDiagonal = cOverriddenMass / 12.0f * cSquaredExtents;
  326. body_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  327. body_settings.mMassPropertiesOverride.mMass = cOverriddenMass;
  328. Body &b2 = *bi.CreateBody(body_settings);
  329. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  330. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInertiaRotation(), Quat::sIdentity());
  331. CHECK_APPROX_EQUAL(b2.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenMassInertiaDiagonal.Reciprocal());
  332. // Override both the mass and inertia
  333. 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
  334. const Quat cOverriddenInertiaRotation = Quat::sRotation(Vec3(1, 1, 1).Normalized(), 0.1f * JPH_PI);
  335. body_settings.mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
  336. body_settings.mMassPropertiesOverride.mInertia = Mat44::sRotation(cOverriddenInertiaRotation) * Mat44::sScale(cOverriddenInertiaDiagonal) * Mat44::sRotation(cOverriddenInertiaRotation.Inversed());
  337. Body &b3 = *bi.CreateBody(body_settings);
  338. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseMass(), 1.0f / cOverriddenMass);
  339. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInertiaRotation(), cOverriddenInertiaRotation);
  340. CHECK_APPROX_EQUAL(b3.GetMotionProperties()->GetInverseInertiaDiagonal(), cOverriddenInertiaDiagonal.Reciprocal());
  341. }
  342. // Test a box free falling under gravity
  343. static void TestPhysicsFreeFall(PhysicsTestContext &ioContext)
  344. {
  345. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  346. const float cSimulationTime = 2.0f;
  347. // Create box
  348. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  349. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition());
  350. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  351. ioContext.Simulate(cSimulationTime);
  352. // Test resulting velocity (due to gravity)
  353. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  354. // Test resulting position
  355. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity, cSimulationTime);
  356. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  357. }
  358. TEST_CASE("TestPhysicsFreeFall")
  359. {
  360. PhysicsTestContext c1(1.0f / 60.0f, 1);
  361. TestPhysicsFreeFall(c1);
  362. PhysicsTestContext c2(2.0f / 60.0f, 2);
  363. TestPhysicsFreeFall(c2);
  364. PhysicsTestContext c4(4.0f / 60.0f, 4);
  365. TestPhysicsFreeFall(c4);
  366. }
  367. // Test acceleration of a box with force applied
  368. static void TestPhysicsApplyForce(PhysicsTestContext &ioContext)
  369. {
  370. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  371. const Vec3 cAcceleration(2.0f, 0.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(cInitialPos, body.GetPosition());
  376. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  377. // Validate mass
  378. float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  379. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  380. // Simulate while applying force
  381. ioContext.Simulate(cSimulationTime, [&]() { body.AddForce(mass * cAcceleration); });
  382. // Test resulting velocity (due to gravity and applied force)
  383. CHECK_APPROX_EQUAL(cSimulationTime * (cGravity + cAcceleration), body.GetLinearVelocity(), 1.0e-4f);
  384. // Test resulting position
  385. RVec3 expected_pos = ioContext.PredictPosition(cInitialPos, Vec3::sZero(), cGravity + cAcceleration, cSimulationTime);
  386. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition());
  387. }
  388. TEST_CASE("TestPhysicsApplyForce")
  389. {
  390. PhysicsTestContext c1(1.0f / 60.0f, 1);
  391. TestPhysicsApplyForce(c1);
  392. PhysicsTestContext c2(2.0f / 60.0f, 2);
  393. TestPhysicsApplyForce(c2);
  394. PhysicsTestContext c4(4.0f / 60.0f, 4);
  395. TestPhysicsApplyForce(c4);
  396. }
  397. // Test angular acceleration for a box by applying torque every frame
  398. static void TestPhysicsApplyTorque(PhysicsTestContext &ioContext)
  399. {
  400. const RVec3 cInitialPos(0.0f, 10.0f, 0.0f);
  401. const Vec3 cAngularAcceleration(0.0f, 2.0f, 0.0f);
  402. const float cSimulationTime = 2.0f;
  403. // Create box
  404. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  405. CHECK_APPROX_EQUAL(Quat::sIdentity(), body.GetRotation());
  406. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  407. // Validate mass and inertia
  408. constexpr float mass = Cubed(2.0f) * 1000.0f; // Density * Volume
  409. CHECK_APPROX_EQUAL(1.0f / mass, body.GetMotionProperties()->GetInverseMass());
  410. constexpr float inertia = mass * 8.0f / 12.0f; // See: https://en.wikipedia.org/wiki/List_of_moments_of_inertia
  411. CHECK_APPROX_EQUAL(Mat44::sScale(1.0f / inertia), body.GetMotionProperties()->GetLocalSpaceInverseInertia());
  412. // Simulate while applying torque
  413. ioContext.Simulate(cSimulationTime, [&]() { body.AddTorque(inertia * cAngularAcceleration); });
  414. // Get resulting angular velocity
  415. CHECK_APPROX_EQUAL(cSimulationTime * cAngularAcceleration, body.GetAngularVelocity(), 1.0e-4f);
  416. // Test resulting rotation
  417. Quat expected_rot = ioContext.PredictOrientation(Quat::sIdentity(), Vec3::sZero(), cAngularAcceleration, cSimulationTime);
  418. CHECK_APPROX_EQUAL(expected_rot, body.GetRotation(), 1.0e-4f);
  419. }
  420. TEST_CASE("TestPhysicsApplyTorque")
  421. {
  422. PhysicsTestContext c1(1.0f / 60.0f, 1);
  423. TestPhysicsApplyTorque(c1);
  424. PhysicsTestContext c2(2.0f / 60.0f, 2);
  425. TestPhysicsApplyTorque(c2);
  426. PhysicsTestContext c4(4.0f / 60.0f, 4);
  427. TestPhysicsApplyTorque(c4);
  428. }
  429. // Let a sphere bounce on the floor with restitution = 1
  430. static void TestPhysicsCollisionElastic(PhysicsTestContext &ioContext)
  431. {
  432. const float cSimulationTime = 1.0f;
  433. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  434. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  435. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  436. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  437. // Create sphere
  438. ioContext.CreateFloor();
  439. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  440. body.SetRestitution(1.0f);
  441. // Simulate until at floor
  442. ioContext.Simulate(cSimulationTime);
  443. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  444. // Assert collision not yet processed
  445. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  446. // Simulate one more step to process the collision
  447. ioContext.SimulateSingleStep();
  448. // Assert that collision is processed and velocity is reversed (which is required for a fully elastic collision).
  449. float sub_step_delta_time = ioContext.GetStepDeltaTime();
  450. float remaining_step_time = ioContext.GetDeltaTime() - ioContext.GetStepDeltaTime();
  451. Vec3 reflected_velocity_after_sub_step = -cSimulationTime * cGravity;
  452. Vec3 reflected_velocity_after_full_step = reflected_velocity_after_sub_step + remaining_step_time * cGravity;
  453. CHECK_APPROX_EQUAL(reflected_velocity_after_full_step, body.GetLinearVelocity(), 1.0e-4f);
  454. // Body should have bounced back
  455. RVec3 pos_after_bounce_sub_step = cFloorHitPos + reflected_velocity_after_sub_step * sub_step_delta_time;
  456. RVec3 pos_after_bounce_full_step = ioContext.PredictPosition(pos_after_bounce_sub_step, reflected_velocity_after_sub_step, cGravity, remaining_step_time);
  457. CHECK_APPROX_EQUAL(pos_after_bounce_full_step, body.GetPosition());
  458. // Simulate same time minus one step, with a fully elastic body we should reach the initial position again
  459. RVec3 expected_pos = ioContext.PredictPosition(pos_after_bounce_full_step, reflected_velocity_after_full_step, cGravity, cSimulationTime - ioContext.GetDeltaTime());
  460. ioContext.Simulate(cSimulationTime - ioContext.GetDeltaTime());
  461. CHECK_APPROX_EQUAL(expected_pos, body.GetPosition(), 1.0e-5f);
  462. CHECK_APPROX_EQUAL(expected_pos, cInitialPos, 1.0e-5f);
  463. // If we do one more step, we should be going down again
  464. RVec3 pre_step_pos = body.GetPosition();
  465. CHECK(body.GetLinearVelocity().GetY() > 0.0f);
  466. ioContext.SimulateSingleStep();
  467. CHECK(body.GetLinearVelocity().GetY() < 1.0e-6f);
  468. CHECK(body.GetPosition().GetY() < pre_step_pos.GetY() + 1.0e-6f);
  469. }
  470. TEST_CASE("TestPhysicsCollisionElastic")
  471. {
  472. PhysicsTestContext c1(1.0f / 60.0f, 1);
  473. TestPhysicsCollisionElastic(c1);
  474. PhysicsTestContext c2(2.0f / 60.0f, 2);
  475. TestPhysicsCollisionElastic(c2);
  476. PhysicsTestContext c4(4.0f / 60.0f, 4);
  477. TestPhysicsCollisionElastic(c4);
  478. }
  479. // Let a sphere with restitution 0.9 bounce on the floor
  480. TEST_CASE("TestPhysicsCollisionPartiallyElastic")
  481. {
  482. PhysicsTestContext c;
  483. c.CreateFloor();
  484. // Create sphere
  485. const RVec3 cInitialPos(0, 10, 0);
  486. constexpr float cRestitution = 0.9f;
  487. constexpr float cRadius = 2.0f;
  488. Body &body = c.CreateSphere(cInitialPos, cRadius, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  489. body.SetRestitution(cRestitution);
  490. // Simple simulation to compare with the actual simulation
  491. RVec3 pos = cInitialPos;
  492. Vec3 vel = Vec3::sZero();
  493. float dt = c.GetDeltaTime();
  494. float penetration_slop = c.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  495. for (int i = 0; i < 1000; ++i)
  496. {
  497. // Simple simulation
  498. Real penetration = cRadius - pos.GetY();
  499. if (penetration > -penetration_slop && vel.GetY() < 0.0f)
  500. vel = -cRestitution * vel;
  501. else
  502. vel += cGravity * dt;
  503. pos += vel * dt;
  504. // Actual step
  505. c.SimulateSingleStep();
  506. // Compare simulations
  507. CHECK_APPROX_EQUAL(pos, body.GetPosition(), 1.0e-5f);
  508. CHECK_APPROX_EQUAL(vel, body.GetLinearVelocity(), 1.0e-5f);
  509. }
  510. }
  511. // 2 spheres bounce with restitution = 1, tests we don't correct for gravity in a perpendicular direction to gravity
  512. static void TestPhysicsCollisionElasticDynamic(PhysicsTestContext &ioContext)
  513. {
  514. // Create spheres
  515. Body &sphere1 = ioContext.CreateSphere(RVec3(-2, 0, 0), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  516. sphere1.SetRestitution(1.0f);
  517. sphere1.SetLinearVelocity(Vec3(5, 0, 0));
  518. Body &sphere2 = ioContext.CreateSphere(RVec3(2, 0, 0), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  519. sphere2.SetRestitution(1.0f);
  520. sphere2.SetLinearVelocity(Vec3(-10, 0, 0));
  521. // Simulate
  522. constexpr float cSimulationTime = 1.0f;
  523. ioContext.Simulate(cSimulationTime);
  524. // Check that velocities match that of a fully elastic collision
  525. CHECK_APPROX_EQUAL(Vec3(-10, 0, 0) + cSimulationTime * cGravity, sphere1.GetLinearVelocity(), 1.0e-5f);
  526. CHECK_APPROX_EQUAL(Vec3(5, 0, 0) + cSimulationTime * cGravity, sphere2.GetLinearVelocity(), 1.0e-5f);
  527. }
  528. TEST_CASE("TestPhysicsCollisionElasticDynamic")
  529. {
  530. PhysicsTestContext c1(1.0f / 60.0f, 1);
  531. TestPhysicsCollisionElasticDynamic(c1);
  532. PhysicsTestContext c2(2.0f / 60.0f, 2);
  533. TestPhysicsCollisionElasticDynamic(c2);
  534. PhysicsTestContext c4(4.0f / 60.0f, 4);
  535. TestPhysicsCollisionElasticDynamic(c4);
  536. }
  537. // Let a sphere bounce on the floor with restitution = 0
  538. static void TestPhysicsCollisionInelastic(PhysicsTestContext &ioContext)
  539. {
  540. const float cSimulationTime = 1.0f;
  541. const RVec3 cDistanceTraveled = ioContext.PredictPosition(RVec3::sZero(), Vec3::sZero(), cGravity, cSimulationTime);
  542. const float cFloorHitEpsilon = 1.0e-4f; // Apply epsilon so that we're sure that the collision algorithm will find a collision
  543. const RVec3 cFloorHitPos(0.0f, 1.0f - cFloorHitEpsilon, 0.0f); // Sphere with radius 1 will hit floor when 1 above the floor
  544. const RVec3 cInitialPos = cFloorHitPos - cDistanceTraveled;
  545. // Create sphere
  546. ioContext.CreateFloor();
  547. Body &body = ioContext.CreateSphere(cInitialPos, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  548. body.SetRestitution(0.0f);
  549. // Simulate until at floor
  550. ioContext.Simulate(cSimulationTime);
  551. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition());
  552. // Assert collision not yet processed
  553. CHECK_APPROX_EQUAL(cSimulationTime * cGravity, body.GetLinearVelocity(), 1.0e-4f);
  554. // Simulate one more step to process the collision
  555. ioContext.SimulateSingleStep();
  556. // Assert that all velocity was lost in the collision
  557. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  558. // Assert that we're on the floor
  559. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  560. // Simulate some more to validate that we remain on the floor
  561. ioContext.Simulate(cSimulationTime);
  562. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity(), 1.0e-4f);
  563. CHECK_APPROX_EQUAL(cFloorHitPos, body.GetPosition(), 1.0e-4f);
  564. }
  565. TEST_CASE("TestPhysicsCollisionInelastic")
  566. {
  567. PhysicsTestContext c1(1.0f / 60.0f, 1);
  568. TestPhysicsCollisionInelastic(c1);
  569. PhysicsTestContext c2(2.0f / 60.0f, 2);
  570. TestPhysicsCollisionInelastic(c2);
  571. PhysicsTestContext c4(4.0f / 60.0f, 4);
  572. TestPhysicsCollisionInelastic(c4);
  573. }
  574. TEST_CASE("TestMinVelocityForRestitution")
  575. {
  576. for (int i = 0; i < 2; ++i)
  577. {
  578. // Create a context
  579. PhysicsTestContext c;
  580. c.ZeroGravity();
  581. Body &sphere1 = c.CreateSphere(RVec3(0, -2, 0), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  582. sphere1.SetRestitution(1.0f);
  583. sphere1.SetLinearVelocity(Vec3(0, 1, 0));
  584. Body &sphere2 = c.CreateSphere(RVec3(0, +2, 0), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  585. sphere2.SetRestitution(1.0f);
  586. sphere2.SetLinearVelocity(Vec3::sZero());
  587. Vec3 expected1, expected2;
  588. PhysicsSettings s = c.GetSystem()->GetPhysicsSettings();
  589. if (i == 0)
  590. {
  591. // Make the minimum velocity for restitution bigger than the speed of the sphere
  592. s.mMinVelocityForRestitution = 1.01f;
  593. // Non elastic collision will make both spheres move at half speed
  594. expected1 = expected2 = 0.5f * sphere1.GetLinearVelocity();
  595. }
  596. else
  597. {
  598. // Make the minimum velocity for restitution smaller than the speed of the sphere
  599. s.mMinVelocityForRestitution = 0.99f;
  600. // Elastic collision will transfer all velocity to sphere 2
  601. expected1 = Vec3::sZero();
  602. expected2 = sphere1.GetLinearVelocity();
  603. }
  604. c.GetSystem()->SetPhysicsSettings(s);
  605. c.Simulate(2.5f);
  606. CHECK_APPROX_EQUAL(sphere1.GetLinearVelocity(), expected1);
  607. CHECK_APPROX_EQUAL(sphere2.GetLinearVelocity(), expected2);
  608. }
  609. }
  610. // Let box intersect with floor by cPenetrationSlop. It should not move, this is the maximum penetration allowed.
  611. static void TestPhysicsPenetrationSlop1(PhysicsTestContext &ioContext)
  612. {
  613. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  614. const float cSimulationTime = 1.0f;
  615. const RVec3 cInitialPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  616. // Create box, penetrating with floor
  617. ioContext.CreateFloor();
  618. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  619. // Simulate
  620. ioContext.Simulate(cSimulationTime);
  621. // Test slop not resolved
  622. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  623. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  624. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  625. }
  626. TEST_CASE("TestPhysicsPenetrationSlop1")
  627. {
  628. PhysicsTestContext c1(1.0f / 60.0f, 1);
  629. TestPhysicsPenetrationSlop1(c1);
  630. PhysicsTestContext c2(2.0f / 60.0f, 2);
  631. TestPhysicsPenetrationSlop1(c2);
  632. PhysicsTestContext c4(4.0f / 60.0f, 4);
  633. TestPhysicsPenetrationSlop1(c4);
  634. }
  635. // Let box intersect with floor with more than cPenetrationSlop. It should be resolved by SolvePositionConstraint until interpenetration is cPenetrationSlop.
  636. static void TestPhysicsPenetrationSlop2(PhysicsTestContext &ioContext)
  637. {
  638. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  639. const float cSimulationTime = 1.0f;
  640. const RVec3 cInitialPos(0.0f, 1.0f - 2.0f * cPenetrationSlop, 0.0f);
  641. const RVec3 cFinalPos(0.0f, 1.0f - cPenetrationSlop, 0.0f);
  642. // Create box, penetrating with floor
  643. ioContext.CreateFloor();
  644. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  645. // Simulate
  646. ioContext.Simulate(cSimulationTime);
  647. // Test resolved until slop
  648. CHECK_APPROX_EQUAL(cFinalPos, body.GetPosition(), 1.0e-5f);
  649. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  650. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  651. }
  652. TEST_CASE("TestPhysicsPenetrationSlop2")
  653. {
  654. PhysicsTestContext c1(1.0f / 60.0f, 1);
  655. TestPhysicsPenetrationSlop2(c1);
  656. PhysicsTestContext c2(2.0f / 60.0f, 2);
  657. TestPhysicsPenetrationSlop2(c2);
  658. PhysicsTestContext c4(4.0f / 60.0f, 4);
  659. TestPhysicsPenetrationSlop2(c4);
  660. }
  661. // Let box intersect with floor with less than cPenetrationSlop. Body should not move because SolveVelocityConstraint should reset velocity.
  662. static void TestPhysicsPenetrationSlop3(PhysicsTestContext &ioContext)
  663. {
  664. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  665. const float cSimulationTime = 1.0f;
  666. const RVec3 cInitialPos(0.0f, 1.0f - 0.1f * cPenetrationSlop, 0.0f);
  667. // Create box, penetrating with floor
  668. ioContext.CreateFloor();
  669. Body &body = ioContext.CreateBox(cInitialPos, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  670. // Simulate
  671. ioContext.Simulate(cSimulationTime);
  672. // Test body remained static
  673. CHECK_APPROX_EQUAL(cInitialPos, body.GetPosition(), 1.0e-5f);
  674. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetLinearVelocity());
  675. CHECK_APPROX_EQUAL(Vec3::sZero(), body.GetAngularVelocity());
  676. }
  677. TEST_CASE("TestPhysicsPenetrationSlop3")
  678. {
  679. PhysicsTestContext c1(1.0f / 60.0f, 1);
  680. TestPhysicsPenetrationSlop3(c1);
  681. PhysicsTestContext c2(2.0f / 60.0f, 2);
  682. TestPhysicsPenetrationSlop3(c2);
  683. PhysicsTestContext c4(4.0f / 60.0f, 4);
  684. TestPhysicsPenetrationSlop3(c4);
  685. }
  686. TEST_CASE("TestPhysicsOutsideOfSpeculativeContactDistance")
  687. {
  688. PhysicsTestContext c;
  689. Body &floor = c.CreateFloor();
  690. c.ZeroGravity();
  691. LoggingContactListener contact_listener;
  692. c.GetSystem()->SetContactListener(&contact_listener);
  693. // Create a box and a sphere just outside the speculative contact distance
  694. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  695. const float cDistanceAboveFloor = 1.1f * cSpeculativeContactDistance;
  696. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  697. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  698. // Make it move 1 m per step down
  699. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  700. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  701. box.SetLinearVelocity(cVelocity);
  702. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  703. sphere.SetLinearVelocity(cVelocity);
  704. // Simulate a step
  705. c.SimulateSingleStep();
  706. // 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)
  707. CHECK(contact_listener.GetEntryCount() == 0);
  708. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  709. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  710. // Simulate a step
  711. c.SimulateSingleStep();
  712. // Check that the contacts are detected now
  713. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  714. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  715. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  716. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  717. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  718. }
  719. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoRestitution")
  720. {
  721. PhysicsTestContext c;
  722. Body &floor = c.CreateFloor();
  723. c.ZeroGravity();
  724. LoggingContactListener contact_listener;
  725. c.GetSystem()->SetContactListener(&contact_listener);
  726. // Create a box and a sphere just inside the speculative contact distance
  727. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  728. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  729. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  730. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  731. // Make it move 1 m per step down
  732. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  733. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  734. box.SetLinearVelocity(cVelocity);
  735. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  736. sphere.SetLinearVelocity(cVelocity);
  737. // Simulate a step
  738. c.SimulateSingleStep();
  739. // Check that it is now on the floor and that 2 collisions have been detected
  740. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  741. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  742. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  743. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  744. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  745. contact_listener.Clear();
  746. // Velocity should have been reduced to exactly hit the floor in this step
  747. const Vec3 cExpectedVelocity(0, -cDistanceAboveFloor / c.GetDeltaTime(), 0);
  748. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  749. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  750. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cExpectedVelocity, 0.05f);
  751. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  752. // Sphere has only 1 contact point so is much more accurate
  753. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0));
  754. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cExpectedVelocity, 1.0e-4f);
  755. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  756. // Simulate a step
  757. c.SimulateSingleStep();
  758. // Check that the contacts persisted
  759. CHECK(contact_listener.GetEntryCount() >= 2); // 2 persist and possibly 2 validates depending on if the cache got reused
  760. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, box.GetID(), floor.GetID()));
  761. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  762. // Box should have come to rest
  763. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 1, 0), 1.0e-3f);
  764. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero(), 0.05f);
  765. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  766. // Sphere should have come to rest
  767. CHECK_APPROX_EQUAL(sphere.GetPosition(), RVec3(5, 1, 0), 1.0e-4f);
  768. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), Vec3::sZero(), 1.0e-4f);
  769. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 1.0e-4f);
  770. }
  771. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceWithRestitution")
  772. {
  773. PhysicsTestContext c;
  774. Body &floor = c.CreateFloor();
  775. c.ZeroGravity();
  776. LoggingContactListener contact_listener;
  777. c.GetSystem()->SetContactListener(&contact_listener);
  778. // Create a box and a sphere just inside the speculative contact distance
  779. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  780. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  781. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  782. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  783. // Make it move 1 m per step down
  784. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  785. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  786. box.SetLinearVelocity(cVelocity);
  787. box.SetRestitution(1.0f);
  788. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  789. sphere.SetLinearVelocity(cVelocity);
  790. sphere.SetRestitution(1.0f);
  791. // Simulate a step
  792. c.SimulateSingleStep();
  793. // Check that it has triggered contact points and has bounced from it's initial position (effectively traveling the extra distance to the floor and back for free)
  794. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  795. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  796. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  797. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  798. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  799. contact_listener.Clear();
  800. // Box collision is less accurate than sphere as it hits with 4 corners so there's some floating point precision loss in the calculation
  801. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox - cVelocity * c.GetDeltaTime(), 0.01f);
  802. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), -cVelocity, 0.1f);
  803. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 0.02f);
  804. // Sphere has only 1 contact point so is much more accurate
  805. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere - cVelocity * c.GetDeltaTime(), 1.0e-5f);
  806. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), -cVelocity, 2.0e-4f);
  807. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero(), 2.0e-4f);
  808. // Simulate a step
  809. c.SimulateSingleStep();
  810. // Check that all contact points are removed
  811. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  812. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  813. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  814. }
  815. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceNoHit")
  816. {
  817. PhysicsTestContext c;
  818. Body &floor = c.CreateFloor();
  819. floor.SetRestitution(1.0f);
  820. c.ZeroGravity();
  821. // Turn off the minimum velocity for restitution, our velocity is lower than the default
  822. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  823. settings.mMinVelocityForRestitution = 0.0f;
  824. c.GetSystem()->SetPhysicsSettings(settings);
  825. LoggingContactListener contact_listener;
  826. c.GetSystem()->SetContactListener(&contact_listener);
  827. // Create a sphere inside speculative contact distance from the ground
  828. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  829. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  830. const RVec3 cInitialPosSphere(0, 1.0f + cDistanceAboveFloor, 0.0f);
  831. // Make it move slow enough so that it will not touch the floor in 1 time step
  832. const Vec3 cVelocity(0, -0.9f * cDistanceAboveFloor / c.GetDeltaTime(), 0);
  833. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  834. sphere.SetLinearVelocity(cVelocity);
  835. sphere.SetRestitution(1.0f);
  836. sphere.GetMotionProperties()->SetLinearDamping(0.0f);
  837. // Simulate a step
  838. c.SimulateSingleStep();
  839. // Check that it has triggered contact points from the speculative contacts
  840. CHECK(contact_listener.GetEntryCount() == 2);
  841. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  842. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  843. contact_listener.Clear();
  844. // Check that sphere didn't actually change velocity (it hasn't actually interacted with the floor, the speculative contact was not an actual contact)
  845. CHECK(sphere.GetLinearVelocity() == cVelocity);
  846. // Simulate a step
  847. c.SimulateSingleStep();
  848. // Check again that it triggered contact points
  849. CHECK(contact_listener.GetEntryCount() == 2);
  850. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  851. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, sphere.GetID(), floor.GetID()));
  852. contact_listener.Clear();
  853. // It should have bounced back up and inverted velocity due to restitution being 1
  854. CHECK_APPROX_EQUAL(-sphere.GetLinearVelocity(), cVelocity);
  855. }
  856. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceSensor")
  857. {
  858. PhysicsTestContext c;
  859. Body &floor = c.CreateFloor();
  860. c.ZeroGravity();
  861. LoggingContactListener contact_listener;
  862. c.GetSystem()->SetContactListener(&contact_listener);
  863. // Create a sphere sensor just inside the speculative contact distance
  864. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  865. const float cRadius = 1.0f;
  866. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  867. const RVec3 cInitialPosSphere(5, cRadius + cDistanceAboveFloor, 0);
  868. // Make it move 1 m per step down
  869. const Vec3 cVelocity(0, -1.0f / c.GetDeltaTime(), 0);
  870. Body &sphere = c.CreateSphere(cInitialPosSphere, cRadius, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  871. sphere.SetIsSensor(true);
  872. sphere.SetLinearVelocity(cVelocity);
  873. // Simulate a step
  874. c.SimulateSingleStep();
  875. CHECK(contact_listener.GetEntryCount() == 0); // We're inside the speculative contact distance but we're a sensor so we shouldn't trigger any contacts
  876. // Simulate a step
  877. c.SimulateSingleStep();
  878. // Check that we're now actually intersecting
  879. CHECK(contact_listener.GetEntryCount() == 2); // 1 validates and 1 contact
  880. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  881. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  882. contact_listener.Clear();
  883. // Sensor should not be affected by the floor
  884. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + 2.0f * c.GetDeltaTime() * cVelocity);
  885. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  886. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  887. }
  888. TEST_CASE("TestPhysicsInsideSpeculativeContactDistanceMovingAway")
  889. {
  890. PhysicsTestContext c;
  891. Body &floor = c.CreateFloor();
  892. c.ZeroGravity();
  893. LoggingContactListener contact_listener;
  894. c.GetSystem()->SetContactListener(&contact_listener);
  895. // Create a box and a sphere just inside the speculative contact distance
  896. const float cSpeculativeContactDistance = c.GetSystem()->GetPhysicsSettings().mSpeculativeContactDistance;
  897. const float cDistanceAboveFloor = 0.9f * cSpeculativeContactDistance;
  898. const RVec3 cInitialPosBox(0, 1.0f + cDistanceAboveFloor, 0.0f);
  899. const RVec3 cInitialPosSphere = cInitialPosBox + Vec3(5, 0, 0);
  900. // Make it move 1 m per step up
  901. const Vec3 cVelocity(0, 1.0f / c.GetDeltaTime(), 0);
  902. Body &box = c.CreateBox(cInitialPosBox, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3(1, 1, 1));
  903. box.SetLinearVelocity(cVelocity);
  904. box.SetRestitution(1.0f);
  905. Body &sphere = c.CreateSphere(cInitialPosSphere, 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING);
  906. sphere.SetLinearVelocity(cVelocity);
  907. sphere.SetRestitution(1.0f);
  908. // Simulate a step
  909. c.SimulateSingleStep();
  910. // 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)
  911. CHECK(contact_listener.GetEntryCount() == 4); // 2 validates and 2 contacts
  912. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, box.GetID(), floor.GetID()));
  913. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, box.GetID(), floor.GetID()));
  914. CHECK(contact_listener.Contains(LoggingContactListener::EType::Validate, sphere.GetID(), floor.GetID()));
  915. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, sphere.GetID(), floor.GetID()));
  916. contact_listener.Clear();
  917. // Box should have moved unimpeded
  918. CHECK_APPROX_EQUAL(box.GetPosition(), cInitialPosBox + cVelocity * c.GetDeltaTime());
  919. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), cVelocity);
  920. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  921. // Sphere should have moved unimpeded
  922. CHECK_APPROX_EQUAL(sphere.GetPosition(), cInitialPosSphere + cVelocity * c.GetDeltaTime());
  923. CHECK_APPROX_EQUAL(sphere.GetLinearVelocity(), cVelocity);
  924. CHECK_APPROX_EQUAL(sphere.GetAngularVelocity(), Vec3::sZero());
  925. // Simulate a step
  926. c.SimulateSingleStep();
  927. // Check that all contact points are removed
  928. CHECK(contact_listener.GetEntryCount() == 2); // 2 removes
  929. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, box.GetID(), floor.GetID()));
  930. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, sphere.GetID(), floor.GetID()));
  931. }
  932. static void TestPhysicsActivationDeactivation(PhysicsTestContext &ioContext)
  933. {
  934. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  935. // Install activation listener
  936. LoggingBodyActivationListener activation_listener;
  937. ioContext.GetSystem()->SetBodyActivationListener(&activation_listener);
  938. // Create floor
  939. Body &floor = ioContext.CreateBox(RVec3(0, -1, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100, 1, 100));
  940. CHECK(!floor.IsActive());
  941. // Create inactive box
  942. Body &box = ioContext.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::DontActivate);
  943. CHECK(!box.IsActive());
  944. CHECK(activation_listener.GetEntryCount() == 0);
  945. // Box should not activate by itself
  946. ioContext.Simulate(1.0f);
  947. CHECK(box.GetPosition() == RVec3(0, 5, 0));
  948. CHECK(!box.IsActive());
  949. CHECK(activation_listener.GetEntryCount() == 0);
  950. // Activate the body and validate it is active now
  951. ioContext.GetBodyInterface().ActivateBody(box.GetID());
  952. CHECK(box.IsActive());
  953. CHECK(box.GetLinearVelocity().IsNearZero());
  954. CHECK(activation_listener.GetEntryCount() == 1);
  955. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, box.GetID()));
  956. activation_listener.Clear();
  957. // Do a single step and check that the body is still active and has gained some velocity
  958. ioContext.SimulateSingleStep();
  959. CHECK(box.IsActive());
  960. CHECK(activation_listener.GetEntryCount() == 0);
  961. CHECK(!box.GetLinearVelocity().IsNearZero());
  962. // Simulate 5 seconds and check it has settled on the floor and is no longer active
  963. ioContext.Simulate(5.0f);
  964. CHECK_APPROX_EQUAL(box.GetPosition(), RVec3(0, 0.5f, 0), 1.1f * cPenetrationSlop);
  965. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), Vec3::sZero());
  966. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero());
  967. CHECK(!box.IsActive());
  968. CHECK(activation_listener.GetEntryCount() == 1);
  969. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Deactivated, box.GetID()));
  970. }
  971. TEST_CASE("TestPhysicsActivationDeactivation")
  972. {
  973. PhysicsTestContext c1(1.0f / 60.0f, 1);
  974. TestPhysicsActivationDeactivation(c1);
  975. PhysicsTestContext c2(2.0f / 60.0f, 2);
  976. TestPhysicsActivationDeactivation(c2);
  977. PhysicsTestContext c4(4.0f / 60.0f, 4);
  978. TestPhysicsActivationDeactivation(c4);
  979. }
  980. // 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
  981. static void TestPhysicsActivateDuringStep(PhysicsTestContext &ioContext, bool inReverseCreate)
  982. {
  983. const float cPenetrationSlop = ioContext.GetSystem()->GetPhysicsSettings().mPenetrationSlop;
  984. const int cNumBodies = 10;
  985. const float cBoxExtent = 0.5f;
  986. PhysicsSystem *system = ioContext.GetSystem();
  987. BodyInterface &bi = ioContext.GetBodyInterface();
  988. LoggingBodyActivationListener activation_listener;
  989. system->SetBodyActivationListener(&activation_listener);
  990. LoggingContactListener contact_listener;
  991. system->SetContactListener(&contact_listener);
  992. // 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
  993. BodyIDVector body_ids;
  994. if (inReverseCreate)
  995. for (int i = cNumBodies - 1; i >= 0; --i)
  996. 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());
  997. else
  998. for (int i = 0; i < cNumBodies; ++i)
  999. 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());
  1000. // Test that nothing is active yet
  1001. CHECK(activation_listener.GetEntryCount() == 0);
  1002. CHECK(contact_listener.GetEntryCount() == 0);
  1003. for (BodyID id : body_ids)
  1004. CHECK(!bi.IsActive(id));
  1005. // 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
  1006. bi.SetLinearVelocity(body_ids.front(), Vec3(500, 0, 0));
  1007. // Test that only the left most box is active
  1008. CHECK(activation_listener.GetEntryCount() == 1);
  1009. CHECK(contact_listener.GetEntryCount() == 0);
  1010. CHECK(bi.IsActive(body_ids.front()));
  1011. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, body_ids.front()));
  1012. for (int i = 1; i < cNumBodies; ++i)
  1013. CHECK(!bi.IsActive(body_ids[i]));
  1014. activation_listener.Clear();
  1015. // Step the world
  1016. ioContext.SimulateSingleStep();
  1017. // Other bodies should now be awake and each body should only collide with its neighbor
  1018. CHECK(activation_listener.GetEntryCount() == cNumBodies - 1);
  1019. CHECK(contact_listener.GetEntryCount() == 2 * (cNumBodies - 1));
  1020. for (int i = 0; i < cNumBodies; ++i)
  1021. {
  1022. BodyID id = body_ids[i];
  1023. // Check body is active
  1024. CHECK(bi.IsActive(id));
  1025. // Check that body moved to the right
  1026. CHECK(bi.GetPosition(id).GetX() > i * (2.0f * cBoxExtent - cPenetrationSlop));
  1027. }
  1028. for (int i = 1; i < cNumBodies; ++i)
  1029. {
  1030. BodyID id1 = body_ids[i - 1];
  1031. BodyID id2 = body_ids[i];
  1032. // Check that we received activation events for each body
  1033. CHECK(activation_listener.Contains(LoggingBodyActivationListener::EType::Activated, id2));
  1034. // Check that we received a validate and an add for each body pair
  1035. int validate = contact_listener.Find(LoggingContactListener::EType::Validate, id1, id2);
  1036. CHECK(validate >= 0);
  1037. int add = contact_listener.Find(LoggingContactListener::EType::Add, id1, id2);
  1038. CHECK(add >= 0);
  1039. CHECK(add > validate);
  1040. // Check that bodies did not tunnel through each other
  1041. CHECK(bi.GetPosition(id1).GetX() < bi.GetPosition(id2).GetX());
  1042. }
  1043. }
  1044. TEST_CASE("TestPhysicsActivateDuringStep")
  1045. {
  1046. PhysicsTestContext c;
  1047. TestPhysicsActivateDuringStep(c, false);
  1048. PhysicsTestContext c2;
  1049. TestPhysicsActivateDuringStep(c2, true);
  1050. }
  1051. TEST_CASE("TestPhysicsBroadPhaseLayers")
  1052. {
  1053. PhysicsTestContext c;
  1054. BodyInterface &bi = c.GetBodyInterface();
  1055. // Reduce slop
  1056. PhysicsSettings settings = c.GetSystem()->GetPhysicsSettings();
  1057. settings.mPenetrationSlop = 0.0f;
  1058. c.GetSystem()->SetPhysicsSettings(settings);
  1059. // Create static floor
  1060. c.CreateFloor();
  1061. // Create MOVING boxes
  1062. Body &moving1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  1063. Body &moving2 = c.CreateBox(RVec3(0, 2, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sReplicate(0.5f), EActivation::Activate);
  1064. // Create HQ_DEBRIS boxes
  1065. Body &hq_debris1 = c.CreateBox(RVec3(0, 3, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  1066. Body &hq_debris2 = c.CreateBox(RVec3(0, 4, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::HQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  1067. // Create LQ_DEBRIS boxes
  1068. Body &lq_debris1 = c.CreateBox(RVec3(0, 5, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  1069. Body &lq_debris2 = c.CreateBox(RVec3(0, 6, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::LQ_DEBRIS, Vec3::sReplicate(0.5f), EActivation::Activate);
  1070. // Check layers
  1071. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  1072. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  1073. CHECK(hq_debris1.GetObjectLayer() == Layers::HQ_DEBRIS);
  1074. CHECK(hq_debris2.GetObjectLayer() == Layers::HQ_DEBRIS);
  1075. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1076. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1077. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1078. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1079. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1080. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1081. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1082. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1083. // Simulate the boxes falling
  1084. c.Simulate(5.0f);
  1085. // Everything should sleep
  1086. CHECK_FALSE(moving1.IsActive());
  1087. CHECK_FALSE(moving2.IsActive());
  1088. CHECK_FALSE(hq_debris1.IsActive());
  1089. CHECK_FALSE(hq_debris2.IsActive());
  1090. CHECK_FALSE(lq_debris1.IsActive());
  1091. CHECK_FALSE(lq_debris2.IsActive());
  1092. // MOVING boxes should have stacked
  1093. float slop = 0.02f;
  1094. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1095. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  1096. // HQ_DEBRIS boxes should have stacked on MOVING boxes but don't collide with each other
  1097. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 2.5f, 0), slop);
  1098. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 2.5f, 0), slop);
  1099. // LQ_DEBRIS should have fallen through all but the floor
  1100. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1101. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1102. // Now change HQ_DEBRIS to LQ_DEBRIS
  1103. bi.SetObjectLayer(hq_debris1.GetID(), Layers::LQ_DEBRIS);
  1104. bi.SetObjectLayer(hq_debris2.GetID(), Layers::LQ_DEBRIS);
  1105. bi.ActivateBody(hq_debris1.GetID());
  1106. bi.ActivateBody(hq_debris2.GetID());
  1107. // Check layers
  1108. CHECK(moving1.GetObjectLayer() == Layers::MOVING);
  1109. CHECK(moving2.GetObjectLayer() == Layers::MOVING);
  1110. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1111. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1112. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1113. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1114. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1115. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1116. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1117. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1118. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1119. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1120. // Simulate again
  1121. c.Simulate(5.0f);
  1122. // Everything should sleep
  1123. CHECK_FALSE(moving1.IsActive());
  1124. CHECK_FALSE(moving2.IsActive());
  1125. CHECK_FALSE(hq_debris1.IsActive());
  1126. CHECK_FALSE(hq_debris2.IsActive());
  1127. CHECK_FALSE(lq_debris1.IsActive());
  1128. CHECK_FALSE(lq_debris2.IsActive());
  1129. // MOVING boxes should have stacked
  1130. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1131. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 1.5f, 0), slop);
  1132. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1133. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1134. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1135. // LQ_DEBRIS should have fallen through all but the floor
  1136. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1137. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1138. // Now change MOVING to HQ_DEBRIS (this doesn't change the broadphase layer so avoids adding/removing bodies)
  1139. bi.SetObjectLayer(moving1.GetID(), Layers::HQ_DEBRIS);
  1140. bi.SetObjectLayer(moving2.GetID(), Layers::HQ_DEBRIS);
  1141. bi.ActivateBody(moving1.GetID());
  1142. bi.ActivateBody(moving2.GetID());
  1143. // Check layers
  1144. CHECK(moving1.GetObjectLayer() == Layers::HQ_DEBRIS);
  1145. CHECK(moving2.GetObjectLayer() == Layers::HQ_DEBRIS);
  1146. CHECK(hq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1147. CHECK(hq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1148. CHECK(lq_debris1.GetObjectLayer() == Layers::LQ_DEBRIS);
  1149. CHECK(lq_debris2.GetObjectLayer() == Layers::LQ_DEBRIS);
  1150. CHECK(moving1.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING); // Broadphase layer didn't change
  1151. CHECK(moving2.GetBroadPhaseLayer() == BroadPhaseLayers::MOVING);
  1152. CHECK(hq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1153. CHECK(hq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1154. CHECK(lq_debris1.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1155. CHECK(lq_debris2.GetBroadPhaseLayer() == BroadPhaseLayers::LQ_DEBRIS);
  1156. // Simulate again
  1157. c.Simulate(5.0f);
  1158. // Everything should sleep
  1159. CHECK_FALSE(moving1.IsActive());
  1160. CHECK_FALSE(moving2.IsActive());
  1161. CHECK_FALSE(hq_debris1.IsActive());
  1162. CHECK_FALSE(hq_debris2.IsActive());
  1163. CHECK_FALSE(lq_debris1.IsActive());
  1164. CHECK_FALSE(lq_debris2.IsActive());
  1165. // MOVING boxes now also fall through
  1166. CHECK_APPROX_EQUAL(moving1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1167. CHECK_APPROX_EQUAL(moving2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1168. // HQ_DEBRIS (now LQ_DEBRIS) boxes have fallen through all but the floor
  1169. CHECK_APPROX_EQUAL(hq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1170. CHECK_APPROX_EQUAL(hq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1171. // LQ_DEBRIS should have fallen through all but the floor
  1172. CHECK_APPROX_EQUAL(lq_debris1.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1173. CHECK_APPROX_EQUAL(lq_debris2.GetPosition(), RVec3(0, 0.5f, 0), slop);
  1174. }
  1175. TEST_CASE("TestMultiplePhysicsSystems")
  1176. {
  1177. PhysicsTestContext c1;
  1178. c1.ZeroGravity();
  1179. PhysicsTestContext c2;
  1180. c2.ZeroGravity();
  1181. const RVec3 cBox1Position(1.0f, 2.0f, 3.0f);
  1182. Body &box1 = c1.CreateBox(cBox1Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sOne(), EActivation::Activate);
  1183. const RVec3 cBox2Position(4.0f, 5.0f, 6.0f);
  1184. Body& box2 = c2.CreateBox(cBox2Position, Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sOne(), EActivation::Activate);
  1185. const Vec3 cBox1Velocity(1.0f, 0, 0);
  1186. const Vec3 cBox2Velocity(2.0f, 0, 0);
  1187. {
  1188. // 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)
  1189. BodyLockWrite lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1190. BodyLockWrite lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1191. CHECK(lock1.GetBody().GetPosition() == cBox1Position);
  1192. CHECK(lock2.GetBody().GetPosition() == cBox2Position);
  1193. lock1.GetBody().SetLinearVelocity(cBox1Velocity);
  1194. lock2.GetBody().SetLinearVelocity(cBox2Velocity);
  1195. }
  1196. const float cTime = 1.0f;
  1197. c1.Simulate(cTime);
  1198. c2.Simulate(cTime);
  1199. {
  1200. BodyLockRead lock1(c1.GetSystem()->GetBodyLockInterface(), box1.GetID());
  1201. BodyLockRead lock2(c2.GetSystem()->GetBodyLockInterface(), box2.GetID());
  1202. // Check that the bodies in the different systems updated correctly
  1203. CHECK_APPROX_EQUAL(lock1.GetBody().GetPosition(), cBox1Position + cBox1Velocity * cTime, 1.0e-5f);
  1204. CHECK_APPROX_EQUAL(lock2.GetBody().GetPosition(), cBox2Position + cBox2Velocity * cTime, 1.0e-5f);
  1205. }
  1206. }
  1207. TEST_CASE("TestOutOfBodies")
  1208. {
  1209. // Create a context with space for a single body
  1210. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1);
  1211. BodyInterface& bi = c.GetBodyInterface();
  1212. // First body
  1213. Body *b1 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1214. CHECK(b1 != nullptr);
  1215. // Second body should fail
  1216. Body *b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1217. CHECK(b2 == nullptr);
  1218. // Free first body
  1219. bi.DestroyBody(b1->GetID());
  1220. // Second body creation should succeed
  1221. b2 = bi.CreateBody(BodyCreationSettings(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1222. CHECK(b2 != nullptr);
  1223. // Clean up
  1224. bi.DestroyBody(b2->GetID());
  1225. }
  1226. static int sStackFullMsgs = 0;
  1227. static int sOtherMsgs = 0;
  1228. static void sStackFullTrace(const char *inFMT, ...)
  1229. {
  1230. if (std::strstr(inFMT, "Stack full") != nullptr)
  1231. ++sStackFullMsgs;
  1232. else
  1233. ++sOtherMsgs;
  1234. }
  1235. TEST_CASE("TestAddSingleBodies")
  1236. {
  1237. PhysicsTestContext c(1.0f / 60.0f, 1, 0);
  1238. BodyInterface& bi = c.GetBodyInterface();
  1239. PhysicsSystem &sys = *c.GetSystem();
  1240. const int cMaxBodies = 128;
  1241. // Add individual bodies in a way that will create an inefficient broad phase and will trigger a warning on query
  1242. RefConst<Shape> sphere = new SphereShape(1.0f);
  1243. bi.CreateAndAddBody(BodyCreationSettings(sphere, RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING), EActivation::Activate); // Leave this body
  1244. for (int repeat = 0; repeat < 10; ++repeat)
  1245. {
  1246. // Create cMaxBodies - 1 bodies
  1247. BodyIDVector body_ids;
  1248. for (int i = 0; i < cMaxBodies - 1; ++i)
  1249. body_ids.push_back(bi.CreateAndAddBody(BodyCreationSettings(sphere, RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING), EActivation::Activate));
  1250. // In all but the last iteration, remove the bodies again
  1251. if (repeat < 9)
  1252. for (BodyID id : body_ids)
  1253. {
  1254. bi.DeactivateBody(id);
  1255. bi.RemoveBody(id);
  1256. bi.DestroyBody(id);
  1257. }
  1258. }
  1259. // Override the trace function to count how many times we get a "Stack full" message
  1260. TraceFunction old_trace = Trace;
  1261. sStackFullMsgs = 0;
  1262. sOtherMsgs = 0;
  1263. Trace = sStackFullTrace;
  1264. // Cast a ray
  1265. AllHitCollisionCollector<CastRayCollector> ray_collector;
  1266. sys.GetNarrowPhaseQuery().CastRay(RRayCast(RVec3(-2, 0, 0), Vec3(2, 0, 0)), {}, ray_collector);
  1267. // Find colliding pairs
  1268. BodyIDVector active_bodies;
  1269. sys.GetActiveBodies(EBodyType::RigidBody, active_bodies);
  1270. AllHitCollisionCollector<BodyPairCollector> body_pair_collector;
  1271. static_cast<const BroadPhase &>(sys.GetBroadPhaseQuery()).FindCollidingPairs(active_bodies.data(), (int)active_bodies.size(), 0.0f, sys.GetObjectVsBroadPhaseLayerFilter(), sys.GetObjectLayerPairFilter(), body_pair_collector);
  1272. // Restore the old trace function
  1273. Trace = old_trace;
  1274. // Assert that we got a "Stack full" message when asserts are enabled
  1275. #ifdef JPH_ENABLE_ASSERTS
  1276. CHECK(sStackFullMsgs == 1);
  1277. #else
  1278. CHECK(sStackFullMsgs == 0);
  1279. #endif
  1280. CHECK(sOtherMsgs == 0);
  1281. // Assert that we hit all bodies
  1282. CHECK(ray_collector.mHits.size() == cMaxBodies);
  1283. CHECK(body_pair_collector.mHits.size() == cMaxBodies * (cMaxBodies - 1) / 2);
  1284. }
  1285. TEST_CASE("TestOutOfContactConstraints")
  1286. {
  1287. // Create a context with space for 8 constraints
  1288. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1289. c.CreateFloor();
  1290. // The first 8 boxes should be fine
  1291. for (int i = 0; i < 8; ++i)
  1292. c.CreateBox(RVec3(3.0_r * i, 0.9_r, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sOne(), EActivation::Activate);
  1293. // Step
  1294. EPhysicsUpdateError errors = c.SimulateSingleStep();
  1295. CHECK(errors == EPhysicsUpdateError::None);
  1296. // Adding one more box should introduce an error
  1297. c.CreateBox(RVec3(24.0_r, 0.9_r, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sOne(), EActivation::Activate);
  1298. // Step
  1299. {
  1300. JPH_IF_ENABLE_ASSERTS(ExpectAssert expect_assert(1);)
  1301. errors = c.SimulateSingleStep();
  1302. }
  1303. CHECK((errors & EPhysicsUpdateError::ContactConstraintsFull) != EPhysicsUpdateError::None);
  1304. }
  1305. TEST_CASE("TestFriction")
  1306. {
  1307. const float friction_floor = 0.9f;
  1308. const float friction_box = 0.8f;
  1309. const float combined_friction = sqrt(friction_floor * friction_box);
  1310. for (float angle = 0; angle < 360.0f; angle += 30.0f)
  1311. {
  1312. // Create a context with space for 8 constraints
  1313. PhysicsTestContext c(1.0f / 60.0f, 1, 0, 1024, 4096, 8);
  1314. // Create floor
  1315. Body &floor = c.CreateFloor();
  1316. floor.SetFriction(friction_floor);
  1317. // Create box with a velocity that will make it slide over the floor (making sure it intersects a little bit initially)
  1318. BodyCreationSettings box_settings(new BoxShape(Vec3::sOne()), RVec3(0, 0.999_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1319. box_settings.mFriction = friction_box;
  1320. box_settings.mLinearDamping = 0;
  1321. box_settings.mLinearVelocity = Vec3(Sin(DegreesToRadians(angle)), 0, Cos(DegreesToRadians(angle))) * 20.0f;
  1322. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1323. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1324. // We know that the friction force equals the normal force times the friction coefficient
  1325. float friction_acceleration = combined_friction * c.GetSystem()->GetGravity().Length();
  1326. // Simulate
  1327. Vec3 velocity = box_settings.mLinearVelocity;
  1328. RVec3 position = box_settings.mPosition;
  1329. for (int i = 0; i < 60; ++i)
  1330. {
  1331. c.SimulateSingleStep();
  1332. // Integrate our own simulation
  1333. velocity -= velocity.Normalized() * friction_acceleration * c.GetDeltaTime();
  1334. position += velocity * c.GetDeltaTime();
  1335. }
  1336. // Note that the result is not very accurate so we need quite a high tolerance
  1337. CHECK_APPROX_EQUAL(box.GetCenterOfMassPosition(), position, 1.0e-2f);
  1338. CHECK_APPROX_EQUAL(box.GetRotation(), box_settings.mRotation, 1.0e-2f);
  1339. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), velocity, 2.0e-2f);
  1340. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), Vec3::sZero(), 1.0e-2f);
  1341. }
  1342. }
  1343. TEST_CASE("TestAllowedDOFs")
  1344. {
  1345. for (uint allowed_dofs = 1; allowed_dofs <= 0b111111; ++allowed_dofs)
  1346. {
  1347. // Create a context
  1348. PhysicsTestContext c;
  1349. c.ZeroGravity();
  1350. // Create box
  1351. RVec3 initial_position(1, 2, 3);
  1352. Quat initial_rotation = Quat::sRotation(Vec3::sReplicate(sqrt(1.0f / 3.0f)), DegreesToRadians(20.0f));
  1353. ShapeRefC box_shape = new BoxShape(Vec3(0.3f, 0.5f, 0.7f));
  1354. BodyCreationSettings box_settings(box_shape, initial_position, initial_rotation, EMotionType::Dynamic, Layers::MOVING);
  1355. box_settings.mLinearDamping = 0;
  1356. box_settings.mAngularDamping = 0;
  1357. box_settings.mAllowedDOFs = (EAllowedDOFs)allowed_dofs;
  1358. Body &box = *c.GetBodyInterface().CreateBody(box_settings);
  1359. c.GetBodyInterface().AddBody(box.GetID(), EActivation::Activate);
  1360. // Apply a force and torque in 3D
  1361. Vec3 force(100000, 110000, 120000);
  1362. box.AddForce(force);
  1363. Vec3 torque(13000, 14000, 15000);
  1364. box.AddTorque(torque);
  1365. // Simulate
  1366. c.SimulateSingleStep();
  1367. // Cancel components that should not be allowed by the allowed DOFs
  1368. Vec3 linear_lock = Vec3::sOne(), angular_lock = Vec3::sOne();
  1369. for (uint axis = 0; axis < 3; ++axis)
  1370. {
  1371. if ((allowed_dofs & (1 << axis)) == 0)
  1372. linear_lock.SetComponent(axis, 0.0f);
  1373. if ((allowed_dofs & (0b1000 << axis)) == 0)
  1374. angular_lock.SetComponent(axis, 0.0f);
  1375. }
  1376. // Check resulting linear velocity
  1377. MassProperties mp = box_shape->GetMassProperties();
  1378. Vec3 expected_linear_velocity = linear_lock * (force / mp.mMass * c.GetDeltaTime());
  1379. CHECK((linear_lock == Vec3::sZero() || expected_linear_velocity.Length() > 1.0f)); // Just to check that we applied a high enough force
  1380. CHECK_APPROX_EQUAL(box.GetLinearVelocity(), expected_linear_velocity);
  1381. RVec3 expected_position = initial_position + expected_linear_velocity * c.GetDeltaTime();
  1382. CHECK_APPROX_EQUAL(box.GetPosition(), expected_position);
  1383. // Check resulting angular velocity
  1384. Mat44 inv_inertia = Mat44::sRotation(initial_rotation) * mp.mInertia.Inversed3x3() * Mat44::sRotation(initial_rotation.Conjugated());
  1385. inv_inertia = Mat44::sScale(angular_lock) * inv_inertia * Mat44::sScale(angular_lock); // Clear row and column for locked axes
  1386. Vec3 expected_angular_velocity = inv_inertia * torque * c.GetDeltaTime();
  1387. CHECK((angular_lock == Vec3::sZero() || expected_angular_velocity.Length() > 1.0f)); // Just to check that we applied a high enough torque
  1388. CHECK_APPROX_EQUAL(box.GetAngularVelocity(), expected_angular_velocity);
  1389. float expected_angular_velocity_len = expected_angular_velocity.Length();
  1390. 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;
  1391. CHECK_APPROX_EQUAL(box.GetRotation(), expected_rotation);
  1392. }
  1393. }
  1394. TEST_CASE("TestAllowedDOFsVsCollision")
  1395. {
  1396. PhysicsTestContext c;
  1397. Body &floor = c.CreateFloor();
  1398. floor.SetFriction(1.0f);
  1399. LoggingContactListener contact_listener;
  1400. c.GetSystem()->SetContactListener(&contact_listener);
  1401. // Create box that can only rotate around Y that intersects with the floor
  1402. RVec3 initial_position(0, 0.99f, 0);
  1403. BodyCreationSettings box_settings(new BoxShape(Vec3::sOne()), initial_position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1404. box_settings.mAllowedDOFs = EAllowedDOFs::RotationY;
  1405. box_settings.mAngularDamping = 0.0f; // No damping to make the calculation for expected angular velocity simple
  1406. box_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  1407. box_settings.mMassPropertiesOverride.mMass = 1.0f;
  1408. box_settings.mFriction = 1.0f; // High friction so that if the collision is processed, we'll slow down the rotation
  1409. Body *body = c.GetBodyInterface().CreateBody(box_settings);
  1410. c.GetBodyInterface().AddBody(body->GetID(), EActivation::Activate);
  1411. // Make the box rotate around Y
  1412. const Vec3 torque(0, 100.0f, 0);
  1413. body->AddTorque(torque);
  1414. // Simulate a step, this will make the box collide with the floor but should not result in the floor stopping the body
  1415. // but will cause the effective mass of the contact to become infinite so is a test if we are properly ignoring the contact in this case
  1416. c.SimulateSingleStep();
  1417. // Check that we did detect the collision
  1418. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), body->GetID()));
  1419. // Check that we have the correct angular velocity
  1420. Vec3 expected_angular_velocity = torque * c.GetDeltaTime() * body->GetInverseInertia()(1, 1);
  1421. CHECK_APPROX_EQUAL(body->GetAngularVelocity(), expected_angular_velocity);
  1422. CHECK(body->GetLinearVelocity() == Vec3::sZero());
  1423. CHECK(body->GetPosition() == initial_position);
  1424. }
  1425. TEST_CASE("TestSelectiveStateSaveAndRestore")
  1426. {
  1427. class MyFilter : public StateRecorderFilter
  1428. {
  1429. public:
  1430. bool ShouldSaveBody(const BodyID &inBodyID) const
  1431. {
  1432. return std::find(mIgnoreBodies.cbegin(), mIgnoreBodies.cend(), inBodyID) == mIgnoreBodies.cend();
  1433. }
  1434. virtual bool ShouldSaveBody(const Body &inBody) const override
  1435. {
  1436. return ShouldSaveBody(inBody.GetID());
  1437. }
  1438. virtual bool ShouldSaveContact(const BodyID &inBody1, const BodyID &inBody2) const override
  1439. {
  1440. return ShouldSaveBody(inBody1) && ShouldSaveBody(inBody2);
  1441. }
  1442. Array<BodyID> mIgnoreBodies;
  1443. };
  1444. for (int mode = 0; mode < 2; mode++)
  1445. {
  1446. PhysicsTestContext c;
  1447. Vec3 gravity = c.GetSystem()->GetGravity();
  1448. Vec3 upside_down_gravity = -gravity;
  1449. // Create the ground.
  1450. Body &ground = c.CreateFloor();
  1451. // Create two sets of bodies that each overlap
  1452. Body &box1 = c.CreateBox(RVec3(0, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sOne(), EActivation::Activate);
  1453. Body &sphere1 = c.CreateSphere(RVec3(0, 1, 0.1f), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate);
  1454. Body &box2 = c.CreateBox(RVec3(5, 1, 0), Quat::sIdentity(), EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, Vec3::sOne(), EActivation::Activate);
  1455. Body &sphere2 = c.CreateSphere(RVec3(5, 1, 0.1f), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate);
  1456. // Store the absolute initial state, that will be used for the final test.
  1457. StateRecorderImpl absolute_initial_state;
  1458. c.GetSystem()->SaveState(absolute_initial_state);
  1459. EStateRecorderState state_to_save = EStateRecorderState::All;
  1460. MyFilter filter;
  1461. if (mode == 1)
  1462. {
  1463. // Don't save the global state
  1464. state_to_save = EStateRecorderState::All ^ EStateRecorderState::Global;
  1465. // Don't save some bodies
  1466. filter.mIgnoreBodies.push_back(ground.GetID());
  1467. filter.mIgnoreBodies.push_back(box2.GetID());
  1468. filter.mIgnoreBodies.push_back(sphere2.GetID());
  1469. }
  1470. // Store the initial transform.
  1471. const RMat44 initial_box1_transform = box1.GetWorldTransform();
  1472. const RMat44 initial_sphere1_transform = sphere1.GetWorldTransform();
  1473. const RMat44 initial_box2_transform = box2.GetWorldTransform();
  1474. const RMat44 initial_sphere2_transform = sphere2.GetWorldTransform();
  1475. // Save partial state
  1476. StateRecorderImpl initial_state;
  1477. c.GetSystem()->SaveState(initial_state, state_to_save, &filter);
  1478. // Simulate for 2 seconds
  1479. c.Simulate(2.0f);
  1480. // The bodies should have moved and come to rest
  1481. const RMat44 intermediate_box1_transform = box1.GetWorldTransform();
  1482. const RMat44 intermediate_sphere1_transform = sphere1.GetWorldTransform();
  1483. const RMat44 intermediate_box2_transform = box2.GetWorldTransform();
  1484. const RMat44 intermediate_sphere2_transform = sphere2.GetWorldTransform();
  1485. CHECK(intermediate_box1_transform != initial_box1_transform);
  1486. CHECK(intermediate_sphere1_transform != initial_sphere1_transform);
  1487. CHECK(intermediate_box2_transform != initial_box2_transform);
  1488. CHECK(intermediate_sphere2_transform != initial_sphere2_transform);
  1489. CHECK(!box1.IsActive());
  1490. CHECK(!sphere1.IsActive());
  1491. CHECK(!box2.IsActive());
  1492. CHECK(!sphere2.IsActive());
  1493. // Save the intermediate state.
  1494. StateRecorderImpl intermediate_state;
  1495. c.GetSystem()->SaveState(intermediate_state, state_to_save, &filter);
  1496. // Change the gravity.
  1497. c.GetSystem()->SetGravity(upside_down_gravity);
  1498. // Restore the initial state.
  1499. c.GetSystem()->RestoreState(initial_state);
  1500. // Make sure the state is properly set back to the initial state.
  1501. CHECK(box1.GetWorldTransform() == initial_box1_transform);
  1502. CHECK(sphere1.GetWorldTransform() == initial_sphere1_transform);
  1503. CHECK(box1.IsActive());
  1504. CHECK(sphere1.IsActive());
  1505. if (mode == 0)
  1506. {
  1507. // Make sure the gravity is restored.
  1508. CHECK(c.GetSystem()->GetGravity() == gravity);
  1509. // The second set of bodies should have been restored as well
  1510. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1511. CHECK(sphere2.GetWorldTransform() == initial_sphere2_transform);
  1512. CHECK(box2.IsActive());
  1513. CHECK(sphere2.IsActive());
  1514. }
  1515. else
  1516. {
  1517. // Make sure the gravity is NOT restored.
  1518. CHECK(c.GetSystem()->GetGravity() == upside_down_gravity);
  1519. c.GetSystem()->SetGravity(gravity);
  1520. // The second set of bodies should NOT have been restored
  1521. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1522. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1523. CHECK(!box2.IsActive());
  1524. CHECK(!sphere2.IsActive());
  1525. // Apply a velocity to the second set of bodies to make sure they are active again
  1526. c.GetBodyInterface().SetLinearVelocity(box2.GetID(), Vec3(0, 0, 0.1f));
  1527. c.GetBodyInterface().SetLinearVelocity(sphere2.GetID(), Vec3(0, 0, 0.1f));
  1528. }
  1529. // Simulate for 2 seconds - again
  1530. c.Simulate(2.0f);
  1531. // The first set of bodies have been saved and should have returned to the same positions again
  1532. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1533. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1534. CHECK(!box1.IsActive());
  1535. CHECK(!sphere1.IsActive());
  1536. if (mode == 0)
  1537. {
  1538. // The second set of bodies have been saved and should have returned to the same positions again
  1539. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1540. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1541. CHECK(!box2.IsActive());
  1542. CHECK(!sphere2.IsActive());
  1543. }
  1544. else
  1545. {
  1546. // The second set of bodies have not been saved and should have moved on
  1547. CHECK(box2.GetWorldTransform() != intermediate_box2_transform);
  1548. CHECK(sphere2.GetWorldTransform() != intermediate_sphere2_transform);
  1549. CHECK(!box2.IsActive());
  1550. CHECK(sphere2.IsActive()); // The sphere keeps rolling
  1551. }
  1552. // Save the final state
  1553. StateRecorderImpl final_state;
  1554. c.GetSystem()->SaveState(final_state, state_to_save, &filter);
  1555. // Compare the states to make sure they are the same
  1556. CHECK(final_state.IsEqual(intermediate_state));
  1557. // Now restore the absolute initial state and make sure all the
  1558. // bodies are being active and ready to be processed again
  1559. c.GetSystem()->RestoreState(absolute_initial_state);
  1560. CHECK(box1.GetWorldTransform() == initial_box1_transform);
  1561. CHECK(sphere1.GetWorldTransform() == initial_sphere1_transform);
  1562. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1563. CHECK(sphere2.GetWorldTransform() == initial_sphere2_transform);
  1564. CHECK(box1.IsActive());
  1565. CHECK(sphere1.IsActive());
  1566. CHECK(box2.IsActive());
  1567. CHECK(sphere2.IsActive());
  1568. // Save the state of a single body
  1569. StateRecorderImpl single_body;
  1570. c.GetSystem()->SaveBodyState(box2, single_body);
  1571. // Simulate for 2 seconds - again
  1572. c.Simulate(2.0f);
  1573. // We should have reached the same state as before
  1574. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1575. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1576. CHECK(box2.GetWorldTransform() == intermediate_box2_transform);
  1577. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1578. CHECK(!box1.IsActive());
  1579. CHECK(!sphere1.IsActive());
  1580. CHECK(!box2.IsActive());
  1581. CHECK(!sphere2.IsActive());
  1582. // Restore the single body
  1583. c.GetSystem()->RestoreBodyState(box2, single_body);
  1584. // Only that body should have been restored
  1585. CHECK(box1.GetWorldTransform() == intermediate_box1_transform);
  1586. CHECK(sphere1.GetWorldTransform() == intermediate_sphere1_transform);
  1587. CHECK(box2.GetWorldTransform() == initial_box2_transform);
  1588. CHECK(sphere2.GetWorldTransform() == intermediate_sphere2_transform);
  1589. CHECK(!box1.IsActive());
  1590. CHECK(!sphere1.IsActive());
  1591. CHECK(box2.IsActive());
  1592. CHECK(!sphere2.IsActive());
  1593. }
  1594. }
  1595. TEST_CASE("TestMultiPartRestoreState")
  1596. {
  1597. class MyFilter : public StateRecorderFilter
  1598. {
  1599. public:
  1600. MyFilter(const Array<BodyID> &inStoredBodies) : mStoredBodies(inStoredBodies) { }
  1601. bool ShouldSaveBody(const BodyID &inBodyID) const
  1602. {
  1603. return std::find(mStoredBodies.cbegin(), mStoredBodies.cend(), inBodyID) != mStoredBodies.cend();
  1604. }
  1605. virtual bool ShouldSaveBody(const Body &inBody) const override
  1606. {
  1607. if (ShouldSaveBody(inBody.GetID()))
  1608. {
  1609. ++mNumBodies;
  1610. return true;
  1611. }
  1612. return false;
  1613. }
  1614. virtual bool ShouldSaveContact(const BodyID &inBody1, const BodyID &inBody2) const override
  1615. {
  1616. if (ShouldSaveBody(inBody1) || ShouldSaveBody(inBody2))
  1617. {
  1618. ++mNumContacts;
  1619. return true;
  1620. }
  1621. return false;
  1622. }
  1623. const Array<BodyID> & mStoredBodies;
  1624. mutable int mNumBodies = 0;
  1625. mutable int mNumContacts = 0;
  1626. };
  1627. PhysicsTestContext c;
  1628. c.CreateFloor();
  1629. // Create 1st set of moving bodies
  1630. constexpr int cNumMoving1 = 10;
  1631. Array<BodyID> moving1;
  1632. for (int i = 0; i < cNumMoving1; ++i)
  1633. moving1.push_back(c.CreateSphere(RVec3(0, 2.0f + 2.0f * i, 0.01f * i), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING, EActivation::Activate).GetID());
  1634. // Create 2nd set of moving bodies, note that although the bodies overlap with the 1st set, they don't collide because of their layer.
  1635. // We need to create disjoint sets for restoring in parts to work.
  1636. constexpr int cNumMoving2 = 12;
  1637. Array<BodyID> moving2;
  1638. for (int i = 0; i < cNumMoving2; ++i)
  1639. moving2.push_back(c.CreateSphere(RVec3(1.0f, 2.0f + 2.0f * i, 0.01f * i), 1.0f, EMotionType::Dynamic, EMotionQuality::Discrete, Layers::MOVING2, EActivation::Activate).GetID());
  1640. // Simulate for a short while to get some contacts
  1641. c.Simulate(2.0f);
  1642. // Save full snapshot
  1643. StateRecorderImpl initial_state;
  1644. c.GetSystem()->SaveState(initial_state);
  1645. // Save everything relating to 1st set of bodies
  1646. MyFilter filter1(moving1);
  1647. StateRecorderImpl state1;
  1648. c.GetSystem()->SaveState(state1, EStateRecorderState::All, &filter1);
  1649. CHECK(filter1.mNumBodies == cNumMoving1);
  1650. CHECK(filter1.mNumContacts > cNumMoving1 / 2); // Many bodies should be in contact now, if not we're not testing contact restoring
  1651. CHECK(state1.GetDataSize() < initial_state.GetDataSize()); // Should be smaller than the full state
  1652. // Save everything relating to 2nd set of bodies
  1653. MyFilter filter2(moving2);
  1654. StateRecorderImpl state2;
  1655. c.GetSystem()->SaveState(state2, EStateRecorderState::Bodies | EStateRecorderState::Contacts, &filter2);
  1656. CHECK(filter2.mNumBodies == cNumMoving2);
  1657. CHECK(filter2.mNumContacts > cNumMoving2 / 2);
  1658. CHECK(state2.GetDataSize() < initial_state.GetDataSize());
  1659. // Simulate for 2 seconds
  1660. c.Simulate(2.0f);
  1661. // Save result
  1662. StateRecorderImpl final_state;
  1663. c.GetSystem()->SaveState(final_state);
  1664. // Restore the initial state in parts
  1665. state1.SetIsLastPart(false);
  1666. c.GetSystem()->RestoreState(state1);
  1667. c.GetSystem()->RestoreState(state2);
  1668. // Verify we're back to the first state
  1669. StateRecorderImpl verify1;
  1670. c.GetSystem()->SaveState(verify1);
  1671. CHECK(initial_state.IsEqual(verify1));
  1672. // Simulate for 2 seconds again
  1673. c.Simulate(2.0f);
  1674. // Check we end up in the final state again
  1675. StateRecorderImpl verify2;
  1676. c.GetSystem()->SaveState(verify2);
  1677. CHECK(final_state.IsEqual(verify2));
  1678. }
  1679. // This tests that when switching UseManifoldReduction on/off we get the correct contact callbacks
  1680. TEST_CASE("TestSwitchUseManifoldReduction")
  1681. {
  1682. PhysicsTestContext c;
  1683. // Install listener
  1684. LoggingContactListener contact_listener;
  1685. c.GetSystem()->SetContactListener(&contact_listener);
  1686. // Create floor
  1687. Body &floor = c.CreateFloor();
  1688. // Create a compound with 4 boxes
  1689. Ref<BoxShape> box_shape = new BoxShape(Vec3::sReplicate(2));
  1690. Ref<StaticCompoundShapeSettings> shape_settings = new StaticCompoundShapeSettings();
  1691. shape_settings->AddShape(Vec3(5, 0, 0), Quat::sIdentity(), box_shape);
  1692. shape_settings->AddShape(Vec3(-5, 0, 0), Quat::sIdentity(), box_shape);
  1693. shape_settings->AddShape(Vec3(0, 0, 5), Quat::sIdentity(), box_shape);
  1694. shape_settings->AddShape(Vec3(0, 0, -5), Quat::sIdentity(), box_shape);
  1695. RefConst<StaticCompoundShape> compound_shape = StaticCast<StaticCompoundShape>(shape_settings->Create().Get());
  1696. SubShapeID sub_shape_ids[] = {
  1697. compound_shape->GetSubShapeIDFromIndex(0, SubShapeIDCreator()).GetID(),
  1698. compound_shape->GetSubShapeIDFromIndex(1, SubShapeIDCreator()).GetID(),
  1699. compound_shape->GetSubShapeIDFromIndex(2, SubShapeIDCreator()).GetID(),
  1700. compound_shape->GetSubShapeIDFromIndex(3, SubShapeIDCreator()).GetID()
  1701. };
  1702. // Embed body a little bit into the floor so we immediately get contact callbacks
  1703. BodyCreationSettings body_settings(compound_shape, RVec3(0, 1.99_r, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  1704. body_settings.mUseManifoldReduction = true;
  1705. BodyID body_id = c.GetBodyInterface().CreateAndAddBody(body_settings, EActivation::Activate);
  1706. // Trigger contact callbacks
  1707. c.SimulateSingleStep();
  1708. // Since manifold reduction is on and the contacts will be coplanar we should only get 1 contact with the floor
  1709. // 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!!
  1710. CHECK(contact_listener.GetEntryCount() == 5); // 4x validate + 1x add
  1711. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1712. contact_listener.Clear();
  1713. // Now disable manifold reduction
  1714. c.GetBodyInterface().SetUseManifoldReduction(body_id, false);
  1715. // Trigger contact callbacks
  1716. c.SimulateSingleStep();
  1717. // Now manifold reduction is off so we should get collisions with each of the sub shapes
  1718. CHECK(contact_listener.GetEntryCount() == 8); // 4x validate + 1x persist + 3x add
  1719. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1720. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[0]));
  1721. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[1]));
  1722. CHECK(contact_listener.Contains(LoggingContactListener::EType::Add, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[2]));
  1723. contact_listener.Clear();
  1724. // Now enable manifold reduction again
  1725. c.GetBodyInterface().SetUseManifoldReduction(body_id, true);
  1726. // Trigger contact callbacks
  1727. c.SimulateSingleStep();
  1728. // We should be back to the first state now where we only have 1 contact
  1729. CHECK(contact_listener.GetEntryCount() == 8); // 4x validate + 1x persist + 3x remove
  1730. CHECK(contact_listener.Contains(LoggingContactListener::EType::Persist, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[3]));
  1731. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[0]));
  1732. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[1]));
  1733. CHECK(contact_listener.Contains(LoggingContactListener::EType::Remove, floor.GetID(), SubShapeID(), body_id, sub_shape_ids[2]));
  1734. }
  1735. // This tests that we don't run out of nodes if we keep adding removing bodies when using OptimizeBroadPhase
  1736. TEST_CASE("TestOptimizeBroadPhase")
  1737. {
  1738. constexpr uint cMaxBodies = 128;
  1739. PhysicsTestContext c(1.0f / 60.0f, 1, 0, cMaxBodies);
  1740. BodyInterface &bi = c.GetBodyInterface();
  1741. // Create max number of bodies
  1742. BodyIDVector bodies;
  1743. BodyCreationSettings bcs(new SphereShape(1.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::MOVING);
  1744. for (uint i = 0; i < cMaxBodies; ++i)
  1745. {
  1746. Body *b = bi.CreateBody(bcs);
  1747. CHECK(b != nullptr);
  1748. bodies.push_back(b->GetID());
  1749. }
  1750. // Repeatedly add and remove bodies
  1751. for (int i = 0; i < 10; ++i)
  1752. {
  1753. BodyInterface::AddState add_state = bi.AddBodiesPrepare(bodies.data(), (int)bodies.size());
  1754. for (const BodyID &id : bodies)
  1755. CHECK(!bi.IsAdded(id));
  1756. bi.AddBodiesFinalize(bodies.data(), (int)bodies.size(), add_state, EActivation::DontActivate);
  1757. for (const BodyID &id : bodies)
  1758. CHECK(bi.IsAdded(id));
  1759. bi.RemoveBodies(bodies.data(), (int)bodies.size());
  1760. for (const BodyID &id : bodies)
  1761. CHECK(!bi.IsAdded(id));
  1762. // Optimize the broad phase to recycle quad tree nodes
  1763. c.GetSystem()->OptimizeBroadPhase();
  1764. }
  1765. }
  1766. }