SamplesApp.cpp 89 KB

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