SamplesApp.cpp 88 KB

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