2
0

SamplesApp.h 9.6 KB

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