SamplesApp.cpp 110 KB

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