SamplesApp.cpp 104 KB

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