CharacterVirtualTests.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  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 OnCharacterContactAdded(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) override
  134. {
  135. mContactLog.OnCharacterContactAdded(inCharacter, inOtherCharacter, inSubShapeID2, inContactPosition, inContactNormal, ioSettings);
  136. }
  137. 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
  138. {
  139. // Don't allow sliding if the character doesn't want to move
  140. if (mHorizontalSpeed.IsNearZero() && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  141. ioNewCharacterVelocity = Vec3::sZero();
  142. }
  143. PhysicsTestContext & mContext;
  144. };
  145. TEST_CASE("TestFallingAndJumping")
  146. {
  147. // Create floor
  148. PhysicsTestContext c;
  149. c.CreateFloor();
  150. // Create character
  151. Character character(c);
  152. character.mInitialPosition = RVec3(0, 2, 0);
  153. character.Create();
  154. // After 1 step we should still be in air
  155. character.Step();
  156. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  157. // After some time we should be on the floor
  158. character.Simulate(1.0f);
  159. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  160. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3::sZero());
  161. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, Vec3::sZero());
  162. // Jump
  163. character.mJumpSpeed = 1.0f;
  164. character.Step();
  165. Vec3 velocity(0, 1.0f + c.GetDeltaTime() * c.GetSystem()->GetGravity().GetY(), 0);
  166. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(velocity * c.GetDeltaTime()));
  167. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, velocity);
  168. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  169. // After some time we should be on the floor again
  170. character.Simulate(1.0f);
  171. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  172. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3::sZero());
  173. CHECK_APPROX_EQUAL(character.mEffectiveVelocity, Vec3::sZero());
  174. }
  175. TEST_CASE("TestMovingOnSlope")
  176. {
  177. constexpr float cFloorHalfHeight = 1.0f;
  178. constexpr float cMovementTime = 1.5f;
  179. // Iterate various slope angles
  180. for (float slope_angle = DegreesToRadians(5.0f); slope_angle < DegreesToRadians(85.0f); slope_angle += DegreesToRadians(10.0f))
  181. {
  182. // Create sloped floor
  183. PhysicsTestContext c;
  184. Quat slope_rotation = Quat::sRotation(Vec3::sAxisZ(), slope_angle);
  185. c.CreateBox(RVec3::sZero(), slope_rotation, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100.0f, cFloorHalfHeight, 100.0f));
  186. // Create character so that it is touching the slope
  187. Character character(c);
  188. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  189. character.mInitialPosition = RVec3(0, (radius_and_padding + cFloorHalfHeight) / Cos(slope_angle) - radius_and_padding, 0);
  190. character.Create();
  191. // Determine if the slope is too steep for the character
  192. bool too_steep = slope_angle > character.mCharacterSettings.mMaxSlopeAngle;
  193. CharacterBase::EGroundState expected_ground_state = (too_steep? CharacterBase::EGroundState::OnSteepGround : CharacterBase::EGroundState::OnGround);
  194. Vec3 gravity = c.GetSystem()->GetGravity();
  195. float time_step = c.GetDeltaTime();
  196. Vec3 slope_normal = slope_rotation.RotateAxisY();
  197. // Calculate expected position after 1 time step
  198. RVec3 position_after_1_step = character.mInitialPosition;
  199. if (too_steep)
  200. {
  201. // Apply 1 frame of gravity and cancel movement in the slope normal direction
  202. Vec3 velocity = gravity * time_step;
  203. velocity -= velocity.Dot(slope_normal) * slope_normal;
  204. position_after_1_step += velocity * time_step;
  205. }
  206. // After 1 step we should be on the slope
  207. character.Step();
  208. CHECK(character.mCharacter->GetGroundState() == expected_ground_state);
  209. CHECK_APPROX_EQUAL(character.GetPosition(), position_after_1_step, 2.0e-6f);
  210. // Cancel any velocity to make the calculation below easier (otherwise we have to take gravity for 1 time step into account)
  211. character.mCharacter->SetLinearVelocity(Vec3::sZero());
  212. RVec3 start_pos = character.GetPosition();
  213. // Start moving in X direction
  214. character.mHorizontalSpeed = Vec3(2.0f, 0, 0);
  215. character.Simulate(cMovementTime);
  216. CHECK(character.mCharacter->GetGroundState() == expected_ground_state);
  217. // Calculate resulting translation
  218. Vec3 translation = Vec3(character.GetPosition() - start_pos);
  219. // Calculate expected translation
  220. Vec3 expected_translation;
  221. if (too_steep)
  222. {
  223. // If too steep, we're just falling. Integrate using an Euler integrator.
  224. Vec3 velocity = Vec3::sZero();
  225. expected_translation = Vec3::sZero();
  226. int num_steps = (int)round(cMovementTime / time_step);
  227. for (int i = 0; i < num_steps; ++i)
  228. {
  229. velocity += gravity * time_step;
  230. expected_translation += velocity * time_step;
  231. }
  232. }
  233. else
  234. {
  235. // Every frame we apply 1 delta time * gravity which gets reset on the next update, add this to the horizontal speed
  236. expected_translation = (character.mHorizontalSpeed + gravity * time_step) * cMovementTime;
  237. }
  238. // Cancel movement in slope direction
  239. expected_translation -= expected_translation.Dot(slope_normal) * slope_normal;
  240. // Check that we traveled the right amount
  241. CHECK_APPROX_EQUAL(translation, expected_translation, 1.0e-4f);
  242. }
  243. }
  244. TEST_CASE("TestStickToFloor")
  245. {
  246. constexpr float cFloorHalfHeight = 1.0f;
  247. constexpr float cSlopeAngle = DegreesToRadians(45.0f);
  248. constexpr float cMovementTime = 1.5f;
  249. for (int mode = 0; mode < 2; ++mode)
  250. {
  251. // If this run is with 'stick to floor' enabled
  252. bool stick_to_floor = mode == 0;
  253. // Create sloped floor
  254. PhysicsTestContext c;
  255. Quat slope_rotation = Quat::sRotation(Vec3::sAxisZ(), cSlopeAngle);
  256. Body &floor = c.CreateBox(RVec3::sZero(), slope_rotation, EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3(100.0f, cFloorHalfHeight, 100.0f));
  257. // Create character so that it is touching the slope
  258. Character character(c);
  259. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  260. character.mInitialPosition = RVec3(0, (radius_and_padding + cFloorHalfHeight) / Cos(cSlopeAngle) - radius_and_padding, 0);
  261. character.mUpdateSettings.mStickToFloorStepDown = stick_to_floor? Vec3(0, -0.5f, 0) : Vec3::sZero();
  262. character.Create();
  263. // After 1 step we should be on the slope
  264. character.Step();
  265. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  266. CHECK(character.mContactLog.GetEntryCount() == 2);
  267. CHECK(character.mContactLog.Contains(LoggingCharacterContactListener::EType::ValidateBody, character.mCharacter, floor.GetID()));
  268. CHECK(character.mContactLog.Contains(LoggingCharacterContactListener::EType::AddBody, character.mCharacter, floor.GetID()));
  269. character.mContactLog.Clear();
  270. // Cancel any velocity to make the calculation below easier (otherwise we have to take gravity for 1 time step into account)
  271. character.mCharacter->SetLinearVelocity(Vec3::sZero());
  272. RVec3 start_pos = character.GetPosition();
  273. float time_step = c.GetDeltaTime();
  274. int num_steps = (int)round(cMovementTime / time_step);
  275. for (int i = 0; i < num_steps; ++i)
  276. {
  277. // Start moving down the slope at a speed high enough so that gravity will not keep us on the floor
  278. character.mHorizontalSpeed = Vec3(-10.0f, 0, 0);
  279. character.Step();
  280. if (stick_to_floor)
  281. {
  282. // Should stick to floor
  283. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  284. // Should have received callbacks
  285. CHECK(character.mContactLog.GetEntryCount() == 2);
  286. CHECK(character.mContactLog.Contains(LoggingCharacterContactListener::EType::ValidateBody, character.mCharacter, floor.GetID()));
  287. CHECK(character.mContactLog.Contains(LoggingCharacterContactListener::EType::AddBody, character.mCharacter, floor.GetID()));
  288. character.mContactLog.Clear();
  289. }
  290. else
  291. {
  292. // Should be off ground
  293. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::InAir);
  294. // No callbacks
  295. CHECK(character.mContactLog.GetEntryCount() == 0);
  296. }
  297. }
  298. // Calculate resulting translation
  299. Vec3 translation = Vec3(character.GetPosition() - start_pos);
  300. // Calculate expected translation
  301. Vec3 expected_translation;
  302. if (stick_to_floor)
  303. {
  304. // We should stick to the floor, so the vertical translation follows the slope perfectly
  305. expected_translation = character.mHorizontalSpeed * cMovementTime;
  306. expected_translation.SetY(expected_translation.GetX() * Tan(cSlopeAngle));
  307. }
  308. else
  309. {
  310. // If too steep, we're just falling. Integrate using an Euler integrator.
  311. Vec3 velocity = character.mHorizontalSpeed;
  312. expected_translation = Vec3::sZero();
  313. Vec3 gravity = c.GetSystem()->GetGravity();
  314. for (int i = 0; i < num_steps; ++i)
  315. {
  316. velocity += gravity * time_step;
  317. expected_translation += velocity * time_step;
  318. }
  319. }
  320. // Check that we traveled the right amount
  321. CHECK_APPROX_EQUAL(translation, expected_translation, 1.0e-4f);
  322. }
  323. }
  324. TEST_CASE("TestWalkStairs")
  325. {
  326. const float cStepHeight = 0.3f;
  327. const int cNumSteps = 10;
  328. // Create stairs from triangles
  329. TriangleList triangles;
  330. for (int i = 0; i < cNumSteps; ++i)
  331. {
  332. // Start of step
  333. Vec3 base(0, cStepHeight * i, cStepHeight * i);
  334. // Left side
  335. Vec3 b1 = base + Vec3(2.0f, 0, 0);
  336. Vec3 s1 = b1 + Vec3(0, cStepHeight, 0);
  337. Vec3 p1 = s1 + Vec3(0, 0, cStepHeight);
  338. // Right side
  339. Vec3 width(-4.0f, 0, 0);
  340. Vec3 b2 = b1 + width;
  341. Vec3 s2 = s1 + width;
  342. Vec3 p2 = p1 + width;
  343. triangles.push_back(Triangle(s1, b1, s2));
  344. triangles.push_back(Triangle(b1, b2, s2));
  345. triangles.push_back(Triangle(s1, p2, p1));
  346. triangles.push_back(Triangle(s1, s2, p2));
  347. }
  348. MeshShapeSettings mesh(triangles);
  349. mesh.SetEmbedded();
  350. BodyCreationSettings mesh_stairs(&mesh, RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  351. // Stair stepping is very delta time sensitive, so test various update frequencies
  352. float frequencies[] = { 60.0f, 120.0f, 240.0f, 360.0f };
  353. for (float frequency : frequencies)
  354. {
  355. float time_step = 1.0f / frequency;
  356. PhysicsTestContext c(time_step);
  357. c.CreateFloor();
  358. c.GetBodyInterface().CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  359. // Create character so that it is touching the slope
  360. Character character(c);
  361. character.mInitialPosition = RVec3(0, 0, -2.0f); // Start in front of the stairs
  362. character.mUpdateSettings.mWalkStairsStepUp = Vec3::sZero(); // No stair walking
  363. character.Create();
  364. // Start moving towards the stairs
  365. character.mHorizontalSpeed = Vec3(0, 0, 4.0f);
  366. character.Simulate(1.0f);
  367. // We should have gotten stuck at the start of the stairs (can't move up)
  368. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  369. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  370. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(0, 0, -radius_and_padding), 1.1e-2f);
  371. // Enable stair walking
  372. character.mUpdateSettings.mWalkStairsStepUp = Vec3(0, 0.4f, 0);
  373. // Calculate time it should take to move up the stairs at constant speed
  374. float movement_time = (cNumSteps * cStepHeight + radius_and_padding) / character.mHorizontalSpeed.GetZ();
  375. 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
  376. // Step until we reach the top of the stairs
  377. RVec3 last_position = character.GetPosition();
  378. bool reached_goal = false;
  379. for (int i = 0; i < max_steps; ++i)
  380. {
  381. character.Step();
  382. // We should always be on the floor during stair stepping
  383. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  384. // Check position progression
  385. RVec3 position = character.GetPosition();
  386. CHECK_APPROX_EQUAL(position.GetX(), 0); // No movement in X
  387. CHECK(position.GetZ() > last_position.GetZ()); // Always moving forward
  388. CHECK(position.GetZ() < cNumSteps * cStepHeight); // No movement beyond stairs
  389. if (position.GetY() > cNumSteps * cStepHeight - 1.0e-3f)
  390. {
  391. reached_goal = true;
  392. break;
  393. }
  394. last_position = position;
  395. }
  396. CHECK(reached_goal);
  397. }
  398. }
  399. TEST_CASE("TestRotatingPlatform")
  400. {
  401. constexpr float cFloorHalfHeight = 1.0f;
  402. constexpr float cFloorHalfWidth = 10.0f;
  403. constexpr float cCharacterPosition = 0.9f * cFloorHalfWidth;
  404. constexpr float cAngularVelocity = 2.0f * JPH_PI;
  405. PhysicsTestContext c;
  406. // Create box
  407. Body &box = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Kinematic, EMotionQuality::Discrete, Layers::MOVING, Vec3(cFloorHalfWidth, cFloorHalfHeight, cFloorHalfWidth));
  408. box.SetAllowSleeping(false);
  409. // Create character so that it is touching the box at the
  410. Character character(c);
  411. character.mInitialPosition = RVec3(cCharacterPosition, cFloorHalfHeight, 0);
  412. character.Create();
  413. // Step to ensure the character is on the box
  414. character.Step();
  415. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  416. // Set the box to rotate a full circle per second
  417. box.SetAngularVelocity(Vec3(0, cAngularVelocity, 0));
  418. // Rotate and check that character stays on the box
  419. for (int t = 0; t < 60; ++t)
  420. {
  421. character.Step();
  422. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  423. // Note that the character moves according to the ground velocity and the ground velocity is updated at the end of the step
  424. // 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.
  425. RVec3 expected_position = RMat44::sRotation(Quat::sRotation(Vec3::sAxisY(), float(t) * c.GetDeltaTime() * cAngularVelocity)) * character.mInitialPosition;
  426. CHECK_APPROX_EQUAL(character.GetPosition(), expected_position, 1.0e-4f);
  427. }
  428. }
  429. TEST_CASE("TestMovingPlatformUp")
  430. {
  431. constexpr float cFloorHalfHeight = 1.0f;
  432. constexpr float cFloorHalfWidth = 10.0f;
  433. constexpr float cLinearVelocity = 0.5f;
  434. PhysicsTestContext c;
  435. // Create box
  436. Body &box = c.CreateBox(RVec3::sZero(), Quat::sIdentity(), EMotionType::Kinematic, EMotionQuality::Discrete, Layers::MOVING, Vec3(cFloorHalfWidth, cFloorHalfHeight, cFloorHalfWidth));
  437. box.SetAllowSleeping(false);
  438. // Create character so that it is touching the box at the
  439. Character character(c);
  440. character.mInitialPosition = RVec3(0, cFloorHalfHeight, 0);
  441. character.Create();
  442. // Step to ensure the character is on the box
  443. character.Step();
  444. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  445. // Set the box to move up
  446. box.SetLinearVelocity(Vec3(0, cLinearVelocity, 0));
  447. // Check that character stays on the box
  448. for (int t = 0; t < 60; ++t)
  449. {
  450. character.Step();
  451. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  452. RVec3 expected_position = box.GetPosition() + character.mInitialPosition;
  453. CHECK_APPROX_EQUAL(character.GetPosition(), expected_position, 1.0e-2f);
  454. }
  455. // Stop box
  456. box.SetLinearVelocity(Vec3::sZero());
  457. character.Simulate(0.5f);
  458. // Set the box to move down
  459. box.SetLinearVelocity(Vec3(0, -cLinearVelocity, 0));
  460. // Check that character stays on the box
  461. for (int t = 0; t < 60; ++t)
  462. {
  463. character.Step();
  464. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  465. RVec3 expected_position = box.GetPosition() + character.mInitialPosition;
  466. CHECK_APPROX_EQUAL(character.GetPosition(), expected_position, 1.0e-2f);
  467. }
  468. }
  469. TEST_CASE("TestContactPointLimit")
  470. {
  471. PhysicsTestContext ctx;
  472. Body &floor = ctx.CreateFloor();
  473. // Create character at the origin
  474. Character character(ctx);
  475. character.mInitialPosition = RVec3(0, 1, 0);
  476. character.mUpdateSettings.mStickToFloorStepDown = Vec3::sZero();
  477. character.mUpdateSettings.mWalkStairsStepUp = Vec3::sZero();
  478. character.Create();
  479. // Radius including padding
  480. const float character_radius = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  481. // Create a half cylinder with caps for testing contact point limit
  482. VertexList vertices;
  483. IndexedTriangleList triangles;
  484. // The half cylinder
  485. const int cPosSegments = 2;
  486. const int cAngleSegments = 768;
  487. const float cCylinderLength = 2.0f;
  488. for (int pos = 0; pos < cPosSegments; ++pos)
  489. for (int angle = 0; angle < cAngleSegments; ++angle)
  490. {
  491. uint32 start = (uint32)vertices.size();
  492. float radius = character_radius + 0.01f;
  493. float angle_rad = (-0.5f + float(angle) / cAngleSegments) * JPH_PI;
  494. float s = Sin(angle_rad);
  495. float c = Cos(angle_rad);
  496. float x = cCylinderLength * (-0.5f + float(pos) / (cPosSegments - 1));
  497. float y = angle == 0 || angle == cAngleSegments - 1? 0.5f : (1.0f - c) * radius;
  498. float z = s * radius;
  499. vertices.push_back(Float3(x, y, z));
  500. if (pos > 0 && angle > 0)
  501. {
  502. triangles.push_back(IndexedTriangle(start, start - 1, start - cAngleSegments));
  503. triangles.push_back(IndexedTriangle(start - 1, start - cAngleSegments - 1, start - cAngleSegments));
  504. }
  505. }
  506. // Add end caps
  507. uint32 end = cAngleSegments * (cPosSegments - 1);
  508. for (int angle = 0; angle < cAngleSegments - 1; ++angle)
  509. {
  510. triangles.push_back(IndexedTriangle(0, angle + 1, angle));
  511. triangles.push_back(IndexedTriangle(end, end + angle, end + angle + 1));
  512. }
  513. // Create test body
  514. MeshShapeSettings mesh(vertices, triangles);
  515. mesh.SetEmbedded();
  516. BodyCreationSettings mesh_cylinder(&mesh, character.mInitialPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  517. BodyID cylinder_id = ctx.GetBodyInterface().CreateAndAddBody(mesh_cylinder, EActivation::DontActivate);
  518. // End positions that can be reached by character
  519. RVec3 pos_end(0.5_r * cCylinderLength - character_radius, 1, 0);
  520. RVec3 neg_end(-0.5_r * cCylinderLength + character_radius, 1, 0);
  521. // Move towards positive cap and test if we hit the end
  522. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  523. for (int t = 0; t < 60; ++t)
  524. {
  525. character.Step();
  526. CHECK(character.mCharacter->GetMaxHitsExceeded());
  527. CHECK(character.GetNumContacts() <= character.mCharacter->GetMaxNumHits());
  528. CHECK(character.mCharacter->GetGroundBodyID() == cylinder_id);
  529. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  530. }
  531. CHECK_APPROX_EQUAL(character.GetPosition(), pos_end, 1.0e-4f);
  532. // Move towards negative cap and test if we hit the end
  533. character.mHorizontalSpeed = Vec3(-cCylinderLength, 0, 0);
  534. for (int t = 0; t < 60; ++t)
  535. {
  536. character.Step();
  537. CHECK(character.mCharacter->GetMaxHitsExceeded());
  538. CHECK(character.GetNumContacts() <= character.mCharacter->GetMaxNumHits());
  539. CHECK(character.mCharacter->GetGroundBodyID() == cylinder_id);
  540. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  541. }
  542. CHECK_APPROX_EQUAL(character.GetPosition(), neg_end, 1.0e-4f);
  543. // Turn off contact point reduction
  544. character.mCharacter->SetHitReductionCosMaxAngle(-1.0f);
  545. // Move towards positive cap and test that we did not reach the end
  546. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  547. for (int t = 0; t < 60; ++t)
  548. {
  549. character.Step();
  550. CHECK(character.mCharacter->GetMaxHitsExceeded());
  551. CHECK(character.GetNumContacts() == character.mCharacter->GetMaxNumHits());
  552. }
  553. RVec3 cur_pos = character.GetPosition();
  554. CHECK((pos_end - cur_pos).Length() > 0.01_r);
  555. // Move towards negative cap and test that we got stuck
  556. character.mHorizontalSpeed = Vec3(-cCylinderLength, 0, 0);
  557. for (int t = 0; t < 60; ++t)
  558. {
  559. character.Step();
  560. CHECK(character.mCharacter->GetMaxHitsExceeded());
  561. CHECK(character.GetNumContacts() == character.mCharacter->GetMaxNumHits());
  562. }
  563. CHECK(cur_pos.IsClose(character.GetPosition(), 1.0e-6f));
  564. // Now teleport the character next to the half cylinder
  565. character.mCharacter->SetPosition(RVec3(0, 0, 1));
  566. // Move in positive X and check that we did not exceed max hits and that we were able to move unimpeded
  567. character.mHorizontalSpeed = Vec3(cCylinderLength, 0, 0);
  568. for (int t = 0; t < 60; ++t)
  569. {
  570. character.Step();
  571. CHECK(!character.mCharacter->GetMaxHitsExceeded());
  572. CHECK(character.GetNumContacts() == 1); // We should only hit the floor
  573. CHECK(character.mCharacter->GetGroundBodyID() == floor.GetID());
  574. CHECK(character.mCharacter->GetGroundNormal().Dot(Vec3::sAxisY()) > 0.999f);
  575. }
  576. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(cCylinderLength, 0, 1), 1.0e-4f);
  577. }
  578. TEST_CASE("TestStairWalkAlongWall")
  579. {
  580. // Stair stepping is very delta time sensitive, so test various update frequencies
  581. float frequencies[] = { 60.0f, 120.0f, 240.0f, 360.0f };
  582. for (float frequency : frequencies)
  583. {
  584. float time_step = 1.0f / frequency;
  585. PhysicsTestContext c(time_step);
  586. c.CreateFloor();
  587. // Create character
  588. Character character(c);
  589. character.Create();
  590. // Create a wall
  591. const float cWallHalfThickness = 0.05f;
  592. 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);
  593. // 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
  594. character.mHorizontalSpeed = Vec3(5.0f, 0, -1.0f);
  595. character.Simulate(1.0f);
  596. // We should have moved along the wall at the desired speed
  597. CHECK(character.mCharacter->GetGroundState() == CharacterBase::EGroundState::OnGround);
  598. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(5.0f, 0, 0), 1.0e-2f);
  599. }
  600. }
  601. TEST_CASE("TestInitiallyIntersecting")
  602. {
  603. PhysicsTestContext c;
  604. c.CreateFloor();
  605. // Create box that is intersecting with the character
  606. c.CreateBox(RVec3(-0.5f, 0.5f, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, Vec3::sReplicate(0.5f));
  607. // Try various penetration recovery values
  608. for (float penetration_recovery : { 0.0f, 0.5f, 0.75f, 1.0f })
  609. {
  610. // Create character
  611. Character character(c);
  612. character.mCharacterSettings.mPenetrationRecoverySpeed = penetration_recovery;
  613. character.Create();
  614. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3::sZero());
  615. // Total radius of character
  616. float radius_and_padding = character.mRadiusStanding + character.mCharacterSettings.mCharacterPadding;
  617. float x = 0.0f;
  618. for (int step = 0; step < 3; ++step)
  619. {
  620. // Calculate expected position
  621. x += penetration_recovery * (radius_and_padding - x);
  622. // Step character and check that it matches expected recovery
  623. character.Step();
  624. CHECK_APPROX_EQUAL(character.GetPosition(), RVec3(x, 0, 0));
  625. }
  626. }
  627. }
  628. TEST_CASE("TestCharacterVsCharacter")
  629. {
  630. PhysicsTestContext c;
  631. BodyID floor_id = c.CreateFloor().GetID();
  632. // Create characters with different radii and padding
  633. Character character1(c);
  634. character1.mInitialPosition = RVec3::sZero();
  635. character1.mRadiusStanding = 0.2f;
  636. character1.mCharacterSettings.mCharacterPadding = 0.04f;
  637. character1.Create();
  638. Character character2(c);
  639. character2.mInitialPosition = RVec3(1, 0, 0);
  640. character2.mRadiusStanding = 0.3f;
  641. character2.mCharacterSettings.mCharacterPadding = 0.03f;
  642. character2.Create();
  643. // Make both collide
  644. character1.mCharacterVsCharacter.Add(character2.mCharacter);
  645. character2.mCharacterVsCharacter.Add(character1.mCharacter);
  646. // Add a box behind character 2, we should never hit this
  647. Vec3 box_extent(0.1f, 1.0f, 1.0f);
  648. c.CreateBox(RVec3(1.5f, 0, 0), Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, box_extent, EActivation::DontActivate);
  649. // Move character 1 towards character 2 so that in 1 step it will hit both character 2 and the box
  650. character1.mHorizontalSpeed = Vec3(600.0f, 0, 0);
  651. character1.Step();
  652. // Character 1 should have stopped at character 2
  653. float character1_radius = character1.mRadiusStanding + character1.mCharacterSettings.mCharacterPadding;
  654. float character2_radius = character2.mRadiusStanding + character2.mCharacterSettings.mCharacterPadding;
  655. float separation = character1_radius + character2_radius;
  656. RVec3 expected_colliding_with_character = character2.mInitialPosition - Vec3(separation, 0, 0);
  657. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_character, 1.0e-3f);
  658. CHECK(character1.GetNumContacts() == 2);
  659. CHECK(character1.HasCollidedWith(floor_id));
  660. CHECK(character1.HasCollidedWith(character2.mCharacter));
  661. // Move character 1 back to its initial position
  662. character1.mCharacter->SetPosition(character1.mInitialPosition);
  663. character1.mCharacter->SetLinearVelocity(Vec3::sZero());
  664. // Now move slowly so that we will detect the collision during the normal collide shape step
  665. character1.mHorizontalSpeed = Vec3(1.0f, 0, 0);
  666. character1.Step();
  667. CHECK(character1.GetNumContacts() == 1);
  668. CHECK(character1.HasCollidedWith(floor_id));
  669. character1.Simulate(1.0f);
  670. // Character 1 should have stopped at character 2
  671. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_character, 1.0e-3f);
  672. CHECK(character1.GetNumContacts() == 2);
  673. CHECK(character1.HasCollidedWith(floor_id));
  674. CHECK(character1.HasCollidedWith(character2.mCharacter));
  675. // Move character 1 back to its initial position
  676. character1.mCharacter->SetPosition(character1.mInitialPosition);
  677. character1.mCharacter->SetLinearVelocity(Vec3::sZero());
  678. // Add a box in between the characters
  679. RVec3 box_position(0.5f, 0, 0);
  680. BodyID box_id = c.CreateBox(box_position, Quat::sIdentity(), EMotionType::Static, EMotionQuality::Discrete, Layers::NON_MOVING, box_extent, EActivation::DontActivate).GetID();
  681. // Move character 1 so that it will step through both the box and the character in 1 time step
  682. character1.mHorizontalSpeed = Vec3(600.0f, 0, 0);
  683. character1.Step();
  684. // Expect that it ends up at the box
  685. RVec3 expected_colliding_with_box = box_position - Vec3(character1_radius + box_extent.GetX(), 0, 0);
  686. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_box, 1.0e-3f);
  687. CHECK(character1.GetNumContacts() == 2);
  688. CHECK(character1.HasCollidedWith(floor_id));
  689. CHECK(character1.HasCollidedWith(box_id));
  690. // Move character 1 back to its initial position
  691. character1.mCharacter->SetPosition(character1.mInitialPosition);
  692. character1.mCharacter->SetLinearVelocity(Vec3::sZero());
  693. // Now move slowly so that we will detect the collision during the normal collide shape step
  694. character1.mHorizontalSpeed = Vec3(1.0f, 0, 0);
  695. character1.Step();
  696. CHECK(character1.GetNumContacts() == 1);
  697. CHECK(character1.HasCollidedWith(floor_id));
  698. character1.Simulate(1.0f);
  699. // Expect that it ends up at the box
  700. CHECK_APPROX_EQUAL(character1.GetPosition(), expected_colliding_with_box, 1.0e-3f);
  701. CHECK(character1.GetNumContacts() == 2);
  702. CHECK(character1.HasCollidedWith(floor_id));
  703. CHECK(character1.HasCollidedWith(box_id));
  704. }
  705. }