SampleComponentManager.cpp 66 KB

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