CharacterVirtualTests.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. // SPDX-FileCopyrightText: 2022 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include "UnitTestFramework.h"
  4. #include "PhysicsTestContext.h"
  5. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  6. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  7. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  8. #include <Jolt/Physics/Character/CharacterVirtual.h>
  9. #include "Layers.h"
  10. TEST_SUITE("CharacterVirtualTests")
  11. {
  12. class Character : public CharacterContactListener
  13. {
  14. public:
  15. // Construct
  16. Character(PhysicsTestContext &ioContext) : mContext(ioContext) { }
  17. // Create the character
  18. void Create()
  19. {
  20. // Create capsule
  21. Ref<Shape> capsule = new CapsuleShape(0.5f * mHeightStanding, mRadiusStanding);
  22. mCharacterSettings.mShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * mHeightStanding + mRadiusStanding, 0), Quat::sIdentity(), capsule).Create().Get();
  23. // Configure supporting volume
  24. mCharacterSettings.mSupportingVolume = Plane(Vec3::sAxisY(), -mHeightStanding); // Accept contacts that touch the lower sphere of the capsule
  25. // Create character
  26. mCharacter = new CharacterVirtual(&mCharacterSettings, mInitialPosition, Quat::sIdentity(), mContext.GetSystem());
  27. mCharacter->SetListener(this);
  28. }
  29. // Step the character and the world
  30. void Step()
  31. {
  32. // Step the world
  33. mContext.SimulateSingleStep();
  34. // Determine new basic velocity
  35. Vec3 current_vertical_velocity = Vec3(0, mCharacter->GetLinearVelocity().GetY(), 0);
  36. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  37. Vec3 new_velocity;
  38. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  39. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  40. {
  41. // Assume velocity of ground when on ground
  42. new_velocity = ground_velocity;
  43. // Jump
  44. new_velocity += Vec3(0, mJumpSpeed, 0);
  45. mJumpSpeed = 0.0f;
  46. }
  47. else
  48. new_velocity = current_vertical_velocity;
  49. // Gravity
  50. PhysicsSystem *system = mContext.GetSystem();
  51. float delta_time = mContext.GetDeltaTime();
  52. new_velocity += system->GetGravity() * delta_time;
  53. // Player input
  54. new_velocity += mHorizontalSpeed;
  55. // Update character velocity
  56. mCharacter->SetLinearVelocity(new_velocity);
  57. Vec3 start_pos = mCharacter->GetPosition();
  58. // Update the character position
  59. TempAllocatorMalloc allocator;
  60. mCharacter->ExtendedUpdate(delta_time,
  61. system->GetGravity(),
  62. mUpdateSettings,
  63. system->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  64. system->GetDefaultLayerFilter(Layers::MOVING),
  65. { },
  66. allocator);
  67. // Calculate effective velocity in this step
  68. mEffectiveVelocity = (mCharacter->GetPosition() - start_pos) / delta_time;
  69. }
  70. // Simulate a longer period of time
  71. void Simulate(float inTime)
  72. {
  73. int num_steps = (int)round(inTime / mContext.GetDeltaTime());
  74. for (int step = 0; step < num_steps; ++step)
  75. Step();
  76. }
  77. // Configuration
  78. Vec3 mInitialPosition = Vec3::sZero();
  79. float mHeightStanding = 1.35f;
  80. float mRadiusStanding = 0.3f;
  81. CharacterVirtualSettings mCharacterSettings;
  82. CharacterVirtual::ExtendedUpdateSettings mUpdateSettings;
  83. // Character movement settings (update to control the movement of the character)
  84. Vec3 mHorizontalSpeed = Vec3::sZero();
  85. float mJumpSpeed = 0.0f; // Character will jump when not 0, will auto reset
  86. // The character
  87. Ref<CharacterVirtual> mCharacter;
  88. // Calculated effective velocity after a step
  89. Vec3 mEffectiveVelocity = Vec3::sZero();
  90. private:
  91. // CharacterContactListener callback
  92. virtual void OnContactSolve(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, Vec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity) override
  93. {
  94. // Don't allow sliding if the character doesn't want to move
  95. if (mHorizontalSpeed.IsNearZero() && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  96. ioNewCharacterVelocity = Vec3::sZero();
  97. }
  98. PhysicsTestContext & mContext;
  99. };
  100. TEST_CASE("TestFallingAndJumping")
  101. {
  102. // Create floor
  103. PhysicsTestContext c;
  104. c.CreateFloor();
  105. // Create character
  106. Character character(c);
  107. character.mInitialPosition = Vec3(0, 2, 0);
  108. character.Create();
  109. // After 1 step we should still be in air
  110. character.Step();
  111. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  112. // After some time we should be on the floor
  113. character.Simulate(1.0f);
  114. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  115. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), Vec3::sZero());
  116. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, Vec3::sZero());
  117. // Jump
  118. character.mJumpSpeed = 1.0f;
  119. character.Step();
  120. Vec3 velocity(0, 1.0f + c.GetDeltaTime() * c.GetSystem()->GetGravity().GetY(), 0);
  121. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), velocity * c.GetDeltaTime());
  122. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, velocity);
  123. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  124. // After some time we should be on the floor again
  125. character.Simulate(1.0f);
  126. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  127. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), Vec3::sZero());
  128. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, Vec3::sZero());
  129. }
  130. TEST_CASE("TestMovingOnSlope")
  131. {
  132. constexpr float cFloorHalfHeight = 1.0f;
  133. constexpr float cMovementTime = 1.5f;
  134. // Iterate various slope angles
  135. for (float slope_angle = DegreesToRadians(5.0f); slope_angle < DegreesToRadians(85.0f); slope_angle += DegreesToRadians(10.0f))
  136. {
  137. // Create sloped floor
  138. PhysicsTestContext c;
  139. Quat slope_rotation = Quat::sRotation(Vec3::sAxisZ(), slope_angle);
  140. c.CreateBox(Vec3::sZero(), slope_rotation, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100.0f, cFloorHalfHeight, 100.0f));
  141. // Create character so that it is touching the slope
  142. Character character(c);
  143. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  144. character.mInitialPosition = Vec3(0, (radius_and_padding + cFloorHalfHeight) / Cos(slope_angle) - radius_and_padding, 0);
  145. character.Create();
  146. // Determine if the slope is too steep for the character
  147. bool too_steep = slope_angle > character.mCharacterSettings.mMaxSlopeAngle;
  148. CharacterBase::EGroundState expected_ground_state = (too_steep? CharacterBase::EGroundState::OnSteepGround : CharacterBase::EGroundState::OnGround);
  149. Vec3 gravity = c.GetSystem()->GetGravity();
  150. float time_step = c.GetDeltaTime();
  151. Vec3 slope_normal = slope_rotation.RotateAxisY();
  152. // Calculate expected position after 1 time step
  153. Vec3 position_after_1_step = character.mInitialPosition;
  154. if (too_steep)
  155. {
  156. // Apply 1 frame of gravity and cancel movement in the slope normal direction
  157. Vec3 velocity = gravity * time_step;
  158. velocity -= velocity.Dot(slope_normal) * slope_normal;
  159. position_after_1_step += velocity * time_step;
  160. }
  161. // After 1 step we should be on the slope
  162. character.Step();
  163. CHECK(character.mCharacter->GetGroundState() == expected_ground_state);
  164. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), position_after_1_step);
  165. // Cancel any velocity to make the calculation below easier (otherwise we have to take gravity for 1 time step into account)
  166. character.mCharacter->SetLinearVelocity(Vec3::sZero());
  167. Vec3 start_pos = character.mCharacter->GetPosition();
  168. // Start moving in X direction
  169. character.mHorizontalSpeed = Vec3(2.0f, 0, 0);
  170. character.Simulate(cMovementTime);
  171. CHECK(character.mCharacter->GetGroundState() == expected_ground_state);
  172. // Calculate resulting translation
  173. Vec3 translation = character.mCharacter->GetPosition() - start_pos;
  174. // Calculate expected translation
  175. Vec3 expected_translation;
  176. if (too_steep)
  177. {
  178. // If too steep, we're just falling. Integrate using an Euler integrator.
  179. Vec3 velocity = Vec3::sZero();
  180. expected_translation = Vec3::sZero();
  181. int num_steps = (int)round(cMovementTime / time_step);
  182. for (int i = 0; i < num_steps; ++i)
  183. {
  184. velocity += gravity * time_step;
  185. expected_translation += velocity * time_step;
  186. }
  187. }
  188. else
  189. {
  190. // Every frame we apply 1 delta time * gravity which gets reset on the next update, add this to the horizontal speed
  191. expected_translation = (character.mHorizontalSpeed + gravity * time_step) * cMovementTime;
  192. }
  193. // Cancel movement in slope direction
  194. expected_translation -= expected_translation.Dot(slope_normal) * slope_normal;
  195. // Check that we travelled the right amount
  196. CHECK_APPROX_EQUAL(translation, expected_translation, 1.0e-4f);
  197. }
  198. }
  199. TEST_CASE("TestStickToFloor")
  200. {
  201. constexpr float cFloorHalfHeight = 1.0f;
  202. constexpr float cSlopeAngle = DegreesToRadians(45.0f);
  203. constexpr float cMovementTime = 1.5f;
  204. for (int mode = 0; mode < 2; ++mode)
  205. {
  206. // If this run is with 'stick to floor' enabled
  207. bool stick_to_floor = mode == 0;
  208. // Create sloped floor
  209. PhysicsTestContext c;
  210. Quat slope_rotation = Quat::sRotation(Vec3::sAxisZ(), cSlopeAngle);
  211. c.CreateBox(Vec3::sZero(), slope_rotation, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100.0f, cFloorHalfHeight, 100.0f));
  212. // Create character so that it is touching the slope
  213. Character character(c);
  214. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  215. character.mInitialPosition = Vec3(0, (radius_and_padding + cFloorHalfHeight) / Cos(cSlopeAngle) - radius_and_padding, 0);
  216. character.mUpdateSettings.mStickToFloorStepDown = stick_to_floor? Vec3(0, -0.5f, 0) : Vec3::sZero();
  217. character.Create();
  218. // After 1 step we should be on the slope
  219. character.Step();
  220. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  221. // Cancel any velocity to make the calculation below easier (otherwise we have to take gravity for 1 time step into account)
  222. character.mCharacter->SetLinearVelocity(Vec3::sZero());
  223. Vec3 start_pos = character.mCharacter->GetPosition();
  224. // Start moving down the slope at a speed high enough so that gravity will not keep us on the floor
  225. character.mHorizontalSpeed = Vec3(-10.0f, 0, 0);
  226. character.Simulate(cMovementTime);
  227. CHECK(character.mCharacter->GetGroundState() == (stick_to_floor? CharacterBase::EGroundState::OnGround : CharacterBase::EGroundState::InAir));
  228. // Calculate resulting translation
  229. Vec3 translation = character.mCharacter->GetPosition() - start_pos;
  230. // Calculate expected translation
  231. Vec3 expected_translation;
  232. if (stick_to_floor)
  233. {
  234. // We should stick to the floor, so the vertical translation follows the slope perfectly
  235. expected_translation = character.mHorizontalSpeed * cMovementTime;
  236. expected_translation.SetY(expected_translation.GetX() * Tan(cSlopeAngle));
  237. }
  238. else
  239. {
  240. Vec3 gravity = c.GetSystem()->GetGravity();
  241. float time_step = c.GetDeltaTime();
  242. // If too steep, we're just falling. Integrate using an Euler integrator.
  243. Vec3 velocity = character.mHorizontalSpeed;
  244. expected_translation = Vec3::sZero();
  245. int num_steps = (int)round(cMovementTime / time_step);
  246. for (int i = 0; i < num_steps; ++i)
  247. {
  248. velocity += gravity * time_step;
  249. expected_translation += velocity * time_step;
  250. }
  251. }
  252. // Check that we travelled the right amount
  253. CHECK_APPROX_EQUAL(translation, expected_translation, 1.0e-4f);
  254. }
  255. }
  256. TEST_CASE("TestWalkStairs")
  257. {
  258. const float cStepHeight = 0.3f;
  259. const int cNumSteps = 10;
  260. // Create stairs from triangles
  261. TriangleList triangles;
  262. for (int i = 0; i < cNumSteps; ++i)
  263. {
  264. // Start of step
  265. Vec3 base(0, cStepHeight * i, cStepHeight * i);
  266. // Left side
  267. Vec3 b1 = base + Vec3(2.0f, 0, 0);
  268. Vec3 s1 = b1 + Vec3(0, cStepHeight, 0);
  269. Vec3 p1 = s1 + Vec3(0, 0, cStepHeight);
  270. // Right side
  271. Vec3 width(-4.0f, 0, 0);
  272. Vec3 b2 = b1 + width;
  273. Vec3 s2 = s1 + width;
  274. Vec3 p2 = p1 + width;
  275. triangles.push_back(Triangle(s1, b1, s2));
  276. triangles.push_back(Triangle(b1, b2, s2));
  277. triangles.push_back(Triangle(s1, p2, p1));
  278. triangles.push_back(Triangle(s1, s2, p2));
  279. }
  280. MeshShapeSettings mesh(triangles);
  281. mesh.SetEmbedded();
  282. BodyCreationSettings mesh_stairs(&mesh, Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  283. // Stair stepping is very delta time sensitive, so test various update frequencies
  284. float frequencies[] = { 60.0f, 120.0f, 240.0f, 360.0f };
  285. for (float frequency : frequencies)
  286. {
  287. float time_step = 1.0f / frequency;
  288. PhysicsTestContext c(time_step);
  289. c.CreateFloor();
  290. c.GetBodyInterface().CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  291. // Create character so that it is touching the slope
  292. Character character(c);
  293. character.mInitialPosition = Vec3(0, 0, -2.0f); // Start in front of the stairs
  294. character.mUpdateSettings.mWalkStairsStepUp = Vec3::sZero(); // No stair walking
  295. character.Create();
  296. // Start moving towards the stairs
  297. character.mHorizontalSpeed = Vec3(0, 0, 4.0f);
  298. character.Simulate(1.0f);
  299. // We should have gotten stuck at the start of the stairs (can't move up)
  300. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  301. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  302. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), Vec3(0, 0, -radius_and_padding), 1.0e-2f);
  303. // Enable stair walking
  304. character.mUpdateSettings.mWalkStairsStepUp = Vec3(0, 0.4f, 0);
  305. // Calculate time it should take to move up the stairs at constant speed
  306. float movement_time = (cNumSteps * cStepHeight + radius_and_padding) / character.mHorizontalSpeed.GetZ();
  307. int max_steps = int(1.5f * round(movement_time / time_step)); // In practise there is a bit of slowdown while stair stepping, so add a bit of slack
  308. // Step until we reach the top of the stairs
  309. Vec3 last_position = character.mCharacter->GetPosition();
  310. bool reached_goal = false;
  311. for (int i = 0; i < max_steps; ++i)
  312. {
  313. character.Step();
  314. // We should always be on the floor during stair stepping
  315. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  316. // Check position progression
  317. Vec3 position = character.mCharacter->GetPosition();
  318. CHECK_APPROX_EQUAL(position.GetX(), 0.0f); // No movement in X
  319. CHECK(position.GetZ() > last_position.GetZ()); // Always moving forward
  320. CHECK(position.GetZ() < cNumSteps * cStepHeight); // No movement beyond stairs
  321. if (position.GetY() > cNumSteps * cStepHeight - 1.0e-3f)
  322. {
  323. reached_goal = true;
  324. break;
  325. }
  326. last_position = position;
  327. }
  328. CHECK(reached_goal);
  329. }
  330. }
  331. TEST_CASE("TestRotatingPlatform")
  332. {
  333. constexpr float cFloorHalfHeight = 1.0f;
  334. constexpr float cFloorHalfWidth = 10.0f;
  335. constexpr float cCharacterPosition = 0.9f * cFloorHalfWidth;
  336. constexpr float cAngularVelocity = 2.0f * JPH_PI;
  337. PhysicsTestContext c;
  338. // Create box
  339. Body &box = c.CreateBox(Vec3::sZero(), Quat::sIdentity(), EMotionType::Kinematic, EMotionQuality::Discrete, Layers::MOVING, Vec3(cFloorHalfWidth, cFloorHalfHeight, cFloorHalfWidth));
  340. box.SetAllowSleeping(false);
  341. // Create character so that it is touching the box at the
  342. Character character(c);
  343. character.mInitialPosition = Vec3(cCharacterPosition, cFloorHalfHeight, 0);
  344. character.Create();
  345. // Step to ensure the character is on the box
  346. character.Step();
  347. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  348. // Set the box to rotate a full circle per second
  349. box.SetAngularVelocity(Vec3(0, cAngularVelocity, 0));
  350. // Rotate and check that character stays on the box
  351. for (int t = 0; t < 60; ++t)
  352. {
  353. character.Step();
  354. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  355. // Note that the character moves according to the ground velocity and the ground velocity is updated at the end of the step
  356. // 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.
  357. Vec3 expected_position = Quat::sRotation(Vec3::sAxisY(), float(t) * c.GetDeltaTime() * cAngularVelocity) * character.mInitialPosition;
  358. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), expected_position, 1.0e-4f);
  359. }
  360. }
  361. TEST_CASE("TestMovingPlatformUp")
  362. {
  363. constexpr float cFloorHalfHeight = 1.0f;
  364. constexpr float cFloorHalfWidth = 10.0f;
  365. constexpr float cLinearVelocity = 0.5f;
  366. PhysicsTestContext c;
  367. // Create box
  368. Body &box = c.CreateBox(Vec3::sZero(), Quat::sIdentity(), EMotionType::Kinematic, EMotionQuality::Discrete, Layers::MOVING, Vec3(cFloorHalfWidth, cFloorHalfHeight, cFloorHalfWidth));
  369. box.SetAllowSleeping(false);
  370. // Create character so that it is touching the box at the
  371. Character character(c);
  372. character.mInitialPosition = Vec3(0, cFloorHalfHeight, 0);
  373. character.Create();
  374. // Step to ensure the character is on the box
  375. character.Step();
  376. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  377. // Set the box to move up
  378. box.SetLinearVelocity(Vec3(0, cLinearVelocity, 0));
  379. // Check that character stays on the box
  380. for (int t = 0; t < 60; ++t)
  381. {
  382. character.Step();
  383. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  384. Vec3 expected_position = box.GetPosition() + character.mInitialPosition;
  385. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), expected_position, 1.0e-2f);
  386. }
  387. // Stop box
  388. box.SetLinearVelocity(Vec3::sZero());
  389. character.Simulate(0.5f);
  390. // Set the box to move down
  391. box.SetLinearVelocity(Vec3(0, -cLinearVelocity, 0));
  392. // Check that character stays on the box
  393. for (int t = 0; t < 60; ++t)
  394. {
  395. character.Step();
  396. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  397. Vec3 expected_position = box.GetPosition() + character.mInitialPosition;
  398. CHECK_APPROX_EQUAL(character.mCharacter->GetPosition(), expected_position, 1.0e-2f);
  399. }
  400. }
  401. }