SamplesApp.cpp 96 KB

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