SampleComponentManager.cpp 74 KB

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