PhysicsTests.cpp 84 KB

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