CharacterBaseTest.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Tests/Character/CharacterBaseTest.h>
  5. #include <Jolt/Physics/PhysicsScene.h>
  6. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  7. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  8. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  9. #include <Jolt/Core/StringTools.h>
  10. #include <Application/DebugUI.h>
  11. #include <Layers.h>
  12. #include <Utils/Log.h>
  13. #include <Renderer/DebugRendererImp.h>
  14. JPH_IMPLEMENT_RTTI_ABSTRACT(CharacterBaseTest)
  15. {
  16. JPH_ADD_BASE_CLASS(CharacterBaseTest, Test)
  17. }
  18. const char *CharacterBaseTest::sScenes[] =
  19. {
  20. "PerlinMesh",
  21. "PerlinHeightField",
  22. "ObstacleCourse",
  23. "Terrain1",
  24. "Terrain2",
  25. };
  26. const char *CharacterBaseTest::sSceneName = "ObstacleCourse";
  27. // Scene constants
  28. static const Vec3 cRotatingPosition(-5, 0.25f, 15);
  29. static const Quat cRotatingOrientation = Quat::sIdentity();
  30. static const Vec3 cVerticallyMovingPosition(0, 2.0f, 15);
  31. static const Quat cVerticallyMovingOrientation = Quat::sIdentity();
  32. static const Vec3 cHorizontallyMovingPosition(5, 1, 15);
  33. static const Quat cHorizontallyMovingOrientation = Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI);
  34. static const Vec3 cRampPosition(15, 2.2f, 15);
  35. static const Quat cRampOrientation = Quat::sRotation(Vec3::sAxisX(), -0.25f * JPH_PI);
  36. static const Vec3 cRampBlocksStart = cRampPosition + Vec3(-3.0f, 3.0f, 1.5f);
  37. static const Vec3 cRampBlocksDelta = Vec3(2.0f, 0, 0);
  38. static const float cRampBlocksTime = 5.0f;
  39. void CharacterBaseTest::Initialize()
  40. {
  41. if (strcmp(sSceneName, "PerlinMesh") == 0)
  42. {
  43. // Default terrain
  44. CreateMeshTerrain();
  45. }
  46. else if (strcmp(sSceneName, "PerlinHeightField") == 0)
  47. {
  48. // Default terrain
  49. CreateHeightFieldTerrain();
  50. }
  51. else if (strcmp(sSceneName, "ObstacleCourse") == 0)
  52. {
  53. // Default terrain
  54. CreateFloor();
  55. {
  56. // Create ramps with different inclinations
  57. Ref<Shape> ramp = RotatedTranslatedShapeSettings(Vec3(0, 0, -2.5f), Quat::sIdentity(), new BoxShape(Vec3(1.0f, 0.05f, 2.5f))).Create().Get();
  58. for (int angle = 0; angle < 18; ++angle)
  59. mBodyInterface->CreateAndAddBody(BodyCreationSettings(ramp, Vec3(-15.0f + angle * 2.0f, 0, -10.0f), Quat::sRotation(Vec3::sAxisX(), DegreesToRadians(10.0f * angle)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  60. }
  61. {
  62. // Create wall consisting of vertical pillars
  63. // Note: Convex radius 0 because otherwise it will be a bumpy wall
  64. Ref<Shape> wall = new BoxShape(Vec3(0.1f, 2.5f, 0.1f), 0.0f);
  65. for (int z = 0; z < 40; ++z)
  66. mBodyInterface->CreateAndAddBody(BodyCreationSettings(wall, Vec3(-10.0f, 2.5f, -10.0f + 0.2f * z), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  67. }
  68. {
  69. // Kinematic blocks to test interacting with moving objects
  70. Ref<Shape> kinematic = new BoxShape(Vec3(1, 0.25f, 3.0f));
  71. mRotatingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cRotatingPosition, cRotatingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  72. mVerticallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cVerticallyMovingPosition, cVerticallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  73. mHorizontallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cHorizontallyMovingPosition, cHorizontallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  74. }
  75. {
  76. // Dynamic blocks to test player pushing blocks
  77. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  78. for (int y = 0; y < 3; ++y)
  79. {
  80. BodyCreationSettings bcs(block, Vec3(5.0f, 0.5f + float(y), 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  81. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  82. bcs.mMassPropertiesOverride.mMass = 10.0f;
  83. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  84. }
  85. }
  86. {
  87. // Create ramp
  88. BodyCreationSettings ramp(new BoxShape(Vec3(4.0f, 0.1f, 3.0f)), cRampPosition, cRampOrientation, EMotionType::Static, Layers::NON_MOVING);
  89. mBodyInterface->CreateAndAddBody(ramp, EActivation::DontActivate);
  90. // Create blocks on ramp
  91. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  92. BodyCreationSettings bcs(block, cRampBlocksStart, cRampOrientation, EMotionType::Dynamic, Layers::MOVING);
  93. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  94. bcs.mMassPropertiesOverride.mMass = 10.0f;
  95. for (int i = 0; i < 4; ++i)
  96. {
  97. mRampBlocks.emplace_back(mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate));
  98. bcs.mPosition += cRampBlocksDelta;
  99. }
  100. }
  101. // Create three funnels with walls that are too steep to climb
  102. Ref<Shape> funnel = new BoxShape(Vec3(0.1f, 1.0f, 1.0f));
  103. for (int i = 0; i < 2; ++i)
  104. {
  105. Quat rotation = Quat::sRotation(Vec3::sAxisY(), JPH_PI * i);
  106. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, Vec3(5.0f, 0.1f, 5.0f) + rotation * Vec3(0.2f, 0, 0), rotation * Quat::sRotation(Vec3::sAxisZ(), -DegreesToRadians(40.0f)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  107. }
  108. for (int i = 0; i < 3; ++i)
  109. {
  110. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 2.0f / 3.0f * JPH_PI * i);
  111. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, Vec3(7.5f, 0.1f, 5.0f) + rotation * Vec3(0.2f, 0, 0), rotation * Quat::sRotation(Vec3::sAxisZ(), -DegreesToRadians(40.0f)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  112. }
  113. for (int i = 0; i < 4; ++i)
  114. {
  115. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 0.5f * JPH_PI * i);
  116. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, Vec3(10.0f, 0.1f, 5.0f) + rotation * Vec3(0.2f, 0, 0), rotation * Quat::sRotation(Vec3::sAxisZ(), -DegreesToRadians(40.0f)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  117. }
  118. }
  119. else
  120. {
  121. // Load scene
  122. Ref<PhysicsScene> scene;
  123. if (!ObjectStreamIn::sReadObject((string("Assets/") + sSceneName + ".bof").c_str(), scene))
  124. FatalError("Failed to load scene");
  125. scene->FixInvalidScales();
  126. for (BodyCreationSettings &settings : scene->GetBodies())
  127. {
  128. settings.mObjectLayer = Layers::NON_MOVING;
  129. settings.mFriction = 0.5f;
  130. }
  131. scene->CreateBodies(mPhysicsSystem);
  132. }
  133. // Create capsule shapes for all stances
  134. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding)).Create().Get();
  135. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching)).Create().Get();
  136. }
  137. void CharacterBaseTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  138. {
  139. // Update scene time
  140. mTime += inParams.mDeltaTime;
  141. // Determine controller input
  142. Vec3 control_input = Vec3::sZero();
  143. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT)) control_input.SetZ(-1);
  144. if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT)) control_input.SetZ(1);
  145. if (inParams.mKeyboard->IsKeyPressed(DIK_UP)) control_input.SetX(1);
  146. if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN)) control_input.SetX(-1);
  147. if (control_input != Vec3::sZero())
  148. control_input = control_input.Normalized();
  149. // Rotate controls to align with the camera
  150. Vec3 cam_fwd = inParams.mCameraState.mForward;
  151. cam_fwd.SetY(0.0f);
  152. cam_fwd = cam_fwd.NormalizedOr(Vec3::sAxisX());
  153. Quat rotation = Quat::sFromTo(Vec3::sAxisX(), cam_fwd);
  154. control_input = rotation * control_input;
  155. // Check actions
  156. bool jump = false;
  157. bool switch_stance = false;
  158. for (int key = inParams.mKeyboard->GetFirstKey(); key != 0; key = inParams.mKeyboard->GetNextKey())
  159. {
  160. if (key == DIK_RSHIFT)
  161. switch_stance = true;
  162. else if (key == DIK_RCONTROL)
  163. jump = true;
  164. }
  165. HandleInput(control_input, jump, switch_stance, inParams.mDeltaTime);
  166. // Animate bodies
  167. if (!mRotatingBody.IsInvalid())
  168. mBodyInterface->MoveKinematic(mRotatingBody, cRotatingPosition, Quat::sRotation(Vec3::sAxisY(), JPH_PI * sin(mTime)), inParams.mDeltaTime);
  169. if (!mHorizontallyMovingBody.IsInvalid())
  170. mBodyInterface->MoveKinematic(mHorizontallyMovingBody, cHorizontallyMovingPosition + Vec3(3.0f * sin(mTime), 0, 0), cHorizontallyMovingOrientation, inParams.mDeltaTime);
  171. if (!mVerticallyMovingBody.IsInvalid())
  172. mBodyInterface->MoveKinematic(mVerticallyMovingBody, cVerticallyMovingPosition + Vec3(0, 1.75f * sin(mTime), 0), cVerticallyMovingOrientation, inParams.mDeltaTime);
  173. // Reset ramp blocks
  174. mRampBlocksTimeLeft -= inParams.mDeltaTime;
  175. if (mRampBlocksTimeLeft < 0.0f)
  176. {
  177. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  178. {
  179. mBodyInterface->SetPositionAndRotation(mRampBlocks[i], cRampBlocksStart + float(i) * cRampBlocksDelta, cRampOrientation, EActivation::Activate);
  180. mBodyInterface->SetLinearAndAngularVelocity(mRampBlocks[i], Vec3::sZero(), Vec3::sZero());
  181. }
  182. mRampBlocksTimeLeft = cRampBlocksTime;
  183. }
  184. }
  185. void CharacterBaseTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  186. {
  187. inUI->CreateTextButton(inSubMenu, "Select Scene", [this, inUI]() {
  188. UIElement *scene_name = inUI->CreateMenu();
  189. for (uint i = 0; i < size(sScenes); ++i)
  190. inUI->CreateTextButton(scene_name, sScenes[i], [this, i]() { sSceneName = sScenes[i]; RestartTest(); });
  191. inUI->ShowMenu(scene_name);
  192. });
  193. }
  194. void CharacterBaseTest::GetInitialCamera(CameraState& ioState) const
  195. {
  196. // This will become the local space offset, look down the x axis and slightly down
  197. ioState.mPos = Vec3::sZero();
  198. ioState.mForward = Vec3(10.0f, -2.0f, 0).Normalized();
  199. }
  200. Mat44 CharacterBaseTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  201. {
  202. // Pivot is center of character + distance behind based on the heading and pitch of the camera
  203. Vec3 fwd = Vec3(cos(inCameraPitch) * cos(inCameraHeading), sin(inCameraPitch), cos(inCameraPitch) * sin(inCameraHeading));
  204. return Mat44::sTranslation(GetCharacterPosition() + Vec3(0, cCharacterHeightStanding + cCharacterRadiusStanding, 0) - 5.0f * fwd);
  205. }
  206. void CharacterBaseTest::SaveState(StateRecorder &inStream) const
  207. {
  208. inStream.Write(mTime);
  209. inStream.Write(mRampBlocksTimeLeft);
  210. }
  211. void CharacterBaseTest::RestoreState(StateRecorder &inStream)
  212. {
  213. inStream.Read(mTime);
  214. inStream.Read(mRampBlocksTimeLeft);
  215. }
  216. void CharacterBaseTest::DrawCharacterState(const CharacterBase *inCharacter, Mat44Arg inCharacterTransform, Vec3Arg inCharacterVelocity)
  217. {
  218. // Draw current location
  219. // Drawing prior to update since the physics system state is also that prior to the simulation step (so that all detected collisions etc. make sense)
  220. mDebugRenderer->DrawCoordinateSystem(inCharacterTransform);
  221. // Determine color
  222. CharacterBase::EGroundState ground_state = inCharacter->GetGroundState();
  223. Color color;
  224. switch (ground_state)
  225. {
  226. case CharacterBase::EGroundState::OnGround:
  227. color = Color::sGreen;
  228. break;
  229. case CharacterBase::EGroundState::Sliding:
  230. color = Color::sOrange;
  231. break;
  232. case CharacterBase::EGroundState::InAir:
  233. default:
  234. color = Color::sRed;
  235. break;
  236. }
  237. // Draw the state of the ground contact
  238. if (ground_state != CharacterBase::EGroundState::InAir)
  239. {
  240. Vec3 ground_position = inCharacter->GetGroundPosition();
  241. Vec3 ground_normal = inCharacter->GetGroundNormal();
  242. Vec3 ground_velocity = inCharacter->GetGroundVelocity();
  243. // Draw ground position
  244. mDebugRenderer->DrawWireSphere(ground_position, 0.1f, Color::sRed);
  245. mDebugRenderer->DrawArrow(ground_position, ground_position + 2.0f * ground_normal, Color::sGreen, 0.1f);
  246. // Draw ground velocity
  247. if (!ground_velocity.IsNearZero())
  248. mDebugRenderer->DrawArrow(ground_position, ground_position + ground_velocity, Color::sBlue, 0.1f);
  249. }
  250. // Draw provided character velocity
  251. if (!inCharacterVelocity.IsNearZero())
  252. mDebugRenderer->DrawArrow(inCharacterTransform.GetTranslation(), inCharacterTransform.GetTranslation() + inCharacterVelocity, Color::sYellow, 0.1f);
  253. // Draw text info
  254. const PhysicsMaterial *ground_material = inCharacter->GetGroundMaterial();
  255. mDebugRenderer->DrawText3D(inCharacterTransform.GetTranslation(), StringFormat("Mat: %s\nVel: %.1f m/s", ground_material->GetDebugName(), (double)inCharacterVelocity.Length()), color, 0.25f);
  256. }