SamplesApp.cpp 85 KB

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