SamplesApp.cpp 112 KB

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