CharacterVirtualTest.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/Character/CharacterVirtualTest.h>
  6. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  7. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  8. #include <Layers.h>
  9. #include <Renderer/DebugRendererImp.h>
  10. #include <Application/DebugUI.h>
  11. JPH_IMPLEMENT_RTTI_VIRTUAL(CharacterVirtualTest)
  12. {
  13. JPH_ADD_BASE_CLASS(CharacterVirtualTest, CharacterBaseTest)
  14. }
  15. void CharacterVirtualTest::Initialize()
  16. {
  17. CharacterBaseTest::Initialize();
  18. // Create 'player' character
  19. Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
  20. settings->mMaxSlopeAngle = sMaxSlopeAngle;
  21. settings->mMaxStrength = sMaxStrength;
  22. settings->mShape = mStandingShape;
  23. settings->mBackFaceMode = sBackFaceMode;
  24. settings->mCharacterPadding = sCharacterPadding;
  25. settings->mPenetrationRecoverySpeed = sPenetrationRecoverySpeed;
  26. settings->mPredictiveContactDistance = sPredictiveContactDistance;
  27. settings->mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  28. mCharacter = new CharacterVirtual(settings, RVec3::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. RMat44 com = mCharacter->GetCenterOfMassTransform();
  36. RMat44 world_transform = mCharacter->GetWorldTransform();
  37. #ifdef JPH_DEBUG_RENDERER
  38. mCharacter->GetShape()->Draw(mDebugRenderer, com, Vec3::sReplicate(1.0f), Color::sGreen, false, true);
  39. #endif // JPH_DEBUG_RENDERER
  40. // Draw shape including padding (only implemented for capsules right now)
  41. if (static_cast<const RotatedTranslatedShape *>(mCharacter->GetShape())->GetInnerShape()->GetSubType() == EShapeSubType::Capsule)
  42. {
  43. if (mCharacter->GetShape() == mStandingShape)
  44. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightStanding, cCharacterRadiusStanding + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  45. else
  46. mDebugRenderer->DrawCapsule(com, 0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching + mCharacter->GetCharacterPadding(), Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  47. }
  48. // Remember old position
  49. RVec3 old_position = mCharacter->GetPosition();
  50. // Settings for our update function
  51. CharacterVirtual::ExtendedUpdateSettings update_settings;
  52. if (!sEnableStickToFloor)
  53. update_settings.mStickToFloorStepDown = Vec3::sZero();
  54. else
  55. update_settings.mStickToFloorStepDown = -mCharacter->GetUp() * update_settings.mStickToFloorStepDown.Length();
  56. if (!sEnableWalkStairs)
  57. update_settings.mWalkStairsStepUp = Vec3::sZero();
  58. else
  59. update_settings.mWalkStairsStepUp = mCharacter->GetUp() * update_settings.mWalkStairsStepUp.Length();
  60. // Update the character position
  61. mCharacter->ExtendedUpdate(inParams.mDeltaTime,
  62. -mCharacter->GetUp() * mPhysicsSystem->GetGravity().Length(),
  63. update_settings,
  64. mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  65. mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING),
  66. { },
  67. { },
  68. *mTempAllocator);
  69. // Calculate effective velocity
  70. RVec3 new_position = mCharacter->GetPosition();
  71. Vec3 velocity = Vec3(new_position - old_position) / inParams.mDeltaTime;
  72. // Draw state of character
  73. DrawCharacterState(mCharacter, world_transform, velocity);
  74. // Draw labels on ramp blocks
  75. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  76. 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);
  77. }
  78. void CharacterVirtualTest::HandleInput(Vec3Arg inMovementDirection, bool inJump, bool inSwitchStance, float inDeltaTime)
  79. {
  80. bool player_controls_horizontal_velocity = sControlMovementDuringJump || mCharacter->IsSupported();
  81. if (player_controls_horizontal_velocity)
  82. {
  83. // Smooth the player input
  84. mDesiredVelocity = sEnableCharacterInertia? 0.25f * inMovementDirection * sCharacterSpeed + 0.75f * mDesiredVelocity : inMovementDirection * sCharacterSpeed;
  85. // True if the player intended to move
  86. mAllowSliding = !inMovementDirection.IsNearZero();
  87. }
  88. else
  89. {
  90. // While in air we allow sliding
  91. mAllowSliding = true;
  92. }
  93. // Update the character rotation and its up vector to match the up vector set by the user settings
  94. Quat character_up_rotation = Quat::sEulerAngles(Vec3(sUpRotationX, 0, sUpRotationZ));
  95. mCharacter->SetUp(character_up_rotation.RotateAxisY());
  96. mCharacter->SetRotation(character_up_rotation);
  97. // A cheaper way to update the character's ground velocity,
  98. // the platforms that the character is standing on may have changed velocity
  99. mCharacter->UpdateGroundVelocity();
  100. // Determine new basic velocity
  101. Vec3 current_vertical_velocity = mCharacter->GetLinearVelocity().Dot(mCharacter->GetUp()) * mCharacter->GetUp();
  102. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  103. Vec3 new_velocity;
  104. bool moving_towards_ground = (current_vertical_velocity.GetY() - ground_velocity.GetY()) < 0.1f;
  105. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  106. && (sEnableCharacterInertia?
  107. moving_towards_ground // Inertia enabled: And not moving away from ground
  108. : !mCharacter->IsSlopeTooSteep(mCharacter->GetGroundNormal()))) // Inertia disabled: And not on a slope that is too steep
  109. {
  110. // Assume velocity of ground when on ground
  111. new_velocity = ground_velocity;
  112. // Jump
  113. if (inJump && moving_towards_ground)
  114. new_velocity += sJumpSpeed * mCharacter->GetUp();
  115. }
  116. else
  117. new_velocity = current_vertical_velocity;
  118. // Gravity
  119. new_velocity += (character_up_rotation * mPhysicsSystem->GetGravity()) * inDeltaTime;
  120. if (player_controls_horizontal_velocity)
  121. {
  122. // Player input
  123. new_velocity += character_up_rotation * mDesiredVelocity;
  124. }
  125. else
  126. {
  127. // Preserve horizontal velocity
  128. Vec3 current_horizontal_velocity = mCharacter->GetLinearVelocity() - current_vertical_velocity;
  129. new_velocity += current_horizontal_velocity;
  130. }
  131. // Update character velocity
  132. mCharacter->SetLinearVelocity(new_velocity);
  133. // Stance switch
  134. if (inSwitchStance)
  135. mCharacter->SetShape(mCharacter->GetShape() == mStandingShape? mCrouchingShape : mStandingShape, 1.5f * mPhysicsSystem->GetPhysicsSettings().mPenetrationSlop, mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING), mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING), { }, { }, *mTempAllocator);
  136. }
  137. void CharacterVirtualTest::AddCharacterMovementSettings(DebugUI* inUI, UIElement* inSubMenu)
  138. {
  139. inUI->CreateCheckBox(inSubMenu, "Enable Character Inertia", sEnableCharacterInertia, [](UICheckBox::EState inState) { sEnableCharacterInertia = inState == UICheckBox::STATE_CHECKED; });
  140. }
  141. void CharacterVirtualTest::AddConfigurationSettings(DebugUI *inUI, UIElement *inSubMenu)
  142. {
  143. inUI->CreateComboBox(inSubMenu, "Back Face Mode", { "Ignore", "Collide" }, (int)sBackFaceMode, [=](int inItem) { sBackFaceMode = (EBackFaceMode)inItem; });
  144. inUI->CreateSlider(inSubMenu, "Up Rotation X (degrees)", RadiansToDegrees(sUpRotationX), -90.0f, 90.0f, 1.0f, [](float inValue) { sUpRotationX = DegreesToRadians(inValue); });
  145. inUI->CreateSlider(inSubMenu, "Up Rotation Z (degrees)", RadiansToDegrees(sUpRotationZ), -90.0f, 90.0f, 1.0f, [](float inValue) { sUpRotationZ = DegreesToRadians(inValue); });
  146. inUI->CreateSlider(inSubMenu, "Max Slope Angle (degrees)", RadiansToDegrees(sMaxSlopeAngle), 0.0f, 90.0f, 1.0f, [](float inValue) { sMaxSlopeAngle = DegreesToRadians(inValue); });
  147. inUI->CreateSlider(inSubMenu, "Max Strength (N)", sMaxStrength, 0.0f, 500.0f, 1.0f, [](float inValue) { sMaxStrength = inValue; });
  148. inUI->CreateSlider(inSubMenu, "Character Padding", sCharacterPadding, 0.01f, 0.5f, 0.01f, [](float inValue) { sCharacterPadding = inValue; });
  149. inUI->CreateSlider(inSubMenu, "Penetration Recovery Speed", sPenetrationRecoverySpeed, 0.0f, 1.0f, 0.05f, [](float inValue) { sPenetrationRecoverySpeed = inValue; });
  150. inUI->CreateSlider(inSubMenu, "Predictive Contact Distance", sPredictiveContactDistance, 0.01f, 1.0f, 0.01f, [](float inValue) { sPredictiveContactDistance = inValue; });
  151. inUI->CreateCheckBox(inSubMenu, "Enable Walk Stairs", sEnableWalkStairs, [](UICheckBox::EState inState) { sEnableWalkStairs = inState == UICheckBox::STATE_CHECKED; });
  152. inUI->CreateCheckBox(inSubMenu, "Enable Stick To Floor", sEnableStickToFloor, [](UICheckBox::EState inState) { sEnableStickToFloor = inState == UICheckBox::STATE_CHECKED; });
  153. }
  154. void CharacterVirtualTest::SaveState(StateRecorder &inStream) const
  155. {
  156. CharacterBaseTest::SaveState(inStream);
  157. mCharacter->SaveState(inStream);
  158. bool is_standing = mCharacter->GetShape() == mStandingShape;
  159. inStream.Write(is_standing);
  160. inStream.Write(mAllowSliding);
  161. inStream.Write(mDesiredVelocity);
  162. }
  163. void CharacterVirtualTest::RestoreState(StateRecorder &inStream)
  164. {
  165. CharacterBaseTest::RestoreState(inStream);
  166. mCharacter->RestoreState(inStream);
  167. bool is_standing = mCharacter->GetShape() == mStandingShape; // Initialize variable for validation mode
  168. inStream.Read(is_standing);
  169. mCharacter->SetShape(is_standing? mStandingShape : mCrouchingShape, FLT_MAX, { }, { }, { }, { }, *mTempAllocator);
  170. inStream.Read(mAllowSliding);
  171. inStream.Read(mDesiredVelocity);
  172. }
  173. void CharacterVirtualTest::OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity)
  174. {
  175. // Apply artificial velocity to the character when standing on the conveyor belt
  176. if (inBody2.GetID() == mConveyorBeltBody)
  177. ioLinearVelocity += Vec3(0, 0, 2);
  178. }
  179. void CharacterVirtualTest::OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  180. {
  181. // Dynamic boxes on the ramp go through all permutations
  182. Array<BodyID>::const_iterator i = find(mRampBlocks.begin(), mRampBlocks.end(), inBodyID2);
  183. if (i != mRampBlocks.end())
  184. {
  185. size_t index = i - mRampBlocks.begin();
  186. ioSettings.mCanPushCharacter = (index & 1) != 0;
  187. ioSettings.mCanReceiveImpulses = (index & 2) != 0;
  188. }
  189. // If we encounter an object that can push us, enable sliding
  190. if (ioSettings.mCanPushCharacter && mPhysicsSystem->GetBodyInterface().GetMotionType(inBodyID2) != EMotionType::Static)
  191. mAllowSliding = true;
  192. }
  193. 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)
  194. {
  195. // Don't allow the player to slide down static not-too-steep surfaces when not actively moving and when not on a moving platform
  196. if (!mAllowSliding && inContactVelocity.IsNearZero() && !inCharacter->IsSlopeTooSteep(inContactNormal))
  197. ioNewCharacterVelocity = Vec3::sZero();
  198. }