SamplesApp.cpp 105 KB

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