CharacterVirtualTests.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2022 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include "UnitTestFramework.h"
  5. #include "PhysicsTestContext.h"
  6. #include "LoggingCharacterContactListener.h"
  7. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  8. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  9. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  10. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  11. #include <Jolt/Physics/Character/CharacterVirtual.h>
  12. #include "Layers.h"
  13. TEST_SUITE("CharacterVirtualTests")
  14. {
  15. class Character : public CharacterContactListener
  16. {
  17. public:
  18. // Construct
  19. Character(PhysicsTestContext &ioContext) : mContext(ioContext) { }
  20. // Create the character
  21. void Create()
  22. {
  23. // Create capsule
  24. Ref<Shape> capsule = new CapsuleShape(0.5f * mHeightStanding, mRadiusStanding);
  25. mCharacterSettings.mShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * mHeightStanding + mRadiusStanding, 0), Quat::sIdentity(), capsule).Create().Get();
  26. // Configure supporting volume
  27. mCharacterSettings.mSupportingVolume = Plane(Vec3::sAxisY(), -mHeightStanding); // Accept contacts that touch the lower sphere of the capsule
  28. // Create character
  29. mCharacter = new CharacterVirtual(&mCharacterSettings, mInitialPosition, Quat::sIdentity(), 0, mContext.GetSystem());
  30. mCharacter->SetListener(this);
  31. mCharacter->SetCharacterVsCharacterCollision(&mCharacterVsCharacter);
  32. }
  33. // Step the character and the world
  34. void Step()
  35. {
  36. // Step the world
  37. mContext.SimulateSingleStep();
  38. // Determine new basic velocity
  39. Vec3 current_vertical_velocity = Vec3(0, mCharacter->GetLinearVelocity().GetY(), 0);
  40. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  41. Vec3 new_velocity;
  42. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  43. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  44. {
  45. // Assume velocity of ground when on ground
  46. new_velocity = ground_velocity;
  47. // Jump
  48. new_velocity += Vec3(0, mJumpSpeed, 0);
  49. mJumpSpeed = 0.0f;
  50. }
  51. else
  52. new_velocity = current_vertical_velocity;
  53. // Gravity
  54. PhysicsSystem *system = mContext.GetSystem();
  55. float delta_time = mContext.GetDeltaTime();
  56. new_velocity += system->GetGravity() * delta_time;
  57. // Player input
  58. new_velocity += mHorizontalSpeed;
  59. // Update character velocity
  60. mCharacter->SetLinearVelocity(new_velocity);
  61. RVec3 start_pos = GetPosition();
  62. // Update the character position
  63. TempAllocatorMalloc allocator;
  64. mCharacter->ExtendedUpdate(delta_time,
  65. system->GetGravity(),
  66. mUpdateSettings,
  67. system->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  68. system->GetDefaultLayerFilter(Layers::MOVING),
  69. { },
  70. { },
  71. allocator);
  72. // Calculate effective velocity in this step
  73. mEffectiveVelocity = Vec3(GetPosition() - start_pos) / delta_time;
  74. }
  75. // Simulate a longer period of time
  76. void Simulate(float inTime)
  77. {
  78. int num_steps = (int)round(inTime / mContext.GetDeltaTime());
  79. for (int step = 0; step < num_steps; ++step)
  80. Step();
  81. }
  82. // Get the number of active contacts
  83. size_t GetNumContacts() const
  84. {
  85. return mCharacter->GetActiveContacts().size();
  86. }
  87. // Check if the character is in contact with another body
  88. bool HasCollidedWith(const BodyID &inBody) const
  89. {
  90. return mCharacter->HasCollidedWith(inBody);
  91. }
  92. // Check if the character is in contact with another character
  93. bool HasCollidedWith(const CharacterVirtual *inCharacter) const
  94. {
  95. return mCharacter->HasCollidedWith(inCharacter);
  96. }
  97. // Get position of character
  98. RVec3 GetPosition() const
  99. {
  100. return mCharacter->GetPosition();
  101. }
  102. // Configuration
  103. RVec3 mInitialPosition = RVec3::sZero();
  104. float mHeightStanding = 1.35f;
  105. float mRadiusStanding = 0.3f;
  106. CharacterVirtualSettings mCharacterSettings;
  107. CharacterVirtual::ExtendedUpdateSettings mUpdateSettings;
  108. // Character movement settings (update to control the movement of the character)
  109. Vec3 mHorizontalSpeed = Vec3::sZero();
  110. float mJumpSpeed = 0.0f; // Character will jump when not 0, will auto reset
  111. // The character
  112. Ref<CharacterVirtual> mCharacter;
  113. // Character vs character
  114. CharacterVsCharacterCollisionSimple mCharacterVsCharacter;
  115. // Calculated effective velocity after a step
  116. Vec3 mEffectiveVelocity = Vec3::sZero();
  117. // Log of contact events
  118. LoggingCharacterContactListener mContactLog;
  119. private:
  120. // CharacterContactListener callback
  121. virtual bool OnContactValidate(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) override
  122. {
  123. return mContactLog.OnContactValidate(inCharacter, inBodyID2, inSubShapeID2);
  124. }
  125. virtual bool OnCharacterContactValidate(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2) override
  126. {
  127. return mContactLog.OnCharacterContactValidate(inCharacter, inOtherCharacter, inSubShapeID2);
  128. }
  129. virtual void OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) override
  130. {
  131. mContactLog.OnContactAdded(inCharacter, inBodyID2, inSubShapeID2, inContactPosition, inContactNormal, ioSettings);
  132. }
  133. virtual void OnContactPersisted(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) override
  134. {
  135. mContactLog.OnContactPersisted(inCharacter, inBodyID2, inSubShapeID2, inContactPosition, inContactNormal, ioSettings);
  136. }
  137. virtual void OnContactRemoved(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) override
  138. {
  139. mContactLog.OnContactRemoved(inCharacter, inBodyID2, inSubShapeID2);
  140. }
  141. virtual void OnCharacterContactAdded(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) override
  142. {
  143. mContactLog.OnCharacterContactAdded(inCharacter, inOtherCharacter, inSubShapeID2, inContactPosition, inContactNormal, ioSettings);
  144. }
  145. virtual void OnCharacterContactPersisted(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) override
  146. {
  147. mContactLog.OnCharacterContactPersisted(inCharacter, inOtherCharacter, inSubShapeID2, inContactPosition, inContactNormal, ioSettings);
  148. }
  149. virtual void OnCharacterContactRemoved(const CharacterVirtual *inCharacter, const CharacterID &inOtherCharacterID, const SubShapeID &inSubShapeID2) override
  150. {
  151. mContactLog.OnCharacterContactRemoved(inCharacter, inOtherCharacterID, inSubShapeID2);
  152. }
  153. virtual void OnContactSolve(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity) override
  154. {
  155. // Don't allow sliding if the character doesn't want to move
  156. if (mHorizontalSpeed.IsNearZero() && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  157. ioNewCharacterVelocity = Vec3::sZero();
  158. }
  159. PhysicsTestContext & mContext;
  160. };
  161. TEST_CASE("TestFallingAndJumping")
  162. {
  163. // Create floor
  164. PhysicsTestContext c;
  165. c.CreateFloor();
  166. // Create character
  167. Character character(c);
  168. character.mInitialPosition = RVec3(0, 2, 0);
  169. character.Create();
  170. // After 1 step we should still be in air
  171. character.Step();
  172. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  173. // After some time we should be on the floor
  174. character.Simulate(1.0f);
  175. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  176. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3::sZero());
  177. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, Vec3::sZero());
  178. // Jump
  179. character.mJumpSpeed = 1.0f;
  180. character.Step();
  181. Vec3 velocity(0, 1.0f + c.GetDeltaTime() * c.GetSystem()->GetGravity().GetY(), 0);
  182. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(velocity * c.GetDeltaTime()));
  183. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, velocity);
  184. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  185. // After some time we should be on the floor again
  186. character.Simulate(1.0f);
  187. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  188. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3::sZero());
  189. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, Vec3::sZero());
  190. }
  191. TEST_CASE("TestMovingOnSlope")
  192. {
  193. constexpr float cFloorHalfHeight = 1.0f;
  194. constexpr float cMovementTime = 1.5f;
  195. // Iterate various slope angles
  196. for (float slope_angle = DegreesToRadians(5.0f); slope_angle < DegreesToRadians(85.0f); slope_angle += DegreesToRadians(10.0f))
  197. {
  198. // Create sloped floor
  199. PhysicsTestContext c;
  200. Quat slope_rotation = Quat::sRotation(Vec3::sAxisZ(), slope_angle);
  201. c.CreateBox(RVec3::sZero(), slope_rotation, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100.0f, cFloorHalfHeight, 100.0f));
  202. // Create character so that it is touching the slope
  203. Character character(c);
  204. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  205. character.mInitialPosition = RVec3(0, (radius_and_padding + cFloorHalfHeight) / Cos(slope_angle) - radius_and_padding, 0);
  206. character.Create();
  207. // Determine if the slope is too steep for the character
  208. bool too_steep = slope_angle > character.mCharacterSettings.mMaxSlopeAngle;
  209. CharacterBase::EGroundState expected_ground_state = (too_steep? CharacterBase::EGroundState::OnSteepGround : CharacterBase::EGroundState::OnGround);
  210. Vec3 gravity = c.GetSystem()->GetGravity();
  211. float time_step = c.GetDeltaTime();
  212. Vec3 slope_normal = slope_rotation.RotateAxisY();
  213. // Calculate expected position after 1 time step
  214. RVec3 position_after_1_step = character.mInitialPosition;
  215. if (too_steep)
  216. {
  217. // Apply 1 frame of gravity and cancel movement in the slope normal direction
  218. Vec3 velocity = gravity * time_step;
  219. velocity -= velocity.Dot(slope_normal) * slope_normal;
  220. position_after_1_step += velocity * time_step;
  221. }
  222. // After 1 step we should be on the slope
  223. character.Step();
  224. CHECK(character.mCharacter->GetGroundState() == expected_ground_state);
  225. CHECK_APPROX_EQUAL(character.GetPosition(), position_after_1_step, 2.0e-6f);
  226. // Cancel any velocity to make the calculation below easier (otherwise we have to take gravity for 1 time step into account)
  227. character.mCharacter->SetLinearVelocity(Vec3::sZero());
  228. RVec3 start_pos = character.GetPosition();
  229. // Start moving in X direction
  230. character.mHorizontalSpeed = Vec3(2.0f, 0, 0);
  231. character.Simulate(cMovementTime);
  232. CHECK(character.mCharacter->GetGroundState() == expected_ground_state);
  233. // Calculate resulting translation
  234. Vec3 translation = Vec3(character.GetPosition() - start_pos);
  235. // Calculate expected translation
  236. Vec3 expected_translation;
  237. if (too_steep)
  238. {
  239. // If too steep, we're just falling. Integrate using an Euler integrator.
  240. Vec3 velocity = Vec3::sZero();
  241. expected_translation = Vec3::sZero();
  242. int num_steps = (int)round(cMovementTime / time_step);
  243. for (int i = 0; i < num_steps; ++i)
  244. {
  245. velocity += gravity * time_step;
  246. expected_translation += velocity * time_step;
  247. }
  248. }
  249. else
  250. {
  251. // Every frame we apply 1 delta time * gravity which gets reset on the next update, add this to the horizontal speed
  252. expected_translation = (character.mHorizontalSpeed + gravity * time_step) * cMovementTime;
  253. }
  254. // Cancel movement in slope direction
  255. expected_translation -= expected_translation.Dot(slope_normal) * slope_normal;
  256. // Check that we traveled the right amount
  257. CHECK_APPROX_EQUAL(translation, expected_translation, 1.0e-4f);
  258. }
  259. }
  260. TEST_CASE("TestStickToFloor")
  261. {
  262. constexpr float cFloorHalfHeight = 1.0f;
  263. constexpr float cSlopeAngle = DegreesToRadians(45.0f);
  264. constexpr float cMovementTime = 1.5f;
  265. for (int mode = 0; mode < 2; ++mode)
  266. {
  267. // If this run is with 'stick to floor' enabled
  268. bool stick_to_floor = mode == 0;
  269. // Create sloped floor
  270. PhysicsTestContext c;
  271. Quat slope_rotation = Quat::sRotation(Vec3::sAxisZ(), cSlopeAngle);
  272. Body &floor = c.CreateBox(RVec3::sZero(), slope_rotation, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100.0f, cFloorHalfHeight, 100.0f));
  273. // Create character so that it is touching the slope
  274. Character character(c);
  275. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  276. character.mInitialPosition = RVec3(0, (radius_and_padding + cFloorHalfHeight) / Cos(cSlopeAngle) - radius_and_padding, 0);
  277. character.mUpdateSettings.mStickToFloorStepDown = stick_to_floor? Vec3(0, -0.5f, 0) : Vec3::sZero();
  278. character.Create();
  279. // After 1 step we should be on the slope
  280. character.Step();
  281. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  282. CHECK(character.mContactLog.GetEntryCount() == 2);
  283. CHECK(character.mContactLog.Contains(LoggingCharacterContactListener::EType::ValidateBody, character.mCharacter, floor.GetID()));
  284. CHECK(character.mContactLog.Contains(LoggingCharacterContactListener::EType::AddBody, character.mCharacter, floor.GetID()));
  285. character.mContactLog.Clear();
  286. // Cancel any velocity to make the calculation below easier (otherwise we have to take gravity for 1 time step into account)
  287. character.mCharacter->SetLinearVelocity(Vec3::sZero());
  288. RVec3 start_pos = character.GetPosition();
  289. float time_step = c.GetDeltaTime();
  290. int num_steps = (int)round(cMovementTime / time_step);
  291. for (int i = 0; i < num_steps; ++i)
  292. {
  293. // Start moving down the slope at a speed high enough so that gravity will not keep us on the floor
  294. character.mHorizontalSpeed = Vec3(-10.0f, 0, 0);
  295. character.Step();
  296. if (stick_to_floor)
  297. {
  298. // Should stick to floor
  299. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  300. // Should have received callbacks
  301. CHECK(character.mContactLog.GetEntryCount() == 2);
  302. CHECK(character.mContactLog.Contains(LoggingCharacterContactListener::EType::ValidateBody, character.mCharacter, floor.GetID()));
  303. CHECK(character.mContactLog.Contains(LoggingCharacterContactListener::EType::PersistBody, character.mCharacter, floor.GetID()));
  304. character.mContactLog.Clear();
  305. }
  306. else
  307. {
  308. // Should be off ground
  309. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  310. // Remove callbacks
  311. CHECK(character.mContactLog.GetEntryCount() == 1);
  312. CHECK(character.mContactLog.Contains(LoggingCharacterContactListener::EType::RemoveBody, character.mCharacter, floor.GetID()));
  313. }
  314. }
  315. // Calculate resulting translation
  316. Vec3 translation = Vec3(character.GetPosition() - start_pos);
  317. // Calculate expected translation
  318. Vec3 expected_translation;
  319. if (stick_to_floor)
  320. {
  321. // We should stick to the floor, so the vertical translation follows the slope perfectly
  322. expected_translation = character.mHorizontalSpeed * cMovementTime;
  323. expected_translation.SetY(expected_translation.GetX() * Tan(cSlopeAngle));
  324. }
  325. else
  326. {
  327. // If too steep, we're just falling. Integrate using an Euler integrator.
  328. Vec3 velocity = character.mHorizontalSpeed;
  329. expected_translation = Vec3::sZero();
  330. Vec3 gravity = c.GetSystem()->GetGravity();
  331. for (int i = 0; i < num_steps; ++i)
  332. {
  333. velocity += gravity * time_step;
  334. expected_translation += velocity * time_step;
  335. }
  336. }
  337. // Check that we traveled the right amount
  338. CHECK_APPROX_EQUAL(translation, expected_translation, 1.0e-4f);
  339. }
  340. }
  341. TEST_CASE("TestWalkStairs")
  342. {
  343. const float cStepHeight = 0.3f;
  344. const int cNumSteps = 10;
  345. // Create stairs from triangles
  346. TriangleList triangles;
  347. for (int i = 0; i < cNumSteps; ++i)
  348. {
  349. // Start of step
  350. Vec3 base(0, cStepHeight * i, cStepHeight * i);
  351. // Left side
  352. Vec3 b1 = base + Vec3(2.0f, 0, 0);
  353. Vec3 s1 = b1 + Vec3(0, cStepHeight, 0);
  354. Vec3 p1 = s1 + Vec3(0, 0, cStepHeight);
  355. // Right side
  356. Vec3 width(-4.0f, 0, 0);
  357. Vec3 b2 = b1 + width;
  358. Vec3 s2 = s1 + width;
  359. Vec3 p2 = p1 + width;
  360. triangles.push_back(Triangle(s1, b1, s2));
  361. triangles.push_back(Triangle(b1, b2, s2));
  362. triangles.push_back(Triangle(s1, p2, p1));
  363. triangles.push_back(Triangle(s1, s2, p2));
  364. }
  365. MeshShapeSettings mesh(triangles);
  366. mesh.SetEmbedded();
  367. BodyCreationSettings mesh_stairs(&mesh, RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  368. // Stair stepping is very delta time sensitive, so test various update frequencies
  369. float frequencies[] = { 60.0f, 120.0f, 240.0f, 360.0f };
  370. for (float frequency : frequencies)
  371. {
  372. float time_step = 1.0f / frequency;
  373. PhysicsTestContext c(time_step);
  374. c.CreateFloor();
  375. c.GetBodyInterface().CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  376. // Create character so that it is touching the slope
  377. Character character(c);
  378. character.mInitialPosition = RVec3(0, 0, -2.0f); // Start in front of the stairs
  379. character.mUpdateSettings.mWalkStairsStepUp = Vec3::sZero(); // No stair walking
  380. character.Create();
  381. // Start moving towards the stairs
  382. character.mHorizontalSpeed = Vec3(0, 0, 4.0f);
  383. character.Simulate(1.0f);
  384. // We should have gotten stuck at the start of the stairs (can't move up)
  385. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  386. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  387. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(0, 0, -radius_and_padding), 1.1e-2f);
  388. // Enable stair walking
  389. character.mUpdateSettings.mWalkStairsStepUp = Vec3(0, 0.4f, 0);
  390. // Calculate time it should take to move up the stairs at constant speed
  391. float movement_time = (cNumSteps * cStepHeight + radius_and_padding) / character.mHorizontalSpeed.GetZ();
  392. int max_steps = int(1.5f * round(movement_time / time_step)); // In practice there is a bit of slowdown while stair stepping, so add a bit of slack
  393. // Step until we reach the top of the stairs
  394. RVec3 last_position = character.GetPosition();
  395. bool reached_goal = false;
  396. for (int i = 0; i < max_steps; ++i)
  397. {
  398. character.Step();
  399. // We should always be on the floor during stair stepping
  400. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  401. // Check position progression
  402. RVec3 position = character.GetPosition();
  403. CHECK_APPROX_EQUAL(position.GetX(), 0); // No movement in X
  404. CHECK(position.GetZ() > last_position.GetZ()); // Always moving forward
  405. CHECK(position.GetZ() < cNumSteps * cStepHeight); // No movement beyond stairs
  406. if (position.GetY() > cNumSteps * cStepHeight - 1.0e-3f)
  407. {
  408. reached_goal = true;
  409. break;
  410. }
  411. last_position = position;
  412. }
  413. CHECK(reached_goal);
  414. }
  415. }
  416. TEST_CASE("TestRotatingPlatform")
  417. {
  418. constexpr float cFloorHalfHeight = 1.0f;
  419. constexpr float cFloorHalfWidth = 10.0f;
  420. constexpr float cCharacterPosition = 0.9f * cFloorHalfWidth;
  421. constexpr float cAngularVelocity = 2.0f * JPH_PI;
  422. PhysicsTestContext c;
  423. // Create box
  424. Body &box = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Kinematic, EMotionQuality::Discrete, Layers::MOVING, Vec3(cFloorHalfWidth, cFloorHalfHeight, cFloorHalfWidth));
  425. box.SetAllowSleeping(false);
  426. // Create character so that it is touching the box at the
  427. Character character(c);
  428. character.mInitialPosition = RVec3(cCharacterPosition, cFloorHalfHeight, 0);
  429. character.Create();
  430. // Step to ensure the character is on the box
  431. character.Step();
  432. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  433. // Set the box to rotate a full circle per second
  434. box.SetAngularVelocity(Vec3(0, cAngularVelocity, 0));
  435. // Rotate and check that character stays on the box
  436. for (int t = 0; t < 60; ++t)
  437. {
  438. character.Step();
  439. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  440. // Note that the character moves according to the ground velocity and the ground velocity is updated at the end of the step
  441. // so the character is always 1 time step behind the platform. This is why we use t and not t + 1 to calculate the expected position.
  442. RVec3 expected_position = RMat44::sRotation(Quat::sRotation(Vec3::sAxisY(), float(t) * c.GetDeltaTime() * cAngularVelocity)) * character.mInitialPosition;
  443. CHECK_APPROX_EQUAL(character.GetPosition(), expected_position, 1.0e-4f);
  444. }
  445. }
  446. TEST_CASE("TestMovingPlatformUp")
  447. {
  448. constexpr float cFloorHalfHeight = 1.0f;
  449. constexpr float cFloorHalfWidth = 10.0f;
  450. constexpr float cLinearVelocity = 0.5f;
  451. PhysicsTestContext c;
  452. // Create box
  453. Body &box = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Kinematic, EMotionQuality::Discrete, Layers::MOVING, Vec3(cFloorHalfWidth, cFloorHalfHeight, cFloorHalfWidth));
  454. box.SetAllowSleeping(false);
  455. // Create character so that it is touching the box at the
  456. Character character(c);
  457. character.mInitialPosition = RVec3(0, cFloorHalfHeight, 0);
  458. character.Create();
  459. // Step to ensure the character is on the box
  460. character.Step();
  461. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  462. // Set the box to move up
  463. box.SetLinearVelocity(Vec3(0, cLinearVelocity, 0));
  464. // Check that character stays on the box
  465. for (int t = 0; t < 60; ++t)
  466. {
  467. character.Step();
  468. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  469. RVec3 expected_position = box.GetPosition() + character.mInitialPosition;
  470. CHECK_APPROX_EQUAL(character.GetPosition(), expected_position, 1.0e-2f);
  471. }
  472. // Stop box
  473. box.SetLinearVelocity(Vec3::sZero());
  474. character.Simulate(0.5f);
  475. // Set the box to move down
  476. box.SetLinearVelocity(Vec3(0, -cLinearVelocity, 0));
  477. // Check that character stays on the box
  478. for (int t = 0; t < 60; ++t)
  479. {
  480. character.Step();
  481. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  482. RVec3 expected_position = box.GetPosition() + character.mInitialPosition;
  483. CHECK_APPROX_EQUAL(character.GetPosition(), expected_position, 1.0e-2f);
  484. }
  485. }
  486. TEST_CASE("TestContactPointLimit")
  487. {
  488. PhysicsTestContext ctx;
  489. Body &floor = ctx.CreateFloor();
  490. // Create character at the origin
  491. Character character(ctx);
  492. character.mInitialPosition = RVec3(0, 1, 0);
  493. character.mUpdateSettings.mStickToFloorStepDown = Vec3::sZero();
  494. character.mUpdateSettings.mWalkStairsStepUp = Vec3::sZero();
  495. character.Create();
  496. // Radius including padding
  497. const float character_radius = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  498. // Create a half cylinder with caps for testing contact point limit
  499. VertexList vertices;
  500. IndexedTriangleList triangles;
  501. // The half cylinder
  502. const int cPosSegments = 2;
  503. const int cAngleSegments = 768;
  504. const float cCylinderLength = 2.0f;
  505. for (int pos = 0; pos < cPosSegments; ++pos)
  506. for (int angle = 0; angle < cAngleSegments; ++angle)
  507. {
  508. uint32 start = (uint32)vertices.size();
  509. float radius = character_radius + 0.01f;
  510. float angle_rad = (-0.5f + float(angle) / cAngleSegments) * JPH_PI;
  511. float s = Sin(angle_rad);
  512. float c = Cos(angle_rad);
  513. float x = cCylinderLength * (-0.5f + float(pos) / (cPosSegments - 1));
  514. float y = angle == 0 || angle == cAngleSegments - 1? 0.5f : (1.0f - c) * radius;
  515. float z = s * radius;
  516. vertices.push_back(Float3(x, y, z));
  517. if (pos > 0 && angle > 0)
  518. {
  519. triangles.push_back(IndexedTriangle(start, start - 1, start - cAngleSegments));
  520. triangles.push_back(IndexedTriangle(start - 1, start - cAngleSegments - 1, start - cAngleSegments));
  521. }
  522. }
  523. // Add end caps
  524. uint32 end = cAngleSegments * (cPosSegments - 1);
  525. for (int angle = 0; angle < cAngleSegments - 1; ++angle)
  526. {
  527. triangles.push_back(IndexedTriangle(0, angle + 1, angle));
  528. triangles.push_back(IndexedTriangle(end, end + angle, end + angle + 1));
  529. }
  530. // Create test body
  531. MeshShapeSettings mesh(vertices, triangles);
  532. mesh.SetEmbedded();
  533. BodyCreationSettings mesh_cylinder(&mesh, character.mInitialPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  534. BodyID cylinder_id = ctx.GetBodyInterface().CreateAndAddBody(mesh_cylinder, EActivation::DontActivate);
  535. // End positions that can be reached by character
  536. RVec3 pos_end(0.5_r * cCylinderLength - character_radius, 1, 0);
  537. RVec3 neg_end(-0.5_r * cCylinderLength + character_radius, 1, 0);
  538. // Move towards positive cap and test if we hit the end
  539. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  540. for (int t = 0; t < 60; ++t)
  541. {
  542. character.Step();
  543. CHECK(character.mCharacter->GetMaxHitsExceeded());
  544. CHECK(character.GetNumContacts() <= character.mCharacter->GetMaxNumHits());
  545. CHECK(character.mCharacter->GetGroundBodyID() == cylinder_id);
  546. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  547. }
  548. CHECK_APPROX_EQUAL(character.GetPosition(), pos_end, 1.0e-4f);
  549. // Move towards negative cap and test if we hit the end
  550. character.mHorizontalSpeed = Vec3(-cCylinderLength, 0, 0);
  551. for (int t = 0; t < 60; ++t)
  552. {
  553. character.Step();
  554. CHECK(character.mCharacter->GetMaxHitsExceeded());
  555. CHECK(character.GetNumContacts() <= character.mCharacter->GetMaxNumHits());
  556. CHECK(character.mCharacter->GetGroundBodyID() == cylinder_id);
  557. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  558. }
  559. CHECK_APPROX_EQUAL(character.GetPosition(), neg_end, 1.0e-4f);
  560. // Turn off contact point reduction
  561. character.mCharacter->SetHitReductionCosMaxAngle(-1.0f);
  562. // Move towards positive cap and test that we did not reach the end
  563. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  564. for (int t = 0; t < 60; ++t)
  565. {
  566. character.Step();
  567. CHECK(character.mCharacter->GetMaxHitsExceeded());
  568. CHECK(character.GetNumContacts() == character.mCharacter->GetMaxNumHits());
  569. }
  570. RVec3 cur_pos = character.GetPosition();
  571. CHECK((pos_end - cur_pos).Length() > 0.01_r);
  572. // Move towards negative cap and test that we got stuck
  573. character.mHorizontalSpeed = Vec3(-cCylinderLength, 0, 0);
  574. for (int t = 0; t < 60; ++t)
  575. {
  576. character.Step();
  577. CHECK(character.mCharacter->GetMaxHitsExceeded());
  578. CHECK(character.GetNumContacts() == character.mCharacter->GetMaxNumHits());
  579. }
  580. CHECK(cur_pos.IsClose(character.GetPosition(), 1.0e-6f));
  581. // Now teleport the character next to the half cylinder
  582. character.mCharacter->SetPosition(RVec3(0, 0, 1));
  583. // Move in positive X and check that we did not exceed max hits and that we were able to move unimpeded
  584. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  585. for (int t = 0; t < 60; ++t)
  586. {
  587. character.Step();
  588. CHECK(!character.mCharacter->GetMaxHitsExceeded());
  589. CHECK(character.GetNumContacts() == 1); // We should only hit the floor
  590. CHECK(character.mCharacter->GetGroundBodyID() == floor.GetID());
  591. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  592. }
  593. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(cCylinderLength, 0, 1), 1.0e-4f);
  594. }
  595. TEST_CASE("TestStairWalkAlongWall")
  596. {
  597. // Stair stepping is very delta time sensitive, so test various update frequencies
  598. float frequencies[] = { 60.0f, 120.0f, 240.0f, 360.0f };
  599. for (float frequency : frequencies)
  600. {
  601. float time_step = 1.0f / frequency;
  602. PhysicsTestContext c(time_step);
  603. c.CreateFloor();
  604. // Create character
  605. Character character(c);
  606. character.Create();
  607. // Create a wall
  608. const float cWallHalfThickness = 0.05f;
  609. c.GetBodyInterface().CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(50.0f, 1.0f, cWallHalfThickness)), RVec3(0, 1.0_r, Real(-character.mRadiusStanding - character.mCharacter->GetCharacterPadding() - cWallHalfThickness)), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  610. // Start moving along the wall, if the stair stepping algorithm is working correctly it should not trigger and not apply extra speed to the character
  611. character.mHorizontalSpeed = Vec3(5.0f, 0, -1.0f);
  612. character.Simulate(1.0f);
  613. // We should have moved along the wall at the desired speed
  614. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  615. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(5.0f, 0, 0), 1.0e-2f);
  616. }
  617. }
  618. TEST_CASE("TestInitiallyIntersecting")
  619. {
  620. PhysicsTestContext c;
  621. c.CreateFloor();
  622. // Create box that is intersecting with the character
  623. c.CreateBox(RVec3(-0.5f, 0.5f, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3::sReplicate(0.5f));
  624. // Try various penetration recovery values
  625. for (float penetration_recovery : { 0.0f, 0.5f, 0.75f, 1.0f })
  626. {
  627. // Create character
  628. Character character(c);
  629. character.mCharacterSettings.mPenetrationRecoverySpeed = penetration_recovery;
  630. character.Create();
  631. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3::sZero());
  632. // Total radius of character
  633. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  634. float x = 0.0f;
  635. for (int step = 0; step < 3; ++step)
  636. {
  637. // Calculate expected position
  638. x += penetration_recovery * (radius_and_padding - x);
  639. // Step character and check that it matches expected recovery
  640. character.Step();
  641. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(x, 0, 0));
  642. }
  643. }
  644. }
  645. TEST_CASE("TestCharacterVsCharacter")
  646. {
  647. PhysicsTestContext c;
  648. BodyID floor_id = c.CreateFloor().GetID();
  649. // Create characters with different radii and padding
  650. Character character1(c);
  651. character1.mInitialPosition = RVec3::sZero();
  652. character1.mRadiusStanding = 0.2f;
  653. character1.mCharacterSettings.mCharacterPadding = 0.04f;
  654. character1.Create();
  655. Character character2(c);
  656. character2.mInitialPosition = RVec3(1, 0, 0);
  657. character2.mRadiusStanding = 0.3f;
  658. character2.mCharacterSettings.mCharacterPadding = 0.03f;
  659. character2.Create();
  660. // Make both collide
  661. character1.mCharacterVsCharacter.Add(character2.mCharacter);
  662. character2.mCharacterVsCharacter.Add(character1.mCharacter);
  663. // Add a box behind character 2, we should never hit this
  664. Vec3 box_extent(0.1f, 1.0f, 1.0f);
  665. c.CreateBox(RVec3(1.5f, 0, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, box_extent, EActivation::DontActivate);
  666. // Move character 1 towards character 2 so that in 1 step it will hit both character 2 and the box
  667. character1.mHorizontalSpeed = Vec3(600.0f, 0, 0);
  668. character1.Step();
  669. // Character 1 should have stopped at character 2
  670. float character1_radius = character1.mRadiusStanding + character1.mCharacterSettings.mCharacterPadding;
  671. float character2_radius = character2.mRadiusStanding + character2.mCharacterSettings.mCharacterPadding;
  672. float separation = character1_radius + character2_radius;
  673. RVec3 expected_colliding_with_character = character2.mInitialPosition - Vec3(separation, 0, 0);
  674. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_character, 1.0e-3f);
  675. CHECK(character1.GetNumContacts() == 2);
  676. CHECK(character1.HasCollidedWith(floor_id));
  677. CHECK(character1.HasCollidedWith(character2.mCharacter));
  678. // Move character 1 back to its initial position
  679. character1.mCharacter->SetPosition(character1.mInitialPosition);
  680. character1.mCharacter->SetLinearVelocity(Vec3::sZero());
  681. // Now move slowly so that we will detect the collision during the normal collide shape step
  682. character1.mHorizontalSpeed = Vec3(1.0f, 0, 0);
  683. character1.Step();
  684. CHECK(character1.GetNumContacts() == 1);
  685. CHECK(character1.HasCollidedWith(floor_id));
  686. character1.Simulate(1.0f);
  687. // Character 1 should have stopped at character 2
  688. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_character, 1.0e-3f);
  689. CHECK(character1.GetNumContacts() == 2);
  690. CHECK(character1.HasCollidedWith(floor_id));
  691. CHECK(character1.HasCollidedWith(character2.mCharacter));
  692. // Move character 1 back to its initial position
  693. character1.mCharacter->SetPosition(character1.mInitialPosition);
  694. character1.mCharacter->SetLinearVelocity(Vec3::sZero());
  695. // Add a box in between the characters
  696. RVec3 box_position(0.5f, 0, 0);
  697. BodyID box_id = c.CreateBox(box_position, Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, box_extent, EActivation::DontActivate).GetID();
  698. // Move character 1 so that it will step through both the box and the character in 1 time step
  699. character1.mHorizontalSpeed = Vec3(600.0f, 0, 0);
  700. character1.Step();
  701. // Expect that it ends up at the box
  702. RVec3 expected_colliding_with_box = box_position - Vec3(character1_radius + box_extent.GetX(), 0, 0);
  703. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_box, 1.0e-3f);
  704. CHECK(character1.GetNumContacts() == 2);
  705. CHECK(character1.HasCollidedWith(floor_id));
  706. CHECK(character1.HasCollidedWith(box_id));
  707. // Move character 1 back to its initial position
  708. character1.mCharacter->SetPosition(character1.mInitialPosition);
  709. character1.mCharacter->SetLinearVelocity(Vec3::sZero());
  710. // Now move slowly so that we will detect the collision during the normal collide shape step
  711. character1.mHorizontalSpeed = Vec3(1.0f, 0, 0);
  712. character1.Step();
  713. CHECK(character1.GetNumContacts() == 1);
  714. CHECK(character1.HasCollidedWith(floor_id));
  715. character1.Simulate(1.0f);
  716. // Expect that it ends up at the box
  717. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_box, 1.0e-3f);
  718. CHECK(character1.GetNumContacts() == 2);
  719. CHECK(character1.HasCollidedWith(floor_id));
  720. CHECK(character1.HasCollidedWith(box_id));
  721. }
  722. }