SamplesApp.cpp 105 KB

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