CharacterVirtualTest.cpp 10 KB

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