CharacterVirtualTest.cpp 14 KB

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