SamplesApp.cpp 106 KB

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