BootstrapSystemComponent.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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 <BootstrapSystemComponent.h>
  9. #include <AzCore/Asset/AssetCommon.h>
  10. #include <AzCore/Component/ComponentApplicationBus.h>
  11. #include <AzCore/Component/ComponentApplicationLifecycle.h>
  12. #include <AzCore/Component/Entity.h>
  13. #include <AzCore/NativeUI/NativeUIRequests.h>
  14. #include <AzCore/Serialization/SerializeContext.h>
  15. #include <AzCore/std/smart_ptr/make_shared.h>
  16. #include <AzCore/Utils/Utils.h>
  17. #include <AzCore/StringFunc/StringFunc.h>
  18. #include <AzFramework/API/ApplicationAPI.h>
  19. #include <AzFramework/Components/TransformComponent.h>
  20. #include <AzFramework/Entity/GameEntityContextBus.h>
  21. #include <AzFramework/Asset/AssetSystemBus.h>
  22. #include <ISystem.h>
  23. #include <Atom/RHI/RHISystemInterface.h>
  24. #include <Atom/RPI.Reflect/Image/AttachmentImageAsset.h>
  25. #include <Atom/RPI.Reflect/Image/AttachmentImageAssetCreator.h>
  26. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  27. #include <Atom/RPI.Public/Pass/Pass.h>
  28. #include <Atom/RPI.Public/Pass/PassSystemInterface.h>
  29. #include <Atom/RPI.Public/RenderPipeline.h>
  30. #include <Atom/RPI.Public/ViewportContextBus.h>
  31. #include <Atom/RPI.Public/RPISystemInterface.h>
  32. #include <Atom/RPI.Public/Shader/ShaderResourceGroup.h>
  33. #include <Atom/RPI.Public/Shader/ShaderSystem.h>
  34. #include <Atom/Bootstrap/DefaultWindowBus.h>
  35. #include <Atom/Bootstrap/BootstrapNotificationBus.h>
  36. #include <Atom/RPI.Reflect/System/AnyAsset.h>
  37. #include <AzCore/Console/IConsole.h>
  38. #include <BootstrapSystemComponent_Traits_Platform.h>
  39. void cvar_r_renderPipelinePath_Changed(const AZ::CVarFixedString& newPipelinePath)
  40. {
  41. auto viewportContextManager = AZ::Interface<AZ::RPI::ViewportContextRequestsInterface>::Get();
  42. if (!viewportContextManager)
  43. {
  44. return;
  45. }
  46. auto viewportContext = viewportContextManager->GetDefaultViewportContext();
  47. if (!viewportContext)
  48. {
  49. return;
  50. }
  51. AZ::Data::Asset<AZ::RPI::AnyAsset> pipelineAsset =
  52. AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::AnyAsset>(newPipelinePath.data(), AZ::RPI::AssetUtils::TraceLevel::Error);
  53. if (pipelineAsset)
  54. {
  55. AZ::RPI::RenderPipelineDescriptor renderPipelineDescriptor =
  56. *AZ::RPI::GetDataFromAnyAsset<AZ::RPI::RenderPipelineDescriptor>(pipelineAsset); // Copy descriptor from asset
  57. AZ::Render::Bootstrap::RequestBus::Broadcast(&AZ::Render::Bootstrap::RequestBus::Events::SwitchRenderPipeline, renderPipelineDescriptor, viewportContext);
  58. }
  59. else
  60. {
  61. AZ_Warning("SetDefaultPipeline", false, "Failed to switch default render pipeline to %s: can't load the asset", newPipelinePath.data());
  62. }
  63. }
  64. AZ_CVAR(AZ::CVarFixedString, r_renderPipelinePath, AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_PIPELINE_NAME, cvar_r_renderPipelinePath_Changed, AZ::ConsoleFunctorFlags::DontReplicate, "The asset (.azasset) path for default render pipeline");
  65. AZ_CVAR(AZ::CVarFixedString, r_default_openxr_pipeline_name, "passes/MultiViewRenderPipeline.azasset", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Default openXr render pipeline name");
  66. AZ_CVAR(AZ::CVarFixedString, r_default_openxr_left_pipeline_name, "passes/XRLeftRenderPipeline.azasset", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Default openXr Left eye render pipeline name");
  67. AZ_CVAR(AZ::CVarFixedString, r_default_openxr_right_pipeline_name, "passes/XRRightRenderPipeline.azasset", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Default openXr Right eye render pipeline name");
  68. AZ_CVAR(uint32_t, r_width, 1920, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Starting window width in pixels.");
  69. AZ_CVAR(uint32_t, r_height, 1080, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Starting window height in pixels.");
  70. AZ_CVAR(uint32_t, r_fullscreen, false, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Starting fullscreen state.");
  71. AZ_CVAR(uint32_t, r_resolutionMode, 0, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "0: render resolution same as window client area size, 1: render resolution use the values specified by r_width and r_height");
  72. namespace AZ
  73. {
  74. namespace Render
  75. {
  76. namespace Bootstrap
  77. {
  78. void BootstrapSystemComponent::Reflect(ReflectContext* context)
  79. {
  80. if (SerializeContext* serialize = azrtti_cast<SerializeContext*>(context))
  81. {
  82. serialize->Class<BootstrapSystemComponent, Component>()
  83. ->Version(1)
  84. ;
  85. if (EditContext* ec = serialize->GetEditContext())
  86. {
  87. ec->Class<BootstrapSystemComponent>("Atom RPI", "Atom Renderer")
  88. ->ClassElement(Edit::ClassElements::EditorData, "")
  89. ->Attribute(Edit::Attributes::AutoExpand, true)
  90. ;
  91. }
  92. }
  93. }
  94. void BootstrapSystemComponent::GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided)
  95. {
  96. provided.push_back(AZ_CRC("BootstrapSystemComponent", 0xb8f32711));
  97. }
  98. void BootstrapSystemComponent::GetRequiredServices(ComponentDescriptor::DependencyArrayType& required)
  99. {
  100. required.push_back(AZ_CRC("RPISystem", 0xf2add773));
  101. required.push_back(AZ_CRC("SceneSystemComponentService", 0xd8975435));
  102. }
  103. void BootstrapSystemComponent::GetDependentServices(ComponentDescriptor::DependencyArrayType& dependent)
  104. {
  105. dependent.push_back(AZ_CRC("ImGuiSystemComponent", 0x2f08b9a7));
  106. dependent.push_back(AZ_CRC("PrimitiveSystemComponent", 0xc860fa59));
  107. dependent.push_back(AZ_CRC("MeshSystemComponent", 0x21e5bbb6));
  108. dependent.push_back(AZ_CRC("CoreLightsService", 0x91932ef6));
  109. dependent.push_back(AZ_CRC("DynamicDrawService", 0x023c1673));
  110. dependent.push_back(AZ_CRC("CommonService", 0x6398eec4));
  111. dependent.push_back(AZ_CRC_CE("HairService"));
  112. }
  113. void BootstrapSystemComponent::GetIncompatibleServices(ComponentDescriptor::DependencyArrayType& incompatible)
  114. {
  115. incompatible.push_back(AZ_CRC("BootstrapSystemComponent", 0xb8f32711));
  116. }
  117. BootstrapSystemComponent::BootstrapSystemComponent()
  118. {
  119. }
  120. BootstrapSystemComponent::~BootstrapSystemComponent()
  121. {
  122. m_viewportContext.reset();
  123. }
  124. //! Helper function that parses the command line arguments
  125. //! looking for r_width, r_height and r_fullscreen.
  126. //! It is important to call this before using r_width, r_height or r_fullscreen
  127. //! because at the moment this system component initializes before Legacy System.cpp gets to parse
  128. //! command line arguments into cvars.
  129. static void UpdateCVarsFromCommandLine()
  130. {
  131. AZ::CommandLine* pCmdLine = nullptr;
  132. ComponentApplicationBus::BroadcastResult(pCmdLine, &AZ::ComponentApplicationBus::Events::GetAzCommandLine);
  133. if (!pCmdLine)
  134. {
  135. return;
  136. }
  137. const AZStd::string fullscreenCvarName("r_fullscreen");
  138. if (pCmdLine->HasSwitch(fullscreenCvarName))
  139. {
  140. auto numValues = pCmdLine->GetNumSwitchValues(fullscreenCvarName);
  141. if (numValues > 0)
  142. {
  143. auto valueStr = pCmdLine->GetSwitchValue(fullscreenCvarName);
  144. if (AZ::StringFunc::LooksLikeBool(valueStr.c_str()))
  145. {
  146. r_fullscreen = AZ::StringFunc::ToBool(valueStr.c_str());
  147. }
  148. }
  149. }
  150. const AZStd::string widthCvarName("r_width");
  151. if (pCmdLine->HasSwitch(widthCvarName))
  152. {
  153. auto numValues = pCmdLine->GetNumSwitchValues(widthCvarName);
  154. if (numValues > 0)
  155. {
  156. auto valueStr = pCmdLine->GetSwitchValue(widthCvarName);
  157. if (AZ::StringFunc::LooksLikeInt(valueStr.c_str()))
  158. {
  159. auto width = AZ::StringFunc::ToInt(valueStr.c_str());
  160. if (width > 0)
  161. {
  162. r_width = width;
  163. }
  164. }
  165. }
  166. }
  167. const AZStd::string heightCvarName("r_height");
  168. if (pCmdLine->HasSwitch(heightCvarName))
  169. {
  170. auto numValues = pCmdLine->GetNumSwitchValues(heightCvarName);
  171. if (numValues > 0)
  172. {
  173. auto valueStr = pCmdLine->GetSwitchValue(heightCvarName);
  174. if (AZ::StringFunc::LooksLikeInt(valueStr.c_str()))
  175. {
  176. auto height = AZ::StringFunc::ToInt(valueStr.c_str());
  177. if (height > 0)
  178. {
  179. r_height = height;
  180. }
  181. }
  182. }
  183. }
  184. const AZStd::string resolutionModeCvarName("r_resolutionMode");
  185. if (pCmdLine->HasSwitch(resolutionModeCvarName))
  186. {
  187. auto numValues = pCmdLine->GetNumSwitchValues(resolutionModeCvarName);
  188. if (numValues > 0)
  189. {
  190. auto valueStr = pCmdLine->GetSwitchValue(resolutionModeCvarName);
  191. if (AZ::StringFunc::LooksLikeInt(valueStr.c_str()))
  192. {
  193. auto resolutionMode = AZ::StringFunc::ToInt(valueStr.c_str());
  194. if (resolutionMode >= 0)
  195. {
  196. r_resolutionMode = resolutionMode;
  197. }
  198. }
  199. }
  200. }
  201. }
  202. void BootstrapSystemComponent::Activate()
  203. {
  204. // Create a native window only if it's a launcher (or standalone)
  205. // LY editor create its own window which we can get its handle through AzFramework::WindowSystemNotificationBus::Handler's OnWindowCreated() function
  206. AZ::ApplicationTypeQuery appType;
  207. ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType);
  208. if (appType.IsHeadless())
  209. {
  210. m_nativeWindow = nullptr;
  211. }
  212. else if (!appType.IsValid() || appType.IsGame())
  213. {
  214. // GFX TODO - investigate window creation being part of the GameApplication.
  215. auto projectTitle = AZ::Utils::GetProjectDisplayName();
  216. // It is important to call this before using r_width, r_height or r_fullscreen
  217. // because at the moment this system component initializes before Legacy System.cpp gets to parse
  218. // command line arguments into cvars.
  219. UpdateCVarsFromCommandLine();
  220. m_nativeWindow = AZStd::make_unique<AzFramework::NativeWindow>(projectTitle.c_str(), AzFramework::WindowGeometry(0, 0, r_width, r_height));
  221. AZ_Assert(m_nativeWindow, "Failed to create the game window\n");
  222. m_nativeWindow->Activate();
  223. m_windowHandle = m_nativeWindow->GetWindowHandle();
  224. }
  225. else
  226. {
  227. // Disable default scene creation for non-games projects
  228. // This can be manually overridden via the DefaultWindowBus.
  229. m_createDefaultScene = false;
  230. }
  231. TickBus::Handler::BusConnect();
  232. // Listen for window system requests (e.g. requests for default window handle)
  233. AzFramework::WindowSystemRequestBus::Handler::BusConnect();
  234. // Listen for window system notifications (e.g. window being created by Editor)
  235. AzFramework::WindowSystemNotificationBus::Handler::BusConnect();
  236. Render::Bootstrap::DefaultWindowBus::Handler::BusConnect();
  237. Render::Bootstrap::RequestBus::Handler::BusConnect();
  238. // Listen for application's window creation/destruction (e.g. window is created/destroyed on Android when suspending the app)
  239. AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusConnect();
  240. // delay one frame for Initialize which asset system is ready by then
  241. AZ::TickBus::QueueFunction(
  242. [this]()
  243. {
  244. Initialize();
  245. SetWindowResolution();
  246. });
  247. }
  248. void BootstrapSystemComponent::Deactivate()
  249. {
  250. AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusDisconnect();
  251. Render::Bootstrap::RequestBus::Handler::BusDisconnect();
  252. Render::Bootstrap::DefaultWindowBus::Handler::BusDisconnect();
  253. AzFramework::WindowSystemRequestBus::Handler::BusDisconnect();
  254. AzFramework::WindowSystemNotificationBus::Handler::BusDisconnect();
  255. TickBus::Handler::BusDisconnect();
  256. m_brdfTexture = nullptr;
  257. RemoveRenderPipeline();
  258. DestroyDefaultScene();
  259. m_viewportContext.reset();
  260. m_nativeWindow = nullptr;
  261. m_windowHandle = nullptr;
  262. }
  263. void BootstrapSystemComponent::Initialize()
  264. {
  265. if (m_isInitialized)
  266. {
  267. return;
  268. }
  269. m_isInitialized = true;
  270. if (!RPI::RPISystemInterface::Get()->IsInitialized())
  271. {
  272. AZ::OSString msgBoxMessage;
  273. msgBoxMessage.append("RPI System could not initialize correctly. Check log for detail.");
  274. AZ::NativeUI::NativeUIRequestBus::Broadcast(
  275. &AZ::NativeUI::NativeUIRequestBus::Events::DisplayOkDialog, "O3DE Fatal Error", msgBoxMessage.c_str(), false);
  276. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop);
  277. return;
  278. }
  279. // In the case of the game we want to call create and register the scene as a soon as we can
  280. // because a level could be loaded in autoexec.cfg and that will assert if there is no scene registered
  281. // to get the feature processors for the components. So we can't wait until the tick (whereas the Editor wants to wait)
  282. if (m_createDefaultScene)
  283. {
  284. CreateDefaultScene();
  285. }
  286. if (m_windowHandle)
  287. {
  288. CreateViewportContext();
  289. if (m_createDefaultScene)
  290. {
  291. CreateDefaultRenderPipeline();
  292. }
  293. }
  294. }
  295. void BootstrapSystemComponent::OnWindowCreated(AzFramework::NativeWindowHandle windowHandle)
  296. {
  297. // only handle the first window (default) created
  298. if (m_windowHandle == nullptr)
  299. {
  300. m_windowHandle = windowHandle;
  301. if (m_isInitialized)
  302. {
  303. CreateViewportContext();
  304. if (m_createDefaultScene)
  305. {
  306. CreateDefaultRenderPipeline();
  307. }
  308. }
  309. SetWindowResolution();
  310. }
  311. }
  312. void BootstrapSystemComponent::OnApplicationWindowCreated()
  313. {
  314. if (!m_nativeWindow)
  315. {
  316. auto projectTitle = AZ::Utils::GetProjectDisplayName();
  317. m_nativeWindow = AZStd::make_unique<AzFramework::NativeWindow>(projectTitle.c_str(), AzFramework::WindowGeometry(0, 0, r_width, r_height));
  318. AZ_Assert(m_nativeWindow, "Failed to create the game window\n");
  319. m_nativeWindow->Activate();
  320. OnWindowCreated(m_nativeWindow->GetWindowHandle());
  321. }
  322. }
  323. void BootstrapSystemComponent::OnApplicationWindowDestroy()
  324. {
  325. m_nativeWindow = nullptr;
  326. }
  327. void BootstrapSystemComponent::CreateViewportContext()
  328. {
  329. RHI::Device* device = RHI::RHISystemInterface::Get()->GetDevice();
  330. RPI::ViewportContextRequestsInterface::CreationParameters params;
  331. params.device = device;
  332. params.windowHandle = m_windowHandle;
  333. params.renderScene = m_defaultScene;
  334. // Setting the default ViewportContextID to an arbitrary and otherwise invalid (negative) value to ensure its uniqueness
  335. params.id = -10;
  336. auto viewContextManager = AZ::Interface<RPI::ViewportContextRequestsInterface>::Get();
  337. m_viewportContext = viewContextManager->CreateViewportContext(
  338. viewContextManager->GetDefaultViewportContextName(), params);
  339. DefaultWindowNotificationBus::Broadcast(&DefaultWindowNotificationBus::Events::DefaultWindowCreated);
  340. // Listen to window notification so we can request exit application when window closes
  341. AzFramework::WindowNotificationBus::Handler::BusConnect(GetDefaultWindowHandle());
  342. }
  343. void BootstrapSystemComponent::SetWindowResolution()
  344. {
  345. if (m_nativeWindow)
  346. {
  347. // wait until swapchain has been created before setting fullscreen state
  348. if (r_resolutionMode > 0u)
  349. {
  350. m_nativeWindow->SetEnableCustomizedResolution(true);
  351. m_nativeWindow->SetRenderResolution(AzFramework::WindowSize(r_width, r_height));
  352. }
  353. else
  354. {
  355. m_nativeWindow->SetEnableCustomizedResolution(false);
  356. }
  357. m_nativeWindow->SetFullScreenState(r_fullscreen);
  358. }
  359. }
  360. AZ::RPI::ScenePtr BootstrapSystemComponent::GetOrCreateAtomSceneFromAzScene(AzFramework::Scene* scene)
  361. {
  362. // Get or create a weak pointer to our scene
  363. // If it's valid, we're done, if not we need to create an Atom scene and update our scene map
  364. auto& atomSceneHandle = m_azSceneToAtomSceneMap[scene];
  365. if (!atomSceneHandle.expired())
  366. {
  367. return atomSceneHandle.lock();
  368. }
  369. // Create and register a scene with all available feature processors
  370. RPI::SceneDescriptor sceneDesc;
  371. sceneDesc.m_nameId = AZ::Name("Main");
  372. AZ::RPI::ScenePtr atomScene = RPI::Scene::CreateScene(sceneDesc);
  373. atomScene->EnableAllFeatureProcessors();
  374. atomScene->Activate();
  375. // Register scene to RPI system so it will be processed/rendered per tick
  376. RPI::RPISystemInterface::Get()->RegisterScene(atomScene);
  377. scene->SetSubsystem(atomScene);
  378. atomSceneHandle = atomScene;
  379. return atomScene;
  380. }
  381. void BootstrapSystemComponent::CreateDefaultScene()
  382. {
  383. // Bind atomScene to the GameEntityContext's AzFramework::Scene
  384. m_defaultFrameworkScene = AzFramework::SceneSystemInterface::Get()->GetScene(AzFramework::Scene::MainSceneName);
  385. // This should never happen unless scene creation has changed.
  386. AZ_Assert(m_defaultFrameworkScene, "Error: Scenes missing during system component initialization");
  387. m_sceneRemovalHandler = AzFramework::Scene::RemovalEvent::Handler(
  388. [this](AzFramework::Scene&, AzFramework::Scene::RemovalEventType eventType)
  389. {
  390. if (eventType == AzFramework::Scene::RemovalEventType::Zombified)
  391. {
  392. m_defaultFrameworkScene.reset();
  393. }
  394. });
  395. m_defaultFrameworkScene->ConnectToEvents(m_sceneRemovalHandler);
  396. m_defaultScene = GetOrCreateAtomSceneFromAzScene(m_defaultFrameworkScene.get());
  397. }
  398. bool BootstrapSystemComponent::EnsureDefaultRenderPipelineInstalledForScene(AZ::RPI::ScenePtr scene, AZ::RPI::ViewportContextPtr viewportContext)
  399. {
  400. AZ::RPI::XRRenderingInterface* xrSystem = AZ::RPI::RPISystemInterface::Get()->GetXRSystem();
  401. const bool loadDefaultRenderPipeline = !xrSystem || xrSystem->GetRHIXRRenderingInterface()->IsDefaultRenderPipelineNeeded();
  402. AZ::RHI::MultisampleState multisampleState;
  403. // Load the main default pipeline if applicable
  404. if (loadDefaultRenderPipeline)
  405. {
  406. AZ::CVarFixedString pipelineName = static_cast<AZ::CVarFixedString>(r_renderPipelinePath);
  407. if (xrSystem)
  408. {
  409. // When running launcher on PC having an XR system present then the default render pipeline is suppose to reflect
  410. // what's being rendered into XR device. XR render pipeline uses multiview render pipeline.
  411. AZ::ApplicationTypeQuery appType;
  412. ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType);
  413. if (appType.IsGame())
  414. {
  415. pipelineName = r_default_openxr_pipeline_name;
  416. }
  417. }
  418. if (!LoadPipeline(scene, viewportContext, pipelineName, AZ::RPI::ViewType::Default, multisampleState))
  419. {
  420. return false;
  421. }
  422. // As part of our initialization we need to create the BRDF texture generation pipeline
  423. AZ::RPI::RenderPipelineDescriptor pipelineDesc;
  424. pipelineDesc.m_mainViewTagName = "MainCamera";
  425. pipelineDesc.m_name = AZStd::string::format("BRDFTexturePipeline_%i", viewportContext->GetId());
  426. pipelineDesc.m_rootPassTemplate = "BRDFTexturePipeline";
  427. pipelineDesc.m_executeOnce = true;
  428. // Save a reference to the generated BRDF texture so it doesn't get deleted if all the passes refering to it get deleted
  429. // and it's ref count goes to zero
  430. if (!m_brdfTexture)
  431. {
  432. const AZStd::shared_ptr<const RPI::PassTemplate> brdfTextureTemplate =
  433. RPI::PassSystemInterface::Get()->GetPassTemplate(Name("BRDFTextureTemplate"));
  434. Data::Asset<RPI::AttachmentImageAsset> brdfImageAsset = RPI::AssetUtils::LoadAssetById<RPI::AttachmentImageAsset>(
  435. brdfTextureTemplate->m_imageAttachments[0].m_assetRef.m_assetId, RPI::AssetUtils::TraceLevel::Error);
  436. if (brdfImageAsset.IsReady())
  437. {
  438. m_brdfTexture = RPI::AttachmentImage::FindOrCreate(brdfImageAsset);
  439. }
  440. }
  441. if (!scene->GetRenderPipeline(AZ::Name(pipelineDesc.m_name)))
  442. {
  443. RPI::RenderPipelinePtr brdfTexturePipeline = AZ::RPI::RenderPipeline::CreateRenderPipeline(pipelineDesc);
  444. scene->AddRenderPipeline(brdfTexturePipeline);
  445. }
  446. }
  447. // Load XR pipelines if applicable
  448. if (xrSystem)
  449. {
  450. for (AZ::u32 i = 0; i < xrSystem->GetNumViews(); i++)
  451. {
  452. const AZ::RPI::ViewType viewType = (i == 0)
  453. ? AZ::RPI::ViewType::XrLeft
  454. : AZ::RPI::ViewType::XrRight;
  455. const AZStd::string_view xrPipelineAssetName = (viewType == AZ::RPI::ViewType::XrLeft)
  456. ? static_cast<AZ::CVarFixedString>(r_default_openxr_left_pipeline_name)
  457. : static_cast<AZ::CVarFixedString>(r_default_openxr_right_pipeline_name);
  458. if (!LoadPipeline(scene, viewportContext, xrPipelineAssetName, viewType, multisampleState))
  459. {
  460. return false;
  461. }
  462. }
  463. }
  464. // Apply MSAA state to all the render pipelines.
  465. // It's important to do this after all the pipelines have
  466. // been created so the same values are applied to all.
  467. // As it cannot be applied MSAA values per pipeline,
  468. // it's setting the MSAA state from the last pipeline loaded.
  469. AZ::RPI::RPISystemInterface::Get()->SetApplicationMultisampleState(multisampleState);
  470. // Send notification when the scene and its pipeline are ready.
  471. // Use the first created pipeline's scene as our default scene for now to allow
  472. // consumers waiting on scene availability to initialize.
  473. if (!m_defaultSceneReady)
  474. {
  475. m_defaultScene = scene;
  476. Render::Bootstrap::NotificationBus::Broadcast(
  477. &Render::Bootstrap::NotificationBus::Handler::OnBootstrapSceneReady, m_defaultScene.get());
  478. m_defaultSceneReady = true;
  479. }
  480. return true;
  481. }
  482. void BootstrapSystemComponent::SwitchRenderPipeline(const AZ::RPI::RenderPipelineDescriptor& newRenderPipelineDesc, AZ::RPI::ViewportContextPtr viewportContext)
  483. {
  484. AZ::RPI::RenderPipelineDescriptor pipelineDescriptor = newRenderPipelineDesc;
  485. pipelineDescriptor.m_name =
  486. AZStd::string::format("%s_%i", pipelineDescriptor.m_name.c_str(), viewportContext->GetId());
  487. if (pipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositionsCount &&
  488. !RHI::RHISystemInterface::Get()->GetDevice()->GetFeatures().m_customSamplePositions)
  489. {
  490. // Disable custom sample positions because they are not supported
  491. AZ_Warning(
  492. "BootstrapSystemComponent",
  493. false,
  494. "Disabling custom sample positions for pipeline %s because they are not supported on this device",
  495. pipelineDescriptor.m_name.c_str());
  496. pipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositions = {};
  497. pipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositionsCount = 0;
  498. }
  499. // Create new render pipeline
  500. auto oldRenderPipeline = viewportContext->GetRenderScene()->GetDefaultRenderPipeline();
  501. RPI::RenderPipelinePtr newRenderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(
  502. pipelineDescriptor, *viewportContext->GetWindowContext().get(), AZ::RPI::ViewType::Default);
  503. // Switch render pipeline
  504. viewportContext->GetRenderScene()->RemoveRenderPipeline(oldRenderPipeline->GetId());
  505. viewportContext->GetRenderScene()->AddRenderPipeline(newRenderPipeline);
  506. newRenderPipeline->SetDefaultView(oldRenderPipeline->GetDefaultView());
  507. AZ::RPI::RPISystemInterface::Get()->SetApplicationMultisampleState(newRenderPipeline->GetRenderSettings().m_multisampleState);
  508. }
  509. RPI::RenderPipelinePtr BootstrapSystemComponent::LoadPipeline( AZ::RPI::ScenePtr scene, AZ::RPI::ViewportContextPtr viewportContext,
  510. AZStd::string_view pipelineName, AZ::RPI::ViewType viewType, AZ::RHI::MultisampleState& multisampleState)
  511. {
  512. // Create a render pipeline from the specified asset for the window context and add the pipeline to the scene.
  513. // When running with an Asset Processor, this will attempt to compile the asset before loading it.
  514. Data::Asset<RPI::AnyAsset> pipelineAsset =
  515. RPI::AssetUtils::LoadCriticalAsset<RPI::AnyAsset>(pipelineName.data(), RPI::AssetUtils::TraceLevel::Error);
  516. if (pipelineAsset)
  517. {
  518. RPI::RenderPipelineDescriptor renderPipelineDescriptor =
  519. *RPI::GetDataFromAnyAsset<RPI::RenderPipelineDescriptor>(pipelineAsset); // Copy descriptor from asset
  520. pipelineAsset.Release();
  521. renderPipelineDescriptor.m_name =
  522. AZStd::string::format("%s_%i", renderPipelineDescriptor.m_name.c_str(), viewportContext->GetId());
  523. if (renderPipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositionsCount &&
  524. !RHI::RHISystemInterface::Get()->GetDevice()->GetFeatures().m_customSamplePositions)
  525. {
  526. // Disable custom sample positions because they are not supported
  527. AZ_Warning(
  528. "BootstrapSystemComponent",
  529. false,
  530. "Disabling custom sample positions for pipeline %s because they are not supported on this device",
  531. pipelineName.data());
  532. renderPipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositions = {};
  533. renderPipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositionsCount = 0;
  534. }
  535. multisampleState = renderPipelineDescriptor.m_renderSettings.m_multisampleState;
  536. // Create and add render pipeline to the scene (when not added already)
  537. RPI::RenderPipelinePtr renderPipeline = scene->GetRenderPipeline(AZ::Name(renderPipelineDescriptor.m_name));
  538. if (!renderPipeline)
  539. {
  540. renderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(
  541. renderPipelineDescriptor, *viewportContext->GetWindowContext().get(), viewType);
  542. scene->AddRenderPipeline(renderPipeline);
  543. }
  544. return renderPipeline;
  545. }
  546. else
  547. {
  548. AZ_Error("AtomBootstrap", false, "Pipeline file failed to load from path: %s.", pipelineName.data());
  549. return nullptr;
  550. }
  551. }
  552. void BootstrapSystemComponent::CreateDefaultRenderPipeline()
  553. {
  554. EnsureDefaultRenderPipelineInstalledForScene(m_defaultScene, m_viewportContext);
  555. const auto pipeline = m_defaultScene->FindRenderPipelineForWindow(m_viewportContext->GetWindowHandle());
  556. if (pipeline)
  557. {
  558. m_renderPipelineId = pipeline->GetId();
  559. }
  560. }
  561. void BootstrapSystemComponent::DestroyDefaultScene()
  562. {
  563. if (m_defaultScene)
  564. {
  565. RPI::RPISystemInterface::Get()->UnregisterScene(m_defaultScene);
  566. // Unbind m_defaultScene to the GameEntityContext's AzFramework::Scene
  567. if (m_defaultFrameworkScene)
  568. {
  569. m_defaultFrameworkScene->UnsetSubsystem(m_defaultScene);
  570. }
  571. m_defaultScene = nullptr;
  572. m_defaultFrameworkScene = nullptr;
  573. }
  574. }
  575. void BootstrapSystemComponent::RemoveRenderPipeline()
  576. {
  577. if (m_defaultScene && m_defaultScene->GetRenderPipeline(m_renderPipelineId))
  578. {
  579. m_defaultScene->RemoveRenderPipeline(m_renderPipelineId);
  580. }
  581. m_renderPipelineId = "";
  582. }
  583. void BootstrapSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time)
  584. {
  585. // Temp: When running in the launcher without the legacy renderer
  586. // we need to call RenderTick on the viewport context each frame.
  587. if (m_viewportContext)
  588. {
  589. AZ::ApplicationTypeQuery appType;
  590. ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType);
  591. if (appType.IsGame())
  592. {
  593. m_viewportContext->RenderTick();
  594. }
  595. }
  596. }
  597. int BootstrapSystemComponent::GetTickOrder()
  598. {
  599. return TICK_LAST;
  600. }
  601. void BootstrapSystemComponent::OnWindowClosed()
  602. {
  603. m_windowHandle = nullptr;
  604. m_viewportContext.reset();
  605. // On some platforms (e.g. Android) the main window is destroyed when the app is suspended
  606. // but this doesn't mean that we need to exit the app. The window will be recreated when the app
  607. // is resumed.
  608. #if AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_EXIT_ON_WINDOW_CLOSE
  609. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop);
  610. #endif
  611. AzFramework::WindowNotificationBus::Handler::BusDisconnect();
  612. }
  613. AzFramework::NativeWindowHandle BootstrapSystemComponent::GetDefaultWindowHandle()
  614. {
  615. return m_windowHandle;
  616. }
  617. AZStd::shared_ptr<RPI::WindowContext> BootstrapSystemComponent::GetDefaultWindowContext()
  618. {
  619. return m_viewportContext ? m_viewportContext->GetWindowContext() : nullptr;
  620. }
  621. void BootstrapSystemComponent::SetCreateDefaultScene(bool create)
  622. {
  623. m_createDefaultScene = create;
  624. }
  625. } // namespace Bootstrap
  626. } // namespace Render
  627. } // namespace AZ