SampleComponentManager.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <SampleComponentManager.h>
  9. #include <SampleComponentConfig.h>
  10. #include <Atom/Component/DebugCamera/CameraComponent.h>
  11. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  12. #include <Atom/Component/DebugCamera/ArcBallControllerComponent.h>
  13. #include <Atom/Feature/AuxGeom/AuxGeomFeatureProcessor.h>
  14. #include <Atom/Feature/ImGui/ImGuiUtils.h>
  15. #include <Atom/Feature/ImGui/SystemBus.h>
  16. #include <Atom/Feature/Mesh/MeshFeatureProcessor.h>
  17. #include <Atom/Feature/PostProcessing/PostProcessingConstants.h>
  18. #include <Atom/Feature/SkinnedMesh/SkinnedMeshInputBuffers.h>
  19. #include <Atom/RPI.Public/Pass/Pass.h>
  20. #include <Atom/RPI.Public/Pass/ParentPass.h>
  21. #include <Atom/RPI.Public/Pass/PassSystemInterface.h>
  22. #include <Atom/RPI.Public/Pass/RenderPass.h>
  23. #include <Atom/RPI.Public/Pass/Specific/SwapChainPass.h>
  24. #include <Atom/RPI.Public/RenderPipeline.h>
  25. #include <Atom/RPI.Public/RPISystemInterface.h>
  26. #include <Atom/RPI.Public/Scene.h>
  27. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  28. #include <Atom/RPI.Reflect/Image/AttachmentImageAsset.h>
  29. #include <Atom/RPI.Reflect/Image/AttachmentImageAssetCreator.h>
  30. #include <Atom/RPI.Reflect/Shader/IShaderVariantFinder.h>
  31. #include <Atom/RHI/Factory.h>
  32. #include <Atom/RHI/RHISystemInterface.h>
  33. #include <Atom/RHI/RHIMemoryStatisticsInterface.h>
  34. #include <Atom/RHI/RHIUtils.h>
  35. #include <Atom/RHI.Reflect/AliasedHeapEnums.h>
  36. #include <Automation/ScriptManager.h>
  37. #include <RHI/AlphaToCoverageExampleComponent.h>
  38. #include <RHI/AsyncComputeExampleComponent.h>
  39. #include <RHI/BasicRHIComponent.h>
  40. #include <RHI/ComputeExampleComponent.h>
  41. #include <RHI/CopyQueueComponent.h>
  42. #include <RHI/DualSourceBlendingComponent.h>
  43. #include <RHI/IndirectRenderingExampleComponent.h>
  44. #include <RHI/InputAssemblyExampleComponent.h>
  45. #include <RHI/SubpassExampleComponent.h>
  46. #include <RHI/MRTExampleComponent.h>
  47. #include <RHI/MSAAExampleComponent.h>
  48. #include <RHI/MultiThreadComponent.h>
  49. #include <RHI/MultiViewportSwapchainComponent.h>
  50. #include <RHI/MultipleViewsComponent.h>
  51. #include <RHI/QueryExampleComponent.h>
  52. #include <RHI/StencilExampleComponent.h>
  53. #include <RHI/SwapchainExampleComponent.h>
  54. #include <RHI/SphericalHarmonicsExampleComponent.h>
  55. #include <RHI/Texture3dExampleComponent.h>
  56. #include <RHI/TextureArrayExampleComponent.h>
  57. #include <RHI/TextureExampleComponent.h>
  58. #include <RHI/TextureMapExampleComponent.h>
  59. #include <RHI/TriangleExampleComponent.h>
  60. #include <RHI/XRExampleComponent.h>
  61. #include <RHI/TrianglesConstantBufferExampleComponent.h>
  62. #include <RHI/BindlessPrototypeExampleComponent.h>
  63. #include <RHI/RayTracingExampleComponent.h>
  64. #include <RHI/MatrixAlignmentTestExampleComponent.h>
  65. #include <RHI/VariableRateShadingExampleComponent.h>
  66. #include <Performance/100KDrawable_SingleView_ExampleComponent.h>
  67. #include <Performance/100KDraw_10KDrawable_MultiView_ExampleComponent.h>
  68. #include <AreaLightExampleComponent.h>
  69. #include <AssetLoadTestComponent.h>
  70. #include <AuxGeomExampleComponent.h>
  71. #include <BakedShaderVariantExampleComponent.h>
  72. #include <SponzaBenchmarkComponent.h>
  73. #include <BloomExampleComponent.h>
  74. #include <CheckerboardExampleComponent.h>
  75. #include <CullingAndLodExampleComponent.h>
  76. #include <DecalExampleComponent.h>
  77. #include <DepthOfFieldExampleComponent.h>
  78. #include <DynamicDrawExampleComponent.h>
  79. #include <DynamicMaterialTestComponent.h>
  80. #include <ExposureExampleComponent.h>
  81. #include <EyeMaterialExampleComponent.h>
  82. #include <SceneReloadSoakTestComponent.h>
  83. #include <LightCullingExampleComponent.h>
  84. #include <MeshExampleComponent.h>
  85. #include <MSAA_RPI_ExampleComponent.h>
  86. #include <MultiRenderPipelineExampleComponent.h>
  87. #include <MultiSceneExampleComponent.h>
  88. #include <ParallaxMappingExampleComponent.h>
  89. #include <RenderTargetTextureExampleComponent.h>
  90. #include <SceneReloadSoakTestComponent.h>
  91. #include <ShadowExampleComponent.h>
  92. #include <ShadowedSponzaExampleComponent.h>
  93. #include <SkinnedMeshExampleComponent.h>
  94. #include <SsaoExampleComponent.h>
  95. #include <StreamingImageExampleComponent.h>
  96. #include <RootConstantsExampleComponent.h>
  97. #include <MultiViewSingleSceneAuxGeomExampleComponent.h>
  98. #include <TonemappingExampleComponent.h>
  99. #include <TransparencyExampleComponent.h>
  100. #include <DiffuseGIExampleComponent.h>
  101. #include <SSRExampleComponent.h>
  102. #include <XRRPIExampleComponent.h>
  103. #include <ShaderReloadTestComponent.h>
  104. #include <ReadbackExampleComponent.h>
  105. #include <Atom/Bootstrap/DefaultWindowBus.h>
  106. #include <AzCore/Component/Entity.h>
  107. #include <AzCore/Debug/Profiler.h>
  108. #include <AzCore/Debug/ProfilerBus.h>
  109. #include <AzCore/IO/IStreamerProfiler.h>
  110. #include <AzCore/Serialization/SerializeContext.h>
  111. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  112. #include <AzCore/std/smart_ptr/make_shared.h>
  113. #include <AzCore/std/algorithm.h>
  114. #include <AzFramework/API/ApplicationAPI.h>
  115. #include <AzFramework/Components/ConsoleBus.h>
  116. #include <AzFramework/Components/TransformComponent.h>
  117. #include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
  118. #include <AzFramework/Entity/GameEntityContextBus.h>
  119. #include <AzFramework/Scene/Scene.h>
  120. #include <AzFramework/Scene/SceneSystemInterface.h>
  121. #include <Passes/RayTracingAmbientOcclusionPass.h>
  122. #include <Utils/Utils.h>
  123. #include <Profiler/ProfilerImGuiBus.h>
  124. #include "ExampleComponentBus.h"
  125. #include <EntityUtilityFunctions.h>
  126. namespace Platform
  127. {
  128. const char* GetPipelineName();
  129. }
  130. namespace AtomSampleViewer
  131. {
  132. namespace
  133. {
  134. constexpr const char* PassTreeToolName = "PassTree";
  135. constexpr const char* CpuProfilerToolName = "CPU Profiler";
  136. constexpr const char* GpuProfilerToolName = "GPU Profiler";
  137. constexpr const char* FileIoProfilerToolName = "File IO Profiler";
  138. constexpr const char* TransientAttachmentProfilerToolName = "Transient Attachment Profiler";
  139. constexpr const char* SampleSetting = "/O3DE/AtomSampleViewer/Sample";
  140. }
  141. bool IsValidNumMSAASamples(int16_t numSamples)
  142. {
  143. return (numSamples == 1) || (numSamples == 2) || (numSamples == 4) || (numSamples == 8);
  144. }
  145. template <typename T>
  146. static SampleEntry NewRHISample(const AZStd::string& name)
  147. {
  148. return NewSample<T>(SamplePipelineType::RHI, "RHI", name);
  149. }
  150. template <typename T>
  151. static SampleEntry NewRHISample(const AZStd::string& name, AZStd::function<bool()> isSupportedFunction)
  152. {
  153. SampleEntry entry = NewSample<T>(SamplePipelineType::RHI, "RHI", name, isSupportedFunction);
  154. entry.m_isSupportedFunc = isSupportedFunction;
  155. return entry;
  156. }
  157. template <typename T>
  158. static SampleEntry NewRPISample(const AZStd::string& name)
  159. {
  160. return NewSample<T>(SamplePipelineType::RPI, "RPI", name);
  161. }
  162. template <typename T>
  163. static SampleEntry NewRPISample(const AZStd::string& name, AZStd::function<bool()> isSupportedFunction)
  164. {
  165. return NewSample<T>(SamplePipelineType::RPI, "RPI", name, isSupportedFunction);
  166. }
  167. template <typename T>
  168. static SampleEntry NewFeaturesSample(const AZStd::string& name)
  169. {
  170. return NewSample<T>(SamplePipelineType::RPI, "Features", name);
  171. }
  172. template <typename T>
  173. static SampleEntry NewFeaturesSample(const AZStd::string& name, AZStd::function<bool()> isSupportedFunction)
  174. {
  175. return NewSample<T>(SamplePipelineType::RPI, "Features", name, isSupportedFunction);
  176. }
  177. template <typename T>
  178. static SampleEntry NewPerfSample(const AZStd::string& name)
  179. {
  180. return NewSample<T>(SamplePipelineType::RPI, "Performance", name);
  181. }
  182. template <typename T>
  183. static SampleEntry NewPerfSample(const AZStd::string& name, AZStd::function<bool()> isSupportedFunction)
  184. {
  185. return NewSample<T>(SamplePipelineType::RPI, "Performance", name, isSupportedFunction);
  186. }
  187. static AZStd::string GetTargetSampleName()
  188. {
  189. //Check command line option
  190. const AzFramework::CommandLine* commandLine = nullptr;
  191. AzFramework::ApplicationRequests::Bus::BroadcastResult(commandLine, &AzFramework::ApplicationRequests::GetCommandLine);
  192. if (commandLine->HasSwitch("sample"))
  193. {
  194. AZStd::string targetSampleName = commandLine->GetSwitchValue("sample", 0);
  195. return targetSampleName;
  196. }
  197. //Check settings registry
  198. if (AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get())
  199. {
  200. if (AZStd::string targetSampleName;
  201. settingsRegistry->Get(targetSampleName, SampleSetting))
  202. {
  203. return targetSampleName;
  204. }
  205. }
  206. return {};
  207. }
  208. void SampleComponentManager::Reflect(AZ::ReflectContext* context)
  209. {
  210. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  211. {
  212. serializeContext->Class<SampleComponentManager, AZ::Component>()
  213. ->Version(0)
  214. ;
  215. // This registration matches ShaderOptionValuesSourceData, which is needed by ImGuiShaderUtils, to support
  216. // generating JSON for shader variants.
  217. serializeContext->RegisterGenericType<AZStd::unordered_map<Name, Name>>();
  218. }
  219. }
  220. void SampleComponentManager::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
  221. {
  222. required.push_back(AZ_CRC("PrototypeLmbrCentralService", 0xe35e6de0));
  223. }
  224. void SampleComponentManager::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  225. {
  226. provided.push_back(AZ_CRC_CE("SampleComponentManagerService"));
  227. }
  228. void SampleComponentManager::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent)
  229. {
  230. dependent.push_back(AZ_CRC("AzFrameworkConfigurationSystemComponentService", 0xcc49c96e)); // Ensures a scene is created for the GameEntityContext
  231. }
  232. AZStd::vector<SampleEntry> SampleComponentManager::GetSamples()
  233. {
  234. return {
  235. NewRHISample<AlphaToCoverageExampleComponent>("AlphaToCoverage"),
  236. NewRHISample<AsyncComputeExampleComponent>("AsyncCompute"),
  237. NewRHISample<BindlessPrototypeExampleComponent>("BindlessPrototype"),
  238. NewRHISample<ComputeExampleComponent>("Compute"),
  239. NewRHISample<CopyQueueComponent>("CopyQueue"),
  240. NewRHISample<DualSourceBlendingComponent>("DualSourceBlending", []() {return Utils::GetRHIDevice()->GetFeatures().m_dualSourceBlending; }),
  241. NewRHISample<IndirectRenderingExampleComponent>("IndirectRendering", []() {return Utils::GetRHIDevice()->GetFeatures().m_indirectCommandTier > RHI::IndirectCommandTiers::Tier0; }),
  242. NewRHISample<InputAssemblyExampleComponent>("InputAssembly"),
  243. NewRHISample<MSAAExampleComponent>("MSAA"),
  244. NewRHISample<MultipleViewsComponent>("MultipleViews"),
  245. NewRHISample<MRTExampleComponent>("MultiRenderTarget"),
  246. NewRHISample<MultiThreadComponent>("MultiThread"),
  247. NewRHISample<MultiViewportSwapchainComponent>("MultiViewportSwapchainComponent", [] { return IsMultiViewportSwapchainSampleSupported(); }),
  248. NewRHISample<QueryExampleComponent>("Queries"),
  249. NewRHISample<RayTracingExampleComponent>("RayTracing", []() {return Utils::GetRHIDevice()->GetFeatures().m_rayTracing; }),
  250. NewRHISample<SphericalHarmonicsExampleComponent>("SphericalHarmonics"),
  251. NewRHISample<StencilExampleComponent>("Stencil"),
  252. NewRHISample<SubpassExampleComponent>("Subpass", []() {return Utils::GetRHIDevice()->GetFeatures().m_renderTargetSubpassInputSupport != AZ::RHI::SubpassInputSupportType::NotSupported; }),
  253. NewRHISample<SwapchainExampleComponent>("Swapchain"),
  254. NewRHISample<TextureExampleComponent>("Texture"),
  255. NewRHISample<Texture3dExampleComponent>("Texture3d"),
  256. NewRHISample<TextureArrayExampleComponent>("TextureArray"),
  257. NewRHISample<TextureMapExampleComponent>("TextureMap"),
  258. NewRHISample<TriangleExampleComponent>("Triangle"),
  259. NewRHISample<TrianglesConstantBufferExampleComponent>("TrianglesConstantBuffer"),
  260. NewRHISample<XRExampleComponent>("OpenXr", []() { return AZ::RHI::RHISystemInterface::Get()->GetXRSystem() != nullptr; }),
  261. NewRHISample<MatrixAlignmentTestExampleComponent>("MatrixAlignmentTest"),
  262. NewRHISample<VariableRateShadingExampleComponent>("VariableRateShading", []() { return Utils::GetRHIDevice()->GetFeatures().m_shadingRateTypeMask != RHI::ShadingRateTypeFlags::None; }),
  263. NewRPISample<AssetLoadTestComponent>("AssetLoadTest"),
  264. NewRPISample<AuxGeomExampleComponent>("AuxGeom"),
  265. NewRPISample<BakedShaderVariantExampleComponent>("BakedShaderVariant"),
  266. NewRPISample<SponzaBenchmarkComponent>("SponzaBenchmark"),
  267. NewRPISample<CullingAndLodExampleComponent>("CullingAndLod"),
  268. NewRPISample<DecalExampleComponent>("Decals"),
  269. NewRPISample<DynamicDrawExampleComponent>("DynamicDraw"),
  270. NewRPISample<DynamicMaterialTestComponent>("DynamicMaterialTest"),
  271. NewRPISample<MeshExampleComponent>("Mesh"),
  272. NewRPISample<MSAA_RPI_ExampleComponent>("MSAA"),
  273. NewRPISample<MultiRenderPipelineExampleComponent>("MultiRenderPipeline"),
  274. NewRPISample<MultiSceneExampleComponent>("MultiScene"),
  275. NewRPISample<MultiViewSingleSceneAuxGeomExampleComponent>("MultiViewSingleSceneAuxGeom"),
  276. NewRPISample<ReadbackExampleComponent>("Readback"),
  277. NewRPISample<RenderTargetTextureExampleComponent>("RenderTargetTexture"),
  278. NewRPISample<RootConstantsExampleComponent>("RootConstants"),
  279. NewRPISample<SceneReloadSoakTestComponent>("SceneReloadSoakTest"),
  280. NewRPISample<StreamingImageExampleComponent>("StreamingImage"),
  281. NewRPISample<ShaderReloadTestComponent>("ShaderReloadTest"),
  282. NewFeaturesSample<AreaLightExampleComponent>("AreaLight"),
  283. NewFeaturesSample<BloomExampleComponent>("Bloom"),
  284. NewFeaturesSample<CheckerboardExampleComponent>("Checkerboard", []() {return (Utils::GetRHIDevice()->GetPhysicalDevice().GetDescriptor().m_vendorId != RHI::VendorId::ARM && Utils::GetRHIDevice()->GetPhysicalDevice().GetDescriptor().m_vendorId != RHI::VendorId::Qualcomm); }),
  285. NewFeaturesSample<DepthOfFieldExampleComponent>("DepthOfField"),
  286. NewFeaturesSample<DiffuseGIExampleComponent>("DiffuseGI", []() {return Utils::GetRHIDevice()->GetFeatures().m_rayTracing; }),
  287. NewFeaturesSample<ExposureExampleComponent>("Exposure"),
  288. NewFeaturesSample<EyeMaterialExampleComponent>("EyeMaterial"),
  289. NewFeaturesSample<LightCullingExampleComponent>("LightCulling"),
  290. NewFeaturesSample<ParallaxMappingExampleComponent>("Parallax"),
  291. NewFeaturesSample<ShadowExampleComponent>("Shadow"),
  292. NewFeaturesSample<ShadowedSponzaExampleComponent>("ShadowedSponza"),
  293. NewFeaturesSample<SkinnedMeshExampleComponent>("SkinnedMesh"),
  294. NewFeaturesSample<SsaoExampleComponent>("SSAO"),
  295. NewFeaturesSample<SSRExampleComponent>("SSR"),
  296. NewFeaturesSample<XRRPIExampleComponent>("OpenXR", []() { return AZ::RPI::RPISystemInterface::Get()->GetXRSystem() != nullptr; }),
  297. NewFeaturesSample<TonemappingExampleComponent>("Tonemapping"),
  298. NewFeaturesSample<TransparencyExampleComponent>("Transparency"),
  299. NewPerfSample<_100KDrawableExampleComponent>("100KDrawable_SingleView"),
  300. NewPerfSample<_100KDraw10KDrawableExampleComponent>("100KDraw_10KDrawable_MultiView"),
  301. };
  302. }
  303. void SampleComponentManager::RegisterSampleComponent(const SampleEntry& sample)
  304. {
  305. if (AZStd::find(m_availableSamples.begin(), m_availableSamples.end(), sample) == m_availableSamples.end())
  306. {
  307. m_availableSamples.push_back(sample);
  308. m_groupedSamples[sample.m_parentMenuName].push_back(static_cast<int32_t>(m_availableSamples.size() - 1));
  309. }
  310. }
  311. ScriptManager* SampleComponentManager::GetScriptManagerInstance()
  312. {
  313. AZ_Assert(m_scriptManager, "Script Manager is nullptr");
  314. return m_scriptManager.get();
  315. }
  316. ScriptableImGui* SampleComponentManager::GetScriptableImGuiInstance()
  317. {
  318. AZ_Assert(m_scriptableImGui, "Scriptable ImGui is nullptr");
  319. return m_scriptableImGui.get();
  320. }
  321. SampleComponentManager::SampleComponentManager()
  322. : m_imguiFrameCaptureSaver("@user@/frame_capture.xml")
  323. {
  324. m_imGuiFrameTimer = AZStd::make_unique<ImGuiHistogramQueue>(FrameTimeDefaultLogSize, FrameTimeDefaultLogSize, 250.0f);
  325. m_exampleEntity = aznew AZ::Entity();
  326. m_entityContextId = AzFramework::EntityContextId::CreateNull();
  327. }
  328. SampleComponentManager::~SampleComponentManager()
  329. {
  330. m_exampleEntity = nullptr;
  331. m_cameraEntity = nullptr;
  332. m_windowContext = nullptr;
  333. m_availableSamples.clear();
  334. }
  335. void SampleComponentManager::Init()
  336. {
  337. AZStd::vector<SampleEntry> samples = GetSamples();
  338. for (const SampleEntry& sample : samples)
  339. {
  340. RegisterSampleComponent(sample);
  341. }
  342. m_scriptManager = AZStd::make_unique<ScriptManager>();
  343. m_scriptableImGui = AZStd::make_unique<ScriptableImGui>();
  344. }
  345. void SampleComponentManager::Activate()
  346. {
  347. // We can only initialize this component after the asset catalog has been loaded.
  348. AzFramework::AssetCatalogEventBus::Handler::BusConnect();
  349. AZ::Render::ImGuiSystemNotificationBus::Handler::BusConnect();
  350. SampleComponentSingletonRequestBus::Handler::BusConnect();
  351. auto* passSystem = AZ::RPI::PassSystemInterface::Get();
  352. AZ_Assert(passSystem, "Cannot get the pass system.");
  353. passSystem->AddPassCreator(Name("RayTracingAmbientOcclusionPass"), &AZ::Render::RayTracingAmbientOcclusionPass::Create);
  354. }
  355. void SampleComponentManager::ActivateInternal()
  356. {
  357. using namespace AZ;
  358. AZ::ApplicationTypeQuery appType;
  359. ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType);
  360. if (!appType.IsValid() || !appType.IsGame())
  361. {
  362. return;
  363. }
  364. // ActivateInternal() may get called twice because the OnCatalogLoaded was called twice When run AtomSampleViewer launcher. One of those two events is from ly launcher framework and the other one is from
  365. // LoadCatalog call in AtomSampleViewer system component. Although load the same asset catalog twice doesn't seem to cause other issue.
  366. if (m_wasActivated)
  367. {
  368. return;
  369. }
  370. Render::Bootstrap::DefaultWindowBus::BroadcastResult(m_windowContext, &Render::Bootstrap::DefaultWindowBus::Events::GetDefaultWindowContext);
  371. AzFramework::GameEntityContextRequestBus::BroadcastResult(m_entityContextId, &AzFramework::GameEntityContextRequestBus::Events::GetGameEntityContextId);
  372. CreateDefaultCamera();
  373. // Add customized pass classes
  374. auto* passSystem = RPI::PassSystemInterface::Get();
  375. passSystem->AddPassCreator(Name("RHISamplePass"), &AtomSampleViewer::RHISamplePass::Create);
  376. // Use scene and render pipeline for RHI samples as default scene and render pipeline
  377. CreateSceneForRHISample();
  378. m_exampleEntity->Init();
  379. m_exampleEntity->Activate();
  380. m_isSampleSupported.resize(m_availableSamples.size());
  381. for (size_t i = 0; i < m_availableSamples.size(); ++i)
  382. {
  383. // Assume that the sample is supported if no m_isSupportedFunc is provided.
  384. m_isSampleSupported[i] = m_availableSamples[i].m_isSupportedFunc ? m_availableSamples[i].m_isSupportedFunc() : true;
  385. }
  386. AZ_Printf("SampleComponentManager", "Available Samples -------------------------\n");
  387. for (size_t i = 0; i < m_availableSamples.size(); ++i)
  388. {
  389. AZStd::string printStr = "\t[" + m_availableSamples[i].m_fullName + "]";
  390. if (!m_isSampleSupported[i])
  391. {
  392. printStr += " Not Supported ";
  393. }
  394. if (i < 9)
  395. {
  396. printStr += AZStd::string::format("\tctrl+%lu", i + 1);
  397. }
  398. printStr += "\n";
  399. AZ_Printf("SampleComponentManager", printStr.data());
  400. }
  401. AZ_Printf("SampleComponentManager", "-------------------------------------------\n");
  402. AzFramework::InputChannelEventListener::BusConnect();
  403. TickBus::Handler::BusConnect();
  404. bool targetSampleFound = false;
  405. if (AZStd::string targetSampleName = GetTargetSampleName();
  406. !targetSampleName.empty())
  407. {
  408. AZStd::to_lower(targetSampleName.begin(), targetSampleName.end());
  409. for (int32_t i = 0; i < m_availableSamples.size(); ++i)
  410. {
  411. AZStd::string sampleName = m_availableSamples[i].m_fullName;
  412. AZStd::to_lower(sampleName.begin(), sampleName.end());
  413. if (sampleName == targetSampleName)
  414. {
  415. if (m_isSampleSupported[i])
  416. {
  417. if (m_availableSamples[i].m_contentWarning.empty())
  418. {
  419. m_selectedSampleIndex = i;
  420. m_sampleChangeRequest = true;
  421. }
  422. else
  423. {
  424. m_contentWarningDialog.OpenPopupConfirmation(
  425. m_availableSamples[i].m_contentWarningTitle,
  426. m_availableSamples[i].m_contentWarning,
  427. [this, i]() {
  428. m_selectedSampleIndex = i;
  429. m_sampleChangeRequest = true;
  430. });
  431. }
  432. targetSampleFound = true;
  433. }
  434. break;
  435. }
  436. }
  437. AZ_Warning("SampleComponentManager", targetSampleFound, "Failed find target sample %s", targetSampleName.c_str());
  438. }
  439. const AzFramework::CommandLine* commandLine = nullptr;
  440. AzFramework::ApplicationRequests::Bus::BroadcastResult(commandLine, &AzFramework::ApplicationRequests::GetCommandLine);
  441. if (commandLine->HasSwitch("timingSamples"))
  442. {
  443. AZStd::string timingSamplesStr = commandLine->GetSwitchValue("timingSamples", 0);
  444. int timingSamplesCount = 0;
  445. if (AZ::StringFunc::LooksLikeInt(timingSamplesStr.c_str(), &timingSamplesCount))
  446. {
  447. timingSamplesCount = AZStd::clamp<int>(timingSamplesCount, FrameTimeMinLogSize, FrameTimeMaxLogSize);
  448. m_imGuiFrameTimer = AZStd::make_unique<ImGuiHistogramQueue>(timingSamplesCount, timingSamplesCount, 250.0f);
  449. }
  450. }
  451. // Set default screenshot folder to relative path 'Screenshots'
  452. AZ::IO::Path screenshotFolder = "Screenshots";
  453. // Get folder from command line if it exists
  454. static const char* screenshotFolderFlagName = "screenshotFolder";
  455. if (commandLine->HasSwitch(screenshotFolderFlagName))
  456. {
  457. screenshotFolder = commandLine->GetSwitchValue(screenshotFolderFlagName, 0);
  458. }
  459. // Make the screenshot directory relative to the Writeable Storage Path
  460. // The Path::operator/ smartly knows how to concatenate two absolute paths
  461. // i.e <absolute path1> / <absolute path2> = <absolute path2>
  462. auto settingsRegistry = AZ::SettingsRegistry::Get();
  463. AZ::IO::Path writableStoragePath;
  464. settingsRegistry->Get(writableStoragePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_DevWriteStorage);
  465. screenshotFolder = writableStoragePath / screenshotFolder;
  466. m_imguiFrameCaptureSaver.SetDefaultFolder(screenshotFolder.Native());
  467. m_imguiFrameCaptureSaver.SetDefaultFileName("screenshot");
  468. m_imguiFrameCaptureSaver.SetAvailableExtensions({ "png", "ppm", "dds" });
  469. m_imguiFrameCaptureSaver.Activate();
  470. SampleComponentManagerRequestBus::Handler::BusConnect();
  471. m_scriptManager->Activate();
  472. m_wasActivated = true;
  473. SampleComponentManagerNotificationBus::Broadcast(&SampleComponentManagerNotificationBus::Events::OnSampleManagerActivated);
  474. }
  475. void SampleComponentManager::Deactivate()
  476. {
  477. DestroyEntity(m_cameraEntity);
  478. AzFramework::AssetCatalogEventBus::Handler::BusDisconnect();
  479. AZ::Render::ImGuiSystemNotificationBus::Handler::BusDisconnect();
  480. m_scriptManager->Deactivate();
  481. m_imguiFrameCaptureSaver.Deactivate();
  482. SampleComponentSingletonRequestBus::Handler::BusDisconnect();
  483. SampleComponentManagerRequestBus::Handler::BusDisconnect();
  484. AZ::TickBus::Handler::BusDisconnect();
  485. AzFramework::InputChannelEventListener::Disconnect();
  486. Render::ImGuiSystemRequestBus::Broadcast(&Render::ImGuiSystemRequests::PopActiveContext);
  487. m_imguiPassTree.Reset();
  488. m_imguiFrameGraphVisualizer.Reset();
  489. m_windowContext = nullptr;
  490. m_brdfTexture.reset();
  491. ReleaseRHIScene();
  492. ReleaseRPIScene();
  493. }
  494. void SampleComponentManager::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  495. {
  496. if (auto* xrSystem = AZ::RPI::RPISystemInterface::Get()->GetXRSystem())
  497. {
  498. EnableRenderPipeline(xrSystem->GetRHIXRRenderingInterface()->IsDefaultRenderPipelineEnabledOnHost());
  499. //Only enable XR pipelines if the XR drivers indicate we have accurate pose information from the device
  500. EnableXrPipelines(xrSystem->ShouldRender());
  501. }
  502. if (m_imGuiFrameTimer)
  503. {
  504. m_imGuiFrameTimer->PushValue(deltaTime * 1000.0f);
  505. }
  506. bool screenshotRequest = false;
  507. if (m_ctrlModifierLDown || m_ctrlModifierRDown)
  508. {
  509. if (m_alphanumericQDown)
  510. {
  511. RequestExit();
  512. return;
  513. }
  514. if (m_alphanumericTDown && m_canCaptureRADTM)
  515. {
  516. #ifdef AZ_PROFILE_TELEMETRY
  517. Utils::ToggleRadTMCapture();
  518. m_canCaptureRADTM = false;
  519. #endif
  520. }
  521. else if (!m_alphanumericTDown)
  522. {
  523. m_canCaptureRADTM = true;
  524. }
  525. if (m_alphanumericPDown)
  526. {
  527. screenshotRequest = true;
  528. }
  529. }
  530. // Request a frame capture only once per key press, even if the keys are held down for multiple ticks.
  531. if (screenshotRequest)
  532. {
  533. ++m_screenshotKeyDownCount;
  534. if (m_screenshotKeyDownCount == 1)
  535. {
  536. RequestFrameCapture(m_imguiFrameCaptureSaver.GetNextAutoSaveFilePath(), true);
  537. }
  538. }
  539. else
  540. {
  541. m_screenshotKeyDownCount = 0;
  542. }
  543. RenderImGui(deltaTime);
  544. // SampleChange needs to happen after RenderImGui as some of the samples create sidebars on a separate ImGui context
  545. // which can interfere with m_imguiContext in the first frame
  546. if (m_sampleChangeRequest && m_canSwitchSample)
  547. {
  548. SampleChange();
  549. m_canSwitchSample = false;
  550. }
  551. else if (m_escapeDown && m_canSwitchSample)
  552. {
  553. Reset();
  554. m_canSwitchSample = false;
  555. Utils::ReportScriptableAction("OpenSample('')");
  556. }
  557. // Once a SampleChange/Reset request has been handled, it will not be handled again until there has been at least one frame where the sample hasn't changed
  558. if (!m_sampleChangeRequest && !m_escapeDown)
  559. {
  560. m_canSwitchSample = true;
  561. }
  562. // Since the event has been handled, clear the request
  563. m_sampleChangeRequest = false;
  564. m_escapeDown = false;
  565. m_scriptManager->TickScript(deltaTime);
  566. if (m_isFrameCapturePending)
  567. {
  568. if (m_countdownForFrameCapture > 0)
  569. {
  570. m_countdownForFrameCapture--;
  571. }
  572. else if (m_countdownForFrameCapture == 0)
  573. {
  574. AZ::Render::FrameCaptureOutcome capOutcome;
  575. AZ::Render::FrameCaptureRequestBus::BroadcastResult(capOutcome, &AZ::Render::FrameCaptureRequestBus::Events::CaptureScreenshot, m_frameCaptureFilePath);
  576. if (capOutcome.IsSuccess()) // if unsuccessfull leave state to attempt again next tick
  577. {
  578. m_frameCaptureId = capOutcome.GetValue();
  579. AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(m_frameCaptureId);
  580. m_countdownForFrameCapture = -1; // Don't call CaptureScreenshot again
  581. }
  582. else
  583. {
  584. m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  585. }
  586. }
  587. }
  588. }
  589. bool SampleComponentManager::OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel)
  590. {
  591. const size_t samplesAvailableCount = m_availableSamples.size();
  592. AZStd::vector<AzFramework::InputChannelId> sampleInputMapping;
  593. sampleInputMapping.reserve(samplesAvailableCount);
  594. for (size_t i = 0; i < samplesAvailableCount; ++i)
  595. {
  596. switch (i)
  597. {
  598. case 0:
  599. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric1);
  600. break;
  601. case 1:
  602. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric2);
  603. break;
  604. case 2:
  605. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric3);
  606. break;
  607. case 3:
  608. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric4);
  609. break;
  610. case 4:
  611. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric5);
  612. break;
  613. case 5:
  614. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric6);
  615. break;
  616. case 6:
  617. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric7);
  618. break;
  619. case 7:
  620. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric8);
  621. break;
  622. case 8:
  623. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric9);
  624. break;
  625. case 9:
  626. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric0);
  627. break;
  628. default:
  629. break;
  630. }
  631. }
  632. const AzFramework::InputChannelId& inputChannelId = inputChannel.GetInputChannelId();
  633. switch (inputChannel.GetState())
  634. {
  635. case AzFramework::InputChannel::State::Began:
  636. case AzFramework::InputChannel::State::Updated:
  637. {
  638. if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlL)
  639. {
  640. m_ctrlModifierLDown = true;
  641. }
  642. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlR)
  643. {
  644. m_ctrlModifierRDown = true;
  645. }
  646. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericQ)
  647. {
  648. m_alphanumericQDown = true;
  649. }
  650. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericT)
  651. {
  652. m_alphanumericTDown = true;
  653. }
  654. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericP)
  655. {
  656. m_alphanumericPDown = true;
  657. }
  658. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::Escape)
  659. {
  660. m_escapeDown = true;
  661. }
  662. break;
  663. }
  664. case AzFramework::InputChannel::State::Ended:
  665. {
  666. if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlL)
  667. {
  668. m_ctrlModifierLDown = false;
  669. }
  670. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlR)
  671. {
  672. m_ctrlModifierRDown = false;
  673. }
  674. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericQ)
  675. {
  676. m_alphanumericQDown = false;
  677. }
  678. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericT)
  679. {
  680. m_alphanumericTDown = false;
  681. }
  682. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericP)
  683. {
  684. m_alphanumericPDown = false;
  685. }
  686. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::Escape)
  687. {
  688. m_escapeDown = false;
  689. }
  690. break;
  691. }
  692. default:
  693. {
  694. break;
  695. }
  696. }
  697. return false;
  698. }
  699. void SampleComponentManager::RenderImGui(float deltaTime)
  700. {
  701. if (!m_isImGuiAvailable)
  702. {
  703. return;
  704. }
  705. ShowMenuBar();
  706. if (m_exitRequested)
  707. {
  708. return;
  709. }
  710. if (m_showResizeViewportDialog)
  711. {
  712. ShowResizeViewportDialog();
  713. }
  714. if (m_showFramerateHistogram)
  715. {
  716. ShowFramerateHistogram(deltaTime);
  717. }
  718. if (m_showFrameCaptureDialog)
  719. {
  720. ShowFrameCaptureDialog();
  721. }
  722. if (m_showImGuiMetrics)
  723. {
  724. ImGui::ShowMetricsWindow(&m_showImGuiMetrics);
  725. }
  726. if (m_showSampleHelper)
  727. {
  728. ShowSampleHelper();
  729. }
  730. if (m_showAbout)
  731. {
  732. ShowAboutWindow();
  733. }
  734. if (m_showPassTree)
  735. {
  736. ShowPassTreeWindow();
  737. }
  738. if (m_showFrameGraphVisualizer)
  739. {
  740. ShowFrameGraphVisualizerWindow();
  741. }
  742. if (m_showCullingDebugWindow)
  743. {
  744. AZ::RPI::Scene* rpiScene = AZ::RPI::RPISystemInterface::Get()->GetSceneByName(AZ::Name("RPI"));
  745. if (rpiScene)
  746. {
  747. AZ::Render::ImGuiDrawCullingDebug(m_showCullingDebugWindow, rpiScene);
  748. }
  749. }
  750. if (m_showCpuProfiler)
  751. {
  752. ShowCpuProfilerWindow();
  753. }
  754. if (m_showGpuProfiler)
  755. {
  756. ShowGpuProfilerWindow();
  757. }
  758. if (m_showFileIoProfiler)
  759. {
  760. ShowFileIoProfilerWindow();
  761. }
  762. if (m_showTransientAttachmentProfiler)
  763. {
  764. ShowTransientAttachmentProfilerWindow();
  765. }
  766. m_scriptManager->TickImGui();
  767. m_contentWarningDialog.TickPopup();
  768. }
  769. void SampleComponentManager::ShowMenuBar()
  770. {
  771. if (ImGui::BeginMainMenuBar())
  772. {
  773. // If imgui doesn't have enough room to render a menu, it will fall back to the safe area which
  774. // is typically 3 pixels. This causes the menu to overlap the menu bar, and makes it easy to
  775. // accidentally select the first item on that menu bar. By altering the safe area temporarily
  776. // while drawing the menu, this problem can be avoided.
  777. ImVec2 cachedSafeArea = ImGui::GetStyle().DisplaySafeAreaPadding;
  778. ImGui::GetStyle().DisplaySafeAreaPadding = ImVec2(cachedSafeArea.x, cachedSafeArea.y + 16.0f);
  779. if (ImGui::BeginMenu("File"))
  780. {
  781. if (ImGui::MenuItem("Exit", "Ctrl-Q"))
  782. {
  783. RequestExit();
  784. }
  785. if (ImGui::MenuItem("Capture Frame...", "Ctrl-P"))
  786. {
  787. m_showFrameCaptureDialog = true;
  788. }
  789. ImGui::EndMenu();
  790. }
  791. if (ImGui::BeginMenu("View"))
  792. {
  793. if (Utils::SupportsResizeClientArea() && ImGui::MenuItem("Resize Viewport..."))
  794. {
  795. m_showResizeViewportDialog = true;
  796. }
  797. if (Utils::SupportsToggleFullScreenOfDefaultWindow() && ImGui::MenuItem("Toggle Full Screen"))
  798. {
  799. Utils::ToggleFullScreenOfDefaultWindow();
  800. }
  801. if (ImGui::MenuItem("Frame Time Histogram"))
  802. {
  803. m_showFramerateHistogram = !m_showFramerateHistogram;
  804. }
  805. if (ImGui::MenuItem("ImGui Metrics"))
  806. {
  807. m_showImGuiMetrics = !m_showImGuiMetrics;
  808. }
  809. if (ImGui::MenuItem("Sample Helper"))
  810. {
  811. m_showSampleHelper = !m_showSampleHelper;
  812. }
  813. if (ImGui::MenuItem("Frame Graph Visualizer"))
  814. {
  815. m_showFrameGraphVisualizer = !m_showFrameGraphVisualizer;
  816. }
  817. ImGui::EndMenu();
  818. }
  819. if (ImGui::BeginMenu("Samples"))
  820. {
  821. for (auto&& [parentMenuName, samples] : m_groupedSamples)
  822. {
  823. if (ImGui::BeginMenu(parentMenuName.c_str()))
  824. {
  825. for (int32_t index : samples)
  826. {
  827. SampleEntry& sample = m_availableSamples[index];
  828. const char* sampleName = sample.m_sampleName.c_str();
  829. bool enabled = m_isSampleSupported[index];
  830. if (ImGui::MenuItem(sampleName, nullptr, false, enabled))
  831. {
  832. Utils::ReportScriptableAction("OpenSample('%s')", sample.m_sampleName.c_str());
  833. if (sample.m_contentWarning.empty())
  834. {
  835. m_sampleChangeRequest = true;
  836. m_selectedSampleIndex = index;
  837. }
  838. else
  839. {
  840. m_contentWarningDialog.OpenPopupConfirmation(
  841. sample.m_contentWarningTitle,
  842. sample.m_contentWarning,
  843. [this, index]() {
  844. m_sampleChangeRequest = true;
  845. m_selectedSampleIndex = index;
  846. });
  847. }
  848. }
  849. }
  850. ImGui::EndMenu();
  851. }
  852. }
  853. ImGui::EndMenu();
  854. }
  855. #ifdef AZ_PROFILE_TELEMETRY
  856. if (ImGui::BeginMenu("RADTelemetry"))
  857. {
  858. if (ImGui::MenuItem("Toggle Capture", "Ctrl-T"))
  859. {
  860. Utils::ToggleRadTMCapture();
  861. }
  862. ImGui::EndMenu();
  863. }
  864. #endif // AZ_PROFILE_TELEMETRY
  865. if (ImGui::BeginMenu("Automation"))
  866. {
  867. const char* AutomationContentWarningTitle = AtomSampleComponent::CommonPhotosensitiveWarningTitle;
  868. const char* AutomationContentWarning = "Running automated scripts will trigger flashing images that could cause seizures or other adverse effects in photosensitive individuals.";
  869. if (ImGui::MenuItem("Run Script..."))
  870. {
  871. m_contentWarningDialog.OpenPopupConfirmation(
  872. AutomationContentWarningTitle,
  873. AutomationContentWarning,
  874. [this]() {
  875. m_scriptManager->OpenScriptRunnerDialog();
  876. });
  877. }
  878. if (ImGui::MenuItem("Run Precommit Wizard..."))
  879. {
  880. m_contentWarningDialog.OpenPopupConfirmation(
  881. AutomationContentWarningTitle,
  882. AutomationContentWarning,
  883. [this]() {
  884. m_scriptManager->OpenPrecommitWizard();
  885. });
  886. }
  887. ImGui::EndMenu();
  888. }
  889. if (ImGui::BeginMenu("Pass"))
  890. {
  891. if (ImGui::MenuItem(PassTreeToolName))
  892. {
  893. m_showPassTree = !m_showPassTree;
  894. Utils::ReportScriptableAction("ShowTool('%s', %s)", PassTreeToolName, m_showPassTree?"true":"false");
  895. }
  896. ImGui::EndMenu();
  897. }
  898. if (ImGui::BeginMenu("Culling"))
  899. {
  900. if (ImGui::MenuItem("Culling Debug Window"))
  901. {
  902. m_showCullingDebugWindow = !m_showCullingDebugWindow;
  903. }
  904. ImGui::EndMenu();
  905. }
  906. if (ImGui::BeginMenu("Profile"))
  907. {
  908. if (ImGui::MenuItem(CpuProfilerToolName))
  909. {
  910. m_showCpuProfiler = !m_showCpuProfiler;
  911. if (auto profilerSystem = AZ::Debug::ProfilerSystemInterface::Get(); profilerSystem)
  912. {
  913. profilerSystem->SetActive(m_showCpuProfiler);
  914. }
  915. Utils::ReportScriptableAction("ShowTool('%s', %s)", CpuProfilerToolName, m_showCpuProfiler ? "true" : "false");
  916. }
  917. if (AZ::IO::StreamerProfiler::Get() != nullptr)
  918. {
  919. if (ImGui::MenuItem(FileIoProfilerToolName))
  920. {
  921. m_showFileIoProfiler = !m_showFileIoProfiler;
  922. Utils::ReportScriptableAction(
  923. "ShowTool('%s', %s)", FileIoProfilerToolName, m_showFileIoProfiler ? "true" : "false");
  924. }
  925. }
  926. if (ImGui::MenuItem(GpuProfilerToolName))
  927. {
  928. m_showGpuProfiler = !m_showGpuProfiler;
  929. Utils::ReportScriptableAction("ShowTool('%s', %s)", GpuProfilerToolName, m_showGpuProfiler ? "true" : "false");
  930. }
  931. if (ImGui::MenuItem(TransientAttachmentProfilerToolName))
  932. {
  933. m_showTransientAttachmentProfiler = !m_showTransientAttachmentProfiler;
  934. AZ::RHI::RHISystemInterface::Get()->ModifyFrameSchedulerStatisticsFlags(
  935. AZ::RHI::FrameSchedulerStatisticsFlags::GatherTransientAttachmentStatistics,
  936. m_showTransientAttachmentProfiler);
  937. Utils::ReportScriptableAction("ShowTool('%s', %s)", TransientAttachmentProfilerToolName, m_showTransientAttachmentProfiler ? "true" : "false");
  938. }
  939. ImGui::EndMenu();
  940. }
  941. if (ImGui::BeginMenu("Help"))
  942. {
  943. if (ImGui::MenuItem("About"))
  944. {
  945. m_showAbout = !m_showAbout;
  946. }
  947. ImGui::EndMenu();
  948. }
  949. // Restore original safe area.
  950. ImGui::GetStyle().DisplaySafeAreaPadding = cachedSafeArea;
  951. ImGui::EndMainMenuBar();
  952. }
  953. }
  954. void SampleComponentManager::ShowSampleHelper()
  955. {
  956. if (ImGui::Begin("Sample Helper", &m_showSampleHelper, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  957. {
  958. if (ImGui::Button("Reset"))
  959. {
  960. //Removes the existing sample component and
  961. //resets the selection index
  962. Reset();
  963. CameraReset();
  964. m_selectedSampleIndex = -1;
  965. }
  966. ImGui::SameLine();
  967. if (ImGui::Button("Reset Sample"))
  968. {
  969. //Force a sample change event when the selection index
  970. //hasn't changed. This resets the sample component.
  971. SampleChange();
  972. }
  973. ImGui::SameLine();
  974. if (ImGui::Button("Reset Camera"))
  975. {
  976. CameraReset();
  977. }
  978. }
  979. ImGui::End();
  980. }
  981. void SampleComponentManager::ShowAboutWindow()
  982. {
  983. if (ImGui::Begin("About", &m_showAbout, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  984. {
  985. ImGui::Text("RHI API: %s", AZ::RHI::Factory::Get().GetName().GetCStr());
  986. }
  987. ImGui::End();
  988. }
  989. void SampleComponentManager::ShowPassTreeWindow()
  990. {
  991. m_imguiPassTree.Draw(m_showPassTree, AZ::RPI::PassSystemInterface::Get()->GetRootPass().get());
  992. }
  993. void SampleComponentManager::ShowFrameGraphVisualizerWindow()
  994. {
  995. AZ::RHI::Device* rhiDevice = Utils::GetRHIDevice().get();
  996. m_imguiFrameGraphVisualizer.Init(rhiDevice);
  997. m_imguiFrameGraphVisualizer.Draw(m_showFrameGraphVisualizer);
  998. }
  999. void SampleComponentManager::ShowCpuProfilerWindow()
  1000. {
  1001. if (auto profilerImGui = Profiler::ProfilerImGuiInterface::Get(); profilerImGui)
  1002. {
  1003. profilerImGui->ShowCpuProfilerWindow(m_showCpuProfiler);
  1004. }
  1005. }
  1006. void SampleComponentManager::ShowFileIoProfilerWindow()
  1007. {
  1008. if (auto profilerImGui = AZ::IO::StreamerProfiler::Get(); profilerImGui)
  1009. {
  1010. profilerImGui->DrawStatistics(m_showFileIoProfiler);
  1011. }
  1012. }
  1013. void SampleComponentManager::ShowGpuProfilerWindow()
  1014. {
  1015. m_imguiGpuProfiler.Draw(m_showGpuProfiler, AZ::RPI::PassSystemInterface::Get()->GetRootPass());
  1016. }
  1017. void SampleComponentManager::ShowTransientAttachmentProfilerWindow()
  1018. {
  1019. auto* transientStats = AZ::RHI::RHIMemoryStatisticsInterface::Get()->GetTransientAttachmentStatistics();
  1020. if (transientStats)
  1021. {
  1022. m_showTransientAttachmentProfiler = m_imguiTransientAttachmentProfiler.Draw(*transientStats);
  1023. }
  1024. }
  1025. void SampleComponentManager::ShowResizeViewportDialog()
  1026. {
  1027. static int size[2] = { 0, 0 };
  1028. if (size[0] <= 0)
  1029. {
  1030. size[0] = aznumeric_cast<int>(m_windowContext->GetViewport().m_maxX - m_windowContext->GetViewport().m_minX);
  1031. }
  1032. if (size[1] <= 0)
  1033. {
  1034. size[1] = aznumeric_cast<int>(m_windowContext->GetViewport().m_maxY - m_windowContext->GetViewport().m_minY);
  1035. }
  1036. bool dialogWasOpen = m_showResizeViewportDialog;
  1037. if (ImGui::Begin("Resize Viewport", &m_showResizeViewportDialog, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  1038. {
  1039. ImGui::InputInt2("Size", size);
  1040. if (ImGui::Button("Resize"))
  1041. {
  1042. Utils::ResizeClientArea(size[0], size[1], AzFramework::WindowPosOptions());
  1043. Utils::ReportScriptableAction("ResizeViewport(%d, %d)", size[0], size[1]);
  1044. // Re-initialize the size fields on the next frame so we can see whether the
  1045. // correct size was achieved (should be the same values the user entered)...
  1046. size[0] = 0;
  1047. size[1] = 0;
  1048. }
  1049. }
  1050. ImGui::End();
  1051. if (dialogWasOpen && !m_showResizeViewportDialog)
  1052. {
  1053. // Re-initialize the size fields next time the dialog is shown...
  1054. size[0] = 0;
  1055. size[1] = 0;
  1056. }
  1057. }
  1058. void SampleComponentManager::ShowFramerateHistogram(float deltaTime)
  1059. {
  1060. if (m_imGuiFrameTimer && ImGui::Begin("Frame Time Histogram", &m_showFramerateHistogram, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  1061. {
  1062. ImGuiHistogramQueue::WidgetSettings settings;
  1063. settings.m_reportInverse = false;
  1064. settings.m_units = "ms";
  1065. m_imGuiFrameTimer->Tick(deltaTime * 1000.0f, settings);
  1066. }
  1067. ImGui::End();
  1068. }
  1069. void SampleComponentManager::RequestFrameCapture(const AZStd::string& filePath, bool hideImGui)
  1070. {
  1071. AZ_Assert(false == m_isFrameCapturePending, "Frame capture already in progress");
  1072. AZ_Assert(AZ::Render::InvalidFrameCaptureId == m_frameCaptureId, "Unfinished frame capture detected");
  1073. m_isFrameCapturePending = true;
  1074. m_hideImGuiDuringFrameCapture = hideImGui;
  1075. m_frameCaptureFilePath = filePath;
  1076. // Don't continue the script while a frame capture is pending in case subsequent changes
  1077. // interfere with the pending capture.
  1078. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  1079. if (m_hideImGuiDuringFrameCapture)
  1080. {
  1081. AZ::Render::ImGuiSystemRequestBus::Broadcast(&AZ::Render::ImGuiSystemRequestBus::Events::HideAllImGuiPasses);
  1082. // We also hide Open 3D Engine's debug text
  1083. AzFramework::ConsoleRequestBus::Broadcast(&AzFramework::ConsoleRequests::ExecuteConsoleCommand, "r_DisplayInfo 0");
  1084. // The ExecuteConsoleCommand request is handled in a deferred manner, so we have to delay the screenshot a bit.
  1085. m_countdownForFrameCapture = 1;
  1086. }
  1087. else
  1088. {
  1089. m_countdownForFrameCapture = 0;
  1090. }
  1091. }
  1092. void SampleComponentManager::OnFrameCaptureFinished(AZ::Render::FrameCaptureResult /*result*/, const AZStd::string& /*info*/)
  1093. {
  1094. AZ::Render::FrameCaptureNotificationBus::Handler::BusDisconnect();
  1095. if (m_hideImGuiDuringFrameCapture)
  1096. {
  1097. AZ::Render::ImGuiSystemRequestBus::Broadcast(&AZ::Render::ImGuiSystemRequestBus::Events::ShowAllImGuiPasses);
  1098. // We also show Open 3D Engine's debug text
  1099. AzFramework::ConsoleRequestBus::Broadcast(&AzFramework::ConsoleRequests::ExecuteConsoleCommand, "r_DisplayInfo 1");
  1100. }
  1101. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  1102. m_isFrameCapturePending = false;
  1103. }
  1104. bool SampleComponentManager::IsFrameCapturePending()
  1105. {
  1106. return m_isFrameCapturePending;
  1107. }
  1108. void SampleComponentManager::RunMainTestSuite(const AZStd::string& suiteFilePath, bool exitOnTestEnd, int randomSeed)
  1109. {
  1110. if (m_scriptManager)
  1111. {
  1112. m_scriptManager->RunMainTestSuite(suiteFilePath, exitOnTestEnd, randomSeed);
  1113. }
  1114. }
  1115. void SampleComponentManager::SetNumMSAASamples(int16_t numMSAASamples)
  1116. {
  1117. AZ_Assert(IsValidNumMSAASamples(numMSAASamples), "Invalid MSAA sample setting");
  1118. m_numMsaaSamples = numMSAASamples;
  1119. }
  1120. int16_t SampleComponentManager::GetNumMSAASamples()
  1121. {
  1122. return m_numMsaaSamples;
  1123. }
  1124. void SampleComponentManager::SetDefaultNumMSAASamples(int16_t defaultNumMsaaSamples)
  1125. {
  1126. m_defaultNumMsaaSamples = defaultNumMsaaSamples;
  1127. }
  1128. int16_t SampleComponentManager::GetDefaultNumMSAASamples()
  1129. {
  1130. return m_defaultNumMsaaSamples;
  1131. }
  1132. void SampleComponentManager::ResetNumMSAASamples()
  1133. {
  1134. m_numMsaaSamples = m_defaultNumMsaaSamples;
  1135. }
  1136. void SampleComponentManager::ResetRPIScene()
  1137. {
  1138. ReleaseRPIScene();
  1139. SwitchSceneForRPISample();
  1140. }
  1141. void SampleComponentManager::ClearRPIScene()
  1142. {
  1143. ReleaseRPIScene();
  1144. }
  1145. void SampleComponentManager::EnableRenderPipeline(bool value)
  1146. {
  1147. if (m_renderPipeline)
  1148. {
  1149. if (value)
  1150. {
  1151. m_renderPipeline->AddToRenderTick();
  1152. }
  1153. else
  1154. {
  1155. m_renderPipeline->RemoveFromRenderTick();
  1156. }
  1157. }
  1158. }
  1159. void SampleComponentManager::EnableXrPipelines(bool value)
  1160. {
  1161. for (RPI::RenderPipelinePtr xrPipeline : m_xrPipelines)
  1162. {
  1163. if (xrPipeline)
  1164. {
  1165. if (value)
  1166. {
  1167. xrPipeline->AddToRenderTick();
  1168. }
  1169. else
  1170. {
  1171. xrPipeline->RemoveFromRenderTick();
  1172. }
  1173. }
  1174. }
  1175. }
  1176. void SampleComponentManager::ShowFrameCaptureDialog()
  1177. {
  1178. static bool requestCaptureOnNextFrame = false;
  1179. static bool hideImGuiFromFrameCapture = true;
  1180. if (requestCaptureOnNextFrame)
  1181. {
  1182. requestCaptureOnNextFrame = false;
  1183. RequestFrameCapture(m_imguiFrameCaptureSaver.GetSaveFilePath(), hideImGuiFromFrameCapture);
  1184. }
  1185. else if (!m_isFrameCapturePending) // Hide this dialog while taking a capture
  1186. {
  1187. if (ImGui::Begin("Frame Capture", &m_showFrameCaptureDialog))
  1188. {
  1189. ImGui::Checkbox("Hide ImGui", &hideImGuiFromFrameCapture);
  1190. ImGuiSaveFilePath::WidgetSettings settings;
  1191. settings.m_labels.m_filePath = "File Path (.png, .ppm, or .dds):";
  1192. m_imguiFrameCaptureSaver.Tick(settings);
  1193. if (ImGui::Button("Capture"))
  1194. {
  1195. // Don't actually do the capture until the next frame, so we can hide this dialog first
  1196. requestCaptureOnNextFrame = true;
  1197. if (hideImGuiFromFrameCapture)
  1198. {
  1199. Utils::ReportScriptableAction("CaptureScreenshot('%s')", m_imguiFrameCaptureSaver.GetSaveFilePath().c_str());
  1200. }
  1201. else
  1202. {
  1203. Utils::ReportScriptableAction("CaptureScreenshotWithImGui('%s')", m_imguiFrameCaptureSaver.GetSaveFilePath().c_str());
  1204. }
  1205. }
  1206. }
  1207. ImGui::End();
  1208. }
  1209. }
  1210. void SampleComponentManager::RequestExit()
  1211. {
  1212. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop);
  1213. AZ::TickBus::Handler::BusDisconnect();
  1214. AzFramework::InputChannelEventListener::Disconnect();
  1215. m_exitRequested = true;
  1216. }
  1217. void SampleComponentManager::ShutdownActiveSample()
  1218. {
  1219. m_exampleEntity->Deactivate();
  1220. // Pointer to all the passes within m_rhiSamplePasses must be nullified before all the samples within m_activeSamples are destroyed.
  1221. SetRHISamplePass(nullptr);
  1222. for (AZ::Component* activeComponent : m_activeSamples)
  1223. {
  1224. if (activeComponent != nullptr)
  1225. {
  1226. // Disable the camera controller just in case the active sample enabled it and didn't disable in Deactivate().
  1227. AZ::Debug::CameraControllerRequestBus::Event(m_cameraEntity->GetId(), &AZ::Debug::CameraControllerRequestBus::Events::Disable);
  1228. m_exampleEntity->RemoveComponent(activeComponent);
  1229. delete activeComponent;
  1230. }
  1231. }
  1232. m_activeSamples.clear();
  1233. // Force a reset of the shader variant finder to get more consistent testing of samples every time they are run, rather
  1234. // than the first time for each sample being "special".
  1235. auto variantFinder = AZ::Interface<AZ::RPI::IShaderVariantFinder>::Get();
  1236. variantFinder->Reset();
  1237. }
  1238. void SampleComponentManager::Reset()
  1239. {
  1240. ShutdownActiveSample();
  1241. m_exampleEntity->Activate();
  1242. // Reset to RHI sample pipeline
  1243. SwitchSceneForRHISample();
  1244. SetRHISamplePass(nullptr);
  1245. }
  1246. void SampleComponentManager::CreateDefaultCamera()
  1247. {
  1248. if (m_cameraEntity)
  1249. {
  1250. return;
  1251. }
  1252. // A camera entity will be created by the entity context request bus so that the component for this entity can use a feature processor.
  1253. AzFramework::EntityContextRequestBus::EventResult(m_cameraEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "CameraEntity");
  1254. //Add debug camera and controller components
  1255. AZ::Debug::CameraComponentConfig cameraConfig(m_windowContext);
  1256. cameraConfig.m_fovY = AZ::Constants::QuarterPi;
  1257. cameraConfig.m_depthFar = 1000.0f;
  1258. m_cameraEntity->CreateComponent(azrtti_typeid<AZ::Debug::CameraComponent>())
  1259. ->SetConfiguration(cameraConfig);
  1260. m_cameraEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  1261. m_cameraEntity->CreateComponent(azrtti_typeid<AZ::Debug::ArcBallControllerComponent>());
  1262. m_cameraEntity->CreateComponent(azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
  1263. m_cameraEntity->Activate();
  1264. m_scriptManager->SetCameraEntity(m_cameraEntity);
  1265. }
  1266. void SampleComponentManager::SetupImGuiContext()
  1267. {
  1268. AdjustImGuiFontScale();
  1269. // Add imgui context
  1270. Render::ImGuiSystemRequestBus::BroadcastResult(m_isImGuiAvailable, &Render::ImGuiSystemRequests::PushActiveContextFromDefaultPass);
  1271. AZ_Assert(m_isImGuiAvailable, "Unable set default imgui context to active. Does your pipeline have an ImGui pass marked as default? Your pass assets may need to be rebuilt.");
  1272. }
  1273. void SampleComponentManager::ActiveImGuiContextChanged(ImGuiContext* context)
  1274. {
  1275. ImGui::SetCurrentContext(context);
  1276. }
  1277. bool SampleComponentManager::OpenSample(const AZStd::string& sampleName)
  1278. {
  1279. for (int32_t i = 0; i < m_availableSamples.size(); i++)
  1280. {
  1281. if (m_availableSamples[i].m_parentMenuName + '/' + m_availableSamples[i].m_sampleName == sampleName)
  1282. {
  1283. if (!m_availableSamples[i].m_isSupportedFunc || m_availableSamples[i].m_isSupportedFunc())
  1284. {
  1285. m_selectedSampleIndex = i;
  1286. m_sampleChangeRequest = true;
  1287. return true;
  1288. }
  1289. else
  1290. {
  1291. AZ_Error("SampleComponentManager", false, "Sample '%s' is not supported on this platform.", sampleName.c_str());
  1292. }
  1293. }
  1294. }
  1295. return false;
  1296. }
  1297. bool SampleComponentManager::ShowTool(const AZStd::string& toolName, bool enable)
  1298. {
  1299. if (toolName == PassTreeToolName)
  1300. {
  1301. m_showPassTree = enable;
  1302. return true;
  1303. }
  1304. else if (toolName == CpuProfilerToolName)
  1305. {
  1306. m_showCpuProfiler = enable;
  1307. return true;
  1308. }
  1309. else if (toolName == FileIoProfilerToolName)
  1310. {
  1311. m_showFileIoProfiler = enable;
  1312. return true;
  1313. }
  1314. else if (toolName == GpuProfilerToolName)
  1315. {
  1316. m_showGpuProfiler = enable;
  1317. return true;
  1318. }
  1319. else if (toolName == TransientAttachmentProfilerToolName)
  1320. {
  1321. m_showTransientAttachmentProfiler = enable;
  1322. return true;
  1323. }
  1324. return false;
  1325. }
  1326. void SampleComponentManager::SampleChange()
  1327. {
  1328. if (m_selectedSampleIndex == -1)
  1329. {
  1330. return;
  1331. }
  1332. ShutdownActiveSample();
  1333. // Reset the camera *before* activating the sample, because the sample's Activate() function might
  1334. // want to reposition the camera.
  1335. CameraReset();
  1336. const SampleEntry& sampleEntry = m_availableSamples[m_selectedSampleIndex];
  1337. // Create scene and render pipeline before create sample component
  1338. if (sampleEntry.m_pipelineType == SamplePipelineType::RHI)
  1339. {
  1340. SwitchSceneForRHISample();
  1341. }
  1342. else if (sampleEntry.m_pipelineType == SamplePipelineType::RPI)
  1343. {
  1344. SwitchSceneForRPISample();
  1345. }
  1346. SampleComponentConfig config(m_windowContext, m_cameraEntity->GetId(), m_entityContextId);
  1347. // special setup for RHI samples
  1348. if (sampleEntry.m_pipelineType == SamplePipelineType::RHI)
  1349. {
  1350. for (AZ::RPI::Ptr<RHISamplePass> samplePass : m_rhiSamplePasses)
  1351. {
  1352. BasicRHIComponent* rhiSampleComponent = static_cast<BasicRHIComponent*>(m_exampleEntity->CreateComponent(sampleEntry.m_sampleUuid));
  1353. rhiSampleComponent->SetConfiguration(config);
  1354. rhiSampleComponent->SetViewIndex(samplePass->GetViewIndex());
  1355. if (rhiSampleComponent->IsSupportedRHISamplePipeline())
  1356. {
  1357. samplePass->SetRHISample(rhiSampleComponent);
  1358. }
  1359. else
  1360. {
  1361. samplePass->SetRHISample(nullptr);
  1362. }
  1363. m_activeSamples.push_back(rhiSampleComponent);
  1364. }
  1365. }
  1366. else
  1367. {
  1368. AZ::Component* newComponent = m_exampleEntity->CreateComponent(sampleEntry.m_sampleUuid);
  1369. newComponent->SetConfiguration(config);
  1370. m_activeSamples.push_back(newComponent);
  1371. }
  1372. m_exampleEntity->Activate();
  1373. // Even though this is done in CameraReset(), the example component wasn't activated at the time so we have to send this event again.
  1374. ExampleComponentRequestBus::Event(m_exampleEntity->GetId(), &ExampleComponentRequestBus::Events::ResetCamera);
  1375. }
  1376. void SampleComponentManager::CameraReset()
  1377. {
  1378. // Reset the camera transform. Some examples do not use a controller or use a controller that doesn't override the whole transform.
  1379. // Set to a transform that is 5 units away from the origin and looking at the origin along the Y axis.
  1380. const AZ::EntityId cameraEntityId = m_cameraEntity->GetId();
  1381. AZ::TransformBus::Event(cameraEntityId, &AZ::TransformBus::Events::SetWorldTM, AZ::Transform::CreateTranslation(AZ::Vector3(0.0f, -5.0f, 0.0f)));
  1382. AZ::Debug::CameraControllerRequestBus::Event(cameraEntityId, &AZ::Debug::CameraControllerRequestBus::Events::Reset);
  1383. // Tell the current example to reset the camera, any example that controls the camera and preserves controller state should implement this event
  1384. ExampleComponentRequestBus::Event(m_exampleEntity->GetId(), &ExampleComponentRequestBus::Events::ResetCamera);
  1385. }
  1386. void SampleComponentManager::CreateSceneForRHISample()
  1387. {
  1388. // Create and register the rhi scene with only feature processors required for AtomShimRenderer (only for AtomSampleViewerLauncher)
  1389. RPI::SceneDescriptor sceneDesc;
  1390. sceneDesc.m_nameId = AZ::Name("RHI");
  1391. sceneDesc.m_featureProcessorNames.push_back("AZ::Render::AuxGeomFeatureProcessor");
  1392. m_rhiScene = RPI::Scene::CreateScene(sceneDesc);
  1393. m_rhiScene->Activate();
  1394. auto* xrSystem = AZ::RHI::RHISystemInterface::Get()->GetXRSystem();
  1395. const bool createDefaultRenderPipeline = !xrSystem || xrSystem->IsDefaultRenderPipelineNeeded();
  1396. if (createDefaultRenderPipeline)
  1397. {
  1398. RPI::RenderPipelineDescriptor pipelineDesc;
  1399. pipelineDesc.m_name = "RHISamplePipeline";
  1400. pipelineDesc.m_rootPassTemplate = "RHISamplePipelineTemplate";
  1401. // Add view to pipeline since there are few RHI samples are using ViewSrg
  1402. pipelineDesc.m_mainViewTagName = "MainCamera";
  1403. m_renderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get());
  1404. m_rhiScene->AddRenderPipeline(m_renderPipeline);
  1405. m_renderPipeline->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1406. // Get RHISamplePass
  1407. AZ::RPI::PassFilter passFilter = AZ::RPI::PassFilter::CreateWithPassName(AZ::Name("RHISamplePass"), m_renderPipeline.get());
  1408. m_rhiSamplePasses.push_back(azrtti_cast<RHISamplePass*>(AZ::RPI::PassSystemInterface::Get()->FindFirstPass(passFilter)));
  1409. // Enable or disable default pipeline on host while there is an xr system.
  1410. if (xrSystem)
  1411. {
  1412. EnableRenderPipeline(xrSystem->IsDefaultRenderPipelineEnabledOnHost());
  1413. }
  1414. }
  1415. if (xrSystem)
  1416. {
  1417. RPI::RenderPipelineDescriptor xrPipelineDesc;
  1418. xrPipelineDesc.m_mainViewTagName = "MainCamera";
  1419. // Build the pipeline for left eye
  1420. xrPipelineDesc.m_name = "RHISamplePipelineXRLeft";
  1421. xrPipelineDesc.m_rootPassTemplate = "RHISamplePipelineXRLeftTemplate";
  1422. RPI::RenderPipelinePtr renderPipelineLeft = RPI::RenderPipeline::CreateRenderPipelineForWindow(xrPipelineDesc, *m_windowContext.get(), AZ::RPI::ViewType::XrLeft);
  1423. // Build the pipeline for right eye
  1424. xrPipelineDesc.m_name = "RHISamplePipelineXRRight";
  1425. xrPipelineDesc.m_rootPassTemplate = "RHISamplePipelineXRRightTemplate";
  1426. RPI::RenderPipelinePtr renderPipelineRight = RPI::RenderPipeline::CreateRenderPipelineForWindow(xrPipelineDesc, *m_windowContext.get(), AZ::RPI::ViewType::XrRight);
  1427. //Add both the pipelines to the scene
  1428. m_rhiScene->AddRenderPipeline(renderPipelineLeft);
  1429. m_rhiScene->AddRenderPipeline(renderPipelineRight);
  1430. renderPipelineLeft->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1431. renderPipelineRight->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1432. // Set the correct view index for the RHI sample passes
  1433. AZ::RPI::PassFilter rhiSamplePassFilterLeft = AZ::RPI::PassFilter::CreateWithPassName(AZ::Name("RHISamplePass"), renderPipelineLeft.get());
  1434. AZ::RPI::Ptr<RHISamplePass> rhiSamplePassLeft = azrtti_cast<RHISamplePass*>(AZ::RPI::PassSystemInterface::Get()->FindFirstPass(rhiSamplePassFilterLeft));
  1435. rhiSamplePassLeft->SetViewIndex(0);
  1436. m_rhiSamplePasses.push_back(rhiSamplePassLeft);
  1437. AZ::RPI::PassFilter rhiSamplePassFilterRight = AZ::RPI::PassFilter::CreateWithPassName(AZ::Name("RHISamplePass"), renderPipelineRight.get());
  1438. AZ::RPI::Ptr<RHISamplePass> rhiSamplePassRight = azrtti_cast<RHISamplePass*>(AZ::RPI::PassSystemInterface::Get()->FindFirstPass(rhiSamplePassFilterRight));
  1439. rhiSamplePassRight->SetViewIndex(1);
  1440. m_rhiSamplePasses.push_back(rhiSamplePassRight);
  1441. //Cache the pipelines in case we want to enable/disable them
  1442. m_xrPipelines.push_back(renderPipelineLeft);
  1443. m_xrPipelines.push_back(renderPipelineRight);
  1444. //Disable XR pipelines by default
  1445. EnableXrPipelines(false);
  1446. }
  1447. // Register the RHi scene
  1448. RPI::RPISystemInterface::Get()->RegisterScene(m_rhiScene);
  1449. // Setup imGui since a new render pipeline with imgui pass was created
  1450. SetupImGuiContext();
  1451. }
  1452. void SampleComponentManager::ReleaseRHIScene()
  1453. {
  1454. if (m_rhiScene)
  1455. {
  1456. m_rhiSamplePasses.clear();
  1457. m_xrPipelines.clear();
  1458. m_renderPipeline = nullptr;
  1459. RPI::RPISystemInterface::Get()->UnregisterScene(m_rhiScene);
  1460. m_rhiScene = nullptr;
  1461. }
  1462. }
  1463. void SampleComponentManager::SwitchSceneForRHISample()
  1464. {
  1465. ReleaseRPIScene();
  1466. ReleaseRHIScene();
  1467. CreateSceneForRHISample();
  1468. }
  1469. void SampleComponentManager::CreateSceneForRPISample()
  1470. {
  1471. // set pipeline MSAA samples
  1472. AZ_Assert(IsValidNumMSAASamples(m_numMsaaSamples), "Invalid MSAA sample setting");
  1473. const bool isNonMsaaPipeline = (m_numMsaaSamples == 1);
  1474. const char* supervariantName = isNonMsaaPipeline ? AZ::RPI::NoMsaaSupervariantName : "";
  1475. AZ::RPI::ShaderSystemInterface::Get()->SetSupervariantName(AZ::Name(supervariantName));
  1476. // Create and register a scene with all available feature processors
  1477. RPI::SceneDescriptor sceneDesc;
  1478. sceneDesc.m_nameId = AZ::Name("RPI");
  1479. m_rpiScene = RPI::Scene::CreateScene(sceneDesc);
  1480. m_rpiScene->EnableAllFeatureProcessors();
  1481. // Bind m_rpiScene to the GameEntityContext's AzFramework::Scene so the RPI Scene can be found by the entity context
  1482. auto sceneSystem = AzFramework::SceneSystemInterface::Get();
  1483. AZ_Assert(sceneSystem, "SampleComponentManager requires an implementation of the scene system.");
  1484. AZStd::shared_ptr<AzFramework::Scene> mainScene = sceneSystem->GetScene(AzFramework::Scene::MainSceneName);
  1485. AZ_Assert(mainScene, "Main scene missing during system component initialization"); // This should never happen unless scene creation has changed.
  1486. // Add RPI::Scene as a sub system for the default AzFramework Scene
  1487. [[maybe_unused]] bool result = mainScene->SetSubsystem(m_rpiScene);
  1488. AZ_Assert(result, "SampleComponentManager failed to register the RPI scene with the general scene.");
  1489. m_rpiScene->Activate();
  1490. // Register scene to RPI system so it will be processed/rendered per tick
  1491. RPI::RPISystemInterface::Get()->RegisterScene(m_rpiScene);
  1492. auto* xrSystem = AZ::RHI::RHISystemInterface::Get()->GetXRSystem();
  1493. const bool createDefaultRenderPipeline = !xrSystem || xrSystem->IsDefaultRenderPipelineNeeded();
  1494. if (createDefaultRenderPipeline)
  1495. {
  1496. // Create MainPipeline as its render pipeline
  1497. RPI::RenderPipelineDescriptor pipelineDesc;
  1498. pipelineDesc.m_name = "RPISamplePipeline";
  1499. pipelineDesc.m_rootPassTemplate = GetRootPassTemplateName();
  1500. pipelineDesc.m_materialPipelineTag = GetMaterialPipelineName();
  1501. pipelineDesc.m_mainViewTagName = "MainCamera";
  1502. pipelineDesc.m_allowModification = true;
  1503. pipelineDesc.m_renderSettings.m_multisampleState.m_samples = static_cast<uint16_t>(m_numMsaaSamples);
  1504. m_renderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get());
  1505. m_rpiScene->AddRenderPipeline(m_renderPipeline);
  1506. m_renderPipeline->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1507. // Enable or disable default pipeline on host while there is an xr system.
  1508. if (xrSystem)
  1509. {
  1510. EnableRenderPipeline(xrSystem->IsDefaultRenderPipelineEnabledOnHost());
  1511. }
  1512. }
  1513. if (xrSystem)
  1514. {
  1515. RPI::RenderPipelineDescriptor xrPipelineDesc;
  1516. xrPipelineDesc.m_mainViewTagName = "MainCamera";
  1517. xrPipelineDesc.m_renderSettings.m_multisampleState.m_samples = static_cast<uint16_t>(m_numMsaaSamples);
  1518. // Build the pipeline for left eye
  1519. xrPipelineDesc.m_name = "RPISamplePipelineXRLeft";
  1520. xrPipelineDesc.m_materialPipelineTag = "MultiViewPipeline";
  1521. xrPipelineDesc.m_rootPassTemplate = "MultiViewPipelineTemplate";
  1522. RPI::RenderPipelinePtr renderPipelineLeft = RPI::RenderPipeline::CreateRenderPipelineForWindow(xrPipelineDesc, *m_windowContext.get(), AZ::RPI::ViewType::XrLeft);
  1523. // Build the pipeline for right eye
  1524. xrPipelineDesc.m_name = "RHISamplePipelineXRRight";
  1525. xrPipelineDesc.m_materialPipelineTag = "MultiViewPipeline";
  1526. xrPipelineDesc.m_rootPassTemplate = "MultiViewPipelineTemplate";
  1527. RPI::RenderPipelinePtr renderPipelineRight = RPI::RenderPipeline::CreateRenderPipelineForWindow(xrPipelineDesc, *m_windowContext.get(), AZ::RPI::ViewType::XrRight);
  1528. //Add both the pipelines to the scene
  1529. m_rpiScene->AddRenderPipeline(renderPipelineLeft);
  1530. m_rpiScene->AddRenderPipeline(renderPipelineRight);
  1531. renderPipelineLeft->SetDefaultStereoscopicViewFromEntity(m_cameraEntity->GetId(), RPI::ViewType::XrLeft); //Left eye
  1532. renderPipelineRight->SetDefaultStereoscopicViewFromEntity(m_cameraEntity->GetId(), RPI::ViewType::XrRight); //Right eye
  1533. //Cache the pipelines in case we want to enable/disable them
  1534. m_xrPipelines.push_back(renderPipelineLeft);
  1535. m_xrPipelines.push_back(renderPipelineRight);
  1536. // Disable XR pipelines by default
  1537. EnableXrPipelines(false);
  1538. }
  1539. // As part of our initialization we need to create the BRDF texture generation pipeline
  1540. AZ::RPI::RenderPipelineDescriptor brdfPipelineDesc;
  1541. brdfPipelineDesc.m_mainViewTagName = "MainCamera";
  1542. brdfPipelineDesc.m_name = "BRDFTexturePipeline";
  1543. brdfPipelineDesc.m_rootPassTemplate = "BRDFTexturePipeline";
  1544. brdfPipelineDesc.m_executeOnce = true;
  1545. RPI::RenderPipelinePtr brdfTexturePipeline = AZ::RPI::RenderPipeline::CreateRenderPipeline(brdfPipelineDesc);
  1546. m_rpiScene->AddRenderPipeline(brdfTexturePipeline);
  1547. // Save a reference to the generated BRDF texture so it doesn't get deleted if all the passes referring to it get deleted and it's ref count goes to zero
  1548. if (!m_brdfTexture)
  1549. {
  1550. const AZStd::shared_ptr<const RPI::PassTemplate> brdfTextureTemplate = RPI::PassSystemInterface::Get()->GetPassTemplate(Name("BRDFTextureTemplate"));
  1551. Data::Asset<RPI::AttachmentImageAsset> brdfImageAsset = RPI::AssetUtils::LoadAssetById<RPI::AttachmentImageAsset>(
  1552. brdfTextureTemplate->m_imageAttachments[0].m_assetRef.m_assetId, RPI::AssetUtils::TraceLevel::Error);
  1553. if (brdfImageAsset.IsReady())
  1554. {
  1555. m_brdfTexture = RPI::AttachmentImage::FindOrCreate(brdfImageAsset);
  1556. }
  1557. }
  1558. // Setup imGui since a new render pipeline with imgui pass was created
  1559. SetupImGuiContext();
  1560. }
  1561. void SampleComponentManager::ReleaseRPIScene()
  1562. {
  1563. if (m_rpiScene)
  1564. {
  1565. m_xrPipelines.clear();
  1566. m_renderPipeline = nullptr;
  1567. RPI::RPISystemInterface::Get()->UnregisterScene(m_rpiScene);
  1568. auto sceneSystem = AzFramework::SceneSystemInterface::Get();
  1569. AZ_Assert(sceneSystem, "Scene system was destroyed before SampleComponentManager was able to unregister the RPI scene.");
  1570. AZStd::shared_ptr<AzFramework::Scene> scene = sceneSystem->GetScene(AzFramework::Scene::MainSceneName);
  1571. AZ_Assert(scene, "The main scene wasn't found in the scene system.");
  1572. [[maybe_unused]] bool result = scene->UnsetSubsystem(m_rpiScene);
  1573. AZ_Assert(result, "SampleComponentManager failed to unregister its RPI scene from the general scene.");
  1574. m_rpiScene = nullptr;
  1575. }
  1576. }
  1577. void SampleComponentManager::SwitchSceneForRPISample()
  1578. {
  1579. ReleaseRHIScene();
  1580. ReleaseRPIScene();
  1581. CreateSceneForRPISample();
  1582. }
  1583. // AzFramework::AssetCatalogEventBus::Handler overrides ...
  1584. void SampleComponentManager::OnCatalogLoaded([[maybe_unused]] const char* catalogFile)
  1585. {
  1586. AZ::TickBus::QueueFunction([&]()
  1587. {
  1588. ActivateInternal();
  1589. });
  1590. }
  1591. void SampleComponentManager::SetRHISamplePass(BasicRHIComponent* sampleComponent)
  1592. {
  1593. for (AZ::RPI::Ptr<RHISamplePass> samplePass : m_rhiSamplePasses)
  1594. {
  1595. samplePass->SetRHISample(sampleComponent);
  1596. }
  1597. }
  1598. } // namespace AtomSampleViewer