CharacterBaseTest.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Samples.h>
  5. #include <Tests/Character/CharacterBaseTest.h>
  6. #include <Jolt/Physics/PhysicsScene.h>
  7. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  8. #include <Jolt/Physics/Collision/Shape/CylinderShape.h>
  9. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  10. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  11. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  12. #include <Jolt/Physics/Collision/Shape/StaticCompoundShape.h>
  13. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  14. #include <Jolt/Physics/Constraints/HingeConstraint.h>
  15. #include <Jolt/Core/StringTools.h>
  16. #include <Jolt/ObjectStream/ObjectStreamIn.h>
  17. #include <Application/DebugUI.h>
  18. #include <Layers.h>
  19. #include <Utils/Log.h>
  20. #include <Utils/AssetStream.h>
  21. #include <Renderer/DebugRendererImp.h>
  22. #include <Input/Keyboard.h>
  23. JPH_IMPLEMENT_RTTI_ABSTRACT(CharacterBaseTest)
  24. {
  25. JPH_ADD_BASE_CLASS(CharacterBaseTest, Test)
  26. }
  27. const char *CharacterBaseTest::sScenes[] =
  28. {
  29. "PerlinMesh",
  30. "PerlinHeightField",
  31. "ObstacleCourse",
  32. "InitiallyIntersecting",
  33. #ifdef JPH_OBJECT_STREAM
  34. "Terrain1",
  35. "Terrain2",
  36. #endif // JPH_OBJECT_STREAM
  37. };
  38. const char *CharacterBaseTest::sSceneName = "ObstacleCourse";
  39. // Scene constants
  40. static const RVec3 cRotatingPosition(-5, 0.15f, 15);
  41. static const Quat cRotatingOrientation = Quat::sIdentity();
  42. static const RVec3 cRotatingWallPosition(5, 1.0f, 25.0f);
  43. static const Quat cRotatingWallOrientation = Quat::sIdentity();
  44. static const RVec3 cRotatingAndTranslatingPosition(-10, 0.15f, 27.5f);
  45. static const Quat cRotatingAndTranslatingOrientation = Quat::sIdentity();
  46. static const RVec3 cSmoothVerticallyMovingPosition(0, 2.0f, 15);
  47. static const Quat cSmoothVerticallyMovingOrientation = Quat::sIdentity();
  48. static const RVec3 cReversingVerticallyMovingPosition(0, 0.15f, 25);
  49. static const Quat cReversingVerticallyMovingOrientation = Quat::sIdentity();
  50. static const RVec3 cHorizontallyMovingPosition(5, 1, 15);
  51. static const Quat cHorizontallyMovingOrientation = Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI);
  52. static const RVec3 cConveyorBeltPosition(-10, 0.15f, 15);
  53. static const RVec3 cRampPosition(15, 2.2f, 15);
  54. static const Quat cRampOrientation = Quat::sRotation(Vec3::sAxisX(), -0.25f * JPH_PI);
  55. static const RVec3 cRampBlocksStart = cRampPosition + Vec3(-3.0f, 3.0f, 1.5f);
  56. static const Vec3 cRampBlocksDelta = Vec3(2.0f, 0, 0);
  57. static const float cRampBlocksTime = 5.0f;
  58. static const RVec3 cSmallBumpsPosition(-5.0f, 0, 2.5f);
  59. static const float cSmallBumpHeight = 0.05f;
  60. static const float cSmallBumpWidth = 0.01f;
  61. static const float cSmallBumpDelta = 0.5f;
  62. static const RVec3 cLargeBumpsPosition(-10.0f, 0, 2.5f);
  63. static const float cLargeBumpHeight = 0.3f;
  64. static const float cLargeBumpWidth = 0.1f;
  65. static const float cLargeBumpDelta = 2.0f;
  66. static const RVec3 cStairsPosition(-15.0f, 0, 2.5f);
  67. static const float cStairsStepHeight = 0.3f;
  68. static const RVec3 cMeshStairsPosition(-20.0f, 0, 2.5f);
  69. static const RVec3 cNoStairsPosition(-15.0f, 0, 10.0f);
  70. static const float cNoStairsStepHeight = 0.3f;
  71. static const float cNoStairsStepDelta = 0.05f;
  72. static const RVec3 cMeshNoStairsPosition(-20.0f, 0, 10.0f);
  73. static const RVec3 cMeshWallPosition(-25.0f, 0, -27.0f);
  74. static const float cMeshWallHeight = 3.0f;
  75. static const float cMeshWallWidth = 2.0f;
  76. static const float cMeshWallStepStart = 0.5f;
  77. static const float cMeshWallStepEnd = 4.0f;
  78. static const int cMeshWallSegments = 25;
  79. static const RVec3 cHalfCylinderPosition(5.0f, 0, 8.0f);
  80. static const RVec3 cMeshBoxPosition(30.0f, 1.5f, 5.0f);
  81. static const RVec3 cSensorPosition(30, 0.9f, -5);
  82. static const RVec3 cCharacterPosition(-3.5f, 0, 3.0f);
  83. static const RVec3 cCharacterVirtualPosition(-5.0f, 0, 3.0f);
  84. static const RVec3 cCharacterVirtualWithInnerBodyPosition(-6.5f, 0, 3.0f);
  85. static const Vec3 cCharacterVelocity(0, 0, 2);
  86. CharacterBaseTest::~CharacterBaseTest()
  87. {
  88. if (mAnimatedCharacter != nullptr)
  89. mAnimatedCharacter->RemoveFromPhysicsSystem();
  90. }
  91. void CharacterBaseTest::Initialize()
  92. {
  93. // Create capsule shapes for all stances
  94. switch (sShapeType)
  95. {
  96. case EType::Capsule:
  97. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding)).Create().Get();
  98. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching)).Create().Get();
  99. mInnerStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cInnerShapeFraction * cCharacterHeightStanding, cInnerShapeFraction * cCharacterRadiusStanding)).Create().Get();
  100. mInnerCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cInnerShapeFraction * cCharacterHeightCrouching, cInnerShapeFraction * cCharacterRadiusCrouching)).Create().Get();
  101. break;
  102. case EType::Cylinder:
  103. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CylinderShape(0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding)).Create().Get();
  104. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CylinderShape(0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching)).Create().Get();
  105. mInnerStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CylinderShape(cInnerShapeFraction * (0.5f * cCharacterHeightStanding + cCharacterRadiusStanding), cInnerShapeFraction * cCharacterRadiusStanding)).Create().Get();
  106. mInnerCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CylinderShape(cInnerShapeFraction * (0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching), cInnerShapeFraction * cCharacterRadiusCrouching)).Create().Get();
  107. break;
  108. case EType::Box:
  109. mStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new BoxShape(Vec3(cCharacterRadiusStanding, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding))).Create().Get();
  110. mCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new BoxShape(Vec3(cCharacterRadiusCrouching, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching))).Create().Get();
  111. mInnerStandingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new BoxShape(cInnerShapeFraction * Vec3(cCharacterRadiusStanding, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding))).Create().Get();
  112. mInnerCrouchingShape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new BoxShape(cInnerShapeFraction * Vec3(cCharacterRadiusCrouching, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching))).Create().Get();
  113. break;
  114. case EType::Compound:
  115. {
  116. StaticCompoundShapeSettings standing_compound;
  117. standing_compound.AddShape(Vec3(-0.3f, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding));
  118. standing_compound.AddShape(Vec3(0.3f, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new BoxShape(Vec3(cCharacterRadiusStanding, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding)));
  119. mStandingShape = standing_compound.Create().Get();
  120. StaticCompoundShapeSettings crouching_compound;
  121. crouching_compound.AddShape(Vec3(-0.3f, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightCrouching, cCharacterRadiusCrouching));
  122. crouching_compound.AddShape(Vec3(0.3f, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new BoxShape(Vec3(cCharacterRadiusCrouching, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching)));
  123. mCrouchingShape = crouching_compound.Create().Get();
  124. StaticCompoundShapeSettings inner_standing_compound;
  125. inner_standing_compound.AddShape(Vec3(-0.3f, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cInnerShapeFraction * cCharacterHeightStanding, cInnerShapeFraction * cCharacterRadiusStanding));
  126. inner_standing_compound.AddShape(Vec3(0.3f, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new BoxShape(cInnerShapeFraction * Vec3(cCharacterRadiusStanding, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, cCharacterRadiusStanding)));
  127. mInnerStandingShape = inner_standing_compound.Create().Get();
  128. StaticCompoundShapeSettings inner_crouching_compound;
  129. inner_crouching_compound.AddShape(Vec3(-0.3f, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cInnerShapeFraction * cCharacterHeightCrouching, cInnerShapeFraction * cCharacterRadiusCrouching));
  130. inner_crouching_compound.AddShape(Vec3(0.3f, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, 0), Quat::sIdentity(), new BoxShape(cInnerShapeFraction * Vec3(cCharacterRadiusCrouching, 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching, cCharacterRadiusCrouching)));
  131. mInnerCrouchingShape = inner_crouching_compound.Create().Get();
  132. }
  133. break;
  134. }
  135. if (strcmp(sSceneName, "PerlinMesh") == 0)
  136. {
  137. // Default terrain
  138. CreateMeshTerrain();
  139. }
  140. else if (strcmp(sSceneName, "PerlinHeightField") == 0)
  141. {
  142. // Default terrain
  143. CreateHeightFieldTerrain();
  144. }
  145. else if (strcmp(sSceneName, "InitiallyIntersecting") == 0)
  146. {
  147. CreateFloor();
  148. // Create a grid of boxes that are initially intersecting with the character
  149. RefConst<Shape> box = new BoxShape(Vec3(0.1f, 0.1f, 0.1f));
  150. BodyCreationSettings settings(box, RVec3(0, 0.5f, 0), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  151. for (int x = 0; x < 4; ++x)
  152. for (int y = 0; y <= 10; ++y)
  153. for (int z = 0; z <= 10; ++z)
  154. {
  155. settings.mPosition = RVec3(-0.5f + 0.1f * x, 0.1f + 0.1f * y, -0.5f + 0.1f * z);
  156. mBodyInterface->CreateAndAddBody(settings, EActivation::DontActivate);
  157. }
  158. }
  159. else if (strcmp(sSceneName, "ObstacleCourse") == 0)
  160. {
  161. // Default terrain
  162. CreateFloor(350.0f);
  163. {
  164. // Create ramps with different inclinations
  165. Ref<Shape> ramp = RotatedTranslatedShapeSettings(Vec3(0, 0, -2.5f), Quat::sIdentity(), new BoxShape(Vec3(1.0f, 0.05f, 2.5f))).Create().Get();
  166. for (int angle = 0; angle < 18; ++angle)
  167. mBodyInterface->CreateAndAddBody(BodyCreationSettings(ramp, RVec3(-15.0f + angle * 2.0f, 0, -10.0f), Quat::sRotation(Vec3::sAxisX(), DegreesToRadians(10.0f * angle)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  168. }
  169. {
  170. // Create ramps with different inclinations intersecting with a steep slope
  171. Ref<Shape> ramp = RotatedTranslatedShapeSettings(Vec3(0, 0, -2.5f), Quat::sIdentity(), new BoxShape(Vec3(1.0f, 0.05f, 2.5f))).Create().Get();
  172. Ref<Shape> ramp2 = RotatedTranslatedShapeSettings(Vec3(0, 2.0f, 0), Quat::sIdentity(), new BoxShape(Vec3(0.05f, 2.0f, 1.0f))).Create().Get();
  173. for (int angle = 0; angle < 9; ++angle)
  174. {
  175. mBodyInterface->CreateAndAddBody(BodyCreationSettings(ramp, RVec3(-15.0f + angle * 2.0f, 0, -20.0f - angle * 0.1f), Quat::sRotation(Vec3::sAxisX(), DegreesToRadians(10.0f * angle)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  176. mBodyInterface->CreateAndAddBody(BodyCreationSettings(ramp2, RVec3(-15.0f + angle * 2.0f, 0, -21.0f), Quat::sRotation(Vec3::sAxisZ(), DegreesToRadians(20.0f)), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  177. }
  178. }
  179. {
  180. // Create wall consisting of vertical pillars
  181. // Note: Convex radius 0 because otherwise it will be a bumpy wall
  182. Ref<Shape> wall = new BoxShape(Vec3(0.1f, 2.5f, 0.1f), 0.0f);
  183. for (int z = 0; z < 30; ++z)
  184. mBodyInterface->CreateAndAddBody(BodyCreationSettings(wall, RVec3(0.0f, 2.5f, 2.0f + 0.2f * z), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  185. }
  186. {
  187. // Kinematic blocks to test interacting with moving objects
  188. Ref<Shape> kinematic = new BoxShape(Vec3(1, 0.15f, 3.0f));
  189. mRotatingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cRotatingPosition, cRotatingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  190. mRotatingWallBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(3.0f, 1, 0.15f)), cRotatingWallPosition, cRotatingWallOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  191. mRotatingAndTranslatingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cRotatingAndTranslatingPosition, cRotatingAndTranslatingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  192. mSmoothVerticallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cSmoothVerticallyMovingPosition, cSmoothVerticallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  193. mReversingVerticallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cReversingVerticallyMovingPosition, cReversingVerticallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  194. mHorizontallyMovingBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(kinematic, cHorizontallyMovingPosition, cHorizontallyMovingOrientation, EMotionType::Kinematic, Layers::MOVING), EActivation::Activate);
  195. }
  196. {
  197. // Conveyor belt (only works with virtual character)
  198. mConveyorBeltBody = mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(1, 0.15f, 3.0f)), cConveyorBeltPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::Activate);
  199. }
  200. {
  201. // A rolling sphere towards the player
  202. BodyCreationSettings bcs(new SphereShape(0.2f), RVec3(0.0f, 0.2f, -1.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  203. bcs.mLinearVelocity = Vec3(0, 0, 2.0f);
  204. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  205. bcs.mMassPropertiesOverride.mMass = 10.0f;
  206. mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate);
  207. }
  208. {
  209. // Dynamic blocks to test player pushing blocks
  210. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  211. for (int y = 0; y < 3; ++y)
  212. {
  213. BodyCreationSettings bcs(block, RVec3(5.0f, 0.5f + float(y), 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  214. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  215. bcs.mMassPropertiesOverride.mMass = 10.0f;
  216. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  217. }
  218. }
  219. {
  220. // Dynamic block on a static step (to test pushing block on stairs)
  221. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(0.5f, 0.15f, 0.5f)), RVec3(10.0f, 0.15f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  222. BodyCreationSettings bcs(new BoxShape(Vec3::sReplicate(0.5f)), RVec3(10.0f, 0.8f, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  223. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  224. bcs.mMassPropertiesOverride.mMass = 10.0f;
  225. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  226. }
  227. {
  228. // Dynamic spheres to test player pushing stuff you can step on
  229. float h = 0.0f;
  230. for (int y = 0; y < 3; ++y)
  231. {
  232. float r = 0.4f - 0.1f * y;
  233. h += r;
  234. BodyCreationSettings bcs(new SphereShape(r), RVec3(15.0f, h, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  235. h += r;
  236. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  237. bcs.mMassPropertiesOverride.mMass = 10.0f;
  238. mBodyInterface->CreateAndAddBody(bcs, EActivation::DontActivate);
  239. }
  240. }
  241. {
  242. // A seesaw to test character gravity
  243. BodyID b1 = mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(1.0f, 0.2f, 0.05f)), RVec3(20.0f, 0.2f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  244. BodyCreationSettings bcs(new BoxShape(Vec3(1.0f, 0.05f, 5.0f)), RVec3(20.0f, 0.45f, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  245. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  246. bcs.mMassPropertiesOverride.mMass = 10.0f;
  247. BodyID b2 = mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate);
  248. // Connect the parts with a hinge
  249. HingeConstraintSettings hinge;
  250. hinge.mPoint1 = hinge.mPoint2 = RVec3(20.0f, 0.4f, 0.0f);
  251. hinge.mHingeAxis1 = hinge.mHingeAxis2 = Vec3::sAxisX();
  252. mPhysicsSystem->AddConstraint(mBodyInterface->CreateConstraint(&hinge, b1, b2));
  253. }
  254. {
  255. // A board above the character to crouch and jump up against
  256. float h = 0.5f * cCharacterHeightCrouching + cCharacterRadiusCrouching + 0.1f;
  257. for (int x = 0; x < 2; ++x)
  258. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(1.0f, h, 0.05f)), RVec3(25.0f, h, x == 0? -0.95f : 0.95f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  259. BodyCreationSettings bcs(new BoxShape(Vec3(1.0f, 0.05f, 1.0f)), RVec3(25.0f, 2.0f * h + 0.05f, 0.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  260. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  261. bcs.mMassPropertiesOverride.mMass = 10.0f;
  262. mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate);
  263. }
  264. {
  265. // A floating static block
  266. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3::sReplicate(0.5f)), RVec3(30.0f, 1.5f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  267. }
  268. {
  269. // Create ramp
  270. BodyCreationSettings ramp(new BoxShape(Vec3(4.0f, 0.1f, 3.0f)), cRampPosition, cRampOrientation, EMotionType::Static, Layers::NON_MOVING);
  271. mBodyInterface->CreateAndAddBody(ramp, EActivation::DontActivate);
  272. // Create blocks on ramp
  273. Ref<Shape> block = new BoxShape(Vec3::sReplicate(0.5f));
  274. BodyCreationSettings bcs(block, cRampBlocksStart, cRampOrientation, EMotionType::Dynamic, Layers::MOVING);
  275. bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  276. bcs.mMassPropertiesOverride.mMass = 10.0f;
  277. for (int i = 0; i < 4; ++i)
  278. {
  279. mRampBlocks.emplace_back(mBodyInterface->CreateAndAddBody(bcs, EActivation::Activate));
  280. bcs.mPosition += cRampBlocksDelta;
  281. }
  282. }
  283. // Create three funnels with walls that are too steep to climb
  284. Ref<Shape> funnel = new BoxShape(Vec3(0.1f, 1.0f, 1.0f));
  285. for (int i = 0; i < 2; ++i)
  286. {
  287. Quat rotation = Quat::sRotation(Vec3::sAxisY(), JPH_PI * i);
  288. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, RVec3(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);
  289. }
  290. for (int i = 0; i < 3; ++i)
  291. {
  292. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 2.0f / 3.0f * JPH_PI * i);
  293. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, RVec3(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);
  294. }
  295. for (int i = 0; i < 4; ++i)
  296. {
  297. Quat rotation = Quat::sRotation(Vec3::sAxisY(), 0.5f * JPH_PI * i);
  298. mBodyInterface->CreateAndAddBody(BodyCreationSettings(funnel, RVec3(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);
  299. }
  300. // Create small bumps
  301. {
  302. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cSmallBumpHeight, 0.5f * cSmallBumpWidth), 0.0f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  303. for (int i = 0; i < 10; ++i)
  304. {
  305. step.mPosition = cSmallBumpsPosition + Vec3(0, 0.5f * cSmallBumpHeight, cSmallBumpDelta * i);
  306. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  307. }
  308. }
  309. // Create large bumps
  310. {
  311. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cLargeBumpHeight, 0.5f * cLargeBumpWidth)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  312. for (int i = 0; i < 5; ++i)
  313. {
  314. step.mPosition = cLargeBumpsPosition + Vec3(0, 0.5f * cLargeBumpHeight, cLargeBumpDelta * i);
  315. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  316. }
  317. }
  318. // Create stairs
  319. {
  320. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cStairsStepHeight, 0.5f * cStairsStepHeight)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  321. for (int i = 0; i < 10; ++i)
  322. {
  323. step.mPosition = cStairsPosition + Vec3(0, cStairsStepHeight * (0.5f + i), cStairsStepHeight * i);
  324. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  325. }
  326. }
  327. // A wall beside the stairs
  328. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(0.5f, 2.0f, 5.0f * cStairsStepHeight)), cStairsPosition + Vec3(-2.5f, 2.0f, 5.0f * cStairsStepHeight), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  329. // Create stairs from triangles
  330. {
  331. TriangleList triangles;
  332. float rear_z = 10 * cStairsStepHeight;
  333. for (int i = 0; i < 10; ++i)
  334. {
  335. // Start of step
  336. Vec3 base(0, cStairsStepHeight * i, cStairsStepHeight * i);
  337. // Left side
  338. Vec3 b1 = base + Vec3(2.0f, 0, 0);
  339. Vec3 s1 = b1 + Vec3(0, cStairsStepHeight, 0);
  340. Vec3 p1 = s1 + Vec3(0, 0, cStairsStepHeight);
  341. // Right side
  342. Vec3 width(-4.0f, 0, 0);
  343. Vec3 b2 = b1 + width;
  344. Vec3 s2 = s1 + width;
  345. Vec3 p2 = p1 + width;
  346. triangles.push_back(Triangle(s1, b1, s2));
  347. triangles.push_back(Triangle(b1, b2, s2));
  348. triangles.push_back(Triangle(s1, p2, p1));
  349. triangles.push_back(Triangle(s1, s2, p2));
  350. // Side of stairs
  351. Vec3 rb2 = b2; rb2.SetZ(rear_z);
  352. Vec3 rs2 = s2; rs2.SetZ(rear_z);
  353. triangles.push_back(Triangle(s2, b2, rs2));
  354. triangles.push_back(Triangle(rs2, b2, rb2));
  355. }
  356. MeshShapeSettings mesh(triangles);
  357. mesh.SetEmbedded();
  358. BodyCreationSettings mesh_stairs(&mesh, cMeshStairsPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  359. mBodyInterface->CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  360. }
  361. // A wall to the side and behind the stairs
  362. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(0.5f, 2.0f, 0.25f)), cStairsPosition + Vec3(-7.5f, 2.0f, 10.0f * cStairsStepHeight + 0.25f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
  363. // Create stairs with too little space between the steps
  364. {
  365. BodyCreationSettings step(new BoxShape(Vec3(2.0f, 0.5f * cNoStairsStepHeight, 0.5f * cNoStairsStepHeight)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  366. for (int i = 0; i < 10; ++i)
  367. {
  368. step.mPosition = cNoStairsPosition + Vec3(0, cNoStairsStepHeight * (0.5f + i), cNoStairsStepDelta * i);
  369. mBodyInterface->CreateAndAddBody(step, EActivation::DontActivate);
  370. }
  371. }
  372. // Create stairs with too little space between the steps consisting of triangles
  373. {
  374. TriangleList triangles;
  375. for (int i = 0; i < 10; ++i)
  376. {
  377. // Start of step
  378. Vec3 base(0, cStairsStepHeight * i, cNoStairsStepDelta * i);
  379. // Left side
  380. Vec3 b1 = base - Vec3(2.0f, 0, 0);
  381. Vec3 s1 = b1 + Vec3(0, cStairsStepHeight, 0);
  382. Vec3 p1 = s1 + Vec3(0, 0, cNoStairsStepDelta);
  383. // Right side
  384. Vec3 width(4.0f, 0, 0);
  385. Vec3 b2 = b1 + width;
  386. Vec3 s2 = s1 + width;
  387. Vec3 p2 = p1 + width;
  388. triangles.push_back(Triangle(s1, s2, b1));
  389. triangles.push_back(Triangle(b1, s2, b2));
  390. triangles.push_back(Triangle(s1, p1, p2));
  391. triangles.push_back(Triangle(s1, p2, s2));
  392. }
  393. MeshShapeSettings mesh(triangles);
  394. mesh.SetEmbedded();
  395. BodyCreationSettings mesh_stairs(&mesh, cMeshNoStairsPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  396. mBodyInterface->CreateAndAddBody(mesh_stairs, EActivation::DontActivate);
  397. }
  398. // Create mesh with walls at varying angles
  399. {
  400. TriangleList triangles;
  401. Vec3 p1(0.5f * cMeshWallWidth, 0, 0);
  402. Vec3 h(0, cMeshWallHeight, 0);
  403. for (int i = 0; i < cMeshWallSegments; ++i)
  404. {
  405. float delta = cMeshWallStepStart + i * (cMeshWallStepEnd - cMeshWallStepStart) / (cMeshWallSegments - 1);
  406. Vec3 p2 = Vec3((i & 1)? 0.5f * cMeshWallWidth : -0.5f * cMeshWallWidth, 0, p1.GetZ() + delta);
  407. triangles.push_back(Triangle(p1, p1 + h, p2 + h));
  408. triangles.push_back(Triangle(p1, p2 + h, p2));
  409. p1 = p2;
  410. }
  411. MeshShapeSettings mesh(triangles);
  412. mesh.SetEmbedded();
  413. BodyCreationSettings wall(&mesh, cMeshWallPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  414. mBodyInterface->CreateAndAddBody(wall, EActivation::DontActivate);
  415. }
  416. // Create a half cylinder with caps for testing contact point limit
  417. {
  418. VertexList vertices;
  419. IndexedTriangleList triangles;
  420. // The half cylinder
  421. const int cPosSegments = 2;
  422. const int cAngleSegments = 512;
  423. const float cCylinderLength = 2.0f;
  424. for (int pos = 0; pos < cPosSegments; ++pos)
  425. for (int angle = 0; angle < cAngleSegments; ++angle)
  426. {
  427. uint32 start = (uint32)vertices.size();
  428. float radius = cCharacterRadiusStanding + 0.05f;
  429. float angle_rad = (-0.5f + float(angle) / cAngleSegments) * JPH_PI;
  430. float s = Sin(angle_rad);
  431. float c = Cos(angle_rad);
  432. float x = cCylinderLength * (-0.5f + float(pos) / (cPosSegments - 1));
  433. float y = angle == 0 || angle == cAngleSegments - 1? 0.5f : (1.0f - c) * radius;
  434. float z = s * radius;
  435. vertices.push_back(Float3(x, y, z));
  436. if (pos > 0 && angle > 0)
  437. {
  438. triangles.push_back(IndexedTriangle(start, start - 1, start - cAngleSegments));
  439. triangles.push_back(IndexedTriangle(start - 1, start - cAngleSegments - 1, start - cAngleSegments));
  440. }
  441. }
  442. // Add end caps
  443. uint32 end = cAngleSegments * (cPosSegments - 1);
  444. for (int angle = 0; angle < cAngleSegments - 1; ++angle)
  445. {
  446. triangles.push_back(IndexedTriangle(0, angle + 1, angle));
  447. triangles.push_back(IndexedTriangle(end, end + angle, end + angle + 1));
  448. }
  449. MeshShapeSettings mesh(std::move(vertices), std::move(triangles));
  450. mesh.SetEmbedded();
  451. BodyCreationSettings mesh_cylinder(&mesh, cHalfCylinderPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  452. mBodyInterface->CreateAndAddBody(mesh_cylinder, EActivation::DontActivate);
  453. }
  454. // Create a box made out of polygons (character should not get stuck behind back facing side)
  455. {
  456. VertexList vertices = {
  457. Float3(-1, 1, -1),
  458. Float3( 1, 1, -1),
  459. Float3( 1, 1, 1),
  460. Float3(-1, 1, 1),
  461. Float3(-1, -1, -1),
  462. Float3( 1, -1, -1),
  463. Float3( 1, -1, 1),
  464. Float3(-1, -1, 1)
  465. };
  466. IndexedTriangleList triangles = {
  467. IndexedTriangle(0, 3, 2),
  468. IndexedTriangle(0, 2, 1),
  469. IndexedTriangle(4, 5, 6),
  470. IndexedTriangle(4, 6, 7),
  471. IndexedTriangle(0, 4, 3),
  472. IndexedTriangle(3, 4, 7),
  473. IndexedTriangle(2, 6, 5),
  474. IndexedTriangle(2, 5, 1),
  475. IndexedTriangle(3, 7, 6),
  476. IndexedTriangle(3, 6, 2),
  477. IndexedTriangle(0, 1, 5),
  478. IndexedTriangle(0, 5, 4)
  479. };
  480. MeshShapeSettings mesh(std::move(vertices), std::move(triangles));
  481. mesh.SetEmbedded();
  482. BodyCreationSettings box(&mesh, cMeshBoxPosition, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
  483. mBodyInterface->CreateAndAddBody(box, EActivation::DontActivate);
  484. }
  485. // Create a sensor
  486. {
  487. BodyCreationSettings sensor(new BoxShape(Vec3::sOne()), cSensorPosition, Quat::sIdentity(), EMotionType::Kinematic, Layers::SENSOR);
  488. sensor.mIsSensor = true;
  489. mSensorBody = mBodyInterface->CreateAndAddBody(sensor, EActivation::Activate);
  490. }
  491. // Create Character
  492. {
  493. CharacterSettings settings;
  494. settings.mLayer = Layers::MOVING;
  495. settings.mShape = mStandingShape;
  496. settings.mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  497. mAnimatedCharacter = new Character(&settings, cCharacterPosition, Quat::sIdentity(), 0, mPhysicsSystem);
  498. mAnimatedCharacter->AddToPhysicsSystem();
  499. }
  500. // Create CharacterVirtual
  501. {
  502. CharacterVirtualSettings settings;
  503. settings.mShape = mStandingShape;
  504. settings.mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  505. mAnimatedCharacterVirtual = new CharacterVirtual(&settings, cCharacterVirtualPosition, Quat::sIdentity(), 0, mPhysicsSystem);
  506. mAnimatedCharacterVirtual->SetCharacterVsCharacterCollision(&mCharacterVsCharacterCollision);
  507. mCharacterVsCharacterCollision.Add(mAnimatedCharacterVirtual);
  508. }
  509. // Create CharacterVirtual with inner rigid body
  510. {
  511. CharacterVirtualSettings settings;
  512. settings.mShape = mStandingShape;
  513. settings.mInnerBodyShape = mInnerStandingShape;
  514. settings.mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
  515. mAnimatedCharacterVirtualWithInnerBody = new CharacterVirtual(&settings, cCharacterVirtualWithInnerBodyPosition, Quat::sIdentity(), 0, mPhysicsSystem);
  516. mAnimatedCharacterVirtualWithInnerBody->SetCharacterVsCharacterCollision(&mCharacterVsCharacterCollision);
  517. mCharacterVsCharacterCollision.Add(mAnimatedCharacterVirtualWithInnerBody);
  518. }
  519. }
  520. #ifdef JPH_OBJECT_STREAM
  521. else
  522. {
  523. // Load scene
  524. Ref<PhysicsScene> scene;
  525. AssetStream stream(String(sSceneName) + ".bof", std::ios::in | std::ios::binary);
  526. if (!ObjectStreamIn::sReadObject(stream.Get(), scene))
  527. FatalError("Failed to load scene");
  528. scene->FixInvalidScales();
  529. for (BodyCreationSettings &settings : scene->GetBodies())
  530. {
  531. settings.mObjectLayer = Layers::NON_MOVING;
  532. settings.mFriction = 0.5f;
  533. }
  534. scene->CreateBodies(mPhysicsSystem);
  535. }
  536. #endif // JPH_OBJECT_STREAM
  537. }
  538. void CharacterBaseTest::ProcessInput(const ProcessInputParams &inParams)
  539. {
  540. // Determine controller input
  541. mControlInput = Vec3::sZero();
  542. if (inParams.mKeyboard->IsKeyPressed(EKey::Left)) mControlInput.SetZ(-1);
  543. if (inParams.mKeyboard->IsKeyPressed(EKey::Right)) mControlInput.SetZ(1);
  544. if (inParams.mKeyboard->IsKeyPressed(EKey::Up)) mControlInput.SetX(1);
  545. if (inParams.mKeyboard->IsKeyPressed(EKey::Down)) mControlInput.SetX(-1);
  546. if (mControlInput != Vec3::sZero())
  547. mControlInput = mControlInput.Normalized();
  548. // Rotate controls to align with the camera
  549. Vec3 cam_fwd = inParams.mCameraState.mForward;
  550. cam_fwd.SetY(0.0f);
  551. cam_fwd = cam_fwd.NormalizedOr(Vec3::sAxisX());
  552. Quat rotation = Quat::sFromTo(Vec3::sAxisX(), cam_fwd);
  553. mControlInput = rotation * mControlInput;
  554. // Check actions
  555. mJump = inParams.mKeyboard->IsKeyPressedAndTriggered(EKey::RControl, mWasJump);
  556. mSwitchStance = inParams.mKeyboard->IsKeyPressedAndTriggered(EKey::RShift, mWasSwitchStance);
  557. }
  558. void CharacterBaseTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  559. {
  560. // Update scene time
  561. mTime += inParams.mDeltaTime;
  562. // Update camera pivot
  563. mCameraPivot = GetCharacterPosition();
  564. // Animate bodies
  565. if (!mRotatingBody.IsInvalid())
  566. mBodyInterface->MoveKinematic(mRotatingBody, cRotatingPosition, Quat::sRotation(Vec3::sAxisY(), JPH_PI * Sin(mTime)), inParams.mDeltaTime);
  567. if (!mRotatingWallBody.IsInvalid())
  568. mBodyInterface->MoveKinematic(mRotatingWallBody, cRotatingWallPosition, Quat::sRotation(Vec3::sAxisY(), JPH_PI * Sin(mTime)), inParams.mDeltaTime);
  569. if (!mRotatingAndTranslatingBody.IsInvalid())
  570. mBodyInterface->MoveKinematic(mRotatingAndTranslatingBody, cRotatingAndTranslatingPosition + 5.0f * Vec3(Sin(JPH_PI * mTime), 0, Cos(JPH_PI * mTime)), Quat::sRotation(Vec3::sAxisY(), JPH_PI * Sin(mTime)), inParams.mDeltaTime);
  571. if (!mHorizontallyMovingBody.IsInvalid())
  572. mBodyInterface->MoveKinematic(mHorizontallyMovingBody, cHorizontallyMovingPosition + Vec3(3.0f * Sin(mTime), 0, 0), cHorizontallyMovingOrientation, inParams.mDeltaTime);
  573. if (!mSmoothVerticallyMovingBody.IsInvalid())
  574. mBodyInterface->MoveKinematic(mSmoothVerticallyMovingBody, cSmoothVerticallyMovingPosition + Vec3(0, 1.75f * Sin(mTime), 0), cSmoothVerticallyMovingOrientation, inParams.mDeltaTime);
  575. if (!mReversingVerticallyMovingBody.IsInvalid())
  576. {
  577. RVec3 pos = mBodyInterface->GetPosition(mReversingVerticallyMovingBody);
  578. if (pos.GetY() < cReversingVerticallyMovingPosition.GetY())
  579. mReversingVerticallyMovingVelocity = 1.0f;
  580. else if (pos.GetY() > cReversingVerticallyMovingPosition.GetY() + 5.0f)
  581. mReversingVerticallyMovingVelocity = -1.0f;
  582. mBodyInterface->MoveKinematic(mReversingVerticallyMovingBody, pos + Vec3(0, mReversingVerticallyMovingVelocity * 3.0f * inParams.mDeltaTime, 0), cReversingVerticallyMovingOrientation, inParams.mDeltaTime);
  583. }
  584. // Animate character
  585. if (mAnimatedCharacter != nullptr)
  586. mAnimatedCharacter->SetLinearVelocity(Sin(mTime) * cCharacterVelocity);
  587. // Animate character virtual
  588. for (CharacterVirtual *character : { mAnimatedCharacterVirtual, mAnimatedCharacterVirtualWithInnerBody })
  589. if (character != nullptr)
  590. {
  591. // Draw the character
  592. DrawPaddedCharacter(character->GetShape(), character->GetCharacterPadding(), character->GetCenterOfMassTransform());
  593. // Update velocity and apply gravity
  594. Vec3 velocity;
  595. if (character->GetGroundState() == CharacterVirtual::EGroundState::OnGround)
  596. velocity = Vec3::sZero();
  597. else
  598. velocity = character->GetLinearVelocity() * mAnimatedCharacter->GetUp() + mPhysicsSystem->GetGravity() * inParams.mDeltaTime;
  599. velocity += Sin(mTime) * cCharacterVelocity;
  600. character->SetLinearVelocity(velocity);
  601. // Move character
  602. CharacterVirtual::ExtendedUpdateSettings update_settings;
  603. character->ExtendedUpdate(inParams.mDeltaTime,
  604. mPhysicsSystem->GetGravity(),
  605. update_settings,
  606. mPhysicsSystem->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
  607. mPhysicsSystem->GetDefaultLayerFilter(Layers::MOVING),
  608. { },
  609. { },
  610. *mTempAllocator);
  611. }
  612. // Reset ramp blocks
  613. mRampBlocksTimeLeft -= inParams.mDeltaTime;
  614. if (mRampBlocksTimeLeft < 0.0f)
  615. {
  616. for (size_t i = 0; i < mRampBlocks.size(); ++i)
  617. {
  618. mBodyInterface->SetPositionAndRotation(mRampBlocks[i], cRampBlocksStart + float(i) * cRampBlocksDelta, cRampOrientation, EActivation::Activate);
  619. mBodyInterface->SetLinearAndAngularVelocity(mRampBlocks[i], Vec3::sZero(), Vec3::sZero());
  620. }
  621. mRampBlocksTimeLeft = cRampBlocksTime;
  622. }
  623. // Call handle input after new velocities have been set to avoid frame delay
  624. HandleInput(mControlInput, mJump, mSwitchStance, inParams.mDeltaTime);
  625. }
  626. void CharacterBaseTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  627. {
  628. inUI->CreateTextButton(inSubMenu, "Select Scene", [this, inUI]() {
  629. UIElement *scene_name = inUI->CreateMenu();
  630. for (uint i = 0; i < size(sScenes); ++i)
  631. inUI->CreateTextButton(scene_name, sScenes[i], [this, i]() { sSceneName = sScenes[i]; RestartTest(); });
  632. inUI->ShowMenu(scene_name);
  633. });
  634. inUI->CreateTextButton(inSubMenu, "Character Movement Settings", [this, inUI]() {
  635. UIElement *movement_settings = inUI->CreateMenu();
  636. inUI->CreateCheckBox(movement_settings, "Control Movement During Jump", sControlMovementDuringJump, [](UICheckBox::EState inState) { sControlMovementDuringJump = inState == UICheckBox::STATE_CHECKED; });
  637. inUI->CreateSlider(movement_settings, "Character Speed", sCharacterSpeed, 0.1f, 10.0f, 0.1f, [](float inValue) { sCharacterSpeed = inValue; });
  638. inUI->CreateSlider(movement_settings, "Character Jump Speed", sJumpSpeed, 0.1f, 10.0f, 0.1f, [](float inValue) { sJumpSpeed = inValue; });
  639. AddCharacterMovementSettings(inUI, movement_settings);
  640. inUI->ShowMenu(movement_settings);
  641. });
  642. inUI->CreateTextButton(inSubMenu, "Configuration Settings", [this, inUI]() {
  643. UIElement *configuration_settings = inUI->CreateMenu();
  644. inUI->CreateComboBox(configuration_settings, "Shape Type", { "Capsule", "Cylinder", "Box", "Compound" }, (int)sShapeType, [](int inItem) { sShapeType = (EType)inItem; });
  645. AddConfigurationSettings(inUI, configuration_settings);
  646. inUI->CreateTextButton(configuration_settings, "Accept Changes", [this]() { RestartTest(); });
  647. inUI->ShowMenu(configuration_settings);
  648. });
  649. }
  650. void CharacterBaseTest::GetInitialCamera(CameraState& ioState) const
  651. {
  652. // This will become the local space offset, look down the x axis and slightly down
  653. ioState.mPos = RVec3::sZero();
  654. ioState.mForward = Vec3(10.0f, -2.0f, 0).Normalized();
  655. }
  656. RMat44 CharacterBaseTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  657. {
  658. // Pivot is center of character + distance behind based on the heading and pitch of the camera
  659. Vec3 fwd = Vec3(Cos(inCameraPitch) * Cos(inCameraHeading), Sin(inCameraPitch), Cos(inCameraPitch) * Sin(inCameraHeading));
  660. return RMat44::sTranslation(mCameraPivot + Vec3(0, cCharacterHeightStanding + cCharacterRadiusStanding, 0) - 5.0f * fwd);
  661. }
  662. void CharacterBaseTest::SaveState(StateRecorder &inStream) const
  663. {
  664. inStream.Write(mTime);
  665. inStream.Write(mRampBlocksTimeLeft);
  666. inStream.Write(mReversingVerticallyMovingVelocity);
  667. if (mAnimatedCharacterVirtual != nullptr)
  668. mAnimatedCharacterVirtual->SaveState(inStream);
  669. if (mAnimatedCharacterVirtualWithInnerBody != nullptr)
  670. mAnimatedCharacterVirtualWithInnerBody->SaveState(inStream);
  671. }
  672. void CharacterBaseTest::RestoreState(StateRecorder &inStream)
  673. {
  674. inStream.Read(mTime);
  675. inStream.Read(mRampBlocksTimeLeft);
  676. inStream.Read(mReversingVerticallyMovingVelocity);
  677. if (mAnimatedCharacterVirtual != nullptr)
  678. mAnimatedCharacterVirtual->RestoreState(inStream);
  679. if (mAnimatedCharacterVirtualWithInnerBody != nullptr)
  680. mAnimatedCharacterVirtualWithInnerBody->RestoreState(inStream);
  681. }
  682. void CharacterBaseTest::SaveInputState(StateRecorder &inStream) const
  683. {
  684. inStream.Write(mControlInput);
  685. inStream.Write(mJump);
  686. inStream.Write(mSwitchStance);
  687. }
  688. void CharacterBaseTest::RestoreInputState(StateRecorder &inStream)
  689. {
  690. inStream.Read(mControlInput);
  691. inStream.Read(mJump);
  692. inStream.Read(mSwitchStance);
  693. }
  694. void CharacterBaseTest::DrawCharacterState(const CharacterBase *inCharacter, RMat44Arg inCharacterTransform, Vec3Arg inCharacterVelocity)
  695. {
  696. // Draw current location
  697. // 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)
  698. mDebugRenderer->DrawCoordinateSystem(inCharacterTransform, 0.1f);
  699. // Draw the state of the ground contact
  700. CharacterBase::EGroundState ground_state = inCharacter->GetGroundState();
  701. if (ground_state != CharacterBase::EGroundState::InAir)
  702. {
  703. RVec3 ground_position = inCharacter->GetGroundPosition();
  704. Vec3 ground_normal = inCharacter->GetGroundNormal();
  705. Vec3 ground_velocity = inCharacter->GetGroundVelocity();
  706. // Draw ground position
  707. mDebugRenderer->DrawMarker(ground_position, Color::sRed, 0.1f);
  708. mDebugRenderer->DrawArrow(ground_position, ground_position + 2.0f * ground_normal, Color::sGreen, 0.1f);
  709. // Draw ground velocity
  710. if (!ground_velocity.IsNearZero())
  711. mDebugRenderer->DrawArrow(ground_position, ground_position + ground_velocity, Color::sBlue, 0.1f);
  712. }
  713. // Draw provided character velocity
  714. if (!inCharacterVelocity.IsNearZero())
  715. mDebugRenderer->DrawArrow(inCharacterTransform.GetTranslation(), inCharacterTransform.GetTranslation() + inCharacterVelocity, Color::sYellow, 0.1f);
  716. // Draw text info
  717. const PhysicsMaterial *ground_material = inCharacter->GetGroundMaterial();
  718. Vec3 horizontal_velocity = inCharacterVelocity;
  719. horizontal_velocity.SetY(0);
  720. mDebugRenderer->DrawText3D(inCharacterTransform.GetTranslation(), StringFormat("State: %s\nMat: %s\nHorizontal Vel: %.1f m/s\nVertical Vel: %.1f m/s", CharacterBase::sToString(ground_state), ground_material->GetDebugName(), (double)horizontal_velocity.Length(), (double)inCharacterVelocity.GetY()), Color::sWhite, 0.25f);
  721. }
  722. void CharacterBaseTest::DrawPaddedCharacter(const Shape *inShape, float inPadding, RMat44Arg inCenterOfMass)
  723. {
  724. if (inShape->GetSubType() == EShapeSubType::Capsule)
  725. {
  726. const CapsuleShape *capsule = static_cast<const CapsuleShape *>(inShape);
  727. mDebugRenderer->DrawCapsule(inCenterOfMass, capsule->GetHalfHeightOfCylinder(), capsule->GetRadius() + inPadding, Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  728. }
  729. else if (inShape->GetSubType() == EShapeSubType::Cylinder)
  730. {
  731. // Not correct as the edges should be rounded
  732. const CylinderShape *cylinder = static_cast<const CylinderShape *>(inShape);
  733. mDebugRenderer->DrawCylinder(inCenterOfMass, cylinder->GetHalfHeight() + inPadding, cylinder->GetRadius() + inPadding, Color::sGrey, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  734. }
  735. else if (inShape->GetSubType() == EShapeSubType::Box)
  736. {
  737. // Not correct as the edges should be rounded
  738. const BoxShape *box = static_cast<const BoxShape *>(inShape);
  739. AABox bounds = box->GetLocalBounds();
  740. bounds.ExpandBy(Vec3::sReplicate(inPadding));
  741. mDebugRenderer->DrawWireBox(inCenterOfMass, bounds, Color::sGrey);
  742. }
  743. else if (inShape->GetSubType() == EShapeSubType::RotatedTranslated)
  744. {
  745. const RotatedTranslatedShape *rt = static_cast<const RotatedTranslatedShape *>(inShape);
  746. DrawPaddedCharacter(rt->GetInnerShape(), inPadding, inCenterOfMass);
  747. }
  748. else if (inShape->GetType() == EShapeType::Compound)
  749. {
  750. const CompoundShape *compound = static_cast<const CompoundShape *>(inShape);
  751. for (const CompoundShape::SubShape &sub_shape : compound->GetSubShapes())
  752. DrawPaddedCharacter(sub_shape.mShape, inPadding, inCenterOfMass * sub_shape.GetLocalTransformNoScale(Vec3::sOne()));
  753. }
  754. }