SamplesApp.cpp 103 KB

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