SamplesApp.cpp 84 KB

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