CharacterVirtualTest.cpp 12 KB

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