SamplesApp.cpp 105 KB

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