SamplesApp.cpp 106 KB

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