SamplesApp.cpp 84 KB

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