SamplesApp.cpp 91 KB

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