CharacterVirtualTest.cpp 11 KB

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