SamplesApp.cpp 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <SamplesApp.h>
  5. #include <Application/EntryPoint.h>
  6. #include <Jolt/Core/JobSystemThreadPool.h>
  7. #include <Jolt/Core/TempAllocator.h>
  8. #include <Jolt/Core/StreamWrapper.h>
  9. #include <Jolt/Geometry/OrientedBox.h>
  10. #include <Jolt/Physics/PhysicsSystem.h>
  11. #include <Jolt/Physics/StateRecorderImpl.h>
  12. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  13. #include <Jolt/Physics/PhysicsScene.h>
  14. #include <Jolt/Physics/Collision/RayCast.h>
  15. #include <Jolt/Physics/Collision/ShapeCast.h>
  16. #include <Jolt/Physics/Collision/CastResult.h>
  17. #include <Jolt/Physics/Collision/CollidePointResult.h>
  18. #include <Jolt/Physics/Collision/AABoxCast.h>
  19. #include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
  20. #include <Jolt/Physics/Collision/Shape/HeightFieldShape.h>
  21. #include <Jolt/Physics/Collision/Shape/MeshShape.h>
  22. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  23. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  24. #include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
  25. #include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
  26. #include <Jolt/Physics/Collision/Shape/TaperedCapsuleShape.h>
  27. #include <Jolt/Physics/Collision/Shape/CylinderShape.h>
  28. #include <Jolt/Physics/Collision/Shape/TriangleShape.h>
  29. #include <Jolt/Physics/Collision/Shape/StaticCompoundShape.h>
  30. #include <Jolt/Physics/Collision/Shape/MutableCompoundShape.h>
  31. #include <Jolt/Physics/Collision/Shape/ScaledShape.h>
  32. #include <Jolt/Physics/Collision/NarrowPhaseStats.h>
  33. #include <Jolt/Physics/Constraints/DistanceConstraint.h>
  34. #include <Jolt/Physics/Character/CharacterVirtual.h>
  35. #include <Utils/Log.h>
  36. #include <Utils/ShapeCreator.h>
  37. #include <Renderer/DebugRendererImp.h>
  38. #include <fstream>
  39. //-----------------------------------------------------------------------------
  40. // RTTI definitions
  41. //-----------------------------------------------------------------------------
  42. struct TestNameAndRTTI
  43. {
  44. const char * mName;
  45. const RTTI * mRTTI;
  46. };
  47. struct TestCategory
  48. {
  49. const char * mName;
  50. TestNameAndRTTI * mTests;
  51. size_t mNumTests;
  52. };
  53. JPH_DECLARE_RTTI_FOR_FACTORY(SimpleTest)
  54. JPH_DECLARE_RTTI_FOR_FACTORY(StackTest)
  55. JPH_DECLARE_RTTI_FOR_FACTORY(WallTest)
  56. JPH_DECLARE_RTTI_FOR_FACTORY(IslandTest)
  57. JPH_DECLARE_RTTI_FOR_FACTORY(FunnelTest)
  58. JPH_DECLARE_RTTI_FOR_FACTORY(FrictionTest)
  59. JPH_DECLARE_RTTI_FOR_FACTORY(FrictionPerTriangleTest)
  60. JPH_DECLARE_RTTI_FOR_FACTORY(GravityFactorTest)
  61. JPH_DECLARE_RTTI_FOR_FACTORY(RestitutionTest)
  62. JPH_DECLARE_RTTI_FOR_FACTORY(DampingTest)
  63. JPH_DECLARE_RTTI_FOR_FACTORY(KinematicTest)
  64. JPH_DECLARE_RTTI_FOR_FACTORY(ContactManifoldTest)
  65. JPH_DECLARE_RTTI_FOR_FACTORY(ManifoldReductionTest)
  66. JPH_DECLARE_RTTI_FOR_FACTORY(CenterOfMassTest)
  67. JPH_DECLARE_RTTI_FOR_FACTORY(HeavyOnLightTest)
  68. JPH_DECLARE_RTTI_FOR_FACTORY(HighSpeedTest)
  69. JPH_DECLARE_RTTI_FOR_FACTORY(ChangeMotionTypeTest)
  70. JPH_DECLARE_RTTI_FOR_FACTORY(ChangeShapeTest)
  71. JPH_DECLARE_RTTI_FOR_FACTORY(ChangeObjectLayerTest)
  72. JPH_DECLARE_RTTI_FOR_FACTORY(LoadSaveSceneTest)
  73. JPH_DECLARE_RTTI_FOR_FACTORY(LoadSaveBinaryTest)
  74. JPH_DECLARE_RTTI_FOR_FACTORY(BigVsSmallTest)
  75. JPH_DECLARE_RTTI_FOR_FACTORY(ActiveEdgesTest)
  76. JPH_DECLARE_RTTI_FOR_FACTORY(MultithreadedTest)
  77. JPH_DECLARE_RTTI_FOR_FACTORY(ContactListenerTest)
  78. JPH_DECLARE_RTTI_FOR_FACTORY(ActivateDuringUpdateTest)
  79. JPH_DECLARE_RTTI_FOR_FACTORY(SensorTest)
  80. JPH_DECLARE_RTTI_FOR_FACTORY(DynamicMeshTest)
  81. static TestNameAndRTTI sGeneralTests[] =
  82. {
  83. { "Simple", JPH_RTTI(SimpleTest) },
  84. { "Stack", JPH_RTTI(StackTest) },
  85. { "Wall", JPH_RTTI(WallTest) },
  86. { "Island", JPH_RTTI(IslandTest) },
  87. { "Funnel", JPH_RTTI(FunnelTest) },
  88. { "Friction", JPH_RTTI(FrictionTest) },
  89. { "Friction (Per Triangle)", JPH_RTTI(FrictionPerTriangleTest) },
  90. { "Gravity Factor", JPH_RTTI(GravityFactorTest) },
  91. { "Restitution", JPH_RTTI(RestitutionTest) },
  92. { "Damping", JPH_RTTI(DampingTest) },
  93. { "Kinematic", JPH_RTTI(KinematicTest) },
  94. { "Contact Manifold", JPH_RTTI(ContactManifoldTest) },
  95. { "Manifold Reduction", JPH_RTTI(ManifoldReductionTest) },
  96. { "Center Of Mass", JPH_RTTI(CenterOfMassTest) },
  97. { "Heavy On Light", JPH_RTTI(HeavyOnLightTest) },
  98. { "High Speed", JPH_RTTI(HighSpeedTest) },
  99. { "Change Motion Type", JPH_RTTI(ChangeMotionTypeTest) },
  100. { "Change Shape", JPH_RTTI(ChangeShapeTest) },
  101. { "Change Object Layer", JPH_RTTI(ChangeObjectLayerTest) },
  102. { "Load/Save Scene", JPH_RTTI(LoadSaveSceneTest) },
  103. { "Load/Save Binary", JPH_RTTI(LoadSaveBinaryTest) },
  104. { "Big vs Small", JPH_RTTI(BigVsSmallTest) },
  105. { "Active Edges", JPH_RTTI(ActiveEdgesTest) },
  106. { "Multithreaded", JPH_RTTI(MultithreadedTest) },
  107. { "Contact Listener", JPH_RTTI(ContactListenerTest) },
  108. { "Activate During Update", JPH_RTTI(ActivateDuringUpdateTest) },
  109. { "Sensor", JPH_RTTI(SensorTest) },
  110. { "Dynamic Mesh", JPH_RTTI(DynamicMeshTest) },
  111. };
  112. JPH_DECLARE_RTTI_FOR_FACTORY(DistanceConstraintTest)
  113. JPH_DECLARE_RTTI_FOR_FACTORY(FixedConstraintTest)
  114. JPH_DECLARE_RTTI_FOR_FACTORY(ConeConstraintTest)
  115. JPH_DECLARE_RTTI_FOR_FACTORY(SwingTwistConstraintTest)
  116. JPH_DECLARE_RTTI_FOR_FACTORY(SixDOFConstraintTest)
  117. JPH_DECLARE_RTTI_FOR_FACTORY(HingeConstraintTest)
  118. JPH_DECLARE_RTTI_FOR_FACTORY(PoweredHingeConstraintTest)
  119. JPH_DECLARE_RTTI_FOR_FACTORY(PointConstraintTest)
  120. JPH_DECLARE_RTTI_FOR_FACTORY(SliderConstraintTest)
  121. JPH_DECLARE_RTTI_FOR_FACTORY(PoweredSliderConstraintTest)
  122. JPH_DECLARE_RTTI_FOR_FACTORY(SpringTest)
  123. JPH_DECLARE_RTTI_FOR_FACTORY(ConstraintSingularityTest)
  124. JPH_DECLARE_RTTI_FOR_FACTORY(PoweredSwingTwistConstraintTest)
  125. JPH_DECLARE_RTTI_FOR_FACTORY(SwingTwistConstraintFrictionTest)
  126. JPH_DECLARE_RTTI_FOR_FACTORY(PathConstraintTest)
  127. static TestNameAndRTTI sConstraintTests[] =
  128. {
  129. { "Point Constraint", JPH_RTTI(PointConstraintTest) },
  130. { "Distance Constraint", JPH_RTTI(DistanceConstraintTest) },
  131. { "Hinge Constraint", JPH_RTTI(HingeConstraintTest) },
  132. { "Powered Hinge Constraint", JPH_RTTI(PoweredHingeConstraintTest) },
  133. { "Slider Constraint", JPH_RTTI(SliderConstraintTest) },
  134. { "Powered Slider Constraint", JPH_RTTI(PoweredSliderConstraintTest) },
  135. { "Fixed Constraint", JPH_RTTI(FixedConstraintTest) },
  136. { "Cone Constraint", JPH_RTTI(ConeConstraintTest) },
  137. { "Swing Twist Constraint", JPH_RTTI(SwingTwistConstraintTest) },
  138. { "Powered Swing Twist Constraint", JPH_RTTI(PoweredSwingTwistConstraintTest) },
  139. { "Swing Twist Constraint Friction", JPH_RTTI(SwingTwistConstraintFrictionTest) },
  140. { "Six DOF Constraint", JPH_RTTI(SixDOFConstraintTest) },
  141. { "Path Constraint", JPH_RTTI(PathConstraintTest) },
  142. { "Spring", JPH_RTTI(SpringTest) },
  143. { "Constraint Singularity", JPH_RTTI(ConstraintSingularityTest) },
  144. };
  145. JPH_DECLARE_RTTI_FOR_FACTORY(BoxShapeTest)
  146. JPH_DECLARE_RTTI_FOR_FACTORY(SphereShapeTest)
  147. JPH_DECLARE_RTTI_FOR_FACTORY(TaperedCapsuleShapeTest)
  148. JPH_DECLARE_RTTI_FOR_FACTORY(CapsuleShapeTest)
  149. JPH_DECLARE_RTTI_FOR_FACTORY(CylinderShapeTest)
  150. JPH_DECLARE_RTTI_FOR_FACTORY(StaticCompoundShapeTest)
  151. JPH_DECLARE_RTTI_FOR_FACTORY(MutableCompoundShapeTest)
  152. JPH_DECLARE_RTTI_FOR_FACTORY(TriangleShapeTest)
  153. JPH_DECLARE_RTTI_FOR_FACTORY(ConvexHullShapeTest)
  154. JPH_DECLARE_RTTI_FOR_FACTORY(MeshShapeTest)
  155. JPH_DECLARE_RTTI_FOR_FACTORY(HeightFieldShapeTest)
  156. JPH_DECLARE_RTTI_FOR_FACTORY(RotatedTranslatedShapeTest)
  157. JPH_DECLARE_RTTI_FOR_FACTORY(OffsetCenterOfMassShapeTest)
  158. static TestNameAndRTTI sShapeTests[] =
  159. {
  160. { "Sphere Shape", JPH_RTTI(SphereShapeTest) },
  161. { "Box Shape", JPH_RTTI(BoxShapeTest) },
  162. { "Capsule Shape", JPH_RTTI(CapsuleShapeTest) },
  163. { "Tapered Capsule Shape", JPH_RTTI(TaperedCapsuleShapeTest) },
  164. { "Cylinder Shape", JPH_RTTI(CylinderShapeTest) },
  165. { "Convex Hull Shape", JPH_RTTI(ConvexHullShapeTest) },
  166. { "Mesh Shape", JPH_RTTI(MeshShapeTest) },
  167. { "Height Field Shape", JPH_RTTI(HeightFieldShapeTest) },
  168. { "Static Compound Shape", JPH_RTTI(StaticCompoundShapeTest) },
  169. { "Mutable Compound Shape", JPH_RTTI(MutableCompoundShapeTest) },
  170. { "Triangle Shape", JPH_RTTI(TriangleShapeTest) },
  171. { "Rotated Translated Shape", JPH_RTTI(RotatedTranslatedShapeTest) },
  172. { "Offset Center Of Mass Shape", JPH_RTTI(OffsetCenterOfMassShapeTest) }
  173. };
  174. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledSphereShapeTest)
  175. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledBoxShapeTest)
  176. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledCapsuleShapeTest)
  177. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledTaperedCapsuleShapeTest)
  178. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledCylinderShapeTest)
  179. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledConvexHullShapeTest)
  180. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledMeshShapeTest)
  181. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledHeightFieldShapeTest)
  182. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledStaticCompoundShapeTest)
  183. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledMutableCompoundShapeTest)
  184. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledTriangleShapeTest)
  185. JPH_DECLARE_RTTI_FOR_FACTORY(ScaledOffsetCenterOfMassShapeTest)
  186. static TestNameAndRTTI sScaledShapeTests[] =
  187. {
  188. { "Sphere Shape", JPH_RTTI(ScaledSphereShapeTest) },
  189. { "Box Shape", JPH_RTTI(ScaledBoxShapeTest) },
  190. { "Capsule Shape", JPH_RTTI(ScaledCapsuleShapeTest) },
  191. { "Tapered Capsule Shape", JPH_RTTI(ScaledTaperedCapsuleShapeTest) },
  192. { "Cylinder Shape", JPH_RTTI(ScaledCylinderShapeTest) },
  193. { "Convex Hull Shape", JPH_RTTI(ScaledConvexHullShapeTest) },
  194. { "Mesh Shape", JPH_RTTI(ScaledMeshShapeTest) },
  195. { "Height Field Shape", JPH_RTTI(ScaledHeightFieldShapeTest) },
  196. { "Static Compound Shape", JPH_RTTI(ScaledStaticCompoundShapeTest) },
  197. { "Mutable Compound Shape", JPH_RTTI(ScaledMutableCompoundShapeTest) },
  198. { "Triangle Shape", JPH_RTTI(ScaledTriangleShapeTest) },
  199. { "Offset Center Of Mass Shape", JPH_RTTI(ScaledOffsetCenterOfMassShapeTest) }
  200. };
  201. JPH_DECLARE_RTTI_FOR_FACTORY(CreateRigTest)
  202. JPH_DECLARE_RTTI_FOR_FACTORY(LoadRigTest)
  203. JPH_DECLARE_RTTI_FOR_FACTORY(KinematicRigTest)
  204. JPH_DECLARE_RTTI_FOR_FACTORY(PoweredRigTest)
  205. JPH_DECLARE_RTTI_FOR_FACTORY(RigPileTest)
  206. JPH_DECLARE_RTTI_FOR_FACTORY(LoadSaveBinaryRigTest)
  207. static TestNameAndRTTI sRigTests[] =
  208. {
  209. { "Create Rig", JPH_RTTI(CreateRigTest) },
  210. { "Load Rig", JPH_RTTI(LoadRigTest) },
  211. { "Load / Save Binary Rig", JPH_RTTI(LoadSaveBinaryRigTest) },
  212. { "Kinematic Rig", JPH_RTTI(KinematicRigTest) },
  213. { "Powered Rig", JPH_RTTI(PoweredRigTest) },
  214. { "Rig Pile", JPH_RTTI(RigPileTest) }
  215. };
  216. JPH_DECLARE_RTTI_FOR_FACTORY(CharacterTest)
  217. JPH_DECLARE_RTTI_FOR_FACTORY(CharacterVirtualTest)
  218. static TestNameAndRTTI sCharacterTests[] =
  219. {
  220. { "Character", JPH_RTTI(CharacterTest) },
  221. { "Character Virtual", JPH_RTTI(CharacterVirtualTest) },
  222. };
  223. JPH_DECLARE_RTTI_FOR_FACTORY(WaterShapeTest)
  224. static TestNameAndRTTI sWaterTests[] =
  225. {
  226. { "Shapes", JPH_RTTI(WaterShapeTest) },
  227. };
  228. JPH_DECLARE_RTTI_FOR_FACTORY(VehicleSixDOFTest)
  229. JPH_DECLARE_RTTI_FOR_FACTORY(VehicleConstraintTest)
  230. JPH_DECLARE_RTTI_FOR_FACTORY(TankTest)
  231. static TestNameAndRTTI sVehicleTests[] =
  232. {
  233. { "Car (VehicleConstraint)", JPH_RTTI(VehicleConstraintTest) },
  234. { "Tank (VehicleConstraint)", JPH_RTTI(TankTest) },
  235. { "Car (SixDOFConstraint)", JPH_RTTI(VehicleSixDOFTest) },
  236. };
  237. JPH_DECLARE_RTTI_FOR_FACTORY(BroadPhaseCastRayTest)
  238. JPH_DECLARE_RTTI_FOR_FACTORY(BroadPhaseInsertionTest)
  239. static TestNameAndRTTI sBroadPhaseTests[] =
  240. {
  241. { "Cast Ray", JPH_RTTI(BroadPhaseCastRayTest) },
  242. { "Insertion", JPH_RTTI(BroadPhaseInsertionTest) }
  243. };
  244. JPH_DECLARE_RTTI_FOR_FACTORY(InteractivePairsTest)
  245. JPH_DECLARE_RTTI_FOR_FACTORY(EPATest)
  246. JPH_DECLARE_RTTI_FOR_FACTORY(ClosestPointTest)
  247. JPH_DECLARE_RTTI_FOR_FACTORY(ConvexHullTest)
  248. JPH_DECLARE_RTTI_FOR_FACTORY(ConvexHullShrinkTest)
  249. JPH_DECLARE_RTTI_FOR_FACTORY(RandomRayTest)
  250. JPH_DECLARE_RTTI_FOR_FACTORY(CapsuleVsBoxTest)
  251. static TestNameAndRTTI sConvexCollisionTests[] =
  252. {
  253. { "Interactive Pairs", JPH_RTTI(InteractivePairsTest) },
  254. { "EPA Test", JPH_RTTI(EPATest) },
  255. { "Closest Point", JPH_RTTI(ClosestPointTest) },
  256. { "Convex Hull", JPH_RTTI(ConvexHullTest) },
  257. { "Convex Hull Shrink", JPH_RTTI(ConvexHullShrinkTest) },
  258. { "Random Ray", JPH_RTTI(RandomRayTest) },
  259. { "Capsule Vs Box", JPH_RTTI(CapsuleVsBoxTest) }
  260. };
  261. JPH_DECLARE_RTTI_FOR_FACTORY(LoadSnapshotTest)
  262. static TestNameAndRTTI sTools[] =
  263. {
  264. { "Load Snapshot", JPH_RTTI(LoadSnapshotTest) },
  265. };
  266. static TestCategory sAllCategories[] =
  267. {
  268. { "General", sGeneralTests, size(sGeneralTests) },
  269. { "Shapes", sShapeTests, size(sShapeTests) },
  270. { "Scaled Shapes", sScaledShapeTests, size(sScaledShapeTests) },
  271. { "Constraints", sConstraintTests, size(sConstraintTests) },
  272. { "Rig", sRigTests, size(sRigTests) },
  273. { "Character", sCharacterTests, size(sCharacterTests) },
  274. { "Water", sWaterTests, size(sWaterTests) },
  275. { "Vehicle", sVehicleTests, size(sVehicleTests) },
  276. { "Broad Phase", sBroadPhaseTests, size(sBroadPhaseTests) },
  277. { "Convex Collision", sConvexCollisionTests, size(sConvexCollisionTests) },
  278. { "Tools", sTools, size(sTools) }
  279. };
  280. //-----------------------------------------------------------------------------
  281. // Configuration
  282. //-----------------------------------------------------------------------------
  283. static constexpr uint cNumBodies = 10240;
  284. static constexpr uint cNumBodyMutexes = 0; // Autodetect
  285. static constexpr uint cMaxBodyPairs = 65536;
  286. static constexpr uint cMaxContactConstraints = 10240;
  287. SamplesApp::SamplesApp()
  288. {
  289. // Allocate temp memory
  290. #ifdef JPH_DISABLE_TEMP_ALLOCATOR
  291. mTempAllocator = new TempAllocatorMalloc();
  292. #else
  293. mTempAllocator = new TempAllocatorImpl(16 * 1024 * 1024);
  294. #endif
  295. // Create job system
  296. mJobSystem = new JobSystemThreadPool(cMaxPhysicsJobs, cMaxPhysicsBarriers, mMaxConcurrentJobs - 1);
  297. // Create job system without extra threads for validating
  298. mJobSystemValidating = new JobSystemThreadPool(cMaxPhysicsJobs, cMaxPhysicsBarriers, 0);
  299. // Create UI
  300. UIElement *main_menu = mDebugUI->CreateMenu();
  301. mDebugUI->CreateTextButton(main_menu, "Select Test", [this]() {
  302. UIElement *tests = mDebugUI->CreateMenu();
  303. for (TestCategory &c : sAllCategories)
  304. {
  305. mDebugUI->CreateTextButton(tests, c.mName, [=]() {
  306. UIElement *category = mDebugUI->CreateMenu();
  307. for (uint j = 0; j < c.mNumTests; ++j)
  308. mDebugUI->CreateTextButton(category, c.mTests[j].mName, [=]() { StartTest(c.mTests[j].mRTTI); });
  309. mDebugUI->ShowMenu(category);
  310. });
  311. }
  312. mDebugUI->ShowMenu(tests);
  313. });
  314. mTestSettingsButton = mDebugUI->CreateTextButton(main_menu, "Test Settings", [this](){
  315. UIElement *test_settings = mDebugUI->CreateMenu();
  316. mTest->CreateSettingsMenu(mDebugUI, test_settings);
  317. mDebugUI->ShowMenu(test_settings);
  318. });
  319. mDebugUI->CreateTextButton(main_menu, "Restart Test (R)", [this]() { StartTest(mTestClass); });
  320. mDebugUI->CreateTextButton(main_menu, "Run All Tests", [this]() { RunAllTests(); });
  321. mNextTestButton = mDebugUI->CreateTextButton(main_menu, "Next Test (N)", [this]() { NextTest(); });
  322. mNextTestButton->SetDisabled(true);
  323. mDebugUI->CreateTextButton(main_menu, "Take Snapshot", [this]() { TakeSnapshot(); });
  324. mDebugUI->CreateTextButton(main_menu, "Take And Reload Snapshot", [this]() { TakeAndReloadSnapshot(); });
  325. mDebugUI->CreateTextButton(main_menu, "Physics Settings", [this]() {
  326. UIElement *phys_settings = mDebugUI->CreateMenu();
  327. mDebugUI->CreateSlider(phys_settings, "Max Concurrent Jobs", float(mMaxConcurrentJobs), 1, float(thread::hardware_concurrency()), 1, [this](float inValue) { mMaxConcurrentJobs = (int)inValue; });
  328. mDebugUI->CreateSlider(phys_settings, "Gravity (m/s^2)", -mPhysicsSystem->GetGravity().GetY(), 0.0f, 20.0f, 1.0f, [this](float inValue) { mPhysicsSystem->SetGravity(Vec3(0, -inValue, 0)); });
  329. mDebugUI->CreateSlider(phys_settings, "Update Frequency (Hz)", mUpdateFrequency, 7.5f, 120.0f, 2.5f, [this](float inValue) { mUpdateFrequency = inValue; });
  330. mDebugUI->CreateSlider(phys_settings, "Num Collision Steps", float(mCollisionSteps), 1.0f, 4.0f, 1.0f, [this](float inValue) { mCollisionSteps = int(inValue); });
  331. mDebugUI->CreateSlider(phys_settings, "Num Integration Sub Steps", float(mIntegrationSubSteps), 1.0f, 4.0f, 1.0f, [this](float inValue) { mIntegrationSubSteps = int(inValue); });
  332. mDebugUI->CreateSlider(phys_settings, "Num Velocity Steps", float(mPhysicsSettings.mNumVelocitySteps), 0, 30, 1, [this](float inValue) { mPhysicsSettings.mNumVelocitySteps = int(round(inValue)); mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  333. mDebugUI->CreateSlider(phys_settings, "Num Position Steps", float(mPhysicsSettings.mNumPositionSteps), 0, 30, 1, [this](float inValue) { mPhysicsSettings.mNumPositionSteps = int(round(inValue)); mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  334. mDebugUI->CreateSlider(phys_settings, "Baumgarte Stabilization Factor", mPhysicsSettings.mBaumgarte, 0.01f, 1.0f, 0.05f, [this](float inValue) { mPhysicsSettings.mBaumgarte = inValue; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  335. mDebugUI->CreateSlider(phys_settings, "Speculative Contact Distance (m)", mPhysicsSettings.mSpeculativeContactDistance, 0.0f, 0.1f, 0.005f, [this](float inValue) { mPhysicsSettings.mSpeculativeContactDistance = inValue; });
  336. mDebugUI->CreateSlider(phys_settings, "Penetration Slop (m)", mPhysicsSettings.mPenetrationSlop, 0.0f, 0.1f, 0.005f, [this](float inValue) { mPhysicsSettings.mPenetrationSlop = inValue; });
  337. mDebugUI->CreateSlider(phys_settings, "Min Velocity For Restitution (m/s)", mPhysicsSettings.mMinVelocityForRestitution, 0.0f, 10.0f, 0.1f, [this](float inValue) { mPhysicsSettings.mMinVelocityForRestitution = inValue; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  338. mDebugUI->CreateSlider(phys_settings, "Time Before Sleep (s)", mPhysicsSettings.mTimeBeforeSleep, 0.1f, 1.0f, 0.1f, [this](float inValue) { mPhysicsSettings.mTimeBeforeSleep = inValue; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  339. mDebugUI->CreateSlider(phys_settings, "Point Velocity Sleep Threshold (m/s)", mPhysicsSettings.mPointVelocitySleepThreshold, 0.01f, 1.0f, 0.01f, [this](float inValue) { mPhysicsSettings.mPointVelocitySleepThreshold = inValue; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  340. mDebugUI->CreateCheckBox(phys_settings, "Constraint Warm Starting", mPhysicsSettings.mConstraintWarmStart, [this](UICheckBox::EState inState) { mPhysicsSettings.mConstraintWarmStart = inState == UICheckBox::STATE_CHECKED; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  341. mDebugUI->CreateCheckBox(phys_settings, "Use Body Pair Contact Cache", mPhysicsSettings.mUseBodyPairContactCache, [this](UICheckBox::EState inState) { mPhysicsSettings.mUseBodyPairContactCache = inState == UICheckBox::STATE_CHECKED; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  342. mDebugUI->CreateCheckBox(phys_settings, "Contact Manifold Reduction", mPhysicsSettings.mUseManifoldReduction, [this](UICheckBox::EState inState) { mPhysicsSettings.mUseManifoldReduction = inState == UICheckBox::STATE_CHECKED; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  343. mDebugUI->CreateCheckBox(phys_settings, "Allow Sleeping", mPhysicsSettings.mAllowSleeping, [this](UICheckBox::EState inState) { mPhysicsSettings.mAllowSleeping = inState == UICheckBox::STATE_CHECKED; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  344. mDebugUI->CreateCheckBox(phys_settings, "Check Active Triangle Edges", mPhysicsSettings.mCheckActiveEdges, [this](UICheckBox::EState inState) { mPhysicsSettings.mCheckActiveEdges = inState == UICheckBox::STATE_CHECKED; mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings); });
  345. mDebugUI->CreateCheckBox(phys_settings, "Record State For Playback", mRecordState, [this](UICheckBox::EState inState) { mRecordState = inState == UICheckBox::STATE_CHECKED; });
  346. mDebugUI->CreateCheckBox(phys_settings, "Check Determinism", mCheckDeterminism, [this](UICheckBox::EState inState) { mCheckDeterminism = inState == UICheckBox::STATE_CHECKED; });
  347. mDebugUI->CreateCheckBox(phys_settings, "Install Contact Listener", mInstallContactListener, [this](UICheckBox::EState inState) { mInstallContactListener = inState == UICheckBox::STATE_CHECKED; StartTest(mTestClass); });
  348. mDebugUI->ShowMenu(phys_settings);
  349. });
  350. #ifdef JPH_DEBUG_RENDERER
  351. mDebugUI->CreateTextButton(main_menu, "Drawing Options", [this]() {
  352. UIElement *drawing_options = mDebugUI->CreateMenu();
  353. mDebugUI->CreateCheckBox(drawing_options, "Draw Shapes (H)", mBodyDrawSettings.mDrawShape, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawShape = inState == UICheckBox::STATE_CHECKED; });
  354. mDebugUI->CreateCheckBox(drawing_options, "Draw Shapes Wireframe (Alt+W)", mBodyDrawSettings.mDrawShapeWireframe, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawShapeWireframe = inState == UICheckBox::STATE_CHECKED; });
  355. mDebugUI->CreateComboBox(drawing_options, "Draw Shape Color", { "Instance", "Shape Type", "Motion Type", "Sleep", "Island", "Material" }, (int)mBodyDrawSettings.mDrawShapeColor, [this](int inItem) { mBodyDrawSettings.mDrawShapeColor = (BodyManager::EShapeColor)inItem; });
  356. mDebugUI->CreateCheckBox(drawing_options, "Draw GetSupport + Cvx Radius (Shift+H)", mBodyDrawSettings.mDrawGetSupportFunction, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawGetSupportFunction = inState == UICheckBox::STATE_CHECKED; });
  357. mDebugUI->CreateCheckBox(drawing_options, "Draw Shapes Using GetTrianglesStart/Next (Alt+H)", mDrawGetTriangles, [this](UICheckBox::EState inState) { mDrawGetTriangles = inState == UICheckBox::STATE_CHECKED; });
  358. mDebugUI->CreateCheckBox(drawing_options, "Draw GetSupport Direction", mBodyDrawSettings.mDrawSupportDirection, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawSupportDirection = inState == UICheckBox::STATE_CHECKED; mBodyDrawSettings.mDrawGetSupportFunction |= mBodyDrawSettings.mDrawSupportDirection; });
  359. mDebugUI->CreateCheckBox(drawing_options, "Draw GetSupportingFace (Shift+F)", mBodyDrawSettings.mDrawGetSupportingFace, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawGetSupportingFace = inState == UICheckBox::STATE_CHECKED; });
  360. mDebugUI->CreateCheckBox(drawing_options, "Draw Constraints (C)", mDrawConstraints, [this](UICheckBox::EState inState) { mDrawConstraints = inState == UICheckBox::STATE_CHECKED; });
  361. mDebugUI->CreateCheckBox(drawing_options, "Draw Constraint Limits (L)", mDrawConstraintLimits, [this](UICheckBox::EState inState) { mDrawConstraintLimits = inState == UICheckBox::STATE_CHECKED; });
  362. mDebugUI->CreateCheckBox(drawing_options, "Draw Constraint Reference Frame", mDrawConstraintReferenceFrame, [this](UICheckBox::EState inState) { mDrawConstraintReferenceFrame = inState == UICheckBox::STATE_CHECKED; });
  363. mDebugUI->CreateCheckBox(drawing_options, "Draw Contact Point (1)", ContactConstraintManager::sDrawContactPoint, [](UICheckBox::EState inState) { ContactConstraintManager::sDrawContactPoint = inState == UICheckBox::STATE_CHECKED; });
  364. mDebugUI->CreateCheckBox(drawing_options, "Draw Supporting Faces (2)", ContactConstraintManager::sDrawSupportingFaces, [](UICheckBox::EState inState) { ContactConstraintManager::sDrawSupportingFaces = inState == UICheckBox::STATE_CHECKED; });
  365. mDebugUI->CreateCheckBox(drawing_options, "Draw Contact Point Reduction (3)", ContactConstraintManager::sDrawContactPointReduction, [](UICheckBox::EState inState) { ContactConstraintManager::sDrawContactPointReduction = inState == UICheckBox::STATE_CHECKED; });
  366. mDebugUI->CreateCheckBox(drawing_options, "Draw Contact Manifolds (M)", ContactConstraintManager::sDrawContactManifolds, [](UICheckBox::EState inState) { ContactConstraintManager::sDrawContactManifolds = inState == UICheckBox::STATE_CHECKED; });
  367. mDebugUI->CreateCheckBox(drawing_options, "Draw Motion Quality Linear Cast", PhysicsSystem::sDrawMotionQualityLinearCast, [](UICheckBox::EState inState) { PhysicsSystem::sDrawMotionQualityLinearCast = inState == UICheckBox::STATE_CHECKED; });
  368. mDebugUI->CreateCheckBox(drawing_options, "Draw Bounding Boxes", mBodyDrawSettings.mDrawBoundingBox, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawBoundingBox = inState == UICheckBox::STATE_CHECKED; });
  369. mDebugUI->CreateCheckBox(drawing_options, "Draw Center of Mass Transforms", mBodyDrawSettings.mDrawCenterOfMassTransform, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawCenterOfMassTransform = inState == UICheckBox::STATE_CHECKED; });
  370. mDebugUI->CreateCheckBox(drawing_options, "Draw World Transforms", mBodyDrawSettings.mDrawWorldTransform, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawWorldTransform = inState == UICheckBox::STATE_CHECKED; });
  371. mDebugUI->CreateCheckBox(drawing_options, "Draw Velocity", mBodyDrawSettings.mDrawVelocity, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawVelocity = inState == UICheckBox::STATE_CHECKED; });
  372. mDebugUI->CreateCheckBox(drawing_options, "Draw Sleep Stats", mBodyDrawSettings.mDrawSleepStats, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawSleepStats = inState == UICheckBox::STATE_CHECKED; });
  373. mDebugUI->CreateCheckBox(drawing_options, "Draw Mass and Inertia (I)", mBodyDrawSettings.mDrawMassAndInertia, [this](UICheckBox::EState inState) { mBodyDrawSettings.mDrawMassAndInertia = inState == UICheckBox::STATE_CHECKED; });
  374. mDebugUI->CreateCheckBox(drawing_options, "Draw Joints", mPoseDrawSettings.mDrawJoints, [this](UICheckBox::EState inState) { mPoseDrawSettings.mDrawJoints = inState == UICheckBox::STATE_CHECKED; });
  375. mDebugUI->CreateCheckBox(drawing_options, "Draw Joint Orientations", mPoseDrawSettings.mDrawJointOrientations, [this](UICheckBox::EState inState) { mPoseDrawSettings.mDrawJointOrientations = inState == UICheckBox::STATE_CHECKED; });
  376. mDebugUI->CreateCheckBox(drawing_options, "Draw Joint Names", mPoseDrawSettings.mDrawJointNames, [this](UICheckBox::EState inState) { mPoseDrawSettings.mDrawJointNames = inState == UICheckBox::STATE_CHECKED; });
  377. mDebugUI->CreateCheckBox(drawing_options, "Draw Convex Hull Shape Face Outlines", ConvexHullShape::sDrawFaceOutlines, [](UICheckBox::EState inState) { ConvexHullShape::sDrawFaceOutlines = inState == UICheckBox::STATE_CHECKED; });
  378. mDebugUI->CreateCheckBox(drawing_options, "Draw Mesh Shape Triangle Groups", MeshShape::sDrawTriangleGroups, [](UICheckBox::EState inState) { MeshShape::sDrawTriangleGroups = inState == UICheckBox::STATE_CHECKED; });
  379. mDebugUI->CreateCheckBox(drawing_options, "Draw Mesh Shape Triangle Outlines", MeshShape::sDrawTriangleOutlines, [](UICheckBox::EState inState) { MeshShape::sDrawTriangleOutlines = inState == UICheckBox::STATE_CHECKED; });
  380. mDebugUI->CreateCheckBox(drawing_options, "Draw Height Field Shape Triangle Outlines", HeightFieldShape::sDrawTriangleOutlines, [](UICheckBox::EState inState) { HeightFieldShape::sDrawTriangleOutlines = inState == UICheckBox::STATE_CHECKED; });
  381. mDebugUI->CreateCheckBox(drawing_options, "Draw Submerged Volumes", Shape::sDrawSubmergedVolumes, [](UICheckBox::EState inState) { Shape::sDrawSubmergedVolumes = inState == UICheckBox::STATE_CHECKED; });
  382. mDebugUI->CreateCheckBox(drawing_options, "Draw Character Virtual Constraints", CharacterVirtual::sDrawConstraints, [](UICheckBox::EState inState) { CharacterVirtual::sDrawConstraints = inState == UICheckBox::STATE_CHECKED; });
  383. mDebugUI->CreateCheckBox(drawing_options, "Draw Character Virtual Walk Stairs", CharacterVirtual::sDrawWalkStairs, [](UICheckBox::EState inState) { CharacterVirtual::sDrawWalkStairs = inState == UICheckBox::STATE_CHECKED; });
  384. mDebugUI->ShowMenu(drawing_options);
  385. });
  386. #endif // JPH_DEBUG_RENDERER
  387. mDebugUI->CreateTextButton(main_menu, "Mouse Probe", [this]() {
  388. UIElement *probe_options = mDebugUI->CreateMenu();
  389. mDebugUI->CreateComboBox(probe_options, "Mode", { "Pick", "Ray", "RayCollector", "CollidePoint", "CollideShape", "CastShape", "TransfShape", "GetTriangles", "BP Ray", "BP Box", "BP Sphere", "BP Point", "BP OBox", "BP Cast Box" }, (int)mProbeMode, [this](int inItem) { mProbeMode = (EProbeMode)inItem; });
  390. mDebugUI->CreateComboBox(probe_options, "Shape", { "Sphere", "Box", "ConvexHull", "Capsule", "TaperedCapsule", "Cylinder", "Triangle", "StaticCompound", "StaticCompound2", "MutableCompound", "Mesh" }, (int)mProbeShape, [=](int inItem) { mProbeShape = (EProbeShape)inItem; });
  391. mDebugUI->CreateCheckBox(probe_options, "Scale Shape", mScaleShape, [this](UICheckBox::EState inState) { mScaleShape = inState == UICheckBox::STATE_CHECKED; });
  392. mDebugUI->CreateSlider(probe_options, "Scale X", mShapeScale.GetX(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShapeScale.SetX(inValue); });
  393. mDebugUI->CreateSlider(probe_options, "Scale Y", mShapeScale.GetY(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShapeScale.SetY(inValue); });
  394. mDebugUI->CreateSlider(probe_options, "Scale Z", mShapeScale.GetZ(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShapeScale.SetZ(inValue); });
  395. mDebugUI->CreateComboBox(probe_options, "Back Face Cull", { "On", "Off" }, (int)mBackFaceMode, [=](int inItem) { mBackFaceMode = (EBackFaceMode)inItem; });
  396. mDebugUI->CreateComboBox(probe_options, "Active Edge Mode", { "Only Active", "All" }, (int)mActiveEdgeMode, [=](int inItem) { mActiveEdgeMode = (EActiveEdgeMode)inItem; });
  397. mDebugUI->CreateComboBox(probe_options, "Collect Faces Mode", { "Collect Faces", "No Faces" }, (int)mCollectFacesMode, [=](int inItem) { mCollectFacesMode = (ECollectFacesMode)inItem; });
  398. mDebugUI->CreateSlider(probe_options, "Max Separation Distance", mMaxSeparationDistance, 0.0f, 5.0f, 0.1f, [this](float inValue) { mMaxSeparationDistance = inValue; });
  399. mDebugUI->CreateCheckBox(probe_options, "Treat Convex As Solid", mTreatConvexAsSolid, [this](UICheckBox::EState inState) { mTreatConvexAsSolid = inState == UICheckBox::STATE_CHECKED; });
  400. mDebugUI->CreateCheckBox(probe_options, "Return Deepest Point", mReturnDeepestPoint, [this](UICheckBox::EState inState) { mReturnDeepestPoint = inState == UICheckBox::STATE_CHECKED; });
  401. mDebugUI->CreateCheckBox(probe_options, "Shrunken Shape + Convex Radius", mUseShrunkenShapeAndConvexRadius, [this](UICheckBox::EState inState) { mUseShrunkenShapeAndConvexRadius = inState == UICheckBox::STATE_CHECKED; });
  402. mDebugUI->CreateSlider(probe_options, "Max Hits", float(mMaxHits), 0, 10, 1, [this](float inValue) { mMaxHits = (int)inValue; });
  403. mDebugUI->ShowMenu(probe_options);
  404. });
  405. mDebugUI->CreateTextButton(main_menu, "Shoot Object", [this]() {
  406. UIElement *shoot_options = mDebugUI->CreateMenu();
  407. mDebugUI->CreateTextButton(shoot_options, "Shoot Object (B)", [=]() { ShootObject(); });
  408. mDebugUI->CreateSlider(shoot_options, "Initial Velocity", mShootObjectVelocity, 0.0f, 500.0f, 10.0f, [this](float inValue) { mShootObjectVelocity = inValue; });
  409. mDebugUI->CreateComboBox(shoot_options, "Shape", { "Sphere", "ConvexHull", "Thin Bar" }, (int)mShootObjectShape, [=](int inItem) { mShootObjectShape = (EShootObjectShape)inItem; });
  410. mDebugUI->CreateComboBox(shoot_options, "Motion Quality", { "Discrete", "LinearCast" }, (int)mShootObjectMotionQuality, [=](int inItem) { mShootObjectMotionQuality = (EMotionQuality)inItem; });
  411. mDebugUI->CreateSlider(shoot_options, "Friction", mShootObjectFriction, 0.0f, 1.0f, 0.05f, [this](float inValue) { mShootObjectFriction = inValue; });
  412. mDebugUI->CreateSlider(shoot_options, "Restitution", mShootObjectRestitution, 0.0f, 1.0f, 0.05f, [this](float inValue) { mShootObjectRestitution = inValue; });
  413. mDebugUI->CreateCheckBox(shoot_options, "Scale Shape", mShootObjectScaleShape, [this](UICheckBox::EState inState) { mShootObjectScaleShape = inState == UICheckBox::STATE_CHECKED; });
  414. mDebugUI->CreateSlider(shoot_options, "Scale X", mShootObjectShapeScale.GetX(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShootObjectShapeScale.SetX(inValue); });
  415. mDebugUI->CreateSlider(shoot_options, "Scale Y", mShootObjectShapeScale.GetY(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShootObjectShapeScale.SetY(inValue); });
  416. mDebugUI->CreateSlider(shoot_options, "Scale Z", mShootObjectShapeScale.GetZ(), -5.0f, 5.0f, 0.1f, [this](float inValue) { mShootObjectShapeScale.SetZ(inValue); });
  417. mDebugUI->ShowMenu(shoot_options);
  418. });
  419. mDebugUI->CreateTextButton(main_menu, "Help", [this](){
  420. UIElement *help = mDebugUI->CreateMenu();
  421. mDebugUI->CreateStaticText(help,
  422. "ESC: Back to previous menu.\n"
  423. "WASD + Mouse: Fly around. Hold Shift to speed up, Ctrl to slow down.\n"
  424. "Space: Hold to pick up and drag a physics object under the crosshair.\n"
  425. "P: Pause / unpause simulation.\n"
  426. "O: Single step the simulation.\n"
  427. ",: Step back (only when Physics Settings / Record State for Playback is on).\n"
  428. ".: Step forward (only when Physics Settings / Record State for Playback is on).\n"
  429. "Shift + ,: Play reverse (only when Physics Settings / Record State for Playback is on).\n"
  430. "Shift + .: Replay forward (only when Physics Settings / Record State for Playback is on).\n"
  431. "T: Dump frame timing information to profile_*.html (when JPH_PROFILE_ENABLED defined)."
  432. );
  433. mDebugUI->ShowMenu(help);
  434. });
  435. mDebugUI->ShowMenu(main_menu);
  436. // Get test name from commandline
  437. string cmd_line = ToLower(GetCommandLineA());
  438. vector<string> args;
  439. StringToVector(cmd_line, args, " ");
  440. if (args.size() == 2)
  441. {
  442. string cmd = args[1];
  443. if (cmd == "alltests")
  444. {
  445. // Run all tests
  446. mCheckDeterminism = true;
  447. mExitAfterRunningTests = true;
  448. RunAllTests();
  449. }
  450. else
  451. {
  452. // Search for the test
  453. const RTTI *test = JPH_RTTI(LoadRigTest);
  454. for (TestCategory &c : sAllCategories)
  455. for (uint i = 0; i < c.mNumTests; ++i)
  456. {
  457. TestNameAndRTTI &t = c.mTests[i];
  458. string test_name = ToLower(t.mRTTI->GetName());
  459. if (test_name == cmd)
  460. {
  461. test = t.mRTTI;
  462. break;
  463. }
  464. }
  465. // Construct test
  466. StartTest(test);
  467. }
  468. }
  469. }
  470. SamplesApp::~SamplesApp()
  471. {
  472. // Clean up
  473. delete mTest;
  474. delete mContactListener;
  475. delete mPhysicsSystem;
  476. delete mJobSystemValidating;
  477. delete mJobSystem;
  478. delete mTempAllocator;
  479. }
  480. void SamplesApp::StartTest(const RTTI *inRTTI)
  481. {
  482. // Pop active menus, we might be in the settings menu for the test which will be dangling after restarting the test
  483. mDebugUI->BackToMain();
  484. // Store old gravity
  485. Vec3 old_gravity = mPhysicsSystem != nullptr? mPhysicsSystem->GetGravity() : Vec3(0, -9.81f, 0);
  486. // Discard old test
  487. delete mTest;
  488. delete mContactListener;
  489. delete mPhysicsSystem;
  490. // Create physics system
  491. mPhysicsSystem = new PhysicsSystem();
  492. mPhysicsSystem->Init(cNumBodies, cNumBodyMutexes, cMaxBodyPairs, cMaxContactConstraints, mBroadPhaseLayerInterface, BroadPhaseCanCollide, ObjectCanCollide);
  493. mPhysicsSystem->SetPhysicsSettings(mPhysicsSettings);
  494. // Restore gravity
  495. mPhysicsSystem->SetGravity(old_gravity);
  496. // Reset dragging
  497. mDragAnchor = nullptr;
  498. mDragConstraint = nullptr;
  499. // Reset playback state
  500. mPlaybackFrames.clear();
  501. mPlaybackMode = EPlaybackMode::Play;
  502. mCurrentPlaybackFrame = -1;
  503. // Set new test
  504. mTestClass = inRTTI;
  505. mTest = static_cast<Test *>(inRTTI->CreateObject());
  506. mTest->SetPhysicsSystem(mPhysicsSystem);
  507. mTest->SetJobSystem(mJobSystem);
  508. mTest->SetDebugRenderer(mDebugRenderer);
  509. mTest->SetTempAllocator(mTempAllocator);
  510. if (mInstallContactListener)
  511. {
  512. mContactListener = new ContactListenerImpl;
  513. mContactListener->SetNextListener(mTest->GetContactListener());
  514. mPhysicsSystem->SetContactListener(mContactListener);
  515. }
  516. else
  517. {
  518. mContactListener = nullptr;
  519. mPhysicsSystem->SetContactListener(mTest->GetContactListener());
  520. }
  521. mTest->Initialize();
  522. // Optimize the broadphase to make the first update fast
  523. mPhysicsSystem->OptimizeBroadPhase();
  524. // Reset the camera to the original position
  525. ResetCamera();
  526. // Start paused
  527. Pause(true);
  528. SingleStep();
  529. // Check if test has settings menu
  530. mTestSettingsButton->SetDisabled(!mTest->HasSettingsMenu());
  531. }
  532. void SamplesApp::RunAllTests()
  533. {
  534. mTestsToRun.clear();
  535. for (const TestCategory &c : sAllCategories)
  536. for (uint i = 0; i < c.mNumTests; ++i)
  537. {
  538. TestNameAndRTTI &t = c.mTests[i];
  539. mTestsToRun.push_back(t.mRTTI);
  540. }
  541. NextTest();
  542. }
  543. bool SamplesApp::NextTest()
  544. {
  545. if (mTestsToRun.empty())
  546. {
  547. if (mExitAfterRunningTests)
  548. return false; // Exit the application now
  549. else
  550. MessageBoxA(nullptr, "Test run complete!", "Complete", MB_OK);
  551. }
  552. else
  553. {
  554. // Start the timer for 10 seconds
  555. mTestTimeLeft = 10.0f;
  556. // Take next test
  557. const RTTI *rtti = mTestsToRun.front();
  558. mTestsToRun.erase(mTestsToRun.begin());
  559. // Start it
  560. StartTest(rtti);
  561. // Unpause
  562. Pause(false);
  563. }
  564. mNextTestButton->SetDisabled(mTestsToRun.empty());
  565. return true;
  566. }
  567. bool SamplesApp::CheckNextTest()
  568. {
  569. if (mTestTimeLeft >= 0.0f)
  570. {
  571. // Update status string
  572. mStatusString = StringFormat("%s: Next test in %.1fs", mTestClass->GetName(), (double)mTestTimeLeft);
  573. // Use physics time
  574. mTestTimeLeft -= 1.0f / mUpdateFrequency;
  575. // If time's up then go to the next test
  576. if (mTestTimeLeft < 0.0f)
  577. return NextTest();
  578. }
  579. else
  580. mStatusString.clear();
  581. return true;
  582. }
  583. void SamplesApp::TakeSnapshot()
  584. {
  585. // Convert physics system to scene
  586. Ref<PhysicsScene> scene = new PhysicsScene();
  587. scene->FromPhysicsSystem(mPhysicsSystem);
  588. // Save scene
  589. ofstream stream("snapshot.bin", ofstream::out | ofstream::trunc | ofstream::binary);
  590. StreamOutWrapper wrapper(stream);
  591. if (stream.is_open())
  592. scene->SaveBinaryState(wrapper, true, true);
  593. }
  594. void SamplesApp::TakeAndReloadSnapshot()
  595. {
  596. TakeSnapshot();
  597. StartTest(JPH_RTTI(LoadSnapshotTest));
  598. }
  599. RefConst<Shape> SamplesApp::CreateProbeShape()
  600. {
  601. // Get the scale
  602. Vec3 scale = mScaleShape? mShapeScale : Vec3::sReplicate(1.0f);
  603. // Make it minimally -0.1 or 0.1 depending on the sign
  604. Vec3 clamped_value = Vec3::sSelect(Vec3::sReplicate(-0.1f), Vec3::sReplicate(0.1f), Vec3::sGreaterOrEqual(scale, Vec3::sZero()));
  605. scale = Vec3::sSelect(scale, clamped_value, Vec3::sLess(scale.Abs(), Vec3::sReplicate(0.1f)));
  606. RefConst<Shape> shape;
  607. switch (mProbeShape)
  608. {
  609. case EProbeShape::Sphere:
  610. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  611. shape = new SphereShape(0.2f);
  612. break;
  613. case EProbeShape::Box:
  614. shape = new BoxShape(Vec3(0.1f, 0.2f, 0.3f));
  615. break;
  616. case EProbeShape::ConvexHull:
  617. {
  618. // Create tetrahedron
  619. vector<Vec3> tetrahedron;
  620. tetrahedron.push_back(Vec3::sZero());
  621. tetrahedron.push_back(Vec3(0.2f, 0, 0.4f));
  622. tetrahedron.push_back(Vec3(0.4f, 0, 0));
  623. tetrahedron.push_back(Vec3(0.2f, -0.2f, 1.0f));
  624. shape = ConvexHullShapeSettings(tetrahedron, 0.01f).Create().Get();
  625. }
  626. break;
  627. case EProbeShape::Capsule:
  628. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  629. shape = new CapsuleShape(0.2f, 0.1f);
  630. break;
  631. case EProbeShape::TaperedCapsule:
  632. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  633. shape = TaperedCapsuleShapeSettings(0.2f, 0.1f, 0.2f).Create().Get();
  634. break;
  635. case EProbeShape::Cylinder:
  636. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_Y, SWIZZLE_X>(); // Scale X must be same as Z
  637. shape = new CylinderShape(0.2f, 0.1f);
  638. break;
  639. case EProbeShape::Triangle:
  640. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  641. shape = new TriangleShape(Vec3(0.1f, 0.9f, 0.3f), Vec3(-0.9f, -0.5f, 0.2f), Vec3(0.7f, -0.3f, -0.1f));
  642. break;
  643. case EProbeShape::StaticCompound:
  644. {
  645. vector<Vec3> tetrahedron;
  646. tetrahedron.push_back(Vec3::sZero());
  647. tetrahedron.push_back(Vec3(-0.2f, 0, 0.4f));
  648. tetrahedron.push_back(Vec3(0, 0.2f, 0));
  649. tetrahedron.push_back(Vec3(0.2f, 0, 0.4f));
  650. RefConst<Shape> convex = ConvexHullShapeSettings(tetrahedron, 0.01f).Create().Get();
  651. StaticCompoundShapeSettings compound_settings;
  652. compound_settings.AddShape(Vec3(-0.5f, 0, 0), Quat::sIdentity(), convex);
  653. compound_settings.AddShape(Vec3(0.5f, 0, 0), Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI), convex);
  654. shape = compound_settings.Create().Get();
  655. }
  656. break;
  657. case EProbeShape::StaticCompound2:
  658. {
  659. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  660. Ref<StaticCompoundShapeSettings> compound = new StaticCompoundShapeSettings();
  661. compound->AddShape(Vec3(0, 0.5f, 0), Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI), new BoxShape(Vec3(0.5f, 0.15f, 0.1f)));
  662. compound->AddShape(Vec3(0.5f, 0, 0), Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI), new CylinderShape(0.5f, 0.1f));
  663. compound->AddShape(Vec3(0, 0, 0.5f), Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI), new TaperedCapsuleShapeSettings(0.5f, 0.15f, 0.1f));
  664. StaticCompoundShapeSettings compound2;
  665. compound2.AddShape(Vec3(0, 0, 0), Quat::sRotation(Vec3::sAxisX(), -0.25f * JPH_PI) * Quat::sRotation(Vec3::sAxisZ(), 0.25f * JPH_PI), compound);
  666. compound2.AddShape(Vec3(0, -0.4f, 0), Quat::sRotation(Vec3::sAxisX(), 0.25f * JPH_PI) * Quat::sRotation(Vec3::sAxisZ(), -0.75f * JPH_PI), compound);
  667. shape = compound2.Create().Get();
  668. }
  669. break;
  670. case EProbeShape::MutableCompound:
  671. {
  672. vector<Vec3> tetrahedron;
  673. tetrahedron.push_back(Vec3::sZero());
  674. tetrahedron.push_back(Vec3(-0.2f, 0, 0.4f));
  675. tetrahedron.push_back(Vec3(0, 0.2f, 0));
  676. tetrahedron.push_back(Vec3(0.2f, 0, 0.4f));
  677. RefConst<Shape> convex = ConvexHullShapeSettings(tetrahedron, 0.01f).Create().Get();
  678. MutableCompoundShapeSettings compound_settings;
  679. compound_settings.AddShape(Vec3(-0.5f, 0, 0), Quat::sIdentity(), convex);
  680. compound_settings.AddShape(Vec3(0.5f, 0, 0), Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI), convex);
  681. shape = compound_settings.Create().Get();
  682. }
  683. break;
  684. case EProbeShape::Mesh:
  685. shape = ShapeCreator::CreateTorusMesh(2.0f, 0.25f);
  686. break;
  687. }
  688. JPH_ASSERT(shape != nullptr);
  689. // Scale the shape
  690. if (scale != Vec3::sReplicate(1.0f))
  691. shape = new ScaledShape(shape, scale);
  692. return shape;
  693. }
  694. RefConst<Shape> SamplesApp::CreateShootObjectShape()
  695. {
  696. // Get the scale
  697. Vec3 scale = mShootObjectScaleShape? mShootObjectShapeScale : Vec3::sReplicate(1.0f);
  698. // Make it minimally -0.1 or 0.1 depending on the sign
  699. Vec3 clamped_value = Vec3::sSelect(Vec3::sReplicate(-0.1f), Vec3::sReplicate(0.1f), Vec3::sGreaterOrEqual(scale, Vec3::sZero()));
  700. scale = Vec3::sSelect(scale, clamped_value, Vec3::sLess(scale.Abs(), Vec3::sReplicate(0.1f)));
  701. RefConst<Shape> shape;
  702. switch (mShootObjectShape)
  703. {
  704. case EShootObjectShape::Sphere:
  705. scale = scale.Swizzle<SWIZZLE_X, SWIZZLE_X, SWIZZLE_X>(); // Only uniform scale supported
  706. shape = new SphereShape(GetWorldScale());
  707. break;
  708. case EShootObjectShape::ConvexHull:
  709. {
  710. vector<Vec3> vertices = {
  711. Vec3(-0.044661f, 0.001230f, 0.003877f),
  712. Vec3(-0.024743f, -0.042562f, 0.003877f),
  713. Vec3(-0.012336f, -0.021073f, 0.048484f),
  714. Vec3(0.016066f, 0.028121f, -0.049904f),
  715. Vec3(-0.023734f, 0.043275f, -0.024153f),
  716. Vec3(0.020812f, 0.036341f, -0.019530f),
  717. Vec3(0.012495f, 0.021936f, 0.045288f),
  718. Vec3(0.026750f, 0.001230f, 0.049273f),
  719. Vec3(0.045495f, 0.001230f, -0.022077f),
  720. Vec3(0.022193f, -0.036274f, -0.021126f),
  721. Vec3(0.022781f, -0.037291f, 0.029558f),
  722. Vec3(0.014691f, -0.023280f, 0.052897f),
  723. Vec3(-0.012187f, -0.020815f, -0.040214f),
  724. Vec3(0.000541f, 0.001230f, -0.056224f),
  725. Vec3(-0.039882f, 0.001230f, -0.019461f),
  726. Vec3(0.000541f, 0.001230f, 0.056022f),
  727. Vec3(-0.020614f, -0.035411f, -0.020551f),
  728. Vec3(-0.019485f, 0.035916f, 0.027001f),
  729. Vec3(-0.023968f, 0.043680f, 0.003877f),
  730. Vec3(-0.020051f, 0.001230f, 0.039543f),
  731. Vec3(0.026213f, 0.001230f, -0.040589f),
  732. Vec3(-0.010797f, 0.020868f, 0.043152f),
  733. Vec3(-0.012378f, 0.023607f, -0.040876f)
  734. };
  735. // This shape was created at 0.2 world scale, rescale it to the current world scale
  736. float vert_scale = GetWorldScale() / 0.2f;
  737. for (Vec3 &v : vertices)
  738. v *= vert_scale;
  739. shape = ConvexHullShapeSettings(vertices).Create().Get();
  740. }
  741. break;
  742. case EShootObjectShape::ThinBar:
  743. shape = BoxShapeSettings(Vec3(0.05f, 0.8f, 0.03f), 0.015f).Create().Get();
  744. break;
  745. }
  746. // Scale shape if needed
  747. if (scale != Vec3::sReplicate(1.0f))
  748. shape = new ScaledShape(shape, scale);
  749. return shape;
  750. }
  751. void SamplesApp::ShootObject()
  752. {
  753. // Configure body
  754. BodyCreationSettings creation_settings(CreateShootObjectShape(), GetCamera().mPos, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  755. creation_settings.mMotionQuality = mShootObjectMotionQuality;
  756. creation_settings.mFriction = mShootObjectFriction;
  757. creation_settings.mRestitution = mShootObjectRestitution;
  758. creation_settings.mLinearVelocity = mShootObjectVelocity * GetCamera().mForward;
  759. // Create body
  760. mPhysicsSystem->GetBodyInterface().CreateAndAddBody(creation_settings, EActivation::Activate);
  761. }
  762. bool SamplesApp::CastProbe(float inProbeLength, float &outFraction, Vec3 &outPosition, BodyID &outID)
  763. {
  764. const CameraState &camera = GetCamera();
  765. Vec3 start = camera.mPos;
  766. Vec3 direction = inProbeLength * camera.mForward;
  767. // Clear output
  768. outPosition = start + direction;
  769. outFraction = 1.0f;
  770. outID = BodyID();
  771. bool had_hit = false;
  772. switch (mProbeMode)
  773. {
  774. case EProbeMode::Pick:
  775. {
  776. // Create ray
  777. RayCast ray { start, direction };
  778. // Cast ray
  779. RayCastResult hit;
  780. had_hit = mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, hit, SpecifiedBroadPhaseLayerFilter(BroadPhaseLayers::MOVING), SpecifiedObjectLayerFilter(Layers::MOVING));
  781. // Fill in results
  782. outPosition = start + hit.mFraction * direction;
  783. outFraction = hit.mFraction;
  784. outID = hit.mBodyID;
  785. if (had_hit)
  786. mDebugRenderer->DrawMarker(outPosition, Color::sYellow, 0.1f);
  787. else
  788. mDebugRenderer->DrawMarker(camera.mPos + 0.1f * camera.mForward, Color::sRed, 0.001f);
  789. }
  790. break;
  791. case EProbeMode::Ray:
  792. {
  793. // Create ray
  794. RayCast ray { start, direction };
  795. // Cast ray
  796. RayCastResult hit;
  797. had_hit = mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, hit);
  798. // Fill in results
  799. outPosition = ray.GetPointOnRay(hit.mFraction);
  800. outFraction = hit.mFraction;
  801. outID = hit.mBodyID;
  802. // Draw results
  803. if (had_hit)
  804. {
  805. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  806. if (lock.Succeeded())
  807. {
  808. const Body &hit_body = lock.GetBody();
  809. // Draw hit
  810. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  811. mDebugRenderer->DrawLine(start, outPosition, color);
  812. mDebugRenderer->DrawLine(outPosition, start + direction, Color::sRed);
  813. // Draw material
  814. const PhysicsMaterial *material2 = hit_body.GetShape()->GetMaterial(hit.mSubShapeID2);
  815. mDebugRenderer->DrawText3D(outPosition, material2->GetDebugName());
  816. // Draw normal
  817. Vec3 normal = hit_body.GetWorldSpaceSurfaceNormal(hit.mSubShapeID2, outPosition);
  818. mDebugRenderer->DrawArrow(outPosition, outPosition + normal, color, 0.01f);
  819. // Draw perpendicular axis to indicate hit position
  820. Vec3 perp1 = normal.GetNormalizedPerpendicular();
  821. Vec3 perp2 = normal.Cross(perp1);
  822. mDebugRenderer->DrawLine(outPosition - 0.1f * perp1, outPosition + 0.1f * perp1, color);
  823. mDebugRenderer->DrawLine(outPosition - 0.1f * perp2, outPosition + 0.1f * perp2, color);
  824. }
  825. }
  826. else
  827. {
  828. mDebugRenderer->DrawMarker(outPosition, Color::sRed, 0.1f);
  829. }
  830. }
  831. break;
  832. case EProbeMode::RayCollector:
  833. {
  834. // Create ray
  835. RayCast ray { start, direction };
  836. // Create settings
  837. RayCastSettings settings;
  838. settings.mBackFaceMode = mBackFaceMode;
  839. settings.mTreatConvexAsSolid = mTreatConvexAsSolid;
  840. // Cast ray
  841. vector<RayCastResult> hits;
  842. if (mMaxHits == 0)
  843. {
  844. AnyHitCollisionCollector<CastRayCollector> collector;
  845. mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, settings, collector);
  846. if (collector.HadHit())
  847. hits.push_back(collector.mHit);
  848. }
  849. else if (mMaxHits == 1)
  850. {
  851. ClosestHitCollisionCollector<CastRayCollector> collector;
  852. mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, settings, collector);
  853. if (collector.HadHit())
  854. hits.push_back(collector.mHit);
  855. }
  856. else
  857. {
  858. AllHitCollisionCollector<CastRayCollector> collector;
  859. mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, settings, collector);
  860. collector.Sort();
  861. hits.insert(hits.end(), collector.mHits.begin(), collector.mHits.end());
  862. if ((int)hits.size() > mMaxHits)
  863. hits.resize(mMaxHits);
  864. }
  865. had_hit = !hits.empty();
  866. if (had_hit)
  867. {
  868. // Fill in results
  869. RayCastResult &first_hit = hits.front();
  870. outPosition = start + first_hit.mFraction * direction;
  871. outFraction = first_hit.mFraction;
  872. outID = first_hit.mBodyID;
  873. // Draw results
  874. Vec3 prev_position = start;
  875. bool c = false;
  876. for (const RayCastResult &hit : hits)
  877. {
  878. // Draw line
  879. Vec3 position = ray.GetPointOnRay(hit.mFraction);
  880. mDebugRenderer->DrawLine(prev_position, position, c? Color::sGrey : Color::sWhite);
  881. c = !c;
  882. prev_position = position;
  883. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  884. if (lock.Succeeded())
  885. {
  886. const Body &hit_body = lock.GetBody();
  887. // Draw material
  888. const PhysicsMaterial *material2 = hit_body.GetShape()->GetMaterial(hit.mSubShapeID2);
  889. mDebugRenderer->DrawText3D(position, material2->GetDebugName());
  890. // Draw normal
  891. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  892. Vec3 normal = hit_body.GetWorldSpaceSurfaceNormal(hit.mSubShapeID2, position);
  893. mDebugRenderer->DrawArrow(position, position + normal, color, 0.01f);
  894. // Draw perpendicular axis to indicate hit position
  895. Vec3 perp1 = normal.GetNormalizedPerpendicular();
  896. Vec3 perp2 = normal.Cross(perp1);
  897. mDebugRenderer->DrawLine(position - 0.1f * perp1, position + 0.1f * perp1, color);
  898. mDebugRenderer->DrawLine(position - 0.1f * perp2, position + 0.1f * perp2, color);
  899. }
  900. }
  901. // Draw remainder of line
  902. mDebugRenderer->DrawLine(start + hits.back().mFraction * direction, start + direction, Color::sRed);
  903. }
  904. else
  905. {
  906. // Draw 'miss'
  907. mDebugRenderer->DrawLine(start, start + direction, Color::sRed);
  908. mDebugRenderer->DrawMarker(start + direction, Color::sRed, 0.1f);
  909. }
  910. }
  911. break;
  912. case EProbeMode::CollidePoint:
  913. {
  914. // Create point
  915. const float fraction = 0.1f;
  916. Vec3 point = start + fraction * direction;
  917. // Collide point
  918. AllHitCollisionCollector<CollidePointCollector> collector;
  919. mPhysicsSystem->GetNarrowPhaseQuery().CollidePoint(point, collector);
  920. had_hit = !collector.mHits.empty();
  921. if (had_hit)
  922. {
  923. // Draw results
  924. for (const CollidePointResult &hit : collector.mHits)
  925. {
  926. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  927. if (lock.Succeeded())
  928. {
  929. const Body &hit_body = lock.GetBody();
  930. // Draw bounding box
  931. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  932. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  933. }
  934. }
  935. }
  936. // Draw test location
  937. mDebugRenderer->DrawMarker(start + fraction * direction, had_hit? Color::sGreen : Color::sRed, 0.1f);
  938. }
  939. break;
  940. case EProbeMode::CollideShape:
  941. {
  942. // Create shape cast
  943. RefConst<Shape> shape = CreateProbeShape();
  944. Mat44 rotation = Mat44::sRotation(Vec3::sAxisX(), 0.1f * JPH_PI) * Mat44::sRotation(Vec3::sAxisY(), 0.2f * JPH_PI);
  945. Mat44 com = Mat44::sTranslation(shape->GetCenterOfMass());
  946. Mat44 shape_transform = Mat44::sTranslation(start + 5.0f * camera.mForward) * rotation * com;
  947. // Create settings
  948. CollideShapeSettings settings;
  949. settings.mActiveEdgeMode = mActiveEdgeMode;
  950. settings.mBackFaceMode = mBackFaceMode;
  951. settings.mCollectFacesMode = mCollectFacesMode;
  952. settings.mMaxSeparationDistance = mMaxSeparationDistance;
  953. vector<CollideShapeResult> hits;
  954. if (mMaxHits == 0)
  955. {
  956. AnyHitCollisionCollector<CollideShapeCollector> collector;
  957. mPhysicsSystem->GetNarrowPhaseQuery().CollideShape(shape, Vec3::sReplicate(1.0f), shape_transform, settings, collector);
  958. if (collector.HadHit())
  959. hits.push_back(collector.mHit);
  960. }
  961. else if (mMaxHits == 1)
  962. {
  963. ClosestHitCollisionCollector<CollideShapeCollector> collector;
  964. mPhysicsSystem->GetNarrowPhaseQuery().CollideShape(shape, Vec3::sReplicate(1.0f), shape_transform, settings, collector);
  965. if (collector.HadHit())
  966. hits.push_back(collector.mHit);
  967. }
  968. else
  969. {
  970. AllHitCollisionCollector<CollideShapeCollector> collector;
  971. mPhysicsSystem->GetNarrowPhaseQuery().CollideShape(shape, Vec3::sReplicate(1.0f), shape_transform, settings, collector);
  972. collector.Sort();
  973. hits.insert(hits.end(), collector.mHits.begin(), collector.mHits.end());
  974. if ((int)hits.size() > mMaxHits)
  975. hits.resize(mMaxHits);
  976. }
  977. had_hit = !hits.empty();
  978. if (had_hit)
  979. {
  980. // Draw results
  981. for (const CollideShapeResult &hit : hits)
  982. {
  983. // Draw 'hit'
  984. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID2);
  985. if (lock.Succeeded())
  986. {
  987. const Body &hit_body = lock.GetBody();
  988. // Draw contact
  989. mDebugRenderer->DrawMarker(hit.mContactPointOn1, Color::sGreen, 0.1f);
  990. mDebugRenderer->DrawMarker(hit.mContactPointOn2, Color::sRed, 0.1f);
  991. Vec3 pen_axis = hit.mPenetrationAxis;
  992. float pen_axis_len = pen_axis.Length();
  993. if (pen_axis_len > 0.0f)
  994. {
  995. pen_axis /= pen_axis_len;
  996. // Draw penetration axis with length of the penetration
  997. mDebugRenderer->DrawArrow(hit.mContactPointOn2, hit.mContactPointOn2 + pen_axis * hit.mPenetrationDepth, Color::sYellow, 0.01f);
  998. // Draw normal (flipped so it points towards body 1)
  999. mDebugRenderer->DrawArrow(hit.mContactPointOn2, hit.mContactPointOn2 - pen_axis, Color::sOrange, 0.01f);
  1000. }
  1001. // Draw material
  1002. const PhysicsMaterial *material2 = hit_body.GetShape()->GetMaterial(hit.mSubShapeID2);
  1003. mDebugRenderer->DrawText3D(hit.mContactPointOn2, material2->GetDebugName());
  1004. // Draw faces
  1005. mDebugRenderer->DrawWirePolygon(hit.mShape1Face, Color::sYellow, 0.01f);
  1006. mDebugRenderer->DrawWirePolygon(hit.mShape2Face, Color::sRed, 0.01f);
  1007. }
  1008. }
  1009. }
  1010. #ifdef JPH_DEBUG_RENDERER
  1011. // Draw shape
  1012. shape->Draw(mDebugRenderer, shape_transform, Vec3::sReplicate(1.0f), had_hit? Color::sGreen : Color::sGrey, false, false);
  1013. #endif // JPH_DEBUG_RENDERER
  1014. }
  1015. break;
  1016. case EProbeMode::CastShape:
  1017. {
  1018. // Create shape cast
  1019. RefConst<Shape> shape = CreateProbeShape();
  1020. Mat44 rotation = Mat44::sRotation(Vec3::sAxisX(), 0.1f * JPH_PI) * Mat44::sRotation(Vec3::sAxisY(), 0.2f * JPH_PI);
  1021. ShapeCast shape_cast = ShapeCast::sFromWorldTransform(shape, Vec3::sReplicate(1.0f), Mat44::sTranslation(start) * rotation, direction);
  1022. // Settings
  1023. ShapeCastSettings settings;
  1024. settings.mUseShrunkenShapeAndConvexRadius = mUseShrunkenShapeAndConvexRadius;
  1025. settings.mActiveEdgeMode = mActiveEdgeMode;
  1026. settings.mBackFaceModeTriangles = mBackFaceMode;
  1027. settings.mBackFaceModeConvex = mBackFaceMode;
  1028. settings.mReturnDeepestPoint = mReturnDeepestPoint;
  1029. settings.mCollectFacesMode = mCollectFacesMode;
  1030. // Cast shape
  1031. vector<ShapeCastResult> hits;
  1032. if (mMaxHits == 0)
  1033. {
  1034. AnyHitCollisionCollector<CastShapeCollector> collector;
  1035. mPhysicsSystem->GetNarrowPhaseQuery().CastShape(shape_cast, settings, collector);
  1036. if (collector.HadHit())
  1037. hits.push_back(collector.mHit);
  1038. }
  1039. else if (mMaxHits == 1)
  1040. {
  1041. ClosestHitCollisionCollector<CastShapeCollector> collector;
  1042. mPhysicsSystem->GetNarrowPhaseQuery().CastShape(shape_cast, settings, collector);
  1043. if (collector.HadHit())
  1044. hits.push_back(collector.mHit);
  1045. }
  1046. else
  1047. {
  1048. AllHitCollisionCollector<CastShapeCollector> collector;
  1049. mPhysicsSystem->GetNarrowPhaseQuery().CastShape(shape_cast, settings, collector);
  1050. collector.Sort();
  1051. hits.insert(hits.end(), collector.mHits.begin(), collector.mHits.end());
  1052. if ((int)hits.size() > mMaxHits)
  1053. hits.resize(mMaxHits);
  1054. }
  1055. had_hit = !hits.empty();
  1056. if (had_hit)
  1057. {
  1058. // Fill in results
  1059. ShapeCastResult &first_hit = hits.front();
  1060. outPosition = start + first_hit.mFraction * direction;
  1061. outFraction = first_hit.mFraction;
  1062. outID = first_hit.mBodyID2;
  1063. // Draw results
  1064. Vec3 prev_position = start;
  1065. bool c = false;
  1066. for (const ShapeCastResult &hit : hits)
  1067. {
  1068. // Draw line
  1069. Vec3 position = start + hit.mFraction * direction;
  1070. mDebugRenderer->DrawLine(prev_position, position, c? Color::sGrey : Color::sWhite);
  1071. c = !c;
  1072. prev_position = position;
  1073. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID2);
  1074. if (lock.Succeeded())
  1075. {
  1076. const Body &hit_body = lock.GetBody();
  1077. // Draw shape
  1078. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1079. #ifdef JPH_DEBUG_RENDERER
  1080. shape_cast.mShape->Draw(mDebugRenderer, shape_cast.mCenterOfMassStart.PostTranslated(hit.mFraction * shape_cast.mDirection), Vec3::sReplicate(1.0f), color, false, false);
  1081. #endif // JPH_DEBUG_RENDERER
  1082. // Draw normal
  1083. Vec3 contact_position1 = hit.mContactPointOn1;
  1084. Vec3 contact_position2 = hit.mContactPointOn2;
  1085. Vec3 normal = hit.mPenetrationAxis.Normalized();
  1086. mDebugRenderer->DrawArrow(contact_position2, contact_position2 - normal, color, 0.01f); // Flip to make it point towards the cast body
  1087. // Contact position 1
  1088. mDebugRenderer->DrawMarker(contact_position1, Color::sGreen, 0.1f);
  1089. // Draw perpendicular axis to indicate contact position 2
  1090. Vec3 perp1 = normal.GetNormalizedPerpendicular();
  1091. Vec3 perp2 = normal.Cross(perp1);
  1092. mDebugRenderer->DrawLine(contact_position2 - 0.1f * perp1, contact_position2 + 0.1f * perp1, color);
  1093. mDebugRenderer->DrawLine(contact_position2 - 0.1f * perp2, contact_position2 + 0.1f * perp2, color);
  1094. // Draw material
  1095. const PhysicsMaterial *material2 = hit_body.GetShape()->GetMaterial(hit.mSubShapeID2);
  1096. mDebugRenderer->DrawText3D(position, material2->GetDebugName());
  1097. // Draw faces
  1098. mDebugRenderer->DrawWirePolygon(hit.mShape1Face, Color::sYellow, 0.01f);
  1099. mDebugRenderer->DrawWirePolygon(hit.mShape2Face, Color::sRed, 0.01f);
  1100. }
  1101. }
  1102. // Draw remainder of line
  1103. mDebugRenderer->DrawLine(start + hits.back().mFraction * direction, start + direction, Color::sRed);
  1104. }
  1105. else
  1106. {
  1107. // Draw 'miss'
  1108. mDebugRenderer->DrawLine(start, start + direction, Color::sRed);
  1109. #ifdef JPH_DEBUG_RENDERER
  1110. shape_cast.mShape->Draw(mDebugRenderer, shape_cast.mCenterOfMassStart.PostTranslated(shape_cast.mDirection), Vec3::sReplicate(1.0f), Color::sRed, false, false);
  1111. #endif // JPH_DEBUG_RENDERER
  1112. }
  1113. }
  1114. break;
  1115. case EProbeMode::TransformedShape:
  1116. {
  1117. // Create box
  1118. const float fraction = 0.2f;
  1119. Vec3 center = start + fraction * direction;
  1120. Vec3 half_extent = 0.5f * mShapeScale;
  1121. AABox box(center - half_extent, center + half_extent);
  1122. // Get shapes
  1123. AllHitCollisionCollector<TransformedShapeCollector> collector;
  1124. mPhysicsSystem->GetNarrowPhaseQuery().CollectTransformedShapes(box, collector);
  1125. // Draw results
  1126. for (const TransformedShape &ts : collector.mHits)
  1127. mDebugRenderer->DrawWireBox(Mat44::sRotationTranslation(ts.mShapeRotation, ts.mShapePositionCOM) * Mat44::sScale(ts.GetShapeScale()), ts.mShape->GetLocalBounds(), Color::sYellow);
  1128. // Draw test location
  1129. mDebugRenderer->DrawWireBox(box, !collector.mHits.empty()? Color::sGreen : Color::sRed);
  1130. }
  1131. break;
  1132. case EProbeMode::GetTriangles:
  1133. {
  1134. // Create box
  1135. const float fraction = 0.2f;
  1136. Vec3 center = start + fraction * direction;
  1137. Vec3 half_extent = 2.0f * mShapeScale;
  1138. AABox box(center - half_extent, center + half_extent);
  1139. // Get shapes
  1140. AllHitCollisionCollector<TransformedShapeCollector> collector;
  1141. mPhysicsSystem->GetNarrowPhaseQuery().CollectTransformedShapes(box, collector);
  1142. // Loop over shapes
  1143. had_hit = false;
  1144. for (const TransformedShape &ts : collector.mHits)
  1145. {
  1146. const int cMaxTriangles = 32;
  1147. Float3 vertices[cMaxTriangles * 3];
  1148. const PhysicsMaterial *materials[cMaxTriangles];
  1149. // Start iterating triangles
  1150. Shape::GetTrianglesContext ctx;
  1151. ts.GetTrianglesStart(ctx, box);
  1152. for (;;)
  1153. {
  1154. // Fetch next triangles
  1155. int count = ts.GetTrianglesNext(ctx, cMaxTriangles, vertices, materials);
  1156. if (count == 0)
  1157. break;
  1158. // Draw triangles
  1159. const PhysicsMaterial **m = materials;
  1160. for (Float3 *v = vertices, *v_end = vertices + 3 * count; v < v_end; v += 3, ++m)
  1161. {
  1162. Vec3 v1(v[0]), v2(v[1]), v3(v[2]);
  1163. Vec3 triangle_center = (v1 + v2 + v3) / 3.0f;
  1164. Vec3 triangle_normal = (v2 - v1).Cross(v3 - v1).Normalized();
  1165. mDebugRenderer->DrawWireTriangle(v1, v2, v3, (*m)->GetDebugColor());
  1166. mDebugRenderer->DrawArrow(triangle_center, triangle_center + triangle_normal, Color::sGreen, 0.01f);
  1167. }
  1168. had_hit = true;
  1169. }
  1170. }
  1171. // Draw test location
  1172. mDebugRenderer->DrawWireBox(box, had_hit? Color::sGreen : Color::sRed);
  1173. }
  1174. break;
  1175. case EProbeMode::BroadPhaseRay:
  1176. {
  1177. // Create ray
  1178. RayCast ray { start, direction };
  1179. // Cast ray
  1180. AllHitCollisionCollector<RayCastBodyCollector> collector;
  1181. mPhysicsSystem->GetBroadPhaseQuery().CastRay(ray, collector);
  1182. collector.Sort();
  1183. had_hit = !collector.mHits.empty();
  1184. if (had_hit)
  1185. {
  1186. // Draw results
  1187. Vec3 prev_position = start;
  1188. bool c = false;
  1189. for (const BroadPhaseCastResult &hit : collector.mHits)
  1190. {
  1191. // Draw line
  1192. Vec3 position = start + hit.mFraction * direction;
  1193. Color cast_color = c? Color::sGrey : Color::sWhite;
  1194. mDebugRenderer->DrawLine(prev_position, position, cast_color);
  1195. mDebugRenderer->DrawMarker(position, cast_color, 0.1f);
  1196. c = !c;
  1197. prev_position = position;
  1198. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  1199. if (lock.Succeeded())
  1200. {
  1201. const Body &hit_body = lock.GetBody();
  1202. // Draw bounding box
  1203. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1204. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1205. }
  1206. }
  1207. // Draw remainder of line
  1208. mDebugRenderer->DrawLine(start + collector.mHits.back().mFraction * direction, start + direction, Color::sRed);
  1209. }
  1210. else
  1211. {
  1212. // Draw 'miss'
  1213. mDebugRenderer->DrawLine(start, start + direction, Color::sRed);
  1214. mDebugRenderer->DrawMarker(start + direction, Color::sRed, 0.1f);
  1215. }
  1216. }
  1217. break;
  1218. case EProbeMode::BroadPhaseBox:
  1219. {
  1220. // Create box
  1221. const float fraction = 0.2f;
  1222. Vec3 center = start + fraction * direction;
  1223. Vec3 half_extent = 2.0f * mShapeScale;
  1224. AABox box(center - half_extent, center + half_extent);
  1225. // Collide box
  1226. AllHitCollisionCollector<CollideShapeBodyCollector> collector;
  1227. mPhysicsSystem->GetBroadPhaseQuery().CollideAABox(box, collector);
  1228. had_hit = !collector.mHits.empty();
  1229. if (had_hit)
  1230. {
  1231. // Draw results
  1232. for (const BodyID &hit : collector.mHits)
  1233. {
  1234. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit);
  1235. if (lock.Succeeded())
  1236. {
  1237. const Body &hit_body = lock.GetBody();
  1238. // Draw bounding box
  1239. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1240. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1241. }
  1242. }
  1243. }
  1244. // Draw test location
  1245. mDebugRenderer->DrawWireBox(box, had_hit? Color::sGreen : Color::sRed);
  1246. }
  1247. break;
  1248. case EProbeMode::BroadPhaseSphere:
  1249. {
  1250. // Create sphere
  1251. const float fraction = 0.2f;
  1252. const float radius = mShapeScale.Length() * 2.0f;
  1253. Vec3 point = start + fraction * direction;
  1254. // Collide sphere
  1255. AllHitCollisionCollector<CollideShapeBodyCollector> collector;
  1256. mPhysicsSystem->GetBroadPhaseQuery().CollideSphere(point, radius, collector);
  1257. had_hit = !collector.mHits.empty();
  1258. if (had_hit)
  1259. {
  1260. // Draw results
  1261. for (const BodyID &hit : collector.mHits)
  1262. {
  1263. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit);
  1264. if (lock.Succeeded())
  1265. {
  1266. const Body &hit_body = lock.GetBody();
  1267. // Draw bounding box
  1268. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1269. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1270. }
  1271. }
  1272. }
  1273. // Draw test location
  1274. mDebugRenderer->DrawWireSphere(start + fraction * direction, radius, had_hit? Color::sGreen : Color::sRed);
  1275. }
  1276. break;
  1277. case EProbeMode::BroadPhasePoint:
  1278. {
  1279. // Create point
  1280. const float fraction = 0.1f;
  1281. Vec3 point = start + fraction * direction;
  1282. // Collide point
  1283. AllHitCollisionCollector<CollideShapeBodyCollector> collector;
  1284. mPhysicsSystem->GetBroadPhaseQuery().CollidePoint(point, collector);
  1285. had_hit = !collector.mHits.empty();
  1286. if (had_hit)
  1287. {
  1288. // Draw results
  1289. for (const BodyID &hit : collector.mHits)
  1290. {
  1291. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit);
  1292. if (lock.Succeeded())
  1293. {
  1294. const Body &hit_body = lock.GetBody();
  1295. // Draw bounding box
  1296. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1297. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1298. }
  1299. }
  1300. }
  1301. // Draw test location
  1302. mDebugRenderer->DrawMarker(start + fraction * direction, had_hit? Color::sGreen : Color::sRed, 0.1f);
  1303. }
  1304. break;
  1305. case EProbeMode::BroadPhaseOrientedBox:
  1306. {
  1307. // Create box
  1308. const float fraction = 0.2f;
  1309. Vec3 center = start + fraction * direction;
  1310. Vec3 half_extent = 2.0f * mShapeScale;
  1311. OrientedBox box(Mat44::sRotationTranslation(Quat::sRotation(Vec3::sAxisZ(), 0.2f * JPH_PI) * Quat::sRotation(Vec3::sAxisX(), 0.1f * JPH_PI), center), half_extent);
  1312. // Collide box
  1313. AllHitCollisionCollector<CollideShapeBodyCollector> collector;
  1314. mPhysicsSystem->GetBroadPhaseQuery().CollideOrientedBox(box, collector);
  1315. had_hit = !collector.mHits.empty();
  1316. if (had_hit)
  1317. {
  1318. // Draw results
  1319. for (const BodyID &hit : collector.mHits)
  1320. {
  1321. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit);
  1322. if (lock.Succeeded())
  1323. {
  1324. const Body &hit_body = lock.GetBody();
  1325. // Draw bounding box
  1326. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1327. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1328. }
  1329. }
  1330. }
  1331. // Draw test location
  1332. mDebugRenderer->DrawWireBox(box, had_hit? Color::sGreen : Color::sRed);
  1333. }
  1334. break;
  1335. case EProbeMode::BroadPhaseCastBox:
  1336. {
  1337. // Create box
  1338. Vec3 half_extent = 2.0f * mShapeScale;
  1339. AABox box(start - half_extent, start + half_extent);
  1340. AABoxCast box_cast { box, direction };
  1341. // Cast box
  1342. AllHitCollisionCollector<CastShapeBodyCollector> collector;
  1343. mPhysicsSystem->GetBroadPhaseQuery().CastAABox(box_cast, collector);
  1344. collector.Sort();
  1345. had_hit = !collector.mHits.empty();
  1346. if (had_hit)
  1347. {
  1348. // Draw results
  1349. Vec3 prev_position = start;
  1350. bool c = false;
  1351. for (const BroadPhaseCastResult &hit : collector.mHits)
  1352. {
  1353. // Draw line
  1354. Vec3 position = start + hit.mFraction * direction;
  1355. Color cast_color = c? Color::sGrey : Color::sWhite;
  1356. mDebugRenderer->DrawLine(prev_position, position, cast_color);
  1357. mDebugRenderer->DrawWireBox(AABox(position - half_extent, position + half_extent), cast_color);
  1358. c = !c;
  1359. prev_position = position;
  1360. BodyLockRead lock(mPhysicsSystem->GetBodyLockInterface(), hit.mBodyID);
  1361. if (lock.Succeeded())
  1362. {
  1363. const Body &hit_body = lock.GetBody();
  1364. // Draw bounding box
  1365. Color color = hit_body.IsDynamic()? Color::sYellow : Color::sOrange;
  1366. mDebugRenderer->DrawWireBox(hit_body.GetWorldSpaceBounds(), color);
  1367. }
  1368. }
  1369. // Draw remainder of line
  1370. mDebugRenderer->DrawLine(start + collector.mHits.back().mFraction * direction, start + direction, Color::sRed);
  1371. }
  1372. else
  1373. {
  1374. // Draw 'miss'
  1375. mDebugRenderer->DrawLine(start, start + direction, Color::sRed);
  1376. mDebugRenderer->DrawWireBox(AABox(start + direction - half_extent, start + direction + half_extent), Color::sRed);
  1377. }
  1378. }
  1379. break;
  1380. }
  1381. return had_hit;
  1382. }
  1383. void SamplesApp::UpdateDebug()
  1384. {
  1385. JPH_PROFILE_FUNCTION();
  1386. const float cDragRayLength = 40.0f;
  1387. BodyInterface &bi = mPhysicsSystem->GetBodyInterface();
  1388. // Handle keyboard input for which simulation needs to be running
  1389. for (int key = mKeyboard->GetFirstKey(); key != 0; key = mKeyboard->GetNextKey())
  1390. switch (key)
  1391. {
  1392. case DIK_B:
  1393. ShootObject();
  1394. break;
  1395. }
  1396. // Allow the user to drag rigid bodies around
  1397. if (mDragConstraint == nullptr)
  1398. {
  1399. // Not dragging yet
  1400. Vec3 hit_position;
  1401. float hit_fraction;
  1402. if (CastProbe(cDragRayLength, hit_fraction, hit_position, mDragBody))
  1403. {
  1404. // If key is pressed create constraint to start dragging
  1405. if (mKeyboard->IsKeyPressed(DIK_SPACE))
  1406. {
  1407. // Target body must be dynamic
  1408. BodyLockWrite lock(mPhysicsSystem->GetBodyLockInterface(), mDragBody);
  1409. if (lock.Succeeded())
  1410. {
  1411. Body &drag_body = lock.GetBody();
  1412. if (drag_body.IsDynamic())
  1413. {
  1414. // Create constraint to drag body
  1415. DistanceConstraintSettings settings;
  1416. settings.mPoint1 = settings.mPoint2 = hit_position;
  1417. settings.mFrequency = 2.0f / GetWorldScale();
  1418. settings.mDamping = 1.0f;
  1419. // Construct fixed body for the mouse constraint
  1420. // Note that we don't add it to the world since we don't want anything to collide with it, we just
  1421. // need an anchor for a constraint
  1422. Body *drag_anchor = bi.CreateBody(BodyCreationSettings(new SphereShape(0.01f), hit_position, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  1423. mDragAnchor = drag_anchor;
  1424. // Construct constraint that connects the drag anchor with the body that we want to drag
  1425. mDragConstraint = settings.Create(*drag_anchor, drag_body);
  1426. mPhysicsSystem->AddConstraint(mDragConstraint);
  1427. mDragFraction = hit_fraction;
  1428. }
  1429. }
  1430. }
  1431. }
  1432. }
  1433. else
  1434. {
  1435. if (!mKeyboard->IsKeyPressed(DIK_SPACE))
  1436. {
  1437. // If key released, destroy constraint
  1438. if (mDragConstraint != nullptr)
  1439. mPhysicsSystem->RemoveConstraint(mDragConstraint);
  1440. mDragConstraint = nullptr;
  1441. // Destroy drag anchor
  1442. bi.DestroyBody(mDragAnchor->GetID());
  1443. mDragAnchor = nullptr;
  1444. // Forget the drag body
  1445. mDragBody = BodyID();
  1446. }
  1447. else
  1448. {
  1449. // Else update position of anchor
  1450. bi.SetPositionAndRotation(mDragAnchor->GetID(), GetCamera().mPos + cDragRayLength * mDragFraction * GetCamera().mForward, Quat::sIdentity(), EActivation::DontActivate);
  1451. // Activate other body
  1452. bi.ActivateBody(mDragBody);
  1453. }
  1454. }
  1455. }
  1456. bool SamplesApp::RenderFrame(float inDeltaTime)
  1457. {
  1458. // Reinitialize the job system if the concurrency setting changed
  1459. if (mMaxConcurrentJobs != mJobSystem->GetMaxConcurrency())
  1460. static_cast<JobSystemThreadPool *>(mJobSystem)->SetNumThreads(mMaxConcurrentJobs - 1);
  1461. // Restart the test if the test requests this
  1462. if (mTest->NeedsRestart())
  1463. {
  1464. StartTest(mTestClass);
  1465. return true;
  1466. }
  1467. // Select the next test if automatic testing times out
  1468. if (!CheckNextTest())
  1469. return false;
  1470. // Handle keyboard input
  1471. bool shift = mKeyboard->IsKeyPressed(DIK_LSHIFT) || mKeyboard->IsKeyPressed(DIK_RSHIFT);
  1472. #ifdef JPH_DEBUG_RENDERER
  1473. bool alt = mKeyboard->IsKeyPressed(DIK_LALT) || mKeyboard->IsKeyPressed(DIK_RALT);
  1474. #endif // JPH_DEBUG_RENDERER
  1475. for (int key = mKeyboard->GetFirstKey(); key != 0; key = mKeyboard->GetNextKey())
  1476. switch (key)
  1477. {
  1478. case DIK_R:
  1479. StartTest(mTestClass);
  1480. return true;
  1481. case DIK_N:
  1482. if (!mTestsToRun.empty())
  1483. NextTest();
  1484. break;
  1485. #ifdef JPH_DEBUG_RENDERER
  1486. case DIK_H:
  1487. if (shift)
  1488. mBodyDrawSettings.mDrawGetSupportFunction = !mBodyDrawSettings.mDrawGetSupportFunction;
  1489. else if (alt)
  1490. mDrawGetTriangles = !mDrawGetTriangles;
  1491. else
  1492. mBodyDrawSettings.mDrawShape = !mBodyDrawSettings.mDrawShape;
  1493. break;
  1494. case DIK_F:
  1495. if (shift)
  1496. mBodyDrawSettings.mDrawGetSupportingFace = !mBodyDrawSettings.mDrawGetSupportingFace;
  1497. break;
  1498. case DIK_I:
  1499. mBodyDrawSettings.mDrawMassAndInertia = !mBodyDrawSettings.mDrawMassAndInertia;
  1500. break;
  1501. case DIK_1:
  1502. ContactConstraintManager::sDrawContactPoint = !ContactConstraintManager::sDrawContactPoint;
  1503. break;
  1504. case DIK_2:
  1505. ContactConstraintManager::sDrawSupportingFaces = !ContactConstraintManager::sDrawSupportingFaces;
  1506. break;
  1507. case DIK_3:
  1508. ContactConstraintManager::sDrawContactPointReduction = !ContactConstraintManager::sDrawContactPointReduction;
  1509. break;
  1510. case DIK_C:
  1511. mDrawConstraints = !mDrawConstraints;
  1512. break;
  1513. case DIK_L:
  1514. mDrawConstraintLimits = !mDrawConstraintLimits;
  1515. break;
  1516. case DIK_M:
  1517. ContactConstraintManager::sDrawContactManifolds = !ContactConstraintManager::sDrawContactManifolds;
  1518. break;
  1519. case DIK_W:
  1520. if (alt)
  1521. mBodyDrawSettings.mDrawShapeWireframe = !mBodyDrawSettings.mDrawShapeWireframe;
  1522. break;
  1523. #endif // JPH_DEBUG_RENDERER
  1524. case DIK_COMMA:
  1525. // Back stepping
  1526. if (mPlaybackFrames.size() > 1)
  1527. {
  1528. if (mPlaybackMode == EPlaybackMode::Play)
  1529. {
  1530. JPH_ASSERT(mCurrentPlaybackFrame == -1);
  1531. mCurrentPlaybackFrame = (int)mPlaybackFrames.size() - 1;
  1532. }
  1533. mPlaybackMode = shift? EPlaybackMode::Rewind : EPlaybackMode::StepBack;
  1534. }
  1535. break;
  1536. case DIK_PERIOD:
  1537. // Forward stepping
  1538. if (mPlaybackMode != EPlaybackMode::Play)
  1539. {
  1540. JPH_ASSERT(mCurrentPlaybackFrame >= 0);
  1541. mPlaybackMode = shift? EPlaybackMode::FastForward : EPlaybackMode::StepForward;
  1542. }
  1543. break;
  1544. }
  1545. // Stop recording if record state is turned off
  1546. if (!mRecordState)
  1547. {
  1548. mPlaybackFrames.clear();
  1549. mPlaybackMode = EPlaybackMode::Play;
  1550. mCurrentPlaybackFrame = -1;
  1551. }
  1552. // Determine if we need to check deterministic simulation
  1553. bool check_determinism = mCheckDeterminism && mTest->IsDeterministic();
  1554. // Check if we've in replay mode
  1555. if (mPlaybackMode != EPlaybackMode::Play)
  1556. {
  1557. JPH_PROFILE("RestoreState");
  1558. // We're in replay mode
  1559. JPH_ASSERT(mCurrentPlaybackFrame >= 0);
  1560. // Ensure the simulation is paused
  1561. Pause(true);
  1562. // Always restore state when not paused, the debug drawing will be cleared
  1563. bool restore_state = inDeltaTime > 0.0f;
  1564. // Advance to the next frame when single stepping or unpausing
  1565. switch (mPlaybackMode)
  1566. {
  1567. case EPlaybackMode::StepBack:
  1568. mPlaybackMode = EPlaybackMode::Stop;
  1569. [[fallthrough]];
  1570. case EPlaybackMode::Rewind:
  1571. if (mCurrentPlaybackFrame > 0)
  1572. {
  1573. mCurrentPlaybackFrame--;
  1574. restore_state = true;
  1575. }
  1576. break;
  1577. case EPlaybackMode::StepForward:
  1578. mPlaybackMode = EPlaybackMode::Stop;
  1579. [[fallthrough]];
  1580. case EPlaybackMode::FastForward:
  1581. if (mCurrentPlaybackFrame < (int)mPlaybackFrames.size() - 1)
  1582. {
  1583. mCurrentPlaybackFrame++;
  1584. restore_state = true;
  1585. }
  1586. break;
  1587. case EPlaybackMode::Stop:
  1588. case EPlaybackMode::Play:
  1589. // Satisfy compiler
  1590. break;
  1591. }
  1592. // If the replay frame changed we need to update state
  1593. if (restore_state)
  1594. {
  1595. // Clear existing debug stuff so we can render this restored frame
  1596. // (if we're paused, we will otherwise not clear the debugging stuff)
  1597. ClearDebugRenderer();
  1598. // Restore state to what it was during that time
  1599. StateRecorderImpl &recorder = mPlaybackFrames[mCurrentPlaybackFrame];
  1600. RestoreState(recorder);
  1601. // Physics world is drawn using debug lines, when not paused
  1602. // Draw state prior to step so that debug lines are created from the same state
  1603. // (the constraints are solved on the current state and then the world is stepped)
  1604. DrawPhysics();
  1605. // Step the world (with fixed frequency)
  1606. StepPhysics(mJobSystem);
  1607. #ifdef JPH_DEBUG_RENDERER
  1608. // Draw any contacts that were collected through the contact listener
  1609. if (mContactListener)
  1610. mContactListener->DrawState();
  1611. #endif // JPH_DEBUG_RENDERER
  1612. // Validate that update result is the same as the previously recorded state
  1613. if (check_determinism && mCurrentPlaybackFrame < (int)mPlaybackFrames.size() - 1)
  1614. ValidateState(mPlaybackFrames[mCurrentPlaybackFrame + 1]);
  1615. }
  1616. // On the last frame go back to play mode
  1617. if (mCurrentPlaybackFrame >= (int)mPlaybackFrames.size() - 1)
  1618. {
  1619. mPlaybackMode = EPlaybackMode::Play;
  1620. mCurrentPlaybackFrame = -1;
  1621. }
  1622. // On the first frame go to stop mode
  1623. if (mCurrentPlaybackFrame == 0)
  1624. mPlaybackMode = EPlaybackMode::Stop;
  1625. }
  1626. else
  1627. {
  1628. // Normal update
  1629. JPH_ASSERT(mCurrentPlaybackFrame == -1);
  1630. if (inDeltaTime > 0.0f)
  1631. {
  1632. // Debugging functionality like shooting a ball and dragging objects
  1633. UpdateDebug();
  1634. if (mRecordState || check_determinism)
  1635. {
  1636. // Record the state prior to the step
  1637. mPlaybackFrames.push_back(StateRecorderImpl());
  1638. SaveState(mPlaybackFrames.back());
  1639. }
  1640. // Physics world is drawn using debug lines, when not paused
  1641. // Draw state prior to step so that debug lines are created from the same state
  1642. // (the constraints are solved on the current state and then the world is stepped)
  1643. DrawPhysics();
  1644. // Update the physics world
  1645. StepPhysics(mJobSystem);
  1646. #ifdef JPH_DEBUG_RENDERER
  1647. // Draw any contacts that were collected through the contact listener
  1648. if (mContactListener)
  1649. mContactListener->DrawState();
  1650. #endif // JPH_DEBUG_RENDERER
  1651. if (check_determinism)
  1652. {
  1653. // Save the current state
  1654. StateRecorderImpl post_step_state;
  1655. SaveState(post_step_state);
  1656. // Restore to the previous state
  1657. RestoreState(mPlaybackFrames.back());
  1658. // Step again
  1659. StepPhysics(mJobSystemValidating);
  1660. // Validate that the result is the same
  1661. ValidateState(post_step_state);
  1662. }
  1663. }
  1664. }
  1665. return true;
  1666. }
  1667. void SamplesApp::DrawPhysics()
  1668. {
  1669. #ifdef JPH_DEBUG_RENDERER
  1670. mPhysicsSystem->DrawBodies(mBodyDrawSettings, mDebugRenderer);
  1671. if (mDrawConstraints)
  1672. mPhysicsSystem->DrawConstraints(mDebugRenderer);
  1673. if (mDrawConstraintLimits)
  1674. mPhysicsSystem->DrawConstraintLimits(mDebugRenderer);
  1675. if (mDrawConstraintReferenceFrame)
  1676. mPhysicsSystem->DrawConstraintReferenceFrame(mDebugRenderer);
  1677. #endif // JPH_DEBUG_RENDERER
  1678. // This map collects the shapes that we used this frame
  1679. ShapeToGeometryMap shape_to_geometry;
  1680. #ifdef JPH_DEBUG_RENDERER
  1681. if (mDrawGetTriangles)
  1682. #endif // JPH_DEBUG_RENDERER
  1683. {
  1684. JPH_PROFILE("DrawGetTriangles");
  1685. // Iterate through all active bodies
  1686. BodyIDVector bodies;
  1687. mPhysicsSystem->GetBodies(bodies);
  1688. const BodyLockInterface &bli = mPhysicsSystem->GetBodyLockInterface();
  1689. for (BodyID b : bodies)
  1690. {
  1691. // Get the body
  1692. BodyLockRead lock(bli, b);
  1693. if (lock.SucceededAndIsInBroadPhase())
  1694. {
  1695. // Collect all leaf shapes for the body and their transforms
  1696. const Body &body = lock.GetBody();
  1697. AllHitCollisionCollector<TransformedShapeCollector> collector;
  1698. body.GetTransformedShape().CollectTransformedShapes(body.GetWorldSpaceBounds(), collector);
  1699. // Draw all leaf shapes
  1700. for (const TransformedShape &transformed_shape : collector.mHits)
  1701. {
  1702. DebugRenderer::GeometryRef geometry;
  1703. // Find geometry from previous frame
  1704. ShapeToGeometryMap::iterator map_iterator = mShapeToGeometry.find(transformed_shape.mShape);
  1705. if (map_iterator != mShapeToGeometry.end())
  1706. geometry = map_iterator->second;
  1707. if (geometry == nullptr)
  1708. {
  1709. // Find geometry from this frame
  1710. map_iterator = shape_to_geometry.find(transformed_shape.mShape);
  1711. if (map_iterator != shape_to_geometry.end())
  1712. geometry = map_iterator->second;
  1713. }
  1714. if (geometry == nullptr)
  1715. {
  1716. // Geometry not cached
  1717. vector<DebugRenderer::Triangle> triangles;
  1718. // Start iterating all triangles of the shape
  1719. Shape::GetTrianglesContext context;
  1720. transformed_shape.mShape->GetTrianglesStart(context, AABox::sBiggest(), Vec3::sZero(), Quat::sIdentity(), Vec3::sReplicate(1.0f));
  1721. for (;;)
  1722. {
  1723. // Get the next batch of vertices
  1724. constexpr int cMaxTriangles = 1000;
  1725. Float3 vertices[3 * cMaxTriangles];
  1726. int triangle_count = transformed_shape.mShape->GetTrianglesNext(context, cMaxTriangles, vertices);
  1727. if (triangle_count == 0)
  1728. break;
  1729. // Allocate space for triangles
  1730. size_t output_index = triangles.size();
  1731. triangles.resize(triangles.size() + triangle_count);
  1732. DebugRenderer::Triangle *triangle = &triangles[output_index];
  1733. // Convert to a renderable triangle
  1734. for (int vertex = 0, vertex_max = 3 * triangle_count; vertex < vertex_max; vertex += 3, ++triangle)
  1735. {
  1736. // Get the vertices
  1737. Vec3 v1(vertices[vertex + 0]);
  1738. Vec3 v2(vertices[vertex + 1]);
  1739. Vec3 v3(vertices[vertex + 2]);
  1740. // Calculate the normal
  1741. Float3 normal;
  1742. (v2 - v1).Cross(v3 - v1).NormalizedOr(Vec3::sZero()).StoreFloat3(&normal);
  1743. v1.StoreFloat3(&triangle->mV[0].mPosition);
  1744. triangle->mV[0].mNormal = normal;
  1745. triangle->mV[0].mColor = Color::sWhite;
  1746. triangle->mV[0].mUV = Float2(0, 0);
  1747. v2.StoreFloat3(&triangle->mV[1].mPosition);
  1748. triangle->mV[1].mNormal = normal;
  1749. triangle->mV[1].mColor = Color::sWhite;
  1750. triangle->mV[1].mUV = Float2(0, 0);
  1751. v3.StoreFloat3(&triangle->mV[2].mPosition);
  1752. triangle->mV[2].mNormal = normal;
  1753. triangle->mV[2].mColor = Color::sWhite;
  1754. triangle->mV[2].mUV = Float2(0, 0);
  1755. }
  1756. }
  1757. // Convert to geometry
  1758. geometry = new DebugRenderer::Geometry(mDebugRenderer->CreateTriangleBatch(triangles), transformed_shape.mShape->GetLocalBounds());
  1759. }
  1760. // Ensure that we cache the geometry for next frame
  1761. shape_to_geometry[transformed_shape.mShape] = geometry;
  1762. // Determine color
  1763. Color color;
  1764. switch (body.GetMotionType())
  1765. {
  1766. case EMotionType::Static:
  1767. color = Color::sGrey;
  1768. break;
  1769. case EMotionType::Kinematic:
  1770. color = Color::sGreen;
  1771. break;
  1772. case EMotionType::Dynamic:
  1773. color = Color::sGetDistinctColor(body.GetID().GetIndex());
  1774. break;
  1775. default:
  1776. JPH_ASSERT(false);
  1777. color = Color::sBlack;
  1778. break;
  1779. }
  1780. // Draw the geometry
  1781. Vec3 scale = transformed_shape.GetShapeScale();
  1782. bool inside_out = ScaleHelpers::IsInsideOut(scale);
  1783. Mat44 matrix = transformed_shape.GetCenterOfMassTransform() * Mat44::sScale(scale);
  1784. mDebugRenderer->DrawGeometry(matrix, color, geometry, inside_out? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace, DebugRenderer::ECastShadow::On, body.IsSensor()? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid);
  1785. }
  1786. }
  1787. }
  1788. }
  1789. // Replace the map with the newly created map so that shapes that we don't draw / were removed are released
  1790. mShapeToGeometry = move(shape_to_geometry);
  1791. }
  1792. void SamplesApp::StepPhysics(JobSystem *inJobSystem)
  1793. {
  1794. float delta_time = 1.0f / mUpdateFrequency;
  1795. {
  1796. // Pre update
  1797. JPH_PROFILE("PrePhysicsUpdate");
  1798. Test::PreUpdateParams pre_update;
  1799. pre_update.mDeltaTime = delta_time;
  1800. pre_update.mKeyboard = mKeyboard;
  1801. pre_update.mCameraState = GetCamera();
  1802. #ifdef JPH_DEBUG_RENDERER
  1803. pre_update.mPoseDrawSettings = &mPoseDrawSettings;
  1804. #endif // JPH_DEBUG_RENDERER
  1805. mTest->PrePhysicsUpdate(pre_update);
  1806. }
  1807. // Remember start tick
  1808. uint64 start_tick = GetProcessorTickCount();
  1809. // Step the world (with fixed frequency)
  1810. mPhysicsSystem->Update(delta_time, mCollisionSteps, mIntegrationSubSteps, mTempAllocator, inJobSystem);
  1811. #ifndef JPH_DISABLE_TEMP_ALLOCATOR
  1812. JPH_ASSERT(static_cast<TempAllocatorImpl *>(mTempAllocator)->IsEmpty());
  1813. #endif // JPH_DISABLE_TEMP_ALLOCATOR
  1814. // Accumulate time
  1815. mTotalTime += GetProcessorTickCount() - start_tick;
  1816. mStepNumber++;
  1817. // Print timing information
  1818. constexpr int cNumSteps = 60;
  1819. if (mStepNumber % cNumSteps == 0)
  1820. {
  1821. double us_per_step = double(mTotalTime / cNumSteps) / double(GetProcessorTicksPerSecond()) * 1.0e6;
  1822. Trace("Timing: %d, %.0f", mStepNumber / cNumSteps, us_per_step);
  1823. mTotalTime = 0;
  1824. }
  1825. #ifdef JPH_TRACK_BROADPHASE_STATS
  1826. if (mStepNumber % 600 == 0)
  1827. mPhysicsSystem->ReportBroadphaseStats();
  1828. #endif // JPH_TRACK_BROADPHASE_STATS
  1829. #ifdef JPH_TRACK_NARROWPHASE_STATS
  1830. if (mStepNumber % 600 == 0)
  1831. NarrowPhaseStat::sReportStats();
  1832. #endif // JPH_TRACK_NARROWPHASE_STATS
  1833. {
  1834. // Post update
  1835. JPH_PROFILE("PostPhysicsUpdate");
  1836. mTest->PostPhysicsUpdate(delta_time);
  1837. }
  1838. }
  1839. void SamplesApp::SaveState(StateRecorderImpl &inStream)
  1840. {
  1841. mTest->SaveState(inStream);
  1842. if (mContactListener)
  1843. mContactListener->SaveState(inStream);
  1844. mPhysicsSystem->SaveState(inStream);
  1845. }
  1846. void SamplesApp::RestoreState(StateRecorderImpl &inStream)
  1847. {
  1848. inStream.Rewind();
  1849. // Restore the state of the test first, this is needed because the test can make changes to
  1850. // the state of bodies that is not tracked by the PhysicsSystem::SaveState.
  1851. // E.g. in the ChangeShapeTest the shape is restored here, which needs to be done first
  1852. // because changing the shape changes Body::mPosition when the center of mass changes.
  1853. mTest->RestoreState(inStream);
  1854. if (mContactListener)
  1855. mContactListener->RestoreState(inStream);
  1856. if (!mPhysicsSystem->RestoreState(inStream))
  1857. FatalError("Failed to restore physics state");
  1858. }
  1859. void SamplesApp::ValidateState(StateRecorderImpl &inExpectedState)
  1860. {
  1861. // Save state
  1862. StateRecorderImpl current_state;
  1863. SaveState(current_state);
  1864. // Compare state with expected state
  1865. if (!current_state.IsEqual(inExpectedState))
  1866. {
  1867. // Mark this stream to break whenever it detects a memory change during reading
  1868. inExpectedState.SetValidating(true);
  1869. // Restore state. Anything that changes indicates a problem with the deterministic simulation.
  1870. RestoreState(inExpectedState);
  1871. // Turn change detection off again
  1872. inExpectedState.SetValidating(false);
  1873. }
  1874. }
  1875. void SamplesApp::GetInitialCamera(CameraState &ioState) const
  1876. {
  1877. // Default if the test doesn't override it
  1878. ioState.mPos = GetWorldScale() * Vec3(30, 10, 30);
  1879. ioState.mForward = -ioState.mPos.Normalized();
  1880. ioState.mFarPlane = 1000.0f;
  1881. mTest->GetInitialCamera(ioState);
  1882. }
  1883. Mat44 SamplesApp::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  1884. {
  1885. return mTest->GetCameraPivot(inCameraHeading, inCameraPitch);
  1886. }
  1887. float SamplesApp::GetWorldScale() const
  1888. {
  1889. return mTest != nullptr? mTest->GetWorldScale() : 1.0f;
  1890. }
  1891. ENTRY_POINT(SamplesApp)