SampleComponentManager.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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/XRExampleComponent.h>
  58. #include <RHI/TrianglesConstantBufferExampleComponent.h>
  59. #include <RHI/BindlessPrototypeExampleComponent.h>
  60. #include <RHI/RayTracingExampleComponent.h>
  61. #include <RHI/MatrixAlignmentTestExampleComponent.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<XRExampleComponent>("OpenXr"),
  273. NewRHISample<MatrixAlignmentTestExampleComponent>("MatrixAlignmentTest"),
  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. AZ::RPI::RPISystemInterface* rpiSystem = AZ::RPI::RPISystemInterface::Get();
  495. if (rpiSystem->GetXRSystem())
  496. {
  497. //Only enable XR pipelines if the XR drivers indicate we have accurate pose information from the device
  498. if (rpiSystem->GetXRSystem()->ShouldRender())
  499. {
  500. EnableXrPipelines();
  501. }
  502. else
  503. {
  504. DisableXrPipelines();
  505. }
  506. }
  507. if (m_imGuiFrameTimer)
  508. {
  509. m_imGuiFrameTimer->PushValue(deltaTime * 1000.0f);
  510. }
  511. bool screenshotRequest = false;
  512. if (m_ctrlModifierLDown || m_ctrlModifierRDown)
  513. {
  514. if (m_alphanumericQDown)
  515. {
  516. RequestExit();
  517. return;
  518. }
  519. if (m_alphanumericTDown && m_canCaptureRADTM)
  520. {
  521. #ifdef AZ_PROFILE_TELEMETRY
  522. Utils::ToggleRadTMCapture();
  523. m_canCaptureRADTM = false;
  524. #endif
  525. }
  526. else if (!m_alphanumericTDown)
  527. {
  528. m_canCaptureRADTM = true;
  529. }
  530. if (m_alphanumericPDown)
  531. {
  532. screenshotRequest = true;
  533. }
  534. }
  535. // Request a frame capture only once per key press, even if the keys are held down for multiple ticks.
  536. if (screenshotRequest)
  537. {
  538. ++m_screenshotKeyDownCount;
  539. if (m_screenshotKeyDownCount == 1)
  540. {
  541. RequestFrameCapture(m_imguiFrameCaptureSaver.GetNextAutoSaveFilePath(), true);
  542. }
  543. }
  544. else
  545. {
  546. m_screenshotKeyDownCount = 0;
  547. }
  548. RenderImGui(deltaTime);
  549. // SampleChange needs to happen after RenderImGui as some of the samples create sidebars on a separate ImGui context
  550. // which can interfere with m_imguiContext in the first frame
  551. if (m_sampleChangeRequest && m_canSwitchSample)
  552. {
  553. SampleChange();
  554. m_canSwitchSample = false;
  555. }
  556. else if (m_escapeDown && m_canSwitchSample)
  557. {
  558. Reset();
  559. m_canSwitchSample = false;
  560. Utils::ReportScriptableAction("OpenSample('')");
  561. }
  562. // 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
  563. if (!m_sampleChangeRequest && !m_escapeDown)
  564. {
  565. m_canSwitchSample = true;
  566. }
  567. // Since the event has been handled, clear the request
  568. m_sampleChangeRequest = false;
  569. m_escapeDown = false;
  570. m_scriptManager->TickScript(deltaTime);
  571. if (m_isFrameCapturePending)
  572. {
  573. if (m_countdownForFrameCapture > 0)
  574. {
  575. m_countdownForFrameCapture--;
  576. }
  577. else if (m_countdownForFrameCapture == 0)
  578. {
  579. AZ::Render::FrameCaptureRequestBus::BroadcastResult(m_frameCaptureId, &AZ::Render::FrameCaptureRequestBus::Events::CaptureScreenshot, m_frameCaptureFilePath);
  580. if (m_frameCaptureId != AZ::Render::InvalidFrameCaptureId ) // if unsuccessfull leave state to attempt again next tick
  581. {
  582. AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(m_frameCaptureId);
  583. m_countdownForFrameCapture = -1; // Don't call CaptureScreenshot again
  584. }
  585. }
  586. }
  587. }
  588. bool SampleComponentManager::OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel)
  589. {
  590. const size_t samplesAvailableCount = m_availableSamples.size();
  591. AZStd::vector<AzFramework::InputChannelId> sampleInputMapping;
  592. sampleInputMapping.reserve(samplesAvailableCount);
  593. for (size_t i = 0; i < samplesAvailableCount; ++i)
  594. {
  595. switch (i)
  596. {
  597. case 0:
  598. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric1);
  599. break;
  600. case 1:
  601. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric2);
  602. break;
  603. case 2:
  604. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric3);
  605. break;
  606. case 3:
  607. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric4);
  608. break;
  609. case 4:
  610. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric5);
  611. break;
  612. case 5:
  613. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric6);
  614. break;
  615. case 6:
  616. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric7);
  617. break;
  618. case 7:
  619. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric8);
  620. break;
  621. case 8:
  622. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric9);
  623. break;
  624. case 9:
  625. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric0);
  626. break;
  627. default:
  628. break;
  629. }
  630. }
  631. const AzFramework::InputChannelId& inputChannelId = inputChannel.GetInputChannelId();
  632. switch (inputChannel.GetState())
  633. {
  634. case AzFramework::InputChannel::State::Began:
  635. case AzFramework::InputChannel::State::Updated:
  636. {
  637. if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlL)
  638. {
  639. m_ctrlModifierLDown = true;
  640. }
  641. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlR)
  642. {
  643. m_ctrlModifierRDown = true;
  644. }
  645. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericQ)
  646. {
  647. m_alphanumericQDown = true;
  648. }
  649. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericT)
  650. {
  651. m_alphanumericTDown = true;
  652. }
  653. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericP)
  654. {
  655. m_alphanumericPDown = true;
  656. }
  657. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::Escape)
  658. {
  659. m_escapeDown = true;
  660. }
  661. break;
  662. }
  663. case AzFramework::InputChannel::State::Ended:
  664. {
  665. if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlL)
  666. {
  667. m_ctrlModifierLDown = false;
  668. }
  669. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlR)
  670. {
  671. m_ctrlModifierRDown = false;
  672. }
  673. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericQ)
  674. {
  675. m_alphanumericQDown = false;
  676. }
  677. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericT)
  678. {
  679. m_alphanumericTDown = false;
  680. }
  681. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericP)
  682. {
  683. m_alphanumericPDown = false;
  684. }
  685. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::Escape)
  686. {
  687. m_escapeDown = false;
  688. }
  689. break;
  690. }
  691. default:
  692. {
  693. break;
  694. }
  695. }
  696. return false;
  697. }
  698. void SampleComponentManager::RenderImGui(float deltaTime)
  699. {
  700. if (!m_isImGuiAvailable)
  701. {
  702. return;
  703. }
  704. ShowMenuBar();
  705. if (m_exitRequested)
  706. {
  707. return;
  708. }
  709. if (m_showResizeViewportDialog)
  710. {
  711. ShowResizeViewportDialog();
  712. }
  713. if (m_showFramerateHistogram)
  714. {
  715. ShowFramerateHistogram(deltaTime);
  716. }
  717. if (m_showFrameCaptureDialog)
  718. {
  719. ShowFrameCaptureDialog();
  720. }
  721. if (m_showImGuiMetrics)
  722. {
  723. ImGui::ShowMetricsWindow(&m_showImGuiMetrics);
  724. }
  725. if (m_showSampleHelper)
  726. {
  727. ShowSampleHelper();
  728. }
  729. if (m_showAbout)
  730. {
  731. ShowAboutWindow();
  732. }
  733. if (m_showPassTree)
  734. {
  735. ShowPassTreeWindow();
  736. }
  737. if (m_showFrameGraphVisualizer)
  738. {
  739. ShowFrameGraphVisualizerWindow();
  740. }
  741. if (m_showCullingDebugWindow)
  742. {
  743. AZ::RPI::Scene* rpiScene = AZ::RPI::RPISystemInterface::Get()->GetSceneByName(AZ::Name("RPI"));
  744. if (rpiScene)
  745. {
  746. AZ::Render::ImGuiDrawCullingDebug(m_showCullingDebugWindow, rpiScene);
  747. }
  748. }
  749. if (m_showCpuProfiler)
  750. {
  751. ShowCpuProfilerWindow();
  752. }
  753. if (m_showGpuProfiler)
  754. {
  755. ShowGpuProfilerWindow();
  756. }
  757. if (m_showFileIoProfiler)
  758. {
  759. ShowFileIoProfilerWindow();
  760. }
  761. if (m_showTransientAttachmentProfiler)
  762. {
  763. ShowTransientAttachmentProfilerWindow();
  764. }
  765. m_scriptManager->TickImGui();
  766. m_contentWarningDialog.TickPopup();
  767. }
  768. void SampleComponentManager::ShowMenuBar()
  769. {
  770. if (ImGui::BeginMainMenuBar())
  771. {
  772. // If imgui doesn't have enough room to render a menu, it will fall back to the safe area which
  773. // is typically 3 pixels. This causes the menu to overlap the menu bar, and makes it easy to
  774. // accidentally select the first item on that menu bar. By altering the safe area temporarily
  775. // while drawing the menu, this problem can be avoided.
  776. ImVec2 cachedSafeArea = ImGui::GetStyle().DisplaySafeAreaPadding;
  777. ImGui::GetStyle().DisplaySafeAreaPadding = ImVec2(cachedSafeArea.x, cachedSafeArea.y + 16.0f);
  778. if (ImGui::BeginMenu("File"))
  779. {
  780. if (ImGui::MenuItem("Exit", "Ctrl-Q"))
  781. {
  782. RequestExit();
  783. }
  784. if (ImGui::MenuItem("Capture Frame...", "Ctrl-P"))
  785. {
  786. m_showFrameCaptureDialog = true;
  787. }
  788. ImGui::EndMenu();
  789. }
  790. if (ImGui::BeginMenu("View"))
  791. {
  792. if (Utils::SupportsResizeClientArea() && ImGui::MenuItem("Resize Viewport..."))
  793. {
  794. m_showResizeViewportDialog = true;
  795. }
  796. if (Utils::SupportsToggleFullScreenOfDefaultWindow() && ImGui::MenuItem("Toggle Full Screen"))
  797. {
  798. Utils::ToggleFullScreenOfDefaultWindow();
  799. }
  800. if (ImGui::MenuItem("Frame Time Histogram"))
  801. {
  802. m_showFramerateHistogram = !m_showFramerateHistogram;
  803. }
  804. if (ImGui::MenuItem("ImGui Metrics"))
  805. {
  806. m_showImGuiMetrics = !m_showImGuiMetrics;
  807. }
  808. if (ImGui::MenuItem("Sample Helper"))
  809. {
  810. m_showSampleHelper = !m_showSampleHelper;
  811. }
  812. if (ImGui::MenuItem("Frame Graph Visualizer"))
  813. {
  814. m_showFrameGraphVisualizer = !m_showFrameGraphVisualizer;
  815. }
  816. ImGui::EndMenu();
  817. }
  818. if (ImGui::BeginMenu("Samples"))
  819. {
  820. for (auto&& [parentMenuName, samples] : m_groupedSamples)
  821. {
  822. if (ImGui::BeginMenu(parentMenuName.c_str()))
  823. {
  824. for (int32_t index : samples)
  825. {
  826. SampleEntry& sample = m_availableSamples[index];
  827. const char* sampleName = sample.m_sampleName.c_str();
  828. bool enabled = m_isSampleSupported[index];
  829. if (ImGui::MenuItem(sampleName, nullptr, false, enabled))
  830. {
  831. Utils::ReportScriptableAction("OpenSample('%s')", sample.m_sampleName.c_str());
  832. if (sample.m_contentWarning.empty())
  833. {
  834. m_sampleChangeRequest = true;
  835. m_selectedSampleIndex = index;
  836. }
  837. else
  838. {
  839. m_contentWarningDialog.OpenPopupConfirmation(
  840. sample.m_contentWarningTitle,
  841. sample.m_contentWarning,
  842. [this, index]() {
  843. m_sampleChangeRequest = true;
  844. m_selectedSampleIndex = index;
  845. });
  846. }
  847. }
  848. }
  849. ImGui::EndMenu();
  850. }
  851. }
  852. ImGui::EndMenu();
  853. }
  854. #ifdef AZ_PROFILE_TELEMETRY
  855. if (ImGui::BeginMenu("RADTelemetry"))
  856. {
  857. if (ImGui::MenuItem("Toggle Capture", "Ctrl-T"))
  858. {
  859. Utils::ToggleRadTMCapture();
  860. }
  861. ImGui::EndMenu();
  862. }
  863. #endif // AZ_PROFILE_TELEMETRY
  864. if (ImGui::BeginMenu("Automation"))
  865. {
  866. const char* AutomationContentWarningTitle = AtomSampleComponent::CommonPhotosensitiveWarningTitle;
  867. const char* AutomationContentWarning = "Running automated scripts will trigger flashing images that could cause seizures or other adverse effects in photosensitive individuals.";
  868. if (ImGui::MenuItem("Run Script..."))
  869. {
  870. m_contentWarningDialog.OpenPopupConfirmation(
  871. AutomationContentWarningTitle,
  872. AutomationContentWarning,
  873. [this]() {
  874. m_scriptManager->OpenScriptRunnerDialog();
  875. });
  876. }
  877. if (ImGui::MenuItem("Run Precommit Wizard..."))
  878. {
  879. m_contentWarningDialog.OpenPopupConfirmation(
  880. AutomationContentWarningTitle,
  881. AutomationContentWarning,
  882. [this]() {
  883. m_scriptManager->OpenPrecommitWizard();
  884. });
  885. }
  886. ImGui::EndMenu();
  887. }
  888. if (ImGui::BeginMenu("Pass"))
  889. {
  890. if (ImGui::MenuItem(PassTreeToolName))
  891. {
  892. m_showPassTree = !m_showPassTree;
  893. Utils::ReportScriptableAction("ShowTool('%s', %s)", PassTreeToolName, m_showPassTree?"true":"false");
  894. }
  895. ImGui::EndMenu();
  896. }
  897. if (ImGui::BeginMenu("Culling"))
  898. {
  899. if (ImGui::MenuItem("Culling Debug Window"))
  900. {
  901. m_showCullingDebugWindow = !m_showCullingDebugWindow;
  902. }
  903. ImGui::EndMenu();
  904. }
  905. if (ImGui::BeginMenu("Profile"))
  906. {
  907. if (ImGui::MenuItem(CpuProfilerToolName))
  908. {
  909. m_showCpuProfiler = !m_showCpuProfiler;
  910. if (auto profilerSystem = AZ::Debug::ProfilerSystemInterface::Get(); profilerSystem)
  911. {
  912. profilerSystem->SetActive(m_showCpuProfiler);
  913. }
  914. Utils::ReportScriptableAction("ShowTool('%s', %s)", CpuProfilerToolName, m_showCpuProfiler ? "true" : "false");
  915. }
  916. if (AZ::IO::StreamerProfiler::Get() != nullptr)
  917. {
  918. if (ImGui::MenuItem(FileIoProfilerToolName))
  919. {
  920. m_showFileIoProfiler = !m_showFileIoProfiler;
  921. Utils::ReportScriptableAction(
  922. "ShowTool('%s', %s)", FileIoProfilerToolName, m_showFileIoProfiler ? "true" : "false");
  923. }
  924. }
  925. if (ImGui::MenuItem(GpuProfilerToolName))
  926. {
  927. m_showGpuProfiler = !m_showGpuProfiler;
  928. Utils::ReportScriptableAction("ShowTool('%s', %s)", GpuProfilerToolName, m_showGpuProfiler ? "true" : "false");
  929. }
  930. if (ImGui::MenuItem(TransientAttachmentProfilerToolName))
  931. {
  932. m_showTransientAttachmentProfiler = !m_showTransientAttachmentProfiler;
  933. AZ::RHI::RHISystemInterface::Get()->ModifyFrameSchedulerStatisticsFlags(
  934. AZ::RHI::FrameSchedulerStatisticsFlags::GatherTransientAttachmentStatistics,
  935. m_showTransientAttachmentProfiler);
  936. Utils::ReportScriptableAction("ShowTool('%s', %s)", TransientAttachmentProfilerToolName, m_showTransientAttachmentProfiler ? "true" : "false");
  937. }
  938. ImGui::EndMenu();
  939. }
  940. if (ImGui::BeginMenu("Help"))
  941. {
  942. if (ImGui::MenuItem("About"))
  943. {
  944. m_showAbout = !m_showAbout;
  945. }
  946. ImGui::EndMenu();
  947. }
  948. // Restore original safe area.
  949. ImGui::GetStyle().DisplaySafeAreaPadding = cachedSafeArea;
  950. ImGui::EndMainMenuBar();
  951. }
  952. }
  953. void SampleComponentManager::ShowSampleHelper()
  954. {
  955. if (ImGui::Begin("Sample Helper", &m_showSampleHelper, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  956. {
  957. if (ImGui::Button("Reset"))
  958. {
  959. //Removes the existing sample component and
  960. //resets the selection index
  961. Reset();
  962. CameraReset();
  963. m_selectedSampleIndex = -1;
  964. }
  965. ImGui::SameLine();
  966. if (ImGui::Button("Reset Sample"))
  967. {
  968. //Force a sample change event when the selection index
  969. //hasn't changed. This resets the sample component.
  970. SampleChange();
  971. }
  972. ImGui::SameLine();
  973. if (ImGui::Button("Reset Camera"))
  974. {
  975. CameraReset();
  976. }
  977. }
  978. ImGui::End();
  979. }
  980. void SampleComponentManager::ShowAboutWindow()
  981. {
  982. if (ImGui::Begin("About", &m_showAbout, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  983. {
  984. ImGui::Text("RHI API: %s", AZ::RHI::Factory::Get().GetName().GetCStr());
  985. }
  986. ImGui::End();
  987. }
  988. void SampleComponentManager::ShowPassTreeWindow()
  989. {
  990. m_imguiPassTree.Draw(m_showPassTree, AZ::RPI::PassSystemInterface::Get()->GetRootPass().get());
  991. }
  992. void SampleComponentManager::ShowFrameGraphVisualizerWindow()
  993. {
  994. AZ::RHI::Device* rhiDevice = Utils::GetRHIDevice().get();
  995. m_imguiFrameGraphVisualizer.Init(rhiDevice);
  996. m_imguiFrameGraphVisualizer.Draw(m_showFrameGraphVisualizer);
  997. }
  998. void SampleComponentManager::ShowCpuProfilerWindow()
  999. {
  1000. if (auto profilerImGui = Profiler::ProfilerImGuiInterface::Get(); profilerImGui)
  1001. {
  1002. profilerImGui->ShowCpuProfilerWindow(m_showCpuProfiler);
  1003. }
  1004. }
  1005. void SampleComponentManager::ShowFileIoProfilerWindow()
  1006. {
  1007. if (auto profilerImGui = AZ::IO::StreamerProfiler::Get(); profilerImGui)
  1008. {
  1009. profilerImGui->DrawStatistics(m_showFileIoProfiler);
  1010. }
  1011. }
  1012. void SampleComponentManager::ShowGpuProfilerWindow()
  1013. {
  1014. m_imguiGpuProfiler.Draw(m_showGpuProfiler, AZ::RPI::PassSystemInterface::Get()->GetRootPass());
  1015. }
  1016. void SampleComponentManager::ShowTransientAttachmentProfilerWindow()
  1017. {
  1018. auto* transientStats = AZ::RHI::RHISystemInterface::Get()->GetTransientAttachmentStatistics();
  1019. if (transientStats)
  1020. {
  1021. m_showTransientAttachmentProfiler = m_imguiTransientAttachmentProfiler.Draw(*transientStats);
  1022. }
  1023. }
  1024. void SampleComponentManager::ShowResizeViewportDialog()
  1025. {
  1026. static int size[2] = { 0, 0 };
  1027. if (size[0] <= 0)
  1028. {
  1029. size[0] = aznumeric_cast<int>(m_windowContext->GetViewport().m_maxX - m_windowContext->GetViewport().m_minX);
  1030. }
  1031. if (size[1] <= 0)
  1032. {
  1033. size[1] = aznumeric_cast<int>(m_windowContext->GetViewport().m_maxY - m_windowContext->GetViewport().m_minY);
  1034. }
  1035. bool dialogWasOpen = m_showResizeViewportDialog;
  1036. if (ImGui::Begin("Resize Viewport", &m_showResizeViewportDialog, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  1037. {
  1038. ImGui::InputInt2("Size", size);
  1039. if (ImGui::Button("Resize"))
  1040. {
  1041. Utils::ResizeClientArea(size[0], size[1], AzFramework::WindowPosOptions());
  1042. Utils::ReportScriptableAction("ResizeViewport(%d, %d)", size[0], size[1]);
  1043. // Re-initialize the size fields on the next frame so we can see whether the
  1044. // correct size was achieved (should be the same values the user entered)...
  1045. size[0] = 0;
  1046. size[1] = 0;
  1047. }
  1048. }
  1049. ImGui::End();
  1050. if (dialogWasOpen && !m_showResizeViewportDialog)
  1051. {
  1052. // Re-initialize the size fields next time the dialog is shown...
  1053. size[0] = 0;
  1054. size[1] = 0;
  1055. }
  1056. }
  1057. void SampleComponentManager::ShowFramerateHistogram(float deltaTime)
  1058. {
  1059. if (m_imGuiFrameTimer && ImGui::Begin("Frame Time Histogram", &m_showFramerateHistogram, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  1060. {
  1061. ImGuiHistogramQueue::WidgetSettings settings;
  1062. settings.m_reportInverse = false;
  1063. settings.m_units = "ms";
  1064. m_imGuiFrameTimer->Tick(deltaTime * 1000.0f, settings);
  1065. }
  1066. ImGui::End();
  1067. }
  1068. void SampleComponentManager::RequestFrameCapture(const AZStd::string& filePath, bool hideImGui)
  1069. {
  1070. AZ_Assert(false == m_isFrameCapturePending, "Frame capture already in progress");
  1071. AZ_Assert(AZ::Render::InvalidFrameCaptureId == m_frameCaptureId, "Unfinished frame capture detected");
  1072. m_isFrameCapturePending = true;
  1073. m_hideImGuiDuringFrameCapture = hideImGui;
  1074. m_frameCaptureFilePath = filePath;
  1075. // Don't continue the script while a frame capture is pending in case subsequent changes
  1076. // interfere with the pending capture.
  1077. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  1078. if (m_hideImGuiDuringFrameCapture)
  1079. {
  1080. AZ::Render::ImGuiSystemRequestBus::Broadcast(&AZ::Render::ImGuiSystemRequestBus::Events::HideAllImGuiPasses);
  1081. // We also hide Open 3D Engine's debug text
  1082. AzFramework::ConsoleRequestBus::Broadcast(&AzFramework::ConsoleRequests::ExecuteConsoleCommand, "r_DisplayInfo 0");
  1083. // The ExecuteConsoleCommand request is handled in a deferred manner, so we have to delay the screenshot a bit.
  1084. m_countdownForFrameCapture = 1;
  1085. }
  1086. else
  1087. {
  1088. m_countdownForFrameCapture = 0;
  1089. }
  1090. }
  1091. void SampleComponentManager::OnFrameCaptureFinished(AZ::Render::FrameCaptureResult /*result*/, const AZStd::string& /*info*/)
  1092. {
  1093. AZ::Render::FrameCaptureNotificationBus::Handler::BusDisconnect();
  1094. if (m_hideImGuiDuringFrameCapture)
  1095. {
  1096. AZ::Render::ImGuiSystemRequestBus::Broadcast(&AZ::Render::ImGuiSystemRequestBus::Events::ShowAllImGuiPasses);
  1097. // We also show Open 3D Engine's debug text
  1098. AzFramework::ConsoleRequestBus::Broadcast(&AzFramework::ConsoleRequests::ExecuteConsoleCommand, "r_DisplayInfo 1");
  1099. }
  1100. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  1101. m_isFrameCapturePending = false;
  1102. }
  1103. bool SampleComponentManager::IsFrameCapturePending()
  1104. {
  1105. return m_isFrameCapturePending;
  1106. }
  1107. void SampleComponentManager::RunMainTestSuite(const AZStd::string& suiteFilePath, bool exitOnTestEnd, int randomSeed)
  1108. {
  1109. if (m_scriptManager)
  1110. {
  1111. m_scriptManager->RunMainTestSuite(suiteFilePath, exitOnTestEnd, randomSeed);
  1112. }
  1113. }
  1114. void SampleComponentManager::SetNumMSAASamples(int numMSAASamples)
  1115. {
  1116. AZ_Assert(IsValidNumMSAASamples(numMSAASamples), "Invalid MSAA sample setting");
  1117. m_numMSAASamples = numMSAASamples;
  1118. }
  1119. void SampleComponentManager::ResetNumMSAASamples()
  1120. {
  1121. m_numMSAASamples = GetDefaultNumMSAASamples();
  1122. }
  1123. void SampleComponentManager::ResetRPIScene()
  1124. {
  1125. ReleaseRPIScene();
  1126. SwitchSceneForRPISample();
  1127. }
  1128. void SampleComponentManager::ClearRPIScene()
  1129. {
  1130. ReleaseRPIScene();
  1131. }
  1132. void SampleComponentManager::ShowFrameCaptureDialog()
  1133. {
  1134. static bool requestCaptureOnNextFrame = false;
  1135. static bool hideImGuiFromFrameCapture = true;
  1136. if (requestCaptureOnNextFrame)
  1137. {
  1138. requestCaptureOnNextFrame = false;
  1139. RequestFrameCapture(m_imguiFrameCaptureSaver.GetSaveFilePath(), hideImGuiFromFrameCapture);
  1140. }
  1141. else if (!m_isFrameCapturePending) // Hide this dialog while taking a capture
  1142. {
  1143. if (ImGui::Begin("Frame Capture", &m_showFrameCaptureDialog))
  1144. {
  1145. ImGui::Checkbox("Hide ImGui", &hideImGuiFromFrameCapture);
  1146. ImGuiSaveFilePath::WidgetSettings settings;
  1147. settings.m_labels.m_filePath = "File Path (.png, .ppm, or .dds):";
  1148. m_imguiFrameCaptureSaver.Tick(settings);
  1149. if (ImGui::Button("Capture"))
  1150. {
  1151. // Don't actually do the capture until the next frame, so we can hide this dialog first
  1152. requestCaptureOnNextFrame = true;
  1153. if (hideImGuiFromFrameCapture)
  1154. {
  1155. Utils::ReportScriptableAction("CaptureScreenshot('%s')", m_imguiFrameCaptureSaver.GetSaveFilePath().c_str());
  1156. }
  1157. else
  1158. {
  1159. Utils::ReportScriptableAction("CaptureScreenshotWithImGui('%s')", m_imguiFrameCaptureSaver.GetSaveFilePath().c_str());
  1160. }
  1161. }
  1162. }
  1163. ImGui::End();
  1164. }
  1165. }
  1166. void SampleComponentManager::RequestExit()
  1167. {
  1168. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop);
  1169. AZ::TickBus::Handler::BusDisconnect();
  1170. AzFramework::InputChannelEventListener::Disconnect();
  1171. m_exitRequested = true;
  1172. }
  1173. void SampleComponentManager::ShutdownActiveSample()
  1174. {
  1175. m_exampleEntity->Deactivate();
  1176. // Pointer to all the passes within m_rhiSamplePasses must be nullified before all the samples within m_activeSamples are destroyed.
  1177. SetRHISamplePass(nullptr);
  1178. for (AZ::Component* activeComponent : m_activeSamples)
  1179. {
  1180. if (activeComponent != nullptr)
  1181. {
  1182. // Disable the camera controller just in case the active sample enabled it and didn't disable in Deactivate().
  1183. AZ::Debug::CameraControllerRequestBus::Event(m_cameraEntity->GetId(), &AZ::Debug::CameraControllerRequestBus::Events::Disable);
  1184. m_exampleEntity->RemoveComponent(activeComponent);
  1185. delete activeComponent;
  1186. }
  1187. }
  1188. m_activeSamples.clear();
  1189. // Force a reset of the shader variant finder to get more consistent testing of samples every time they are run, rather
  1190. // than the first time for each sample being "special".
  1191. auto variantFinder = AZ::Interface<AZ::RPI::IShaderVariantFinder>::Get();
  1192. variantFinder->Reset();
  1193. }
  1194. void SampleComponentManager::Reset()
  1195. {
  1196. ShutdownActiveSample();
  1197. m_exampleEntity->Activate();
  1198. // Reset to RHI sample pipeline
  1199. SwitchSceneForRHISample();
  1200. SetRHISamplePass(nullptr);
  1201. }
  1202. void SampleComponentManager::CreateDefaultCamera()
  1203. {
  1204. if (m_cameraEntity)
  1205. {
  1206. return;
  1207. }
  1208. // A camera entity will be created by the entity context request bus so that the component for this entity can use a feature processor.
  1209. AzFramework::EntityContextRequestBus::EventResult(m_cameraEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "CameraEntity");
  1210. //Add debug camera and controller components
  1211. AZ::Debug::CameraComponentConfig cameraConfig(m_windowContext);
  1212. cameraConfig.m_fovY = AZ::Constants::QuarterPi;
  1213. cameraConfig.m_depthFar = 1000.0f;
  1214. m_cameraEntity->CreateComponent(azrtti_typeid<AZ::Debug::CameraComponent>())
  1215. ->SetConfiguration(cameraConfig);
  1216. m_cameraEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  1217. m_cameraEntity->CreateComponent(azrtti_typeid<AZ::Debug::ArcBallControllerComponent>());
  1218. m_cameraEntity->CreateComponent(azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
  1219. m_cameraEntity->Activate();
  1220. m_scriptManager->SetCameraEntity(m_cameraEntity);
  1221. }
  1222. void SampleComponentManager::SetupImGuiContext()
  1223. {
  1224. AdjustImGuiFontScale();
  1225. // Add imgui context
  1226. Render::ImGuiSystemRequestBus::BroadcastResult(m_isImGuiAvailable, &Render::ImGuiSystemRequests::PushActiveContextFromDefaultPass);
  1227. 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.");
  1228. }
  1229. void SampleComponentManager::ActiveImGuiContextChanged(ImGuiContext* context)
  1230. {
  1231. ImGui::SetCurrentContext(context);
  1232. }
  1233. bool SampleComponentManager::OpenSample(const AZStd::string& sampleName)
  1234. {
  1235. for (int32_t i = 0; i < m_availableSamples.size(); i++)
  1236. {
  1237. if (m_availableSamples[i].m_parentMenuName + '/' + m_availableSamples[i].m_sampleName == sampleName)
  1238. {
  1239. if (!m_availableSamples[i].m_isSupportedFunc || m_availableSamples[i].m_isSupportedFunc())
  1240. {
  1241. m_selectedSampleIndex = i;
  1242. m_sampleChangeRequest = true;
  1243. return true;
  1244. }
  1245. else
  1246. {
  1247. AZ_Error("SampleComponentManager", false, "Sample '%s' is not supported on this platform.", sampleName.c_str());
  1248. }
  1249. }
  1250. }
  1251. return false;
  1252. }
  1253. bool SampleComponentManager::ShowTool(const AZStd::string& toolName, bool enable)
  1254. {
  1255. if (toolName == PassTreeToolName)
  1256. {
  1257. m_showPassTree = enable;
  1258. return true;
  1259. }
  1260. else if (toolName == CpuProfilerToolName)
  1261. {
  1262. m_showCpuProfiler = enable;
  1263. return true;
  1264. }
  1265. else if (toolName == FileIoProfilerToolName)
  1266. {
  1267. m_showFileIoProfiler = enable;
  1268. return true;
  1269. }
  1270. else if (toolName == GpuProfilerToolName)
  1271. {
  1272. m_showGpuProfiler = enable;
  1273. return true;
  1274. }
  1275. else if (toolName == TransientAttachmentProfilerToolName)
  1276. {
  1277. m_showTransientAttachmentProfiler = enable;
  1278. return true;
  1279. }
  1280. return false;
  1281. }
  1282. void SampleComponentManager::SampleChange()
  1283. {
  1284. if (m_selectedSampleIndex == -1)
  1285. {
  1286. return;
  1287. }
  1288. ShutdownActiveSample();
  1289. // Reset the camera *before* activating the sample, because the sample's Activate() function might
  1290. // want to reposition the camera.
  1291. CameraReset();
  1292. const SampleEntry& sampleEntry = m_availableSamples[m_selectedSampleIndex];
  1293. // Create scene and render pipeline before create sample component
  1294. if (sampleEntry.m_pipelineType == SamplePipelineType::RHI)
  1295. {
  1296. SwitchSceneForRHISample();
  1297. }
  1298. else if (sampleEntry.m_pipelineType == SamplePipelineType::RPI)
  1299. {
  1300. SwitchSceneForRPISample();
  1301. }
  1302. SampleComponentConfig config(m_windowContext, m_cameraEntity->GetId(), m_entityContextId);
  1303. // special setup for RHI samples
  1304. if (sampleEntry.m_pipelineType == SamplePipelineType::RHI)
  1305. {
  1306. for (AZ::RPI::Ptr<RHISamplePass> samplePass : m_rhiSamplePasses)
  1307. {
  1308. BasicRHIComponent* rhiSampleComponent = static_cast<BasicRHIComponent*>(m_exampleEntity->CreateComponent(sampleEntry.m_sampleUuid));
  1309. rhiSampleComponent->SetConfiguration(config);
  1310. rhiSampleComponent->SetViewIndex(samplePass->GetViewIndex());
  1311. if (rhiSampleComponent->IsSupportedRHISamplePipeline())
  1312. {
  1313. samplePass->SetRHISample(rhiSampleComponent);
  1314. }
  1315. else
  1316. {
  1317. samplePass->SetRHISample(nullptr);
  1318. }
  1319. m_activeSamples.push_back(rhiSampleComponent);
  1320. }
  1321. }
  1322. else
  1323. {
  1324. AZ::Component* newComponent = m_exampleEntity->CreateComponent(sampleEntry.m_sampleUuid);
  1325. newComponent->SetConfiguration(config);
  1326. m_activeSamples.push_back(newComponent);
  1327. }
  1328. m_exampleEntity->Activate();
  1329. // Even though this is done in CameraReset(), the example component wasn't activated at the time so we have to send this event again.
  1330. ExampleComponentRequestBus::Event(m_exampleEntity->GetId(), &ExampleComponentRequestBus::Events::ResetCamera);
  1331. }
  1332. void SampleComponentManager::CameraReset()
  1333. {
  1334. // Reset the camera transform. Some examples do not use a controller or use a controller that doesn't override the whole transform.
  1335. // Set to a transform that is 5 units away from the origin and looking at the origin along the Y axis.
  1336. const AZ::EntityId cameraEntityId = m_cameraEntity->GetId();
  1337. AZ::TransformBus::Event(cameraEntityId, &AZ::TransformBus::Events::SetWorldTM, AZ::Transform::CreateTranslation(AZ::Vector3(0.0f, -5.0f, 0.0f)));
  1338. AZ::Debug::CameraControllerRequestBus::Event(cameraEntityId, &AZ::Debug::CameraControllerRequestBus::Events::Reset);
  1339. // Tell the current example to reset the camera, any example that controls the camera and preserves controller state should implement this event
  1340. ExampleComponentRequestBus::Event(m_exampleEntity->GetId(), &ExampleComponentRequestBus::Events::ResetCamera);
  1341. }
  1342. void SampleComponentManager::CreateSceneForRHISample()
  1343. {
  1344. // Create and register the rhi scene with only feature processors required for AtomShimRenderer (only for AtomSampleViewerLauncher)
  1345. RPI::SceneDescriptor sceneDesc;
  1346. sceneDesc.m_nameId = AZ::Name("RHI");
  1347. sceneDesc.m_featureProcessorNames.push_back("AZ::Render::AuxGeomFeatureProcessor");
  1348. m_rhiScene = RPI::Scene::CreateScene(sceneDesc);
  1349. m_rhiScene->Activate();
  1350. RPI::RenderPipelineDescriptor pipelineDesc;
  1351. pipelineDesc.m_name = "RHISamplePipeline";
  1352. pipelineDesc.m_rootPassTemplate = "RHISamplePipelineTemplate";
  1353. // Add view to pipeline since there are few RHI samples are using ViewSrg
  1354. pipelineDesc.m_mainViewTagName = "MainCamera";
  1355. m_renderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get());
  1356. m_rhiScene->AddRenderPipeline(m_renderPipeline);
  1357. m_renderPipeline->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1358. // Get RHISamplePass
  1359. AZ::RPI::PassFilter passFilter = AZ::RPI::PassFilter::CreateWithPassName(AZ::Name("RHISamplePass"), m_renderPipeline.get());
  1360. m_rhiSamplePasses.push_back(azrtti_cast<RHISamplePass*>(AZ::RPI::PassSystemInterface::Get()->FindFirstPass(passFilter)));
  1361. AZ::RPI::RPISystemInterface* rpiSystem = AZ::RPI::RPISystemInterface::Get();
  1362. if (rpiSystem->GetXRSystem())
  1363. {
  1364. // Build the pipeline for left eye
  1365. pipelineDesc.m_name = "RHISamplePipelineXRLeft";
  1366. pipelineDesc.m_rootPassTemplate = "RHISamplePipelineXRLeftTemplate";
  1367. RPI::RenderPipelinePtr renderPipelineLeft = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get(), AZ::RPI::WindowContext::SwapChainMode::XrLeft);
  1368. // Build the pipeline for right eye
  1369. pipelineDesc.m_name = "RHISamplePipelineXRRight";
  1370. pipelineDesc.m_rootPassTemplate = "RHISamplePipelineXRRightTemplate";
  1371. RPI::RenderPipelinePtr renderPipelineRight = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get(), AZ::RPI::WindowContext::SwapChainMode::XrRight);
  1372. //Add both the pipelines to the scene
  1373. m_rhiScene->AddRenderPipeline(renderPipelineLeft);
  1374. m_rhiScene->AddRenderPipeline(renderPipelineRight);
  1375. renderPipelineLeft->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1376. renderPipelineRight->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1377. // Set the correct view index for the RHI sample passes
  1378. AZ::RPI::PassFilter rhiSamplePassFilterLeft = AZ::RPI::PassFilter::CreateWithPassName(AZ::Name("RHISamplePass"), renderPipelineLeft.get());
  1379. AZ::RPI::Ptr<RHISamplePass> rhiSamplePassLeft = azrtti_cast<RHISamplePass*>(AZ::RPI::PassSystemInterface::Get()->FindFirstPass(rhiSamplePassFilterLeft));
  1380. rhiSamplePassLeft->SetViewIndex(0);
  1381. m_rhiSamplePasses.push_back(rhiSamplePassLeft);
  1382. AZ::RPI::PassFilter rhiSamplePassFilterRight = AZ::RPI::PassFilter::CreateWithPassName(AZ::Name("RHISamplePass"), renderPipelineRight.get());
  1383. AZ::RPI::Ptr<RHISamplePass> rhiSamplePassRight = azrtti_cast<RHISamplePass*>(AZ::RPI::PassSystemInterface::Get()->FindFirstPass(rhiSamplePassFilterRight));
  1384. rhiSamplePassRight->SetViewIndex(1);
  1385. m_rhiSamplePasses.push_back(rhiSamplePassRight);
  1386. //Cache the pipelines in case we want to enable/disable them
  1387. m_xrPipelines.push_back(renderPipelineLeft);
  1388. m_xrPipelines.push_back(renderPipelineRight);
  1389. //Disable XR pipelines by default
  1390. DisableXrPipelines();
  1391. }
  1392. // Register the RHi scene
  1393. RPI::RPISystemInterface::Get()->RegisterScene(m_rhiScene);
  1394. // Setup imGui since a new render pipeline with imgui pass was created
  1395. SetupImGuiContext();
  1396. }
  1397. void SampleComponentManager::ReleaseRHIScene()
  1398. {
  1399. if (m_rhiScene)
  1400. {
  1401. m_rhiSamplePasses.clear();
  1402. m_xrPipelines.clear();
  1403. m_renderPipeline = nullptr;
  1404. RPI::RPISystemInterface::Get()->UnregisterScene(m_rhiScene);
  1405. m_rhiScene = nullptr;
  1406. }
  1407. }
  1408. void SampleComponentManager::SwitchSceneForRHISample()
  1409. {
  1410. ReleaseRPIScene();
  1411. ReleaseRHIScene();
  1412. CreateSceneForRHISample();
  1413. }
  1414. void SampleComponentManager::CreateSceneForRPISample()
  1415. {
  1416. // Create and register a scene with all available feature processors
  1417. RPI::SceneDescriptor sceneDesc;
  1418. sceneDesc.m_nameId = AZ::Name("RPI");
  1419. m_rpiScene = RPI::Scene::CreateScene(sceneDesc);
  1420. m_rpiScene->EnableAllFeatureProcessors();
  1421. // Bind m_rpiScene to the GameEntityContext's AzFramework::Scene so the RPI Scene can be found by the entity context
  1422. auto sceneSystem = AzFramework::SceneSystemInterface::Get();
  1423. AZ_Assert(sceneSystem, "SampleComponentManager requires an implementation of the scene system.");
  1424. AZStd::shared_ptr<AzFramework::Scene> mainScene = sceneSystem->GetScene(AzFramework::Scene::MainSceneName);
  1425. AZ_Assert(mainScene, "Main scene missing during system component initialization"); // This should never happen unless scene creation has changed.
  1426. // Add RPI::Scene as a sub system for the default AzFramework Scene
  1427. [[maybe_unused]] bool result = mainScene->SetSubsystem(m_rpiScene);
  1428. AZ_Assert(result, "SampleComponentManager failed to register the RPI scene with the general scene.");
  1429. m_rpiScene->Activate();
  1430. // Register scene to RPI system so it will be processed/rendered per tick
  1431. RPI::RPISystemInterface::Get()->RegisterScene(m_rpiScene);
  1432. // Create MainPipeline as its render pipeline
  1433. RPI::RenderPipelineDescriptor pipelineDesc;
  1434. pipelineDesc.m_name = "RPISamplePipeline";
  1435. pipelineDesc.m_rootPassTemplate = GetRootPassTemplateName();
  1436. pipelineDesc.m_mainViewTagName = "MainCamera";
  1437. pipelineDesc.m_allowModification = true;
  1438. // set pipeline MSAA samples
  1439. AZ_Assert(IsValidNumMSAASamples(m_numMSAASamples), "Invalid MSAA sample setting");
  1440. pipelineDesc.m_renderSettings.m_multisampleState.m_samples = static_cast<uint16_t>(m_numMSAASamples);
  1441. bool isNonMsaaPipeline = (pipelineDesc.m_renderSettings.m_multisampleState.m_samples == 1);
  1442. const char* supervariantName = isNonMsaaPipeline ? AZ::RPI::NoMsaaSupervariantName : "";
  1443. AZ::RPI::ShaderSystemInterface::Get()->SetSupervariantName(AZ::Name(supervariantName));
  1444. RPI::RenderPipelinePtr renderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get());
  1445. m_rpiScene->AddRenderPipeline(renderPipeline);
  1446. renderPipeline->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1447. // As part of our initialization we need to create the BRDF texture generation pipeline
  1448. AZ::RPI::RenderPipelineDescriptor brdfPipelineDesc;
  1449. brdfPipelineDesc.m_mainViewTagName = "MainCamera";
  1450. brdfPipelineDesc.m_name = "BRDFTexturePipeline";
  1451. brdfPipelineDesc.m_rootPassTemplate = "BRDFTexturePipeline";
  1452. brdfPipelineDesc.m_executeOnce = true;
  1453. RPI::RenderPipelinePtr brdfTexturePipeline = AZ::RPI::RenderPipeline::CreateRenderPipeline(brdfPipelineDesc);
  1454. m_rpiScene->AddRenderPipeline(brdfTexturePipeline);
  1455. // 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
  1456. if (!m_brdfTexture)
  1457. {
  1458. const AZStd::shared_ptr<const RPI::PassTemplate> brdfTextureTemplate = RPI::PassSystemInterface::Get()->GetPassTemplate(Name("BRDFTextureTemplate"));
  1459. Data::Asset<RPI::AttachmentImageAsset> brdfImageAsset = RPI::AssetUtils::LoadAssetById<RPI::AttachmentImageAsset>(
  1460. brdfTextureTemplate->m_imageAttachments[0].m_assetRef.m_assetId, RPI::AssetUtils::TraceLevel::Error);
  1461. if (brdfImageAsset.IsReady())
  1462. {
  1463. m_brdfTexture = RPI::AttachmentImage::FindOrCreate(brdfImageAsset);
  1464. }
  1465. }
  1466. // Setup imGui since a new render pipeline with imgui pass was created
  1467. SetupImGuiContext();
  1468. }
  1469. void SampleComponentManager::ReleaseRPIScene()
  1470. {
  1471. if (m_rpiScene)
  1472. {
  1473. RPI::RPISystemInterface::Get()->UnregisterScene(m_rpiScene);
  1474. auto sceneSystem = AzFramework::SceneSystemInterface::Get();
  1475. AZ_Assert(sceneSystem, "Scene system was destroyed before SampleComponentManager was able to unregister the RPI scene.");
  1476. AZStd::shared_ptr<AzFramework::Scene> scene = sceneSystem->GetScene(AzFramework::Scene::MainSceneName);
  1477. AZ_Assert(scene, "The main scene wasn't found in the scene system.");
  1478. [[maybe_unused]] bool result = scene->UnsetSubsystem(m_rpiScene);
  1479. AZ_Assert(result, "SampleComponentManager failed to unregister its RPI scene from the general scene.");
  1480. m_rpiScene = nullptr;
  1481. }
  1482. }
  1483. void SampleComponentManager::SwitchSceneForRPISample()
  1484. {
  1485. ReleaseRHIScene();
  1486. ReleaseRPIScene();
  1487. CreateSceneForRPISample();
  1488. }
  1489. // AzFramework::AssetCatalogEventBus::Handler overrides ...
  1490. void SampleComponentManager::OnCatalogLoaded([[maybe_unused]] const char* catalogFile)
  1491. {
  1492. AZ::TickBus::QueueFunction([&]()
  1493. {
  1494. ActivateInternal();
  1495. });
  1496. }
  1497. void SampleComponentManager::SetRHISamplePass(BasicRHIComponent* sampleComponent)
  1498. {
  1499. for (AZ::RPI::Ptr<RHISamplePass> samplePass : m_rhiSamplePasses)
  1500. {
  1501. samplePass->SetRHISample(sampleComponent);
  1502. }
  1503. }
  1504. void SampleComponentManager::DisableXrPipelines()
  1505. {
  1506. for (RPI::RenderPipelinePtr xrPipeline : m_xrPipelines)
  1507. {
  1508. xrPipeline->RemoveFromRenderTick();
  1509. }
  1510. }
  1511. void SampleComponentManager::EnableXrPipelines()
  1512. {
  1513. for (RPI::RenderPipelinePtr xrPipeline : m_xrPipelines)
  1514. {
  1515. xrPipeline->AddToRenderTick();
  1516. }
  1517. }
  1518. } // namespace AtomSampleViewer