CharacterBaseTest.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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/Physics/Collision/Shape/MeshShape.h>
  10. #include <Jolt/Core/StringTools.h>
  11. #include <Jolt/ObjectStream/ObjectStreamIn.h>
  12. #include <Application/DebugUI.h>
  13. #include <Layers.h>
  14. #include <Utils/Log.h>
  15. #include <Renderer/DebugRendererImp.h>
  16. JPH_IMPLEMENT_RTTI_ABSTRACT(CharacterBaseTest)
  17. {
  18. JPH_ADD_BASE_CLASS(CharacterBaseTest, Test)
  19. }
  20. const char *CharacterBaseTest::sScenes[] =
  21. {
  22. "PerlinMesh",
  23. "PerlinHeightField",
  24. "ObstacleCourse",
  25. "Terrain1",
  26. "Terrain2",
  27. };
  28. const char *CharacterBaseTest::sSceneName = "ObstacleCourse";
  29. // Scene constants
  30. static const Vec3 cRotatingPosition(-5, 0.15f, 15);
  31. static const Quat cRotatingOrientation = Quat::sIdentity();
  32. static const Vec3 cVerticallyMovingPosition(0, 2.0f, 15);
  33. static const Quat cVerticallyMovingOrientation = Quat::sIdentity();
  34. static const Vec3 cHorizontallyMovingPosition(5, 1, 15);
  35. static const Quat cHorizontallyMovingOrientation = Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI);
  36. static const Vec3 cRampPosition(15, 2.2f, 15);
  37. static const Quat cRampOrientation = Quat::sRotation(Vec3::sAxisX(), -0.25f * JPH_PI);
  38. static const Vec3 cRampBlocksStart = cRampPosition + Vec3(-3.0f, 3.0f, 1.5f);
  39. static const Vec3 cRampBlocksDelta = Vec3(2.0f, 0, 0);
  40. static const float cRampBlocksTime = 5.0f;
  41. static const Vec3 cSmallBumpsPosition = Vec3(-5.0f, 0, 2.5f);
  42. static const float cSmallBumpHeight = 0.05f;
  43. static const float cSmallBumpWidth = 0.01f;
  44. static const float cSmallBumpDelta = 0.5f;
  45. static const Vec3 cLargeBumpsPosition = Vec3(-10.0f, 0, 2.5f);
  46. static const float cLargeBumpHeight = 0.3f;
  47. static const float cLargeBumpWidth = 0.1f;
  48. static const float cLargeBumpDelta = 2.0f;
  49. static const Vec3 cStairsPosition = Vec3(-15.0f, 0, 2.5f);
  50. static const float cStairsStepHeight = 0.3f;
  51. static const Vec3 cNoStairsPosition = Vec3(-15.0f, 0, 10.0f);
  52. static const float cNoStairsStepHeight = 0.3f;
  53. static const float cNoStairsStepDelta = 0.05f;
  54. static const Vec3 cMeshWallPosition = Vec3(-20.0f, 0, -27.0f);
  55. static const float cMeshWallHeight = 3.0f;
  56. static const float cMeshWallWidth = 2.0f;
  57. static const float cMeshWallStepStart = 0.5f;
  58. static const float cMeshWallStepEnd = 4.0f;
  59. static const int cMeshWallSegments = 25;
  60. void CharacterBaseTest::Initialize()
  61. {
  62. if (strcmp(sSceneName, "PerlinMesh") == 0)
  63. {
  64. // Default terrain
  65. CreateMeshTerrain();
  66. }
  67. else if (strcmp(sSceneName, "PerlinHeightField") == 0)
  68. {
  69. // Default terrain
  70. CreateHeightFieldTerrain();
  71. }
  72. else if (strcmp(sSceneName, "ObstacleCourse") == 0)
  73. {
  74. // Default terrain
  75. CreateFloor(300.0f);
  76. {
  77. // Create ramps with different inclinations
  78. Ref<Shape> ramp = RotatedTranslatedShapeSettings(Vec3(0, 0, -2.5f), Quat::sIdentity(), new BoxShape(Vec3(1.0f, 0.05f, 2.5f))).Create().Get();
  79. for (int angle = 0; angle < 18; ++angle)
  80. 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);
  81. }
  82. {
  83. // Create wall consisting of vertical pillars
  84. // Note: Convex radius 0 because otherwise it will be a bumpy wall
  85. Ref<Shape> wall = new BoxShape(Vec3(0.1f, 2.5f, 0.1f), 0.0f);
  86. for (int z = 0; z < 30; ++z)
  87. mBodyInterface->CreateAndAddBody(BodyCreationSettings(wall, Vec3(0.0f, 2.5f, 2.0f + 0.2f * z), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  88. }
  89. {
  90. // Kinematic blocks to test interacting with moving objects
  91. Ref<Shape> kinematic = new BoxShape(Vec3(1, 0.15f, 3.0f));
  92. mRotatingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cRotatingPosition, cRotatingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  93. mVerticallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cVerticallyMovingPosition, cVerticallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  94. mHorizontallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cHorizontallyMovingPosition, cHorizontallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  95. }
  96. {
  97. // Dynamic blocks to test player pushing blocks
  98. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  99. for (int y = 0; y < 3; ++y)
  100. {
  101. BodyCreationSettings bcs(block, Vec3(5.0f, 0.5f + float(y), 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  102. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  103. bcs.mMassPropertiesOverride.mMass = 10.0f;
  104. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  105. }
  106. }
  107. {
  108. // Create ramp
  109. BodyCreationSettings ramp(new BoxShape(Vec3(4.0f, 0.1f, 3.0f)), cRampPosition, cRampOrientation, EMotionType::Static, Layers::NON_MOVING);
  110. mBodyInterface->CreateAndAddBody(ramp, EActivation::DontActivate);
  111. // Create blocks on ramp
  112. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  113. BodyCreationSettings bcs(block, cRampBlocksStart, cRampOrientation, EMotionType::Dynamic, Layers::MOVING);
  114. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  115. bcs.mMassPropertiesOverride.mMass = 10.0f;
  116. for (int i = 0; i < 4; ++i)
  117. {
  118. mRampBlocks.emplace_back(mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate));
  119. bcs.mPosition += cRampBlocksDelta;
  120. }
  121. }
  122. // Create three funnels with walls that are too steep to climb
  123. Ref<Shape> funnel = new BoxShape(Vec3(0.1f, 1.0f, 1.0f));
  124. for (int i = 0; i < 2; ++i)
  125. {
  126. Quat rotation = Quat::sRotation(Vec3::sAxisY(), JPH_PI * i);
  127. 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);
  128. }
  129. for (int i = 0; i < 3; ++i)
  130. {
  131. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 2.0f / 3.0f * JPH_PI * i);
  132. 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);
  133. }
  134. for (int i = 0; i < 4; ++i)
  135. {
  136. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 0.5f * JPH_PI * i);
  137. 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);
  138. }
  139. // Create small bumps
  140. {
  141. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cSmallBumpHeight, 0.5f * cSmallBumpWidth), 0.0f), Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  142. for (int i = 0; i < 10; ++i)
  143. {
  144. step.mPosition = cSmallBumpsPosition + Vec3(0, 0.5f * cSmallBumpHeight, cSmallBumpDelta * i);
  145. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  146. }
  147. }
  148. // Create large bumps
  149. {
  150. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cLargeBumpHeight, 0.5f * cLargeBumpWidth)), Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  151. for (int i = 0; i < 5; ++i)
  152. {
  153. step.mPosition = cLargeBumpsPosition + Vec3(0, 0.5f * cLargeBumpHeight, cLargeBumpDelta * i);
  154. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  155. }
  156. }
  157. // Create stairs
  158. {
  159. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cStairsStepHeight, 0.5f * cStairsStepHeight)), Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  160. for (int i = 0; i < 10; ++i)
  161. {
  162. step.mPosition = cStairsPosition + Vec3(0, cStairsStepHeight * (0.5f + i), cStairsStepHeight * i);
  163. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  164. }
  165. }
  166. // Create stairs with too little space between the steps
  167. {
  168. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cNoStairsStepHeight, 0.5f * cNoStairsStepHeight)), Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  169. for (int i = 0; i < 10; ++i)
  170. {
  171. step.mPosition = cNoStairsPosition + Vec3(0, cNoStairsStepHeight * (0.5f + i), cNoStairsStepDelta * i);
  172. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  173. }
  174. }
  175. // Create mesh with walls at varying angles
  176. {
  177. TriangleList triangles;
  178. Vec3 p1(0.5f * cMeshWallWidth, 0, 0);
  179. Vec3 h(0, cMeshWallHeight, 0);
  180. for (int i = 0; i < cMeshWallSegments; ++i)
  181. {
  182. float delta = cMeshWallStepStart + i * (cMeshWallStepEnd - cMeshWallStepStart) / (cMeshWallSegments - 1);
  183. Vec3 p2 = Vec3((i & 1)? 0.5f * cMeshWallWidth : -0.5f * cMeshWallWidth, 0, p1.GetZ() + delta);
  184. triangles.push_back(Triangle(p1, p1 + h, p2 + h));
  185. triangles.push_back(Triangle(p1, p2 + h, p2));
  186. p1 = p2;
  187. }
  188. MeshShapeSettings mesh(triangles);
  189. mesh.SetEmbedded();
  190. BodyCreationSettings wall(&mesh, cMeshWallPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  191. mBodyInterface->CreateAndAddBody(wall, EActivation::DontActivate);
  192. }
  193. }
  194. else
  195. {
  196. // Load scene
  197. Ref<PhysicsScene> scene;
  198. if (!ObjectStreamIn::sReadObject((String("Assets/") + sSceneName + ".bof").c_str(), scene))
  199. FatalError("Failed to load scene");
  200. scene->FixInvalidScales();
  201. for (BodyCreationSettings &settings : scene->GetBodies())
  202. {
  203. settings.mObjectLayer = Layers::NON_MOVING;
  204. settings.mFriction = 0.5f;
  205. }
  206. scene->CreateBodies(mPhysicsSystem);
  207. }
  208. // Create capsule shapes for all stances
  209. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding)).Create().Get();
  210. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching)).Create().Get();
  211. }
  212. void CharacterBaseTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  213. {
  214. // Update scene time
  215. mTime += inParams.mDeltaTime;
  216. // Determine controller input
  217. Vec3 control_input = Vec3::sZero();
  218. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT)) control_input.SetZ(-1);
  219. if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT)) control_input.SetZ(1);
  220. if (inParams.mKeyboard->IsKeyPressed(DIK_UP)) control_input.SetX(1);
  221. if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN)) control_input.SetX(-1);
  222. if (control_input != Vec3::sZero())
  223. control_input = control_input.Normalized();
  224. // Rotate controls to align with the camera
  225. Vec3 cam_fwd = inParams.mCameraState.mForward;
  226. cam_fwd.SetY(0.0f);
  227. cam_fwd = cam_fwd.NormalizedOr(Vec3::sAxisX());
  228. Quat rotation = Quat::sFromTo(Vec3::sAxisX(), cam_fwd);
  229. control_input = rotation * control_input;
  230. // Check actions
  231. bool jump = false;
  232. bool switch_stance = false;
  233. for (int key = inParams.mKeyboard->GetFirstKey(); key != 0; key = inParams.mKeyboard->GetNextKey())
  234. {
  235. if (key == DIK_RSHIFT)
  236. switch_stance = true;
  237. else if (key == DIK_RCONTROL)
  238. jump = true;
  239. }
  240. HandleInput(control_input, jump, switch_stance, inParams.mDeltaTime);
  241. // Animate bodies
  242. if (!mRotatingBody.IsInvalid())
  243. mBodyInterface->MoveKinematic(mRotatingBody, cRotatingPosition, Quat::sRotation(Vec3::sAxisY(), JPH_PI * Sin(mTime)), inParams.mDeltaTime);
  244. if (!mHorizontallyMovingBody.IsInvalid())
  245. mBodyInterface->MoveKinematic(mHorizontallyMovingBody, cHorizontallyMovingPosition + Vec3(3.0f * Sin(mTime), 0, 0), cHorizontallyMovingOrientation, inParams.mDeltaTime);
  246. if (!mVerticallyMovingBody.IsInvalid())
  247. mBodyInterface->MoveKinematic(mVerticallyMovingBody, cVerticallyMovingPosition + Vec3(0, 1.75f * Sin(mTime), 0), cVerticallyMovingOrientation, inParams.mDeltaTime);
  248. // Reset ramp blocks
  249. mRampBlocksTimeLeft -= inParams.mDeltaTime;
  250. if (mRampBlocksTimeLeft < 0.0f)
  251. {
  252. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  253. {
  254. mBodyInterface->SetPositionAndRotation(mRampBlocks[i], cRampBlocksStart + float(i) * cRampBlocksDelta, cRampOrientation, EActivation::Activate);
  255. mBodyInterface->SetLinearAndAngularVelocity(mRampBlocks[i], Vec3::sZero(), Vec3::sZero());
  256. }
  257. mRampBlocksTimeLeft = cRampBlocksTime;
  258. }
  259. }
  260. void CharacterBaseTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  261. {
  262. inUI->CreateTextButton(inSubMenu, "Select Scene", [this, inUI]() {
  263. UIElement *scene_name = inUI->CreateMenu();
  264. for (uint i = 0; i < size(sScenes); ++i)
  265. inUI->CreateTextButton(scene_name, sScenes[i], [this, i]() { sSceneName = sScenes[i]; RestartTest(); });
  266. inUI->ShowMenu(scene_name);
  267. });
  268. }
  269. void CharacterBaseTest::GetInitialCamera(CameraState& ioState) const
  270. {
  271. // This will become the local space offset, look down the x axis and slightly down
  272. ioState.mPos = Vec3::sZero();
  273. ioState.mForward = Vec3(10.0f, -2.0f, 0).Normalized();
  274. }
  275. Mat44 CharacterBaseTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  276. {
  277. // Pivot is center of character + distance behind based on the heading and pitch of the camera
  278. Vec3 fwd = Vec3(Cos(inCameraPitch) * Cos(inCameraHeading), Sin(inCameraPitch), Cos(inCameraPitch) * Sin(inCameraHeading));
  279. return Mat44::sTranslation(GetCharacterPosition() + Vec3(0, cCharacterHeightStanding + cCharacterRadiusStanding, 0) - 5.0f * fwd);
  280. }
  281. void CharacterBaseTest::SaveState(StateRecorder &inStream) const
  282. {
  283. inStream.Write(mTime);
  284. inStream.Write(mRampBlocksTimeLeft);
  285. }
  286. void CharacterBaseTest::RestoreState(StateRecorder &inStream)
  287. {
  288. inStream.Read(mTime);
  289. inStream.Read(mRampBlocksTimeLeft);
  290. }
  291. void CharacterBaseTest::DrawCharacterState(const CharacterBase *inCharacter, Mat44Arg inCharacterTransform, Vec3Arg inCharacterVelocity)
  292. {
  293. // Draw current location
  294. // 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)
  295. mDebugRenderer->DrawCoordinateSystem(inCharacterTransform, 0.1f);
  296. // Determine color
  297. CharacterBase::EGroundState ground_state = inCharacter->GetGroundState();
  298. Color color;
  299. switch (ground_state)
  300. {
  301. case CharacterBase::EGroundState::OnGround:
  302. color = Color::sGreen;
  303. break;
  304. case CharacterBase::EGroundState::OnSteepGround:
  305. color = Color::sOrange;
  306. break;
  307. case CharacterBase::EGroundState::InAir:
  308. default:
  309. color = Color::sRed;
  310. break;
  311. }
  312. // Draw the state of the ground contact
  313. if (ground_state != CharacterBase::EGroundState::InAir)
  314. {
  315. Vec3 ground_position = inCharacter->GetGroundPosition();
  316. Vec3 ground_normal = inCharacter->GetGroundNormal();
  317. Vec3 ground_velocity = inCharacter->GetGroundVelocity();
  318. // Draw ground position
  319. mDebugRenderer->DrawMarker(ground_position, Color::sRed, 0.1f);
  320. mDebugRenderer->DrawArrow(ground_position, ground_position + 2.0f * ground_normal, Color::sGreen, 0.1f);
  321. // Draw ground velocity
  322. if (!ground_velocity.IsNearZero())
  323. mDebugRenderer->DrawArrow(ground_position, ground_position + ground_velocity, Color::sBlue, 0.1f);
  324. }
  325. // Draw provided character velocity
  326. if (!inCharacterVelocity.IsNearZero())
  327. mDebugRenderer->DrawArrow(inCharacterTransform.GetTranslation(), inCharacterTransform.GetTranslation() + inCharacterVelocity, Color::sYellow, 0.1f);
  328. // Draw text info
  329. const PhysicsMaterial *ground_material = inCharacter->GetGroundMaterial();
  330. Vec3 horizontal_velocity = inCharacterVelocity;
  331. horizontal_velocity.SetY(0);
  332. mDebugRenderer->DrawText3D(inCharacterTransform.GetTranslation(), StringFormat("Mat: %s\nHorizontal Vel: %.1f m/s\nVertical Vel: %.1f m/s", ground_material->GetDebugName(), (double)horizontal_velocity.Length(), (double)inCharacterVelocity.GetY()), color, 0.25f);
  333. }