SamplesApp.cpp 86 KB

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