SamplesApp.cpp 111 KB

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