SamplesApp.cpp 85 KB

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