CharacterVirtualTest.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Tests/Character/CharacterVirtualTest.h>
  5. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  6. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  7. #include <Layers.h>
  8. #include <Renderer/DebugRendererImp.h>
  9. #include <Application/DebugUI.h>
  10. JPH_IMPLEMENT_RTTI_VIRTUAL(CharacterVirtualTest)
  11. {
  12. JPH_ADD_BASE_CLASS(CharacterVirtualTest, CharacterBaseTest)
  13. }
  14. static const Vec3 cStepUpHeight = Vec3(0.0f, 0.4f, 0.0f);
  15. static const float cMinStepForward = 0.02f;
  16. static const float cStepForwardTest = 0.15f;
  17. void CharacterVirtualTest::Initialize()
  18. {
  19. CharacterBaseTest::Initialize();
  20. // Create 'player' character
  21. Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
  22. settings->mMaxSlopeAngle = sMaxSlopeAngle;
  23. settings->mMaxStrength = sMaxStrength;
  24. settings->mShape = mStandingShape;
  25. settings->mCharacterPadding = sCharacterPadding;
  26. settings->mPenetrationRecoverySpeed = sPenetrationRecoverySpeed;
  27. settings->mPredictiveContactDistance = sPredictiveContactDistance;
  28. mCharacter = new CharacterVirtual(settings, Vec3::sZero(), Quat::sIdentity(), mPhysicsSystem);
  29. mCharacter->SetListener(this);
  30. }
  31. void CharacterVirtualTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  32. {
  33. CharacterBaseTest::PrePhysicsUpdate(inParams);
  34. // Draw character pre update (the sim is also drawn pre update)
  35. Mat44 com = mCharacter->GetCenterOfMassTransform();
  36. if (mCharacter->GetShape() == mStandingShape)
  37. {
  38. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightStanding, cCharacterRadiusStanding, Color::sGreen, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  39. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightStanding, cCharacterRadiusStanding + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  40. }
  41. else
  42. {
  43. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching, Color::sGreen, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  44. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  45. }
  46. // Remember old position
  47. Vec3 old_position = mCharacter->GetPosition();
  48. // Track that on ground before the update
  49. bool ground_to_air = mCharacter->GetGroundState() != CharacterBase::EGroundState::InAir;
  50. // Update the character position (instant, do not have to wait for physics update)
  51. mCharacter->Update(inParams.mDeltaTime, mPhysicsSystem->GetGravity(), mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  52. // ... and that we got into air after
  53. if (mCharacter->GetGroundState() != CharacterBase::EGroundState::InAir)
  54. ground_to_air = false;
  55. // Allow user to turn off walk stairs algorithm
  56. if (sEnableWalkStairs)
  57. {
  58. // Calculate how much we wanted to move horizontally
  59. Vec3 desired_horizontal_step = mDesiredVelocity * inParams.mDeltaTime;
  60. float desired_horizontal_step_len = desired_horizontal_step.Length();
  61. if (desired_horizontal_step_len > 0.0f)
  62. {
  63. // Calculate how much we moved horizontally
  64. Vec3 achieved_horizontal_step = mCharacter->GetPosition() - old_position;
  65. achieved_horizontal_step.SetY(0);
  66. // Only count movement in the direction of the desired movement
  67. // (otherwise we find it ok if we're sliding downhill while we're trying to climb uphill)
  68. Vec3 step_forward_normalized = desired_horizontal_step / desired_horizontal_step_len;
  69. achieved_horizontal_step = max(0.0f, achieved_horizontal_step.Dot(step_forward_normalized)) * step_forward_normalized;
  70. float achieved_horizontal_step_len = achieved_horizontal_step.Length();
  71. // If we didn't move as far as we wanted and we're against a slope that's too steep
  72. if (achieved_horizontal_step_len + 1.0e-4f < desired_horizontal_step_len
  73. && mCharacter->CanWalkStairs(mDesiredVelocity))
  74. {
  75. // CanWalkStairs should not have returned true if we are in air
  76. JPH_ASSERT(!ground_to_air);
  77. // Calculate how much we should step forward
  78. // Note that we clamp the step forward to a minimum distance. This is done because at very high frame rates the delta time
  79. // may be very small, causing a very small step forward. If the step becomes small enough, we may not move far enough
  80. // horizontally to actually end up at the top of the step.
  81. Vec3 step_forward = step_forward_normalized * max(cMinStepForward, desired_horizontal_step_len - achieved_horizontal_step_len);
  82. // Calculate how far to scan ahead for a floor. This is only used in case the floor normal at step_forward is too steep.
  83. // In that case an additional check will be performed at this distance to check if that normal is not too steep.
  84. Vec3 step_forward_test = step_forward_normalized * cStepForwardTest;
  85. mCharacter->WalkStairs(inParams.mDeltaTime, mPhysicsSystem->GetGravity(), cStepUpHeight, step_forward, step_forward_test, Vec3::sZero(), mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  86. }
  87. }
  88. }
  89. // Calculate effective velocity
  90. Vec3 new_position = mCharacter->GetPosition();
  91. Vec3 velocity = (new_position - old_position) / inParams.mDeltaTime;
  92. if (sEnableStickToFloor)
  93. {
  94. // If we're in air for the first frame and we're not moving up, stick to the floor
  95. if (ground_to_air && velocity.GetY() <= 1.0e-6f)
  96. mCharacter->StickToFloor(Vec3(0, -0.5f, 0), mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  97. }
  98. // Draw state of character
  99. DrawCharacterState(mCharacter, mCharacter->GetWorldTransform(), velocity);
  100. // Draw labels on ramp blocks
  101. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  102. mDebugRenderer->DrawText3D(mBodyInterface->GetPosition(mRampBlocks[i]), StringFormat("PushesPlayer: %s\nPushable: %s", (i & 1) != 0? "True" : "False", (i & 2) != 0? "True" : "False"), Color::sWhite, 0.25f);
  103. }
  104. void CharacterVirtualTest::HandleInput(Vec3Arg inMovementDirection, bool inJump, bool inSwitchStance, float inDeltaTime)
  105. {
  106. // Smooth the player input
  107. mDesiredVelocity = 0.25f * inMovementDirection * cCharacterSpeed + 0.75f * mDesiredVelocity;
  108. // True if the player intended to move
  109. mAllowSliding = !inMovementDirection.IsNearZero();
  110. // Cancel movement in opposite direction of normal when sliding
  111. CharacterVirtual::EGroundState ground_state = mCharacter->GetGroundState();
  112. Vec3 desired_velocity = mDesiredVelocity;
  113. if (ground_state == CharacterVirtual::EGroundState::OnSteepGround)
  114. {
  115. Vec3 normal = mCharacter->GetGroundNormal();
  116. normal.SetY(0.0f);
  117. float dot = normal.Dot(desired_velocity);
  118. if (dot < 0.0f)
  119. desired_velocity -= (dot * normal) / normal.LengthSq();
  120. }
  121. Vec3 current_vertical_velocity = Vec3(0, mCharacter->GetLinearVelocity().GetY(), 0);
  122. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  123. Vec3 new_velocity;
  124. if (ground_state == CharacterVirtual::EGroundState::OnGround // If on ground
  125. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  126. {
  127. // Assume velocity of ground when on ground
  128. new_velocity = ground_velocity;
  129. // Jump
  130. if (inJump)
  131. new_velocity += Vec3(0, cJumpSpeed, 0);
  132. }
  133. else
  134. new_velocity = current_vertical_velocity;
  135. // Gravity
  136. new_velocity += mPhysicsSystem->GetGravity() * inDeltaTime;
  137. // Player input
  138. new_velocity += desired_velocity;
  139. // Update the velocity
  140. mCharacter->SetLinearVelocity(new_velocity);
  141. // Stance switch
  142. if (inSwitchStance)
  143. mCharacter->SetShape(mCharacter->GetShape() == mStandingShape? mCrouchingShape : mStandingShape, 1.5f * mPhysicsSystem->GetPhysicsSettings().mPenetrationSlop, mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  144. }
  145. void CharacterVirtualTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  146. {
  147. CharacterBaseTest::CreateSettingsMenu(inUI, inSubMenu);
  148. inUI->CreateTextButton(inSubMenu, "Configuration Settings", [=]() {
  149. UIElement *configuration_settings = inUI->CreateMenu();
  150. inUI->CreateSlider(configuration_settings, "Max Slope Angle (degrees)", RadiansToDegrees(sMaxSlopeAngle), 0.0f, 90.0f, 1.0f, [](float inValue) { sMaxSlopeAngle = DegreesToRadians(inValue); });
  151. inUI->CreateSlider(configuration_settings, "Max Strength (N)", sMaxStrength, 0.0f, 500.0f, 1.0f, [](float inValue) { sMaxStrength = inValue; });
  152. inUI->CreateSlider(configuration_settings, "Character Padding", sCharacterPadding, 0.01f, 0.5f, 0.01f, [](float inValue) { sCharacterPadding = inValue; });
  153. inUI->CreateSlider(configuration_settings, "Penetration Recovery Speed", sPenetrationRecoverySpeed, 0.0f, 1.0f, 0.05f, [](float inValue) { sPenetrationRecoverySpeed = inValue; });
  154. inUI->CreateSlider(configuration_settings, "Predictive Contact Distance", sPredictiveContactDistance, 0.01f, 1.0f, 0.01f, [](float inValue) { sPredictiveContactDistance = inValue; });
  155. inUI->CreateCheckBox(configuration_settings, "Enable Walk Stairs", sEnableWalkStairs, [](UICheckBox::EState inState) { sEnableWalkStairs = inState == UICheckBox::STATE_CHECKED; });
  156. inUI->CreateCheckBox(configuration_settings, "Enable Stick To Floor", sEnableStickToFloor, [](UICheckBox::EState inState) { sEnableStickToFloor = inState == UICheckBox::STATE_CHECKED; });
  157. inUI->CreateTextButton(configuration_settings, "Accept Changes", [=]() { RestartTest(); });
  158. inUI->ShowMenu(configuration_settings);
  159. });
  160. }
  161. void CharacterVirtualTest::SaveState(StateRecorder &inStream) const
  162. {
  163. CharacterBaseTest::SaveState(inStream);
  164. mCharacter->SaveState(inStream);
  165. bool is_standing = mCharacter->GetShape() == mStandingShape;
  166. inStream.Write(is_standing);
  167. inStream.Write(mDesiredVelocity);
  168. }
  169. void CharacterVirtualTest::RestoreState(StateRecorder &inStream)
  170. {
  171. CharacterBaseTest::RestoreState(inStream);
  172. mCharacter->RestoreState(inStream);
  173. bool is_standing = mCharacter->GetShape() == mStandingShape; // Initialize variable for validation mode
  174. inStream.Read(is_standing);
  175. mCharacter->SetShape(is_standing? mStandingShape : mCrouchingShape, FLT_MAX, { }, { }, { }, *mTempAllocator);
  176. inStream.Read(mDesiredVelocity);
  177. }
  178. void CharacterVirtualTest::OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, Vec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  179. {
  180. // Dynamic boxes on the ramp go through all permutations
  181. Array<BodyID>::const_iterator i = find(mRampBlocks.begin(), mRampBlocks.end(), inBodyID2);
  182. if (i != mRampBlocks.end())
  183. {
  184. size_t index = i - mRampBlocks.begin();
  185. ioSettings.mCanPushCharacter = (index & 1) != 0;
  186. ioSettings.mCanReceiveImpulses = (index & 2) != 0;
  187. }
  188. // If we encounter an object that can push us, enable sliding
  189. if (ioSettings.mCanPushCharacter && mPhysicsSystem->GetBodyInterface().GetMotionType(inBodyID2) != EMotionType::Static)
  190. mAllowSliding = true;
  191. }
  192. void CharacterVirtualTest::OnContactSolve(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, Vec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity)
  193. {
  194. // Don't allow the player to slide down static not-too-steep surfaces when not actively moving and when not on a moving platform
  195. if (!mAllowSliding && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  196. ioNewCharacterVelocity = Vec3::sZero();
  197. }