SamplesApp.cpp 99 KB

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