PhysicsTests.cpp 88 KB

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