SamplesApp.cpp 91 KB

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