SamplesApp.cpp 101 KB

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