SamplesApp.cpp 88 KB

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