SamplesApp.cpp 110 KB

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