SamplesApp.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Application/Application.h>
  6. #include <UI/UIManager.h>
  7. #include <Application/DebugUI.h>
  8. #include <Jolt/Physics/Collision/CollideShape.h>
  9. #include <Jolt/Skeleton/SkeletonPose.h>
  10. #include <Tests/Test.h>
  11. #include <Utils/ContactListenerImpl.h>
  12. #include <Renderer/DebugRendererImp.h>
  13. #include <Jolt/Physics/StateRecorderImpl.h>
  14. #include <Layers.h>
  15. namespace JPH {
  16. class JobSystem;
  17. class TempAllocator;
  18. };
  19. // Application class that runs the samples
  20. class SamplesApp : public Application
  21. {
  22. public:
  23. // Constructor / destructor
  24. SamplesApp();
  25. virtual ~SamplesApp() override;
  26. // Render the frame.
  27. virtual bool RenderFrame(float inDeltaTime) override;
  28. // Override to specify the initial camera state (local to GetCameraPivot)
  29. virtual void GetInitialCamera(CameraState &ioState) const override;
  30. // Override to specify a camera pivot point and orientation (world space)
  31. virtual RMat44 GetCameraPivot(float inCameraHeading, float inCameraPitch) const override;
  32. // Get scale factor for this world, used to boost camera speed and to scale detail of the shadows
  33. virtual float GetWorldScale() const override;
  34. private:
  35. // Start running a new test
  36. void StartTest(const RTTI *inRTTI);
  37. // Run all tests one by one
  38. void RunAllTests();
  39. // Run the next test. Returns false when the application should exit.
  40. bool NextTest();
  41. // Check if we've got to start the next test. Returns false when the application should exit.
  42. bool CheckNextTest();
  43. // Create a snapshot of the physics system and save it to disc
  44. void TakeSnapshot();
  45. // Create a snapshot of the physics system, save it to disc and immediately reload it
  46. void TakeAndReloadSnapshot();
  47. // Probing the collision world
  48. RefConst<Shape> CreateProbeShape();
  49. bool CastProbe(float inProbeLength, float &outFraction, RVec3 &outPosition, BodyID &outID);
  50. // Shooting an object
  51. RefConst<Shape> CreateShootObjectShape();
  52. void ShootObject();
  53. // Debug functionality: firing a ball, mouse dragging
  54. void UpdateDebug(float inDeltaTime);
  55. // Draw the state of the physics system
  56. void DrawPhysics();
  57. // Update the physics system with a fixed delta time
  58. void StepPhysics(JobSystem *inJobSystem);
  59. // Save state of simulation
  60. void SaveState(StateRecorderImpl &inStream);
  61. // Restore state of simulation
  62. void RestoreState(StateRecorderImpl &inStream);
  63. // Compare current physics state with inExpectedState
  64. void ValidateState(StateRecorderImpl &inExpectedState);
  65. // Global settings
  66. int mMaxConcurrentJobs = thread::hardware_concurrency(); // How many jobs to run in parallel
  67. float mUpdateFrequency = 60.0f; // Physics update frequency
  68. int mCollisionSteps = 1; // How many collision detection steps per physics update
  69. TempAllocator * mTempAllocator = nullptr; // Allocator for temporary allocations
  70. JobSystem * mJobSystem = nullptr; // The job system that runs physics jobs
  71. JobSystem * mJobSystemValidating = nullptr; // The job system to use when validating determinism
  72. BPLayerInterfaceImpl mBroadPhaseLayerInterface; // The broadphase layer interface that maps object layers to broadphase layers
  73. ObjectVsBroadPhaseLayerFilterImpl mObjectVsBroadPhaseLayerFilter; // Class that filters object vs broadphase layers
  74. ObjectLayerPairFilterImpl mObjectVsObjectLayerFilter; // Class that filters object vs object layers
  75. PhysicsSystem * mPhysicsSystem = nullptr; // The physics system that simulates the world
  76. ContactListenerImpl * mContactListener = nullptr; // Contact listener implementation
  77. PhysicsSettings mPhysicsSettings; // Main physics simulation settings
  78. // Drawing settings
  79. #ifdef JPH_DEBUG_RENDERER
  80. bool mDrawGetTriangles = false; // Draw all shapes using Shape::GetTrianglesStart/Next
  81. bool mDrawConstraints = false; // If the constraints should be drawn
  82. bool mDrawConstraintLimits = false; // If the constraint limits should be drawn
  83. bool mDrawConstraintReferenceFrame = false; // If the constraint reference frames should be drawn
  84. BodyManager::DrawSettings mBodyDrawSettings; // Settings for how to draw bodies from the body manager
  85. SkeletonPose::DrawSettings mPoseDrawSettings; // Settings for drawing skeletal poses
  86. #endif // JPH_DEBUG_RENDERER
  87. // Drawing using GetTriangles interface
  88. using ShapeToGeometryMap = UnorderedMap<RefConst<Shape>, DebugRenderer::GeometryRef>;
  89. ShapeToGeometryMap mShapeToGeometry;
  90. // The test to run
  91. const RTTI * mTestClass = nullptr; // RTTI information for the test we're currently running
  92. Test * mTest = nullptr; // The test we're currently running
  93. UITextButton * mTestSettingsButton = nullptr; // Button that activates the menu that the test uses to configure additional settings
  94. // Automatic cycling through tests
  95. Array<const RTTI *> mTestsToRun; // The list of tests that are still waiting to be run
  96. float mTestTimeLeft = -1.0f; // How many seconds the test is still supposed to run
  97. bool mExitAfterRunningTests = false; // When true, the application will quit when mTestsToRun becomes empty
  98. UITextButton * mNextTestButton = nullptr; // Button that activates the next test when we're running all tests
  99. // Test settings
  100. bool mInstallContactListener = false; // When true, the contact listener is installed the next time the test is reset
  101. // State recording and determinism checks
  102. bool mRecordState = false; // When true, the state of the physics system is recorded in mPlaybackFrames every physics update
  103. bool mCheckDeterminism = false; // When true, the physics state is rolled back after every update and run again to verify that the state is the same
  104. Array<StateRecorderImpl> mPlaybackFrames; // A list of recorded world states, one per physics simulation step
  105. enum class EPlaybackMode
  106. {
  107. Rewind,
  108. StepBack,
  109. Stop,
  110. StepForward,
  111. FastForward,
  112. Play
  113. };
  114. EPlaybackMode mPlaybackMode = EPlaybackMode::Play; // Current playback state. Indicates if we're playing or scrubbing back/forward.
  115. int mCurrentPlaybackFrame = -1; // Current playback frame
  116. // Which mode the probe is operating in.
  117. enum class EProbeMode
  118. {
  119. Pick,
  120. Ray,
  121. RayCollector,
  122. CollidePoint,
  123. CollideShape,
  124. CastShape,
  125. CollideSoftBody,
  126. TransformedShape,
  127. GetTriangles,
  128. BroadPhaseRay,
  129. BroadPhaseBox,
  130. BroadPhaseSphere,
  131. BroadPhasePoint,
  132. BroadPhaseOrientedBox,
  133. BroadPhaseCastBox,
  134. };
  135. // Which probe shape to use.
  136. enum class EProbeShape
  137. {
  138. Sphere,
  139. Box,
  140. ConvexHull,
  141. Capsule,
  142. TaperedCapsule,
  143. Cylinder,
  144. Triangle,
  145. StaticCompound,
  146. StaticCompound2,
  147. MutableCompound,
  148. Mesh,
  149. };
  150. // Probe settings
  151. EProbeMode mProbeMode = EProbeMode::Pick; // Mouse probe mode. Determines what happens under the crosshair.
  152. EProbeShape mProbeShape = EProbeShape::Sphere; // Shape to use for the mouse probe.
  153. bool mScaleShape = false; // If the shape is scaled or not. When true mShapeScale is taken into account.
  154. Vec3 mShapeScale = Vec3::sReplicate(1.0f); // Scale in local space for the probe shape.
  155. EBackFaceMode mBackFaceMode = EBackFaceMode::CollideWithBackFaces; // How to handle back facing triangles when doing a collision probe check.
  156. EActiveEdgeMode mActiveEdgeMode = EActiveEdgeMode::CollideOnlyWithActive; // How to handle active edges when doing a collision probe check.
  157. ECollectFacesMode mCollectFacesMode = ECollectFacesMode::NoFaces; // If we should collect colliding faces
  158. float mMaxSeparationDistance = 0.0f; // Max separation distance for collide shape test
  159. bool mTreatConvexAsSolid = true; // For ray casts if the shape should be treated as solid or if the ray should only collide with the surface
  160. bool mReturnDeepestPoint = true; // For shape casts, when true this will return the deepest point
  161. bool mUseShrunkenShapeAndConvexRadius = false; // Shrink then expand the shape by the convex radius
  162. bool mDrawSupportingFace = false; // Draw the result of GetSupportingFace
  163. int mMaxHits = 10; // The maximum number of hits to request for a collision probe.
  164. // Which object to shoot
  165. enum class EShootObjectShape
  166. {
  167. Sphere,
  168. ConvexHull,
  169. ThinBar,
  170. SoftBodyCube,
  171. };
  172. // Shoot object settings
  173. EShootObjectShape mShootObjectShape = EShootObjectShape::Sphere; // Type of object to shoot
  174. float mShootObjectVelocity = 20.0f; // Speed at which objects are ejected
  175. EMotionQuality mShootObjectMotionQuality = EMotionQuality::Discrete; // Motion quality for the object that we're shooting
  176. float mShootObjectFriction = 0.2f; // Friction for the object that is shot
  177. float mShootObjectRestitution = 0.0f; // Restitution for the object that is shot
  178. bool mShootObjectScaleShape = false; // If the shape should be scaled
  179. Vec3 mShootObjectShapeScale = Vec3::sReplicate(1.0f); // Scale of the object to shoot
  180. // Mouse dragging
  181. Body * mDragAnchor = nullptr; // Rigid bodies only: A anchor point for the distance constraint. Corresponds to the current crosshair position.
  182. BodyID mDragBody; // The body ID of the body that the user is currently dragging.
  183. Ref<Constraint> mDragConstraint; // Rigid bodies only: The distance constraint that connects the body to be dragged and the anchor point.
  184. uint mDragVertexIndex = ~uint(0); // Soft bodies only: The vertex index of the body that the user is currently dragging.
  185. float mDragVertexPreviousInvMass = 0.0f; // Soft bodies only: The inverse mass of the vertex that the user is currently dragging.
  186. float mDragFraction; // Fraction along cDragRayLength (see cpp) where the hit occurred. This will be combined with the crosshair position to get a 3d anchor point.
  187. // Timing
  188. uint mStepNumber = 0; // Which step number we're accumulating
  189. chrono::microseconds mTotalTime { 0 }; // How many nano seconds we spent simulating
  190. };