SamplesApp.cpp 112 KB

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