CharacterVirtualTest.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. void CharacterVirtualTest::Initialize()
  15. {
  16. CharacterBaseTest::Initialize();
  17. // Create 'player' character
  18. Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
  19. settings->mMaxSlopeAngle = sMaxSlopeAngle;
  20. settings->mMaxStrength = sMaxStrength;
  21. settings->mShape = mStandingShape;
  22. settings->mCharacterPadding = sCharacterPadding;
  23. settings->mPenetrationRecoverySpeed = sPenetrationRecoverySpeed;
  24. settings->mPredictiveContactDistance = sPredictiveContactDistance;
  25. settings->mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  26. mCharacter = new CharacterVirtual(settings, Vec3::sZero(), Quat::sIdentity(), mPhysicsSystem);
  27. mCharacter->SetListener(this);
  28. }
  29. void CharacterVirtualTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  30. {
  31. CharacterBaseTest::PrePhysicsUpdate(inParams);
  32. // Draw character pre update (the sim is also drawn pre update)
  33. Mat44 com = mCharacter->GetCenterOfMassTransform();
  34. #ifdef JPH_DEBUG_RENDERER
  35. mCharacter->GetShape()->Draw(mDebugRenderer, com, Vec3::sReplicate(1.0f), Color::sGreen, false, true);
  36. #endif // JPH_DEBUG_RENDERER
  37. // Draw shape including padding (only implemented for capsules right now)
  38. if (static_cast<const RotatedTranslatedShape *>(mCharacter->GetShape())->GetInnerShape()->GetSubType() == EShapeSubType::Capsule)
  39. {
  40. if (mCharacter->GetShape() == mStandingShape)
  41. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightStanding, cCharacterRadiusStanding + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  42. else
  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. // Settings for our update function
  48. CharacterVirtual::ExtendedUpdateSettings update_settings;
  49. if (!sEnableStickToFloor)
  50. update_settings.mStickToFloorStepDown = Vec3::sZero();
  51. if (!sEnableWalkStairs)
  52. update_settings.mWalkStairsStepUp = Vec3::sZero();
  53. // Update the character position
  54. mCharacter->ExtendedUpdate(inParams.mDeltaTime,
  55. mPhysicsSystem->GetGravity(),
  56. update_settings,
  57. mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  58. mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING),
  59. { },
  60. *mTempAllocator);
  61. // Calculate effective velocity
  62. Vec3 new_position = mCharacter->GetPosition();
  63. Vec3 velocity = (new_position - old_position) / inParams.mDeltaTime;
  64. // Draw state of character
  65. DrawCharacterState(mCharacter, mCharacter->GetWorldTransform(), velocity);
  66. // Draw labels on ramp blocks
  67. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  68. 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);
  69. }
  70. void CharacterVirtualTest::HandleInput(Vec3Arg inMovementDirection, bool inJump, bool inSwitchStance, float inDeltaTime)
  71. {
  72. // Smooth the player input
  73. mDesiredVelocity = 0.25f * inMovementDirection * cCharacterSpeed + 0.75f * mDesiredVelocity;
  74. // True if the player intended to move
  75. mAllowSliding = !inMovementDirection.IsNearZero();
  76. // Determine new basic velocity
  77. Vec3 current_vertical_velocity = Vec3(0, mCharacter->GetLinearVelocity().GetY(), 0);
  78. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  79. Vec3 new_velocity;
  80. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  81. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  82. {
  83. // Assume velocity of ground when on ground
  84. new_velocity = ground_velocity;
  85. // Jump
  86. if (inJump)
  87. new_velocity += Vec3(0, cJumpSpeed, 0);
  88. }
  89. else
  90. new_velocity = current_vertical_velocity;
  91. // Gravity
  92. new_velocity += mPhysicsSystem->GetGravity() * inDeltaTime;
  93. // Player input
  94. new_velocity += mDesiredVelocity;
  95. // Update character velocity
  96. mCharacter->SetLinearVelocity(new_velocity);
  97. // Stance switch
  98. if (inSwitchStance)
  99. mCharacter->SetShape(mCharacter->GetShape() == mStandingShape? mCrouchingShape : mStandingShape, 1.5f * mPhysicsSystem->GetPhysicsSettings().mPenetrationSlop, mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, *mTempAllocator);
  100. }
  101. void CharacterVirtualTest::AddConfigurationSettings(DebugUI *inUI, UIElement *inSubMenu)
  102. {
  103. inUI->CreateSlider(inSubMenu, "Max Slope Angle (degrees)", RadiansToDegrees(sMaxSlopeAngle), 0.0f, 90.0f, 1.0f, [](float inValue) { sMaxSlopeAngle = DegreesToRadians(inValue); });
  104. inUI->CreateSlider(inSubMenu, "Max Strength (N)", sMaxStrength, 0.0f, 500.0f, 1.0f, [](float inValue) { sMaxStrength = inValue; });
  105. inUI->CreateSlider(inSubMenu, "Character Padding", sCharacterPadding, 0.01f, 0.5f, 0.01f, [](float inValue) { sCharacterPadding = inValue; });
  106. inUI->CreateSlider(inSubMenu, "Penetration Recovery Speed", sPenetrationRecoverySpeed, 0.0f, 1.0f, 0.05f, [](float inValue) { sPenetrationRecoverySpeed = inValue; });
  107. inUI->CreateSlider(inSubMenu, "Predictive Contact Distance", sPredictiveContactDistance, 0.01f, 1.0f, 0.01f, [](float inValue) { sPredictiveContactDistance = inValue; });
  108. inUI->CreateCheckBox(inSubMenu, "Enable Walk Stairs", sEnableWalkStairs, [](UICheckBox::EState inState) { sEnableWalkStairs = inState == UICheckBox::STATE_CHECKED; });
  109. inUI->CreateCheckBox(inSubMenu, "Enable Stick To Floor", sEnableStickToFloor, [](UICheckBox::EState inState) { sEnableStickToFloor = inState == UICheckBox::STATE_CHECKED; });
  110. }
  111. void CharacterVirtualTest::SaveState(StateRecorder &inStream) const
  112. {
  113. CharacterBaseTest::SaveState(inStream);
  114. mCharacter->SaveState(inStream);
  115. bool is_standing = mCharacter->GetShape() == mStandingShape;
  116. inStream.Write(is_standing);
  117. inStream.Write(mDesiredVelocity);
  118. }
  119. void CharacterVirtualTest::RestoreState(StateRecorder &inStream)
  120. {
  121. CharacterBaseTest::RestoreState(inStream);
  122. mCharacter->RestoreState(inStream);
  123. bool is_standing = mCharacter->GetShape() == mStandingShape; // Initialize variable for validation mode
  124. inStream.Read(is_standing);
  125. mCharacter->SetShape(is_standing? mStandingShape : mCrouchingShape, FLT_MAX, { }, { }, { }, *mTempAllocator);
  126. inStream.Read(mDesiredVelocity);
  127. }
  128. void CharacterVirtualTest::OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, Vec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  129. {
  130. // Dynamic boxes on the ramp go through all permutations
  131. Array<BodyID>::const_iterator i = find(mRampBlocks.begin(), mRampBlocks.end(), inBodyID2);
  132. if (i != mRampBlocks.end())
  133. {
  134. size_t index = i - mRampBlocks.begin();
  135. ioSettings.mCanPushCharacter = (index & 1) != 0;
  136. ioSettings.mCanReceiveImpulses = (index & 2) != 0;
  137. }
  138. // If we encounter an object that can push us, enable sliding
  139. if (ioSettings.mCanPushCharacter && mPhysicsSystem->GetBodyInterface().GetMotionType(inBodyID2) != EMotionType::Static)
  140. mAllowSliding = true;
  141. }
  142. 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)
  143. {
  144. // Don't allow the player to slide down static not-too-steep surfaces when not actively moving and when not on a moving platform
  145. if (!mAllowSliding && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  146. ioNewCharacterVelocity = Vec3::sZero();
  147. }