SamplesApp.cpp 82 KB

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