CharacterVirtualTest.cpp 10 KB

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