BoatTest.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2024 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/Water/BoatTest.h>
  6. #include <Jolt/Core/QuickSort.h>
  7. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  8. #include <Jolt/Physics/Collision/Shape/CylinderShape.h>
  9. #include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
  10. #include <Jolt/Physics/Collision/Shape/OffsetCenterOfMassShape.h>
  11. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  12. #include <Layers.h>
  13. #include <Renderer/DebugRendererImp.h>
  14. JPH_IMPLEMENT_RTTI_VIRTUAL(BoatTest)
  15. {
  16. JPH_ADD_BASE_CLASS(BoatTest, Test)
  17. }
  18. void BoatTest::Initialize()
  19. {
  20. // Create boat
  21. ConvexHullShapeSettings boat_hull;
  22. boat_hull.mPoints = {
  23. Vec3(-cHalfBoatTopWidth, cHalfBoatHeight, -cHalfBoatLength),
  24. Vec3(cHalfBoatTopWidth, cHalfBoatHeight, -cHalfBoatLength),
  25. Vec3(-cHalfBoatTopWidth, cHalfBoatHeight, cHalfBoatLength),
  26. Vec3(cHalfBoatTopWidth, cHalfBoatHeight, cHalfBoatLength),
  27. Vec3(-cHalfBoatBottomWidth, -cHalfBoatHeight, -cHalfBoatLength),
  28. Vec3(cHalfBoatBottomWidth, -cHalfBoatHeight, -cHalfBoatLength),
  29. Vec3(-cHalfBoatBottomWidth, -cHalfBoatHeight, cHalfBoatLength),
  30. Vec3(cHalfBoatBottomWidth, -cHalfBoatHeight, cHalfBoatLength),
  31. Vec3(0, cHalfBoatHeight, cHalfBoatLength + cBoatBowLength)
  32. };
  33. boat_hull.SetEmbedded();
  34. OffsetCenterOfMassShapeSettings com_offset(Vec3(0, -cHalfBoatHeight, 0), &boat_hull);
  35. com_offset.SetEmbedded();
  36. RVec3 position(0, cMaxWaterHeight + 2, 0);
  37. BodyCreationSettings boat(&com_offset, position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  38. boat.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  39. boat.mMassPropertiesOverride.mMass = cBoatMass;
  40. mBoatBody = mBodyInterface->CreateBody(boat);
  41. mBodyInterface->AddBody(mBoatBody->GetID(), EActivation::Activate);
  42. // Create water sensor. We use this to detect which bodies entered the water (in this sample we could have assumed everything is in the water)
  43. BodyCreationSettings water_sensor(new BoxShape(Vec3(cWaterWidth, cMaxWaterHeight, cWaterWidth)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::SENSOR);
  44. water_sensor.mIsSensor = true;
  45. mWaterSensor = mBodyInterface->CreateAndAddBody(water_sensor, EActivation::Activate);
  46. // Create some barrels to float in the water
  47. default_random_engine random;
  48. BodyCreationSettings barrel(new CylinderShape(1.0f, 0.7f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  49. barrel.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  50. barrel.mMassPropertiesOverride.mMass = cBarrelMass;
  51. for (int i = 0; i < 10; ++i)
  52. {
  53. barrel.mPosition = RVec3(-10.0f + i * 2.0f, cMaxWaterHeight + 2, 10);
  54. barrel.mRotation = Quat::sRandom(random);
  55. mBodyInterface->CreateAndAddBody(barrel, EActivation::Activate);
  56. }
  57. UpdateCameraPivot();
  58. }
  59. void BoatTest::ProcessInput(const ProcessInputParams &inParams)
  60. {
  61. // Determine acceleration and brake
  62. mForward = 0.0f;
  63. if (inParams.mKeyboard->IsKeyPressed(EKey::Up))
  64. mForward = 1.0f;
  65. else if (inParams.mKeyboard->IsKeyPressed(EKey::Down))
  66. mForward = -1.0f;
  67. // Steering
  68. mRight = 0.0f;
  69. if (inParams.mKeyboard->IsKeyPressed(EKey::Left))
  70. mRight = -1.0f;
  71. else if (inParams.mKeyboard->IsKeyPressed(EKey::Right))
  72. mRight = 1.0f;
  73. }
  74. RVec3 BoatTest::GetWaterSurfacePosition(RVec3Arg inXZPosition) const
  75. {
  76. return RVec3(inXZPosition.GetX(), cMinWaterHeight + Sin(0.1f * float(inXZPosition.GetZ()) + mTime) * (cMaxWaterHeight - cMinWaterHeight), inXZPosition.GetZ());
  77. }
  78. void BoatTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  79. {
  80. // Update time
  81. mTime += inParams.mDeltaTime;
  82. // Draw the water surface
  83. const float step = 1.0f;
  84. for (float z = -cWaterWidth; z < cWaterWidth; z += step)
  85. {
  86. RVec3 p1 = GetWaterSurfacePosition(RVec3(-cWaterWidth, 0, z));
  87. RVec3 p2 = GetWaterSurfacePosition(RVec3(-cWaterWidth, 0, z + step));
  88. RVec3 p3 = GetWaterSurfacePosition(RVec3(cWaterWidth, 0, z));
  89. RVec3 p4 = GetWaterSurfacePosition(RVec3(cWaterWidth, 0, z + step));
  90. mDebugRenderer->DrawTriangle(p1, p2, p3, Color::sBlue);
  91. mDebugRenderer->DrawTriangle(p2, p4, p3, Color::sBlue);
  92. }
  93. // Apply buoyancy to all bodies in the water
  94. {
  95. lock_guard<Mutex> lock(mBodiesInWaterMutex);
  96. for (const BodyID &id : mBodiesInWater)
  97. {
  98. BodyLockWrite body_lock(mPhysicsSystem->GetBodyLockInterface(), id);
  99. Body &body = body_lock.GetBody();
  100. if (body.IsActive())
  101. {
  102. // Use center of mass position to determine water surface position (you could test multiple points on the actual shape of the boat to get a more accurate result)
  103. RVec3 surface_position = GetWaterSurfacePosition(body.GetCenterOfMassPosition());
  104. // Crude way of approximating the surface normal
  105. RVec3 p2 = GetWaterSurfacePosition(body.GetCenterOfMassPosition() + Vec3(0, 0, 1));
  106. RVec3 p3 = GetWaterSurfacePosition(body.GetCenterOfMassPosition() + Vec3(1, 0, 0));
  107. Vec3 surface_normal = Vec3(p2 - surface_position).Cross(Vec3(p3 - surface_position)).Normalized();
  108. // Determine buoyancy and drag
  109. float buoyancy, linear_drag, angular_drag;
  110. if (id == mBoatBody->GetID())
  111. {
  112. buoyancy = cBoatBuoyancy;
  113. linear_drag = cBoatLinearDrag;
  114. angular_drag = cBoatAngularDrag;
  115. }
  116. else
  117. {
  118. buoyancy = cBarrelBuoyancy;
  119. linear_drag = cBarrelLinearDrag;
  120. angular_drag = cBarrelAngularDrag;
  121. }
  122. // Apply buoyancy to the body
  123. body.ApplyBuoyancyImpulse(surface_position, surface_normal, buoyancy, linear_drag, angular_drag, Vec3::sZero(), mPhysicsSystem->GetGravity(), inParams.mDeltaTime);
  124. }
  125. }
  126. }
  127. // On user input, assure that the boat is active
  128. if (mRight != 0.0f || mForward != 0.0f)
  129. mBodyInterface->ActivateBody(mBoatBody->GetID());
  130. // Apply forces to rear of boat where the propeller would be but only when the propeller is under water
  131. RVec3 propeller_position = mBoatBody->GetWorldTransform() * Vec3(0, -cHalfBoatHeight, -cHalfBoatLength);
  132. RVec3 propeller_surface_position = GetWaterSurfacePosition(propeller_position);
  133. if (propeller_surface_position.GetY() > propeller_position.GetY())
  134. {
  135. Vec3 forward = mBoatBody->GetRotation().RotateAxisZ();
  136. Vec3 right = mBoatBody->GetRotation().RotateAxisX();
  137. mBoatBody->AddImpulse((forward * mForward * cForwardAcceleration + right * Sign(mForward) * mRight * cSteerAcceleration) * cBoatMass * inParams.mDeltaTime, propeller_position);
  138. }
  139. UpdateCameraPivot();
  140. }
  141. void BoatTest::SaveInputState(StateRecorder &inStream) const
  142. {
  143. inStream.Write(mForward);
  144. inStream.Write(mRight);
  145. }
  146. void BoatTest::RestoreInputState(StateRecorder &inStream)
  147. {
  148. inStream.Read(mForward);
  149. inStream.Read(mRight);
  150. }
  151. void BoatTest::SaveState(StateRecorder &inStream) const
  152. {
  153. inStream.Write(mTime);
  154. inStream.Write(mBodiesInWater);
  155. }
  156. void BoatTest::RestoreState(StateRecorder &inStream)
  157. {
  158. inStream.Read(mTime);
  159. inStream.Read(mBodiesInWater);
  160. }
  161. void BoatTest::GetInitialCamera(CameraState &ioState) const
  162. {
  163. // Position camera behind boat
  164. RVec3 cam_tgt = RVec3(0, 0, 5);
  165. ioState.mPos = RVec3(0, 5, -10);
  166. ioState.mForward = Vec3(cam_tgt - ioState.mPos).Normalized();
  167. }
  168. void BoatTest::UpdateCameraPivot()
  169. {
  170. // Pivot is center of boat and rotates with boat around Y axis only
  171. Vec3 fwd = mBoatBody->GetRotation().RotateAxisZ();
  172. fwd.SetY(0.0f);
  173. float len = fwd.Length();
  174. if (len != 0.0f)
  175. fwd /= len;
  176. else
  177. fwd = Vec3::sAxisZ();
  178. Vec3 up = Vec3::sAxisY();
  179. Vec3 right = up.Cross(fwd);
  180. mCameraPivot = RMat44(Vec4(right, 0), Vec4(up, 0), Vec4(fwd, 0), mBoatBody->GetPosition());
  181. }
  182. void BoatTest::OnContactAdded(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &ioSettings)
  183. {
  184. // When a body enters the water add it to the list of bodies in the water
  185. lock_guard<Mutex> lock(mBodiesInWaterMutex);
  186. if (inBody1.GetID() == mWaterSensor)
  187. mBodiesInWater.push_back(inBody2.GetID());
  188. else if (inBody2.GetID() == mWaterSensor)
  189. mBodiesInWater.push_back(inBody1.GetID());
  190. QuickSort(mBodiesInWater.begin(), mBodiesInWater.end()); // Sort to make deterministic (OnContactAdded is called from multiple threads and the order is not guaranteed)
  191. }
  192. void BoatTest::OnContactRemoved(const SubShapeIDPair &inSubShapePair)
  193. {
  194. // When a body leaves the water remove it from the list of bodies in the water
  195. lock_guard<Mutex> lock(mBodiesInWaterMutex);
  196. if (inSubShapePair.GetBody1ID() == mWaterSensor)
  197. mBodiesInWater.erase(std::find(mBodiesInWater.begin(), mBodiesInWater.end(), inSubShapePair.GetBody2ID()));
  198. else if (inSubShapePair.GetBody2ID() == mWaterSensor)
  199. mBodiesInWater.erase(std::find(mBodiesInWater.begin(), mBodiesInWater.end(), inSubShapePair.GetBody1ID()));
  200. }