MotorcycleTest.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2023 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/Vehicle/MotorcycleTest.h>
  6. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  7. #include <Jolt/Physics/Collision/Shape/OffsetCenterOfMassShape.h>
  8. #include <Jolt/Physics/Vehicle/MotorcycleController.h>
  9. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  10. #include <Application/DebugUI.h>
  11. #include <Layers.h>
  12. #include <Renderer/DebugRendererImp.h>
  13. JPH_IMPLEMENT_RTTI_VIRTUAL(MotorcycleTest)
  14. {
  15. JPH_ADD_BASE_CLASS(MotorcycleTest, VehicleTest)
  16. }
  17. MotorcycleTest::~MotorcycleTest()
  18. {
  19. mPhysicsSystem->RemoveStepListener(mVehicleConstraint);
  20. }
  21. void MotorcycleTest::Initialize()
  22. {
  23. VehicleTest::Initialize();
  24. // Loosely based on: https://www.whitedogbikes.com/whitedogblog/yamaha-xj-900-specs/
  25. const float back_wheel_radius = 0.31f;
  26. const float back_wheel_width = 0.05f;
  27. const float back_wheel_pos_z = -0.75f;
  28. const float back_suspension_min_length = 0.3f;
  29. const float back_suspension_max_length = 0.5f;
  30. const float back_suspension_freq = 2.0f;
  31. const float back_brake_torque = 250.0f;
  32. const float front_wheel_radius = 0.31f;
  33. const float front_wheel_width = 0.05f;
  34. const float front_wheel_pos_z = 0.75f;
  35. const float front_suspension_min_length = 0.3f;
  36. const float front_suspension_max_length = 0.5f;
  37. const float front_suspension_freq = 1.5f;
  38. const float front_brake_torque = 500.0f;
  39. const float half_vehicle_length = 0.4f;
  40. const float half_vehicle_width = 0.2f;
  41. const float half_vehicle_height = 0.3f;
  42. const float max_steering_angle = DegreesToRadians(30);
  43. // Angle of the front suspension
  44. const float caster_angle = DegreesToRadians(30);
  45. // Create vehicle body
  46. RVec3 position(0, 2, 0);
  47. RefConst<Shape> motorcycle_shape = OffsetCenterOfMassShapeSettings(Vec3(0, -half_vehicle_height, 0), new BoxShape(Vec3(half_vehicle_width, half_vehicle_height, half_vehicle_length))).Create().Get();
  48. BodyCreationSettings motorcycle_body_settings(motorcycle_shape, position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  49. motorcycle_body_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  50. motorcycle_body_settings.mMassPropertiesOverride.mMass = 240.0f;
  51. mMotorcycleBody = mBodyInterface->CreateBody(motorcycle_body_settings);
  52. mBodyInterface->AddBody(mMotorcycleBody->GetID(), EActivation::Activate);
  53. // Create vehicle constraint
  54. VehicleConstraintSettings vehicle;
  55. vehicle.mDrawConstraintSize = 0.1f;
  56. vehicle.mMaxPitchRollAngle = DegreesToRadians(60.0f);
  57. // Wheels
  58. WheelSettingsWV *front = new WheelSettingsWV;
  59. front->mPosition = Vec3(0.0f, -0.9f * half_vehicle_height, front_wheel_pos_z);
  60. front->mMaxSteerAngle = max_steering_angle;
  61. front->mSuspensionDirection = Vec3(0, -1, Tan(caster_angle)).Normalized();
  62. front->mSteeringAxis = -front->mSuspensionDirection;
  63. front->mRadius = front_wheel_radius;
  64. front->mWidth = front_wheel_width;
  65. front->mSuspensionMinLength = front_suspension_min_length;
  66. front->mSuspensionMaxLength = front_suspension_max_length;
  67. front->mSuspensionSpring.mFrequency = front_suspension_freq;
  68. front->mMaxBrakeTorque = front_brake_torque;
  69. WheelSettingsWV *back = new WheelSettingsWV;
  70. back->mPosition = Vec3(0.0f, -0.9f * half_vehicle_height, back_wheel_pos_z);
  71. back->mMaxSteerAngle = 0.0f;
  72. back->mRadius = back_wheel_radius;
  73. back->mWidth = back_wheel_width;
  74. back->mSuspensionMinLength = back_suspension_min_length;
  75. back->mSuspensionMaxLength = back_suspension_max_length;
  76. back->mSuspensionSpring.mFrequency = back_suspension_freq;
  77. back->mMaxBrakeTorque = back_brake_torque;
  78. if (sOverrideFrontSuspensionForcePoint)
  79. {
  80. front->mEnableSuspensionForcePoint = true;
  81. front->mSuspensionForcePoint = front->mPosition + front->mSuspensionDirection * front->mSuspensionMinLength;
  82. }
  83. if (sOverrideRearSuspensionForcePoint)
  84. {
  85. back->mEnableSuspensionForcePoint = true;
  86. back->mSuspensionForcePoint = back->mPosition + back->mSuspensionDirection * back->mSuspensionMinLength;
  87. }
  88. vehicle.mWheels = { front, back };
  89. MotorcycleControllerSettings *controller = new MotorcycleControllerSettings;
  90. controller->mEngine.mMaxTorque = 150.0f;
  91. controller->mEngine.mMinRPM = 1000.0f;
  92. controller->mEngine.mMaxRPM = 10000.0f;
  93. controller->mTransmission.mShiftDownRPM = 2000.0f;
  94. controller->mTransmission.mShiftUpRPM = 8000.0f;
  95. controller->mTransmission.mGearRatios = { 2.27f, 1.63f, 1.3f, 1.09f, 0.96f, 0.88f }; // From: https://www.blocklayer.com/rpm-gear-bikes
  96. controller->mTransmission.mReverseGearRatios = { -4.0f };
  97. controller->mTransmission.mClutchStrength = 2.0f;
  98. vehicle.mController = controller;
  99. // Differential (not really applicable to a motorcycle but we need one anyway to drive it)
  100. controller->mDifferentials.resize(1);
  101. controller->mDifferentials[0].mLeftWheel = -1;
  102. controller->mDifferentials[0].mRightWheel = 1;
  103. controller->mDifferentials[0].mDifferentialRatio = 1.93f * 40.0f / 16.0f; // Combining primary and final drive (back divided by front sprockets) from: https://www.blocklayer.com/rpm-gear-bikes
  104. mVehicleConstraint = new VehicleConstraint(*mMotorcycleBody, vehicle);
  105. mVehicleConstraint->SetVehicleCollisionTester(new VehicleCollisionTesterCastCylinder(Layers::MOVING, 1.0f)); // Use half wheel width as convex radius so we get a rounded cylinder
  106. mPhysicsSystem->AddConstraint(mVehicleConstraint);
  107. mPhysicsSystem->AddStepListener(mVehicleConstraint);
  108. UpdateCameraPivot();
  109. }
  110. void MotorcycleTest::ProcessInput(const ProcessInputParams &inParams)
  111. {
  112. // Determine acceleration and brake
  113. mForward = 0.0f;
  114. mBrake = 0.0f;
  115. if (inParams.mKeyboard->IsKeyPressed(DIK_Z))
  116. mBrake = 1.0f;
  117. else if (inParams.mKeyboard->IsKeyPressed(DIK_UP))
  118. mForward = 1.0f;
  119. else if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN))
  120. mForward = -1.0f;
  121. // Check if we're reversing direction
  122. if (mPreviousForward * mForward < 0.0f)
  123. {
  124. // Get vehicle velocity in local space to the body of the vehicle
  125. float velocity = (mMotorcycleBody->GetRotation().Conjugated() * mMotorcycleBody->GetLinearVelocity()).GetZ();
  126. if ((mForward > 0.0f && velocity < -0.1f) || (mForward < 0.0f && velocity > 0.1f))
  127. {
  128. // Brake while we've not stopped yet
  129. mForward = 0.0f;
  130. mBrake = 1.0f;
  131. }
  132. else
  133. {
  134. // When we've come to a stop, accept the new direction
  135. mPreviousForward = mForward;
  136. }
  137. }
  138. // Steering
  139. float right = 0.0f;
  140. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT))
  141. right = -1.0f;
  142. else if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT))
  143. right = 1.0f;
  144. const float steer_speed = 4.0f;
  145. if (right > mRight)
  146. mRight = min(mRight + steer_speed * inParams.mDeltaTime, right);
  147. else if (right < mRight)
  148. mRight = max(mRight - steer_speed * inParams.mDeltaTime, right);
  149. // When leaned, we don't want to use the brakes fully as we'll spin out
  150. if (mBrake > 0.0f)
  151. {
  152. Vec3 world_up = -mPhysicsSystem->GetGravity().Normalized();
  153. Vec3 up = mMotorcycleBody->GetRotation() * mVehicleConstraint->GetLocalUp();
  154. Vec3 fwd = mMotorcycleBody->GetRotation() * mVehicleConstraint->GetLocalForward();
  155. float sin_lean_angle = abs(world_up.Cross(up).Dot(fwd));
  156. float brake_multiplier = Square(1.0f - sin_lean_angle);
  157. mBrake *= brake_multiplier;
  158. }
  159. }
  160. void MotorcycleTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  161. {
  162. VehicleTest::PrePhysicsUpdate(inParams);
  163. UpdateCameraPivot();
  164. // On user input, assure that the motorcycle is active
  165. if (mRight != 0.0f || mForward != 0.0f || mBrake != 0.0f)
  166. mBodyInterface->ActivateBody(mMotorcycleBody->GetID());
  167. // Pass the input on to the constraint
  168. MotorcycleController *controller = static_cast<MotorcycleController *>(mVehicleConstraint->GetController());
  169. controller->SetDriverInput(mForward, mRight, mBrake, false);
  170. controller->EnableLeanController(sEnableLeanController);
  171. // Draw our wheels (this needs to be done in the pre update since we draw the bodies too in the state before the step)
  172. for (uint w = 0; w < 2; ++w)
  173. {
  174. const WheelSettings *settings = mVehicleConstraint->GetWheels()[w]->GetSettings();
  175. RMat44 wheel_transform = mVehicleConstraint->GetWheelWorldTransform(w, Vec3::sAxisY(), Vec3::sAxisX()); // The cylinder we draw is aligned with Y so we specify that as rotational axis
  176. mDebugRenderer->DrawCylinder(wheel_transform, 0.5f * settings->mWidth, settings->mRadius, Color::sGreen);
  177. }
  178. }
  179. void MotorcycleTest::SaveInputState(StateRecorder &inStream) const
  180. {
  181. inStream.Write(mForward);
  182. inStream.Write(mPreviousForward);
  183. inStream.Write(mRight);
  184. inStream.Write(mBrake);
  185. }
  186. void MotorcycleTest::RestoreInputState(StateRecorder &inStream)
  187. {
  188. inStream.Read(mForward);
  189. inStream.Read(mPreviousForward);
  190. inStream.Read(mRight);
  191. inStream.Read(mBrake);
  192. }
  193. void MotorcycleTest::GetInitialCamera(CameraState &ioState) const
  194. {
  195. // Position camera behind motorcycle
  196. RVec3 cam_tgt = RVec3(0, 0, 5);
  197. ioState.mPos = RVec3(0, 2.5f, -5);
  198. ioState.mForward = Vec3(cam_tgt - ioState.mPos).Normalized();
  199. }
  200. void MotorcycleTest::UpdateCameraPivot()
  201. {
  202. // Pivot is center of motorcycle and rotates with motorcycle around Y axis only
  203. Vec3 fwd = mMotorcycleBody->GetRotation().RotateAxisZ();
  204. fwd.SetY(0.0f);
  205. float len = fwd.Length();
  206. if (len != 0.0f)
  207. fwd /= len;
  208. else
  209. fwd = Vec3::sAxisZ();
  210. Vec3 up = Vec3::sAxisY();
  211. Vec3 right = up.Cross(fwd);
  212. mCameraPivot = RMat44(Vec4(right, 0), Vec4(up, 0), Vec4(fwd, 0), mMotorcycleBody->GetPosition());
  213. }
  214. void MotorcycleTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  215. {
  216. VehicleTest::CreateSettingsMenu(inUI, inSubMenu);
  217. inUI->CreateCheckBox(inSubMenu, "Override Front Suspension Force Point", sOverrideFrontSuspensionForcePoint, [](UICheckBox::EState inState) { sOverrideFrontSuspensionForcePoint = inState == UICheckBox::STATE_CHECKED; });
  218. inUI->CreateCheckBox(inSubMenu, "Override Rear Suspension Force Point", sOverrideRearSuspensionForcePoint, [](UICheckBox::EState inState) { sOverrideRearSuspensionForcePoint = inState == UICheckBox::STATE_CHECKED; });
  219. inUI->CreateCheckBox(inSubMenu, "Enable Lean Controller", sEnableLeanController, [](UICheckBox::EState inState) { sEnableLeanController = inState == UICheckBox::STATE_CHECKED; });
  220. inUI->CreateTextButton(inSubMenu, "Accept", [this]() { RestartTest(); });
  221. }