CharacterPlanetTest.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2024 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/Character/CharacterPlanetTest.h>
  6. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  7. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  8. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  9. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  10. #include <Layers.h>
  11. JPH_IMPLEMENT_RTTI_VIRTUAL(CharacterPlanetTest)
  12. {
  13. JPH_ADD_BASE_CLASS(CharacterPlanetTest, Test)
  14. }
  15. void CharacterPlanetTest::Initialize()
  16. {
  17. // Create planet
  18. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new SphereShape(cPlanetRadius), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  19. // Create spheres
  20. BodyCreationSettings sphere(new SphereShape(0.5f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  21. sphere.mGravityFactor = 0.0f; // We do our own gravity
  22. sphere.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  23. sphere.mMassPropertiesOverride.mMass = 10.0f;
  24. sphere.mAngularDamping = 0.5f;
  25. default_random_engine random;
  26. for (int i = 0; i < 200; ++i)
  27. {
  28. uniform_real_distribution<float> theta(0, JPH_PI);
  29. uniform_real_distribution<float> phi(0, 2 * JPH_PI);
  30. sphere.mPosition = RVec3(1.1f * cPlanetRadius * Vec3::sUnitSpherical(theta(random), phi(random)));
  31. mBodyInterface->CreateAndAddBody(sphere, EActivation::Activate);
  32. }
  33. // Register to receive OnStep callbacks to apply gravity
  34. mPhysicsSystem->AddStepListener(this);
  35. // Create 'player' character
  36. Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
  37. settings->mShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding)).Create().Get();
  38. settings->mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  39. mCharacter = new CharacterVirtual(settings, RVec3(0, cPlanetRadius, 0), Quat::sIdentity(), 0, mPhysicsSystem);
  40. mCharacter->SetListener(this);
  41. }
  42. void CharacterPlanetTest::ProcessInput(const ProcessInputParams &inParams)
  43. {
  44. // Determine controller input
  45. Vec3 control_input = Vec3::sZero();
  46. if (inParams.mKeyboard->IsKeyPressed(EKey::Left)) control_input.SetZ(-1);
  47. if (inParams.mKeyboard->IsKeyPressed(EKey::Right)) control_input.SetZ(1);
  48. if (inParams.mKeyboard->IsKeyPressed(EKey::Up)) control_input.SetX(1);
  49. if (inParams.mKeyboard->IsKeyPressed(EKey::Down)) control_input.SetX(-1);
  50. if (control_input != Vec3::sZero())
  51. control_input = control_input.Normalized();
  52. // Smooth the player input
  53. mDesiredVelocity = 0.25f * control_input * cCharacterSpeed + 0.75f * mDesiredVelocity;
  54. // Convert player input to world space
  55. Vec3 up = mCharacter->GetUp();
  56. Vec3 right = inParams.mCameraState.mForward.Cross(up).NormalizedOr(Vec3::sAxisZ());
  57. Vec3 forward = up.Cross(right).NormalizedOr(Vec3::sAxisX());
  58. mDesiredVelocityWS = right * mDesiredVelocity.GetZ() + forward * mDesiredVelocity.GetX();
  59. // Check actions
  60. mJump = inParams.mKeyboard->IsKeyPressedAndTriggered(EKey::RControl, mWasJump);
  61. }
  62. void CharacterPlanetTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  63. {
  64. // Calculate up vector based on position on planet surface
  65. Vec3 old_up = mCharacter->GetUp();
  66. Vec3 up = Vec3(mCharacter->GetPosition()).Normalized();
  67. mCharacter->SetUp(up);
  68. // Rotate capsule so it points up relative to the planet surface
  69. mCharacter->SetRotation((Quat::sFromTo(old_up, up) * mCharacter->GetRotation()).Normalized());
  70. // Draw character pre update (the sim is also drawn pre update)
  71. #ifdef JPH_DEBUG_RENDERER
  72. mCharacter->GetShape()->Draw(mDebugRenderer, mCharacter->GetCenterOfMassTransform(), Vec3::sOne(), Color::sGreen, false, true);
  73. #endif // JPH_DEBUG_RENDERER
  74. // Determine new character velocity
  75. Vec3 current_vertical_velocity = mCharacter->GetLinearVelocity().Dot(up) * up;
  76. Vec3 ground_velocity = mCharacter->GetGroundVelocity();
  77. Vec3 new_velocity;
  78. if (mCharacter->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
  79. && (current_vertical_velocity - ground_velocity).Dot(up) < 0.1f) // And not moving away from ground
  80. {
  81. // Assume velocity of ground when on ground
  82. new_velocity = ground_velocity;
  83. // Jump
  84. if (mJump)
  85. new_velocity += cJumpSpeed * up;
  86. }
  87. else
  88. new_velocity = current_vertical_velocity;
  89. // Apply gravity
  90. Vec3 gravity = -up * mPhysicsSystem->GetGravity().Length();
  91. new_velocity += gravity * inParams.mDeltaTime;
  92. // Apply player input
  93. new_velocity += mDesiredVelocityWS;
  94. // Update character velocity
  95. mCharacter->SetLinearVelocity(new_velocity);
  96. // Update the character position
  97. CharacterVirtual::ExtendedUpdateSettings update_settings;
  98. mCharacter->ExtendedUpdate(inParams.mDeltaTime,
  99. gravity,
  100. update_settings,
  101. mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  102. mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING),
  103. { },
  104. { },
  105. *mTempAllocator);
  106. }
  107. void CharacterPlanetTest::GetInitialCamera(CameraState& ioState) const
  108. {
  109. ioState.mPos = RVec3(0, 0.5f, 0);
  110. ioState.mForward = Vec3(1, -0.3f, 0).Normalized();
  111. }
  112. RMat44 CharacterPlanetTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  113. {
  114. // Pivot is center of character + distance behind based on the heading and pitch of the camera.
  115. Vec3 fwd = Vec3(Cos(inCameraPitch) * Cos(inCameraHeading), Sin(inCameraPitch), Cos(inCameraPitch) * Sin(inCameraHeading));
  116. RVec3 cam_pos = mCharacter->GetPosition() - 5.0f * (mCharacter->GetRotation() * fwd);
  117. return RMat44::sRotationTranslation(mCharacter->GetRotation(), cam_pos);
  118. }
  119. void CharacterPlanetTest::SaveState(StateRecorder &inStream) const
  120. {
  121. mCharacter->SaveState(inStream);
  122. // Save character up, it's not stored by default but we use it in this case update the rotation of the character
  123. inStream.Write(mCharacter->GetUp());
  124. }
  125. void CharacterPlanetTest::RestoreState(StateRecorder &inStream)
  126. {
  127. mCharacter->RestoreState(inStream);
  128. Vec3 up = mCharacter->GetUp();
  129. inStream.Read(up);
  130. mCharacter->SetUp(up);
  131. }
  132. void CharacterPlanetTest::SaveInputState(StateRecorder &inStream) const
  133. {
  134. inStream.Write(mDesiredVelocity);
  135. inStream.Write(mDesiredVelocityWS);
  136. inStream.Write(mJump);
  137. }
  138. void CharacterPlanetTest::RestoreInputState(StateRecorder &inStream)
  139. {
  140. inStream.Read(mDesiredVelocity);
  141. inStream.Read(mDesiredVelocityWS);
  142. inStream.Read(mJump);
  143. }
  144. void CharacterPlanetTest::OnStep(const PhysicsStepListenerContext &inContext)
  145. {
  146. // Use the length of the global gravity vector
  147. float gravity = inContext.mPhysicsSystem->GetGravity().Length();
  148. // We don't need to lock the bodies since they're already locked in the OnStep callback.
  149. // Note that this means we're responsible for avoiding race conditions with other step listeners while accessing bodies.
  150. // We know that this is safe because in this demo there's only one step listener.
  151. const BodyLockInterface &body_interface = inContext.mPhysicsSystem->GetBodyLockInterfaceNoLock();
  152. // Loop over all active bodies
  153. BodyIDVector body_ids;
  154. inContext.mPhysicsSystem->GetActiveBodies(EBodyType::RigidBody, body_ids);
  155. for (const BodyID &id : body_ids)
  156. {
  157. BodyLockWrite lock(body_interface, id);
  158. if (lock.Succeeded())
  159. {
  160. // Apply gravity towards the center of the planet
  161. Body &body = lock.GetBody();
  162. RVec3 position = body.GetPosition();
  163. float mass = 1.0f / body.GetMotionProperties()->GetInverseMass();
  164. body.AddForce(-gravity * mass * Vec3(position).Normalized());
  165. }
  166. }
  167. }
  168. void CharacterPlanetTest::OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings)
  169. {
  170. // We don't want the spheres to push the player character
  171. ioSettings.mCanPushCharacter = false;
  172. }