CharacterVirtualTest.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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, RVec3::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. RMat44 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. RVec3 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. else
  52. update_settings.mStickToFloorStepDown = -mCharacter->GetUp() * update_settings.mStickToFloorStepDown.Length();
  53. if (!sEnableWalkStairs)
  54. update_settings.mWalkStairsStepUp = Vec3::sZero();
  55. else
  56. update_settings.mWalkStairsStepUp = mCharacter->GetUp() * update_settings.mWalkStairsStepUp.Length();
  57. // Update the character position
  58. mCharacter->ExtendedUpdate(inParams.mDeltaTime,
  59. -mCharacter->GetUp() * mPhysicsSystem->GetGravity().Length(),
  60. update_settings,
  61. mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  62. mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING),
  63. { },
  64. { },
  65. *mTempAllocator);
  66. // Calculate effective velocity
  67. RVec3 new_position = mCharacter->GetPosition();
  68. Vec3 velocity = Vec3(new_position - old_position) / inParams.mDeltaTime;
  69. // Draw state of character
  70. DrawCharacterState(mCharacter, mCharacter->GetWorldTransform(), velocity);
  71. // Draw labels on ramp blocks
  72. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  73. 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);
  74. }
  75. void CharacterVirtualTest::HandleInput(Vec3Arg inMovementDirection, bool inJump, bool inSwitchStance, float inDeltaTime)
  76. {
  77. // Smooth the player input
  78. mDesiredVelocity = 0.25f * inMovementDirection * cCharacterSpeed + 0.75f * mDesiredVelocity;
  79. // True if the player intended to move
  80. mAllowSliding = !inMovementDirection.IsNearZero();
  81. // Update the character rotation and its up vector to match the up vector set by the user settings
  82. Quat character_up_rotation = Quat::sEulerAngles(Vec3(sUpRotationX, 0, sUpRotationZ));
  83. mCharacter->SetUp(character_up_rotation.RotateAxisY());
  84. mCharacter->SetRotation(character_up_rotation);
  85. // Determine new basic velocity
  86. Vec3 current_vertical_velocity = mCharacter->GetLinearVelocity().Dot(mCharacter->GetUp()) * mCharacter->GetUp();
  87. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  88. Vec3 new_velocity;
  89. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  90. && (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f) // And not moving away from ground
  91. {
  92. // Assume velocity of ground when on ground
  93. new_velocity = ground_velocity;
  94. // Jump
  95. if (inJump)
  96. new_velocity += cJumpSpeed * mCharacter->GetUp();
  97. }
  98. else
  99. new_velocity = current_vertical_velocity;
  100. // Gravity
  101. new_velocity += (character_up_rotation * mPhysicsSystem->GetGravity()) * inDeltaTime;
  102. // Player input
  103. new_velocity += character_up_rotation * mDesiredVelocity;
  104. // Update character velocity
  105. mCharacter->SetLinearVelocity(new_velocity);
  106. // Stance switch
  107. if (inSwitchStance)
  108. mCharacter->SetShape(mCharacter->GetShape() == mStandingShape? mCrouchingShape : mStandingShape, 1.5f * mPhysicsSystem->GetPhysicsSettings().mPenetrationSlop, mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, { }, *mTempAllocator);
  109. }
  110. void CharacterVirtualTest::AddConfigurationSettings(DebugUI *inUI, UIElement *inSubMenu)
  111. {
  112. inUI->CreateSlider(inSubMenu, "Up Rotation X (degrees)", RadiansToDegrees(sUpRotationX), -90.0f, 90.0f, 1.0f, [](float inValue) { sUpRotationX = DegreesToRadians(inValue); });
  113. inUI->CreateSlider(inSubMenu, "Up Rotation Z (degrees)", RadiansToDegrees(sUpRotationZ), -90.0f, 90.0f, 1.0f, [](float inValue) { sUpRotationZ = DegreesToRadians(inValue); });
  114. inUI->CreateSlider(inSubMenu, "Max Slope Angle (degrees)", RadiansToDegrees(sMaxSlopeAngle), 0.0f, 90.0f, 1.0f, [](float inValue) { sMaxSlopeAngle = DegreesToRadians(inValue); });
  115. inUI->CreateSlider(inSubMenu, "Max Strength (N)", sMaxStrength, 0.0f, 500.0f, 1.0f, [](float inValue) { sMaxStrength = inValue; });
  116. inUI->CreateSlider(inSubMenu, "Character Padding", sCharacterPadding, 0.01f, 0.5f, 0.01f, [](float inValue) { sCharacterPadding = inValue; });
  117. inUI->CreateSlider(inSubMenu, "Penetration Recovery Speed", sPenetrationRecoverySpeed, 0.0f, 1.0f, 0.05f, [](float inValue) { sPenetrationRecoverySpeed = inValue; });
  118. inUI->CreateSlider(inSubMenu, "Predictive Contact Distance", sPredictiveContactDistance, 0.01f, 1.0f, 0.01f, [](float inValue) { sPredictiveContactDistance = inValue; });
  119. inUI->CreateCheckBox(inSubMenu, "Enable Walk Stairs", sEnableWalkStairs, [](UICheckBox::EState inState) { sEnableWalkStairs = inState == UICheckBox::STATE_CHECKED; });
  120. inUI->CreateCheckBox(inSubMenu, "Enable Stick To Floor", sEnableStickToFloor, [](UICheckBox::EState inState) { sEnableStickToFloor = inState == UICheckBox::STATE_CHECKED; });
  121. }
  122. void CharacterVirtualTest::SaveState(StateRecorder &inStream) const
  123. {
  124. CharacterBaseTest::SaveState(inStream);
  125. mCharacter->SaveState(inStream);
  126. bool is_standing = mCharacter->GetShape() == mStandingShape;
  127. inStream.Write(is_standing);
  128. inStream.Write(mAllowSliding);
  129. inStream.Write(mDesiredVelocity);
  130. }
  131. void CharacterVirtualTest::RestoreState(StateRecorder &inStream)
  132. {
  133. CharacterBaseTest::RestoreState(inStream);
  134. mCharacter->RestoreState(inStream);
  135. bool is_standing = mCharacter->GetShape() == mStandingShape; // Initialize variable for validation mode
  136. inStream.Read(is_standing);
  137. mCharacter->SetShape(is_standing? mStandingShape : mCrouchingShape, FLT_MAX, { }, { }, { }, { }, *mTempAllocator);
  138. inStream.Read(mAllowSliding);
  139. inStream.Read(mDesiredVelocity);
  140. }
  141. void CharacterVirtualTest::OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity)
  142. {
  143. // Apply artificial velocity to the character when standing on the conveyor belt
  144. if (inBody2.GetID() == mConveyorBeltBody)
  145. ioLinearVelocity += Vec3(0, 0, 2);
  146. }
  147. void CharacterVirtualTest::OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  148. {
  149. // Dynamic boxes on the ramp go through all permutations
  150. Array<BodyID>::const_iterator i = find(mRampBlocks.begin(), mRampBlocks.end(), inBodyID2);
  151. if (i != mRampBlocks.end())
  152. {
  153. size_t index = i - mRampBlocks.begin();
  154. ioSettings.mCanPushCharacter = (index & 1) != 0;
  155. ioSettings.mCanReceiveImpulses = (index & 2) != 0;
  156. }
  157. // If we encounter an object that can push us, enable sliding
  158. if (ioSettings.mCanPushCharacter && mPhysicsSystem->GetBodyInterface().GetMotionType(inBodyID2) != EMotionType::Static)
  159. mAllowSliding = true;
  160. }
  161. void CharacterVirtualTest::OnContactSolve(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity)
  162. {
  163. // Don't allow the player to slide down static not-too-steep surfaces when not actively moving and when not on a moving platform
  164. if (!mAllowSliding && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  165. ioNewCharacterVelocity = Vec3::sZero();
  166. }