SamplesApp.cpp 105 KB

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