VehicleTest.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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/Vehicle/VehicleTest.h>
  6. #include <Jolt/Physics/Constraints/DistanceConstraint.h>
  7. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  8. #include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
  9. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  10. #include <Jolt/Physics/Collision/GroupFilterTable.h>
  11. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  12. #include <Jolt/Physics/PhysicsScene.h>
  13. #include <Jolt/ObjectStream/ObjectStreamIn.h>
  14. #include <Layers.h>
  15. #include <Application/DebugUI.h>
  16. #include <Utils/Log.h>
  17. #include <Renderer/DebugRendererImp.h>
  18. JPH_IMPLEMENT_RTTI_VIRTUAL(VehicleTest)
  19. {
  20. JPH_ADD_BASE_CLASS(VehicleTest, Test)
  21. }
  22. const char *VehicleTest::sScenes[] =
  23. {
  24. "Flat",
  25. "Flat With Slope",
  26. "Steep Slope",
  27. "Step",
  28. "Dynamic Step",
  29. "Playground",
  30. "Loop",
  31. #ifdef JPH_OBJECT_STREAM
  32. "Terrain1",
  33. #endif // JPH_OBJECT_STREAM
  34. };
  35. const char *VehicleTest::sSceneName = "Playground";
  36. void VehicleTest::Initialize()
  37. {
  38. if (strcmp(sSceneName, "Flat") == 0)
  39. {
  40. // Flat test floor
  41. Body &floor = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(1000.0f, 1.0f, 1000.0f), 0.0f), RVec3(0.0f, -1.0f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  42. floor.SetFriction(1.0f);
  43. mBodyInterface->AddBody(floor.GetID(), EActivation::DontActivate);
  44. // Load a race track to have something to assess speed and steering behavior
  45. LoadRaceTrack("Assets/Racetracks/Zandvoort.csv");
  46. }
  47. else if (strcmp(sSceneName, "Flat With Slope") == 0)
  48. {
  49. const float cSlopeStartDistance = 100.0f;
  50. const float cSlopeLength = 100.0f;
  51. const float cSlopeAngle = DegreesToRadians(30.0f);
  52. // Flat test floor
  53. Body &floor = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(1000.0f, 1.0f, 1000.0f), 0.0f), RVec3(0.0f, -1.0f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  54. floor.SetFriction(1.0f);
  55. mBodyInterface->AddBody(floor.GetID(), EActivation::DontActivate);
  56. Body &slope_up = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(25.0f, 1.0f, cSlopeLength), 0.0f), RVec3(0.0f, cSlopeLength * Sin(cSlopeAngle) - 1.0f, cSlopeStartDistance + cSlopeLength * Cos(cSlopeAngle)), Quat::sRotation(Vec3::sAxisX(), -cSlopeAngle), EMotionType::Static, Layers::NON_MOVING));
  57. slope_up.SetFriction(1.0f);
  58. mBodyInterface->AddBody(slope_up.GetID(), EActivation::DontActivate);
  59. Body &slope_down = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(25.0f, 1.0f, cSlopeLength), 0.0f), RVec3(0.0f, cSlopeLength * Sin(cSlopeAngle) - 1.0f, cSlopeStartDistance + 3.0f * cSlopeLength * Cos(cSlopeAngle)), Quat::sRotation(Vec3::sAxisX(), cSlopeAngle), EMotionType::Static, Layers::NON_MOVING));
  60. slope_down.SetFriction(1.0f);
  61. mBodyInterface->AddBody(slope_down.GetID(), EActivation::DontActivate);
  62. }
  63. else if (strcmp(sSceneName, "Steep Slope") == 0)
  64. {
  65. // Steep slope test floor (20 degrees = 36% grade)
  66. Body &floor = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(1000.0f, 1.0f, 1000.0f), 0.0f), RVec3(0.0f, -1.0f, 0.0f), Quat::sRotation(Vec3::sAxisX(), DegreesToRadians(-20.0f)), EMotionType::Static, Layers::NON_MOVING));
  67. floor.SetFriction(1.0f);
  68. mBodyInterface->AddBody(floor.GetID(), EActivation::DontActivate);
  69. }
  70. else if (strcmp(sSceneName, "Step") == 0)
  71. {
  72. // Flat test floor
  73. Body &floor = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(1000.0f, 1.0f, 1000.0f), 0.0f), RVec3(0.0f, -1.0f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  74. floor.SetFriction(1.0f);
  75. mBodyInterface->AddBody(floor.GetID(), EActivation::DontActivate);
  76. // A 5cm step rotated under an angle
  77. constexpr float cStepHeight = 0.05f;
  78. Body &step = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(5.0f, 0.5f * cStepHeight, 5.0f), 0.0f), RVec3(-2.0f, 0.5f * cStepHeight, 60.0f), Quat::sRotation(Vec3::sAxisY(), -0.3f * JPH_PI), EMotionType::Static, Layers::NON_MOVING));
  79. step.SetFriction(1.0f);
  80. mBodyInterface->AddBody(step.GetID(), EActivation::DontActivate);
  81. }
  82. else if (strcmp(sSceneName, "Dynamic Step") == 0)
  83. {
  84. // Flat test floor
  85. Body &floor = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(1000.0f, 1.0f, 1000.0f), 0.0f), RVec3(0.0f, -1.0f, 0.0f), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  86. floor.SetFriction(1.0f);
  87. mBodyInterface->AddBody(floor.GetID(), EActivation::DontActivate);
  88. // A dynamic body that acts as a step to test sleeping behavior
  89. constexpr float cStepHeight = 0.05f;
  90. Body &step = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(15.0f, 0.5f * cStepHeight, 15.0f), 0.0f), RVec3(-2.0f, 0.5f * cStepHeight, 30.0f), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING));
  91. step.SetFriction(1.0f);
  92. mBodyInterface->AddBody(step.GetID(), EActivation::Activate);
  93. }
  94. else if (strcmp(sSceneName, "Playground") == 0)
  95. {
  96. // Scene with hilly terrain and some objects to drive into
  97. Body &floor = CreateMeshTerrain();
  98. floor.SetFriction(1.0f);
  99. CreateBridge();
  100. CreateWall();
  101. CreateRubble();
  102. }
  103. else if (strcmp(sSceneName, "Loop") == 0)
  104. {
  105. CreateFloor();
  106. TriangleList triangles;
  107. const int cNumSegments = 100;
  108. const float cLoopWidth = 20.0f;
  109. const float cLoopRadius = 20.0f;
  110. const float cLoopThickness = 0.5f;
  111. Vec3 prev_center = Vec3::sZero();
  112. Vec3 prev_center_bottom = Vec3::sZero();
  113. for (int i = 0; i < cNumSegments; ++i)
  114. {
  115. float angle = i * 2.0f * JPH_PI / (cNumSegments - 1);
  116. Vec3 radial(0, -Cos(angle), Sin(angle));
  117. Vec3 center = Vec3(-i * cLoopWidth / (cNumSegments - 1), cLoopRadius, cLoopRadius) + cLoopRadius * radial;
  118. Vec3 half_width(0.5f * cLoopWidth, 0, 0);
  119. Vec3 center_bottom = center + cLoopThickness * radial;
  120. if (i > 0)
  121. {
  122. // Top surface
  123. triangles.push_back(Triangle(prev_center + half_width, prev_center - half_width, center - half_width));
  124. triangles.push_back(Triangle(prev_center + half_width, center - half_width, center + half_width));
  125. // Bottom surface
  126. triangles.push_back(Triangle(prev_center_bottom + half_width, center_bottom - half_width, prev_center_bottom - half_width));
  127. triangles.push_back(Triangle(prev_center_bottom + half_width, center_bottom + half_width, center_bottom - half_width));
  128. // Sides
  129. triangles.push_back(Triangle(prev_center + half_width, center + half_width, prev_center_bottom + half_width));
  130. triangles.push_back(Triangle(prev_center_bottom + half_width, center + half_width, center_bottom + half_width));
  131. triangles.push_back(Triangle(prev_center - half_width, prev_center_bottom - half_width, center - half_width));
  132. triangles.push_back(Triangle(prev_center_bottom - half_width, center_bottom - half_width, center - half_width));
  133. }
  134. prev_center = center;
  135. prev_center_bottom = center_bottom;
  136. }
  137. MeshShapeSettings mesh(triangles);
  138. mesh.SetEmbedded();
  139. Body &loop = *mBodyInterface->CreateBody(BodyCreationSettings(&mesh, RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  140. loop.SetFriction(1.0f);
  141. mBodyInterface->AddBody(loop.GetID(), EActivation::Activate);
  142. }
  143. #ifdef JPH_OBJECT_STREAM
  144. else
  145. {
  146. // Load scene
  147. Ref<PhysicsScene> scene;
  148. if (!ObjectStreamIn::sReadObject((String("Assets/") + sSceneName + ".bof").c_str(), scene))
  149. FatalError("Failed to load scene");
  150. for (BodyCreationSettings &body : scene->GetBodies())
  151. body.mObjectLayer = Layers::NON_MOVING;
  152. scene->FixInvalidScales();
  153. scene->CreateBodies(mPhysicsSystem);
  154. }
  155. #endif // JPH_OBJECT_STREAM
  156. }
  157. void VehicleTest::CreateBridge()
  158. {
  159. const int cChainLength = 20;
  160. // Build a collision group filter that disables collision between adjacent bodies
  161. Ref<GroupFilterTable> group_filter = new GroupFilterTable(cChainLength);
  162. for (CollisionGroup::SubGroupID i = 0; i < cChainLength - 1; ++i)
  163. group_filter->DisableCollision(i, i + 1);
  164. Vec3 part_half_size = Vec3(2.5f, 0.25f, 1.0f);
  165. RefConst<Shape> part_shape = new BoxShape(part_half_size);
  166. Vec3 large_part_half_size = Vec3(2.5f, 0.25f, 22.5f);
  167. RefConst<Shape> large_part_shape = new BoxShape(large_part_half_size);
  168. Quat first_part_rot = Quat::sRotation(Vec3::sAxisX(), DegreesToRadians(-10.0f));
  169. RVec3 prev_pos(-25, 7, 0);
  170. Body *prev_part = nullptr;
  171. for (int i = 0; i < cChainLength; ++i)
  172. {
  173. RVec3 pos = prev_pos + Vec3(0, 0, 2.0f * part_half_size.GetZ());
  174. Body &part = i == 0? *mBodyInterface->CreateBody(BodyCreationSettings(large_part_shape, pos - first_part_rot * Vec3(0, large_part_half_size.GetY() - part_half_size.GetY(), large_part_half_size.GetZ() - part_half_size.GetZ()), first_part_rot, EMotionType::Static, Layers::NON_MOVING))
  175. : *mBodyInterface->CreateBody(BodyCreationSettings(part_shape, pos, Quat::sIdentity(), i == 19? EMotionType::Static : EMotionType::Dynamic, i == 19? Layers::NON_MOVING : Layers::MOVING));
  176. part.SetCollisionGroup(CollisionGroup(group_filter, 1, CollisionGroup::SubGroupID(i)));
  177. part.SetFriction(1.0f);
  178. mBodyInterface->AddBody(part.GetID(), EActivation::Activate);
  179. if (prev_part != nullptr)
  180. {
  181. DistanceConstraintSettings dc;
  182. dc.mPoint1 = prev_pos + Vec3(-part_half_size.GetX(), 0, part_half_size.GetZ());
  183. dc.mPoint2 = pos + Vec3(-part_half_size.GetX(), 0, -part_half_size.GetZ());
  184. mPhysicsSystem->AddConstraint(dc.Create(*prev_part, part));
  185. dc.mPoint1 = prev_pos + Vec3(part_half_size.GetX(), 0, part_half_size.GetZ());
  186. dc.mPoint2 = pos + Vec3(part_half_size.GetX(), 0, -part_half_size.GetZ());
  187. mPhysicsSystem->AddConstraint(dc.Create(*prev_part, part));
  188. }
  189. prev_part = &part;
  190. prev_pos = pos;
  191. }
  192. }
  193. void VehicleTest::CreateWall()
  194. {
  195. RefConst<Shape> box_shape = new BoxShape(Vec3(0.5f, 0.5f, 0.5f));
  196. for (int i = 0; i < 3; ++i)
  197. for (int j = i / 2; j < 5 - (i + 1) / 2; ++j)
  198. {
  199. RVec3 position(2.0f + j * 1.0f + (i & 1? 0.5f : 0.0f), 2.0f + i * 1.0f, 10.0f);
  200. mBodyInterface->CreateAndAddBody(BodyCreationSettings(box_shape, position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING), EActivation::Activate);
  201. }
  202. }
  203. void VehicleTest::CreateRubble()
  204. {
  205. // Flat and light objects
  206. RefConst<Shape> box_shape = new BoxShape(Vec3(0.5f, 0.1f, 0.5f));
  207. for (int i = 0; i < 5; ++i)
  208. for (int j = 0; j < 5; ++j)
  209. {
  210. RVec3 position(-5.0f + j, 2.0f + i * 0.2f, 10.0f + 0.5f * i);
  211. mBodyInterface->CreateAndAddBody(BodyCreationSettings(box_shape, position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING), EActivation::Activate);
  212. }
  213. // Light convex shapes
  214. default_random_engine random;
  215. uniform_real_distribution<float> hull_size(0.2f, 0.4f);
  216. for (int i = 0; i < 10; ++i)
  217. for (int j = 0; j < 10; ++j)
  218. {
  219. // Create random points
  220. Array<Vec3> points;
  221. for (int k = 0; k < 20; ++k)
  222. points.push_back(hull_size(random) * Vec3::sRandom(random));
  223. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new ConvexHullShapeSettings(points), RVec3(-5.0f + 0.5f * j, 2.0f, 15.0f + 0.5f * i), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING), EActivation::Activate);
  224. }
  225. }
  226. void VehicleTest::LoadRaceTrack(const char *inFileName)
  227. {
  228. // Open the track file
  229. std::ifstream stream;
  230. stream.open(inFileName, std::ifstream::in);
  231. if (!stream.is_open())
  232. return;
  233. // Ignore header line
  234. String line;
  235. std::getline(stream, line);
  236. // Read coordinates
  237. struct Segment
  238. {
  239. RVec3 mCenter;
  240. float mWidthLeft;
  241. float mWidthRight;
  242. };
  243. Array<Segment> segments;
  244. Real x, y;
  245. float wl, wr;
  246. char c;
  247. RVec3 track_center = RVec3::sZero();
  248. while (stream >> x >> c >> y >> c >> wl >> c >> wr)
  249. {
  250. RVec3 center(x, 0, -y);
  251. segments.push_back({ center, wl, wr });
  252. track_center += center;
  253. }
  254. if (!segments.empty())
  255. track_center /= (float)segments.size();
  256. // Convert to line segments
  257. RVec3 prev_tleft = RVec3::sZero(), prev_tright = RVec3::sZero();
  258. for (size_t i = 0; i < segments.size(); ++i)
  259. {
  260. const Segment &segment = segments[i];
  261. const Segment &next_segment = segments[(i + 1) % segments.size()];
  262. // Calculate left and right point of the track
  263. Vec3 fwd = Vec3(next_segment.mCenter - segment.mCenter);
  264. Vec3 right = fwd.Cross(Vec3::sAxisY()).Normalized();
  265. RVec3 tcenter = segment.mCenter - track_center + Vec3(0, 0.1f, 0); // Put a bit above the floor to avoid z fighting
  266. RVec3 tleft = tcenter - right * segment.mWidthLeft;
  267. RVec3 tright = tcenter + right * segment.mWidthRight;
  268. mTrackData.push_back({ tleft, tright });
  269. // Connect left and right point with the previous left and right point
  270. if (i > 0)
  271. {
  272. mTrackData.push_back({ prev_tleft, tleft });
  273. mTrackData.push_back({ prev_tright, tright });
  274. }
  275. prev_tleft = tleft;
  276. prev_tright = tright;
  277. }
  278. }
  279. void VehicleTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  280. {
  281. // Render the track
  282. for (const Line &l : mTrackData)
  283. mDebugRenderer->DrawLine(l.mStart, l.mEnd, Color::sBlack);
  284. }
  285. void VehicleTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  286. {
  287. inUI->CreateTextButton(inSubMenu, "Select Scene", [this, inUI]() {
  288. UIElement *scene_name = inUI->CreateMenu();
  289. for (uint i = 0; i < size(sScenes); ++i)
  290. inUI->CreateTextButton(scene_name, sScenes[i], [this, i]() { sSceneName = sScenes[i]; RestartTest(); });
  291. inUI->ShowMenu(scene_name);
  292. });
  293. }