2
0

AsyncComputeExampleComponent.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  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 <Atom/Component/DebugCamera/ArcBallControllerComponent.h>
  9. #include <Atom/RHI/CommandList.h>
  10. #include <Atom/RHI/Factory.h>
  11. #include <Atom/RHI/FrameScheduler.h>
  12. #include <Atom/RHI/Image.h>
  13. #include <Atom/RHI/ImagePool.h>
  14. #include <Atom/RHI/ScopeProducerFunction.h>
  15. #include <Atom/RHI.Reflect/InputStreamLayoutBuilder.h>
  16. #include <AzCore/Math/MatrixUtils.h>
  17. #include <Atom/RPI.Reflect/Shader/ShaderAsset.h>
  18. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  19. #include <Atom/RPI.Public/Model/Model.h>
  20. #include <Atom/RPI.Public/View.h>
  21. #include <Atom/RPI.Public/ViewProviderBus.h>
  22. #include <Atom/RHI.Reflect/RenderAttachmentLayoutBuilder.h>
  23. #include <Automation/ScriptRunnerBus.h>
  24. #include <AzCore/Asset/AssetCommon.h>
  25. #include <AzCore/Asset/AssetManagerBus.h>
  26. #include <AzCore/Math/Vector3.h>
  27. #include <AzCore/Math/Vector4.h>
  28. #include <AzCore/Serialization/SerializeContext.h>
  29. #include <RHI/AsyncComputeExampleComponent.h>
  30. #include <SampleComponentConfig.h>
  31. #include <SampleComponentManager.h>
  32. #include <Utils/Utils.h>
  33. namespace AtomSampleViewer
  34. {
  35. using namespace AZ;
  36. namespace AsyncCompute
  37. {
  38. static const char* sampleName = "AsyncComputeComponent";
  39. static constexpr uint32_t s_shadowMapSize = 1024;
  40. static constexpr uint32_t s_luminanceMapSize = 1024;
  41. }
  42. void AsyncComputeExampleComponent::Reflect(AZ::ReflectContext* context)
  43. {
  44. if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  45. {
  46. serializeContext->Class<AsyncComputeExampleComponent, AZ::Component>()->Version(0);
  47. }
  48. }
  49. AsyncComputeExampleComponent::AsyncComputeExampleComponent()
  50. {
  51. m_supportRHISamplePipeline = true;
  52. }
  53. void AsyncComputeExampleComponent::FrameBeginInternal(RHI::FrameGraphBuilder& frameGraphBuilder)
  54. {
  55. if (!m_fullyActivated)
  56. {
  57. return;
  58. }
  59. RHI::Ptr<RHI::Device> device = Utils::GetRHIDevice();
  60. // Import non transient images
  61. for (uint32_t i = 0; i < m_sceneImages.size(); ++i)
  62. {
  63. frameGraphBuilder.GetAttachmentDatabase().ImportImage(m_sceneIds[i], m_sceneImages[i]);
  64. }
  65. // Generate transient images
  66. {
  67. const RHI::ImageDescriptor imageDescriptor = RHI::ImageDescriptor::Create2D(
  68. RHI::ImageBindFlags::DepthStencil | RHI::ImageBindFlags::ShaderRead,
  69. AsyncCompute::s_shadowMapSize,
  70. AsyncCompute::s_shadowMapSize,
  71. RHI::Format::D32_FLOAT);
  72. frameGraphBuilder.GetAttachmentDatabase().CreateTransientImage(RHI::TransientImageDescriptor(m_shadowAttachmentId, imageDescriptor));
  73. }
  74. {
  75. RHI::Format depthStencilFormat = device->GetNearestSupportedFormat(RHI::Format::D24_UNORM_S8_UINT, AZ::RHI::FormatCapabilities::DepthStencil);
  76. const RHI::ImageDescriptor imageDescriptor = RHI::ImageDescriptor::Create2D(
  77. RHI::ImageBindFlags::DepthStencil, m_outputWidth, m_outputHeight, depthStencilFormat);
  78. const RHI::TransientImageDescriptor transientImageDescriptor(m_forwardDepthStencilId, imageDescriptor);
  79. frameGraphBuilder.GetAttachmentDatabase().CreateTransientImage(transientImageDescriptor);
  80. }
  81. {
  82. const RHI::ImageDescriptor imageDescriptor = RHI::ImageDescriptor::Create2D(
  83. RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderRead,
  84. AsyncCompute::s_luminanceMapSize,
  85. AsyncCompute::s_luminanceMapSize,
  86. RHI::Format::R32_FLOAT);
  87. frameGraphBuilder.GetAttachmentDatabase().CreateTransientImage(RHI::TransientImageDescriptor(m_luminanceMapAttachmentId, imageDescriptor));
  88. }
  89. // Swap scene image index
  90. AZStd::swap(m_currentSceneImageIndex, m_previousSceneImageIndex);
  91. }
  92. void AsyncComputeExampleComponent::OnTick([[maybe_unused]] float deltaTime, AZ::ScriptTimePoint time)
  93. {
  94. AZ_UNUSED(time);
  95. if (!m_fullyActivated)
  96. {
  97. return;
  98. }
  99. if (m_imguiSidebar.Begin())
  100. {
  101. ScriptableImGui::Checkbox("Enable/Disable Async Compute", &m_asyncComputeEnabled);
  102. m_imguiSidebar.End();
  103. }
  104. }
  105. void AsyncComputeExampleComponent::ResetCamera()
  106. {
  107. const float pitch = -AZ::Constants::QuarterPi / 2.0f;
  108. const float distance = 35.0f;
  109. AZ::Debug::ArcBallControllerRequestBus::Event(m_cameraEntityId, &AZ::Debug::ArcBallControllerRequestBus::Events::SetCenter, AZ::Vector3(0.f));
  110. AZ::Debug::ArcBallControllerRequestBus::Event(m_cameraEntityId, &AZ::Debug::ArcBallControllerRequestBus::Events::SetDistance, distance);
  111. AZ::Debug::ArcBallControllerRequestBus::Event(m_cameraEntityId, &AZ::Debug::ArcBallControllerRequestBus::Events::SetMaxDistance, 50.0f);
  112. AZ::Debug::ArcBallControllerRequestBus::Event(m_cameraEntityId, &AZ::Debug::ArcBallControllerRequestBus::Events::SetPitch, pitch);
  113. // Set the camera Transform so we don't have a jump on the first frame.
  114. AZ::Quaternion orientation = AZ::Quaternion::CreateRotationX(pitch);
  115. AZ::Vector3 position = orientation.TransformVector(AZ::Vector3(0, -distance, 0));
  116. AZ::TransformBus::Event(m_cameraEntityId, &AZ::TransformBus::Events::SetWorldTM, AZ::Transform::CreateFromQuaternionAndTranslation(orientation, position));
  117. }
  118. void AsyncComputeExampleComponent::CreateSceneRenderTargets()
  119. {
  120. m_imagePool = aznew RHI::ImagePool();
  121. RHI::ImagePoolDescriptor imagePoolDesc;
  122. imagePoolDesc.m_bindFlags = RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderReadWrite;
  123. m_imagePool->Init(imagePoolDesc);
  124. for (auto& image : m_sceneImages)
  125. {
  126. image = aznew RHI::Image();
  127. RHI::ImageInitRequest initImageRequest;
  128. RHI::ClearValue clearValue = RHI::ClearValue::CreateVector4Float(0, 0, 0, 0);
  129. initImageRequest.m_image = image.get();
  130. initImageRequest.m_descriptor = RHI::ImageDescriptor::Create2D(
  131. RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderReadWrite,
  132. m_outputWidth,
  133. m_outputHeight,
  134. RHI::Format::R16G16B16A16_FLOAT);
  135. initImageRequest.m_optimizedClearValue = &clearValue;
  136. m_imagePool->InitImage(initImageRequest);
  137. }
  138. }
  139. void AsyncComputeExampleComponent::CreateQuad()
  140. {
  141. m_quadBufferPool = aznew RHI::BufferPool();
  142. RHI::BufferPoolDescriptor bufferPoolDesc;
  143. bufferPoolDesc.m_bindFlags = RHI::BufferBindFlags::InputAssembly;
  144. bufferPoolDesc.m_heapMemoryLevel = RHI::HeapMemoryLevel::Device;
  145. m_quadBufferPool->Init(bufferPoolDesc);
  146. struct BufferData
  147. {
  148. AZStd::array<VertexPosition, 4> m_positions;
  149. AZStd::array<VertexUV, 4> m_uvs;
  150. AZStd::array<VertexNormal, 4> m_normals;
  151. AZStd::array<uint16_t, 6> m_indices;
  152. };
  153. BufferData bufferData;
  154. SetFullScreenRect(bufferData.m_positions.data(), bufferData.m_uvs.data(), bufferData.m_indices.data());
  155. bufferData.m_normals.fill({ { 0, 0, 1.0f } });
  156. for (auto& uv : bufferData.m_uvs)
  157. {
  158. uv.m_uv[1] = 1.0f - uv.m_uv[1];
  159. }
  160. m_quadInputAssemblyBuffer = aznew RHI::Buffer();
  161. RHI::ResultCode result = RHI::ResultCode::Success;
  162. RHI::BufferInitRequest request;
  163. request.m_buffer = m_quadInputAssemblyBuffer.get();
  164. request.m_descriptor = RHI::BufferDescriptor{ RHI::BufferBindFlags::InputAssembly, sizeof(bufferData) };
  165. request.m_initialData = &bufferData;
  166. result = m_quadBufferPool->InitBuffer(request);
  167. if (result != RHI::ResultCode::Success)
  168. {
  169. AZ_Error("AsyncComputeComponent", false, "Failed to initialize buffer with error code %d", result);
  170. return;
  171. }
  172. AZ::RHI::StreamBufferView positionsBufferView =
  173. {
  174. *m_quadInputAssemblyBuffer,
  175. offsetof(BufferData, m_positions),
  176. sizeof(BufferData::m_positions),
  177. sizeof(VertexPosition)
  178. };
  179. AZ::RHI::StreamBufferView normalsBufferView =
  180. {
  181. *m_quadInputAssemblyBuffer,
  182. offsetof(BufferData, m_normals),
  183. sizeof(BufferData::m_normals),
  184. sizeof(VertexNormal)
  185. };
  186. AZ::RHI::StreamBufferView uvsBufferView =
  187. {
  188. *m_quadInputAssemblyBuffer,
  189. offsetof(BufferData, m_uvs),
  190. sizeof(BufferData::m_uvs),
  191. sizeof(VertexUV)
  192. };
  193. m_geometryViews[ShadowScope].AddStreamBufferView(positionsBufferView);
  194. m_geometryViews[ForwardScope].AddStreamBufferView(positionsBufferView);
  195. m_geometryViews[ForwardScope].AddStreamBufferView(normalsBufferView);
  196. m_geometryViews[CopyTextureScope].AddStreamBufferView(positionsBufferView);
  197. m_geometryViews[CopyTextureScope].AddStreamBufferView(uvsBufferView);
  198. m_geometryViews[LuminanceMapScope] = m_geometryViews[CopyTextureScope];
  199. AZ::RHI::IndexBufferView quadIndexBufferView =
  200. {
  201. *m_quadInputAssemblyBuffer,
  202. offsetof(BufferData, m_indices),
  203. sizeof(BufferData::m_indices),
  204. RHI::IndexFormat::Uint16
  205. };
  206. for (u32 i = 0; i < AsyncComputeScopes::NumScopes; ++i)
  207. {
  208. m_geometryViews[i].SetDrawArguments(RHI::DrawIndexed(0, 6, 0));
  209. m_geometryViews[i].SetIndexBufferView(quadIndexBufferView);
  210. }
  211. }
  212. void AsyncComputeExampleComponent::LoadShaders()
  213. {
  214. AZStd::vector<const char*> shaders = {
  215. "Shaders/RHI/CopyQueue.azshader", // Vertex + Fragment
  216. "Shaders/RHI/MultipleViewsDepth.azshader", // Vertex
  217. "Shaders/RHI/AsyncComputeShadow.azshader", // Vertex + Fragment
  218. "Shaders/RHI/AsyncComputeLuminanceMap.azshader", // Vertex + Fragment
  219. "Shaders/RHI/AsyncComputeLuminanceReduce.azshader", // Compute
  220. "Shaders/RHI/AsyncComputeTonemapping.azshader"}; // Compute
  221. for (size_t i = 0; i < shaders.size(); ++i)
  222. {
  223. auto shader = LoadShader(*m_assetLoadManager.get(), shaders[i], AsyncCompute::sampleName);
  224. if (shader == nullptr)
  225. return;
  226. m_shaders[i] = shader;
  227. if (shader->GetPipelineStateType() == AZ::RHI::PipelineStateType::Dispatch)
  228. {
  229. const auto& numThreads = shader->GetAsset()->GetAttribute(RHI::ShaderStage::Compute, Name("numthreads"));
  230. if (numThreads)
  231. {
  232. const RHI::ShaderStageAttributeArguments& args = *numThreads;
  233. m_numThreads[i].m_X = args[0].type() == azrtti_typeid<int>() ? AZStd::any_cast<int>(args[0]) : m_numThreads[i].m_X;
  234. m_numThreads[i].m_Y = args[1].type() == azrtti_typeid<int>() ? AZStd::any_cast<int>(args[1]) : m_numThreads[i].m_Y;
  235. m_numThreads[i].m_Z = args[2].type() == azrtti_typeid<int>() ? AZStd::any_cast<int>(args[2]) : m_numThreads[i].m_Z;
  236. }
  237. else
  238. {
  239. AZ_Error(AsyncCompute::sampleName, false, "Did not find expected numthreads attribute");
  240. }
  241. }
  242. }
  243. }
  244. void AsyncComputeExampleComponent::LoadModel()
  245. {
  246. // Load the asset
  247. auto modelAsset = m_assetLoadManager->GetAsset<AZ::RPI::ModelAsset>("objects/shaderball_simple.fbx.azmodel");
  248. AZ_Assert(modelAsset.IsReady(), "The model asset is supposed to be ready.");
  249. m_model = AZ::RPI::Model::FindOrCreate(modelAsset);
  250. AZ_Error(AsyncCompute::sampleName, m_model, "Failed to load model");
  251. }
  252. void AsyncComputeExampleComponent::CreatePipelines()
  253. {
  254. RHI::Ptr<RHI::Device> device = Utils::GetRHIDevice();
  255. RHI::RenderAttachmentLayoutBuilder attachmentsBuilder;
  256. {
  257. // Shadow Scope Pipelines
  258. const auto& shader = m_shaders[ShadowScope];
  259. auto& variant = shader->GetVariant(AZ::RPI::ShaderAsset::RootShaderVariantStableId);
  260. RHI::PipelineStateDescriptorForDraw pipelineDesc;
  261. variant.ConfigurePipelineState(pipelineDesc);
  262. pipelineDesc.m_renderStates.m_depthStencilState.m_depth.m_enable = 1;
  263. pipelineDesc.m_renderStates.m_depthStencilState.m_depth.m_func = RHI::ComparisonFunc::LessEqual;
  264. attachmentsBuilder.AddSubpass()
  265. ->DepthStencilAttachment(RHI::Format::D32_FLOAT);
  266. [[maybe_unused]] RHI::ResultCode result = attachmentsBuilder.End(pipelineDesc.m_renderAttachmentConfiguration.m_renderAttachmentLayout);
  267. AZ_Assert(result == RHI::ResultCode::Success, "Failed to create render attachment layout");
  268. {
  269. // Terrain Pipeline
  270. RHI::InputStreamLayoutBuilder layoutBuilder;
  271. layoutBuilder.AddBuffer()->Channel("POSITION", RHI::Format::R32G32B32_FLOAT);
  272. pipelineDesc.m_inputStreamLayout = layoutBuilder.End();
  273. if (!RHI::ValidateStreamBufferViews(
  274. pipelineDesc.m_inputStreamLayout,
  275. m_geometryViews[ShadowScope],
  276. m_geometryViews[ShadowScope].GetFullStreamBufferIndices()))
  277. {
  278. AZ_Error(AsyncCompute::sampleName, false, "Invalid stream buffer views for terrain");
  279. return;
  280. }
  281. m_terrainPipelineStates[ShadowScope] = shader->AcquirePipelineState(pipelineDesc);
  282. if (!m_terrainPipelineStates[ShadowScope])
  283. {
  284. AZ_Error(AsyncCompute::sampleName, false, "Failed to acquire default pipeline state for shadow shader");
  285. return;
  286. }
  287. }
  288. {
  289. // Model Pipeline
  290. Data::Instance<AZ::RPI::ModelLod> modelLod = m_model->GetLods()[0];
  291. modelLod->GetStreamsForMesh(
  292. pipelineDesc.m_inputStreamLayout,
  293. m_modelStreamBufferIndices[ShadowScope],
  294. nullptr,
  295. shader->GetInputContract(),
  296. 0);
  297. m_modelPipelineStates[ShadowScope] = shader->AcquirePipelineState(pipelineDesc);
  298. if (!m_modelPipelineStates[ShadowScope])
  299. {
  300. AZ_Error(AsyncCompute::sampleName, false, "Failed to acquire default pipeline state for shader");
  301. return;
  302. }
  303. }
  304. }
  305. {
  306. // Forward Scope Pipelines
  307. const auto& shader = m_shaders[ForwardScope];
  308. auto& variant = shader->GetVariant(AZ::RPI::ShaderAsset::RootShaderVariantStableId);
  309. RHI::PipelineStateDescriptorForDraw pipelineDesc;
  310. variant.ConfigurePipelineState(pipelineDesc);
  311. pipelineDesc.m_renderStates.m_depthStencilState = RHI::DepthStencilState::CreateReverseDepth();
  312. attachmentsBuilder.Reset();
  313. RHI::Format depthStencilFormat = device->GetNearestSupportedFormat(RHI::Format::D24_UNORM_S8_UINT, AZ::RHI::FormatCapabilities::DepthStencil);
  314. attachmentsBuilder.AddSubpass()
  315. ->RenderTargetAttachment(RHI::Format::R16G16B16A16_FLOAT)
  316. ->DepthStencilAttachment(depthStencilFormat);
  317. [[maybe_unused]] RHI::ResultCode result = attachmentsBuilder.End(pipelineDesc.m_renderAttachmentConfiguration.m_renderAttachmentLayout);
  318. AZ_Assert(result == RHI::ResultCode::Success, "Failed to create render attachment layout");
  319. {
  320. // Terrain Pipeline
  321. RHI::InputStreamLayoutBuilder layoutBuilder;
  322. layoutBuilder.AddBuffer()->Channel("POSITION", RHI::Format::R32G32B32_FLOAT);
  323. layoutBuilder.AddBuffer()->Channel("NORMAL", RHI::Format::R32G32B32_FLOAT);
  324. pipelineDesc.m_inputStreamLayout = layoutBuilder.End();
  325. if (!RHI::ValidateStreamBufferViews(
  326. pipelineDesc.m_inputStreamLayout,
  327. m_geometryViews[ForwardScope],
  328. m_geometryViews[ForwardScope].GetFullStreamBufferIndices()))
  329. {
  330. AZ_Error(AsyncCompute::sampleName, false, "Invalid stream buffer views for terrain");
  331. return;
  332. }
  333. m_terrainPipelineStates[ForwardScope] = shader->AcquirePipelineState(pipelineDesc);
  334. if (!m_terrainPipelineStates[ForwardScope])
  335. {
  336. AZ_Error(AsyncCompute::sampleName, false, "Failed to acquire default pipeline state for shadow shader");
  337. return;
  338. }
  339. }
  340. {
  341. // Model Pipeline
  342. Data::Instance<AZ::RPI::ModelLod> modelLod = m_model->GetLods()[0];
  343. modelLod->GetStreamsForMesh(
  344. pipelineDesc.m_inputStreamLayout,
  345. m_modelStreamBufferIndices[ForwardScope],
  346. nullptr,
  347. shader->GetInputContract(),
  348. 0);
  349. m_modelPipelineStates[ForwardScope] = shader->AcquirePipelineState(pipelineDesc);
  350. if (!m_modelPipelineStates[ForwardScope])
  351. {
  352. AZ_Error(AsyncCompute::sampleName, false, "Failed to acquire default pipeline state for shader");
  353. return;
  354. }
  355. }
  356. }
  357. {
  358. // Copy texture Pipeline
  359. const auto& shader = m_shaders[CopyTextureScope];
  360. auto& variant = shader->GetVariant(AZ::RPI::ShaderAsset::RootShaderVariantStableId);
  361. RHI::PipelineStateDescriptorForDraw pipelineDesc;
  362. variant.ConfigurePipelineState(pipelineDesc);
  363. pipelineDesc.m_renderStates.m_depthStencilState.m_depth.m_enable = 0;
  364. attachmentsBuilder.Reset();
  365. attachmentsBuilder.AddSubpass()
  366. ->RenderTargetAttachment(m_outputFormat);
  367. [[maybe_unused]] RHI::ResultCode result = attachmentsBuilder.End(pipelineDesc.m_renderAttachmentConfiguration.m_renderAttachmentLayout);
  368. AZ_Assert(result == RHI::ResultCode::Success, "Failed to create render attachment layout");
  369. RHI::TargetBlendState& blendstate = pipelineDesc.m_renderStates.m_blendState.m_targets[0];
  370. blendstate.m_enable = true;
  371. blendstate.m_blendDest = RHI::BlendFactor::AlphaSourceInverse;
  372. blendstate.m_blendSource = RHI::BlendFactor::AlphaSource;
  373. blendstate.m_blendOp = RHI::BlendOp::Add;
  374. RHI::InputStreamLayoutBuilder layoutBuilder;
  375. layoutBuilder.AddBuffer()->Channel("POSITION", RHI::Format::R32G32B32_FLOAT);
  376. layoutBuilder.AddBuffer()->Channel("UV", RHI::Format::R32G32_FLOAT);
  377. pipelineDesc.m_inputStreamLayout = layoutBuilder.End();
  378. if (!RHI::ValidateStreamBufferViews(
  379. pipelineDesc.m_inputStreamLayout,
  380. m_geometryViews[CopyTextureScope],
  381. m_geometryViews[CopyTextureScope].GetFullStreamBufferIndices()))
  382. {
  383. AZ_Error(AsyncCompute::sampleName, false, "Invalid stream buffer views for LuminanceMap");
  384. return;
  385. }
  386. m_copyTexturePipelineState = shader->AcquirePipelineState(pipelineDesc);
  387. if (!m_copyTexturePipelineState)
  388. {
  389. AZ_Error(AsyncCompute::sampleName, false, "Failed to acquire default pipeline state for copy texture");
  390. return;
  391. }
  392. }
  393. {
  394. // LuminanceMap pipeline
  395. const auto& shader = m_shaders[LuminanceMapScope];
  396. auto& variant = shader->GetVariant(AZ::RPI::ShaderAsset::RootShaderVariantStableId);
  397. RHI::PipelineStateDescriptorForDraw pipelineDesc;
  398. variant.ConfigurePipelineState(pipelineDesc);
  399. pipelineDesc.m_renderStates.m_depthStencilState.m_depth.m_enable = 0;
  400. attachmentsBuilder.Reset();
  401. attachmentsBuilder.AddSubpass()
  402. ->RenderTargetAttachment(RHI::Format::R32_FLOAT);
  403. [[maybe_unused]] RHI::ResultCode result = attachmentsBuilder.End(pipelineDesc.m_renderAttachmentConfiguration.m_renderAttachmentLayout);
  404. AZ_Assert(result == RHI::ResultCode::Success, "Failed to create render attachment layout");
  405. RHI::InputStreamLayoutBuilder layoutBuilder;
  406. layoutBuilder.AddBuffer()->Channel("POSITION", RHI::Format::R32G32B32_FLOAT);
  407. layoutBuilder.AddBuffer()->Channel("UV", RHI::Format::R32G32_FLOAT);
  408. pipelineDesc.m_inputStreamLayout = layoutBuilder.End();
  409. if (!RHI::ValidateStreamBufferViews(
  410. pipelineDesc.m_inputStreamLayout,
  411. m_geometryViews[LuminanceMapScope],
  412. m_geometryViews[LuminanceMapScope].GetFullStreamBufferIndices()))
  413. {
  414. AZ_Error(AsyncCompute::sampleName, false, "Invalid stream buffer views for LuminanceMap");
  415. return;
  416. }
  417. m_luminancePipelineState = shader->AcquirePipelineState(pipelineDesc);
  418. if (!m_luminancePipelineState)
  419. {
  420. AZ_Error(AsyncCompute::sampleName, false, "Failed to acquire default pipeline state for luminance map");
  421. return;
  422. }
  423. }
  424. {
  425. // Luminance reduce pipelines
  426. const auto& shader = m_shaders[LuminanceReduceScope];
  427. RHI::PipelineStateDescriptorForDispatch pipelineDesc;
  428. shader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId).ConfigurePipelineState(pipelineDesc);
  429. m_luminanceReducePipelineState = shader->AcquirePipelineState(pipelineDesc);
  430. if (!m_luminanceReducePipelineState)
  431. {
  432. AZ_Error(AsyncCompute::sampleName, false, "Failed to acquire default pipeline state for luminance reduce");
  433. return;
  434. }
  435. }
  436. {
  437. // Tonemapping pipeline
  438. const auto& shader = m_shaders[TonemappingScope];
  439. RHI::PipelineStateDescriptorForDispatch pipelineDesc;
  440. shader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId).ConfigurePipelineState(pipelineDesc);
  441. m_tonemappingPipelineState = shader->AcquirePipelineState(pipelineDesc);
  442. if (!m_tonemappingPipelineState)
  443. {
  444. AZ_Error(AsyncCompute::sampleName, false, "Failed to acquire default pipeline state for tonemapping");
  445. return;
  446. }
  447. }
  448. }
  449. void AsyncComputeExampleComponent::Activate()
  450. {
  451. m_assetLoadManager = AZStd::make_unique<AZ::AssetCollectionAsyncLoader>();
  452. m_forwardDepthStencilId = AZ::Name("ForwardDepthStencilId");
  453. m_shadowAttachmentId = AZ::Name("ShadowAttachmentId");
  454. m_luminanceMapAttachmentId = AZ::Name("LuminanceMapAttachmentId");
  455. m_averageLuminanceAttachmentId = AZ::Name("LuminanceReduce1");
  456. // List of all assets this example needs.
  457. AZStd::vector<AssetCollectionAsyncLoader::AssetToLoadInfo> assetList = {
  458. {"Shaders/RHI/CopyQueue.azshader", azrtti_typeid<RPI::ShaderAsset>()}, // Vertex + Fragment
  459. {"Shaders/RHI/MultipleViewsDepth.azshader", azrtti_typeid<RPI::ShaderAsset>()}, // Vertex
  460. {"Shaders/RHI/AsyncComputeShadow.azshader", azrtti_typeid<RPI::ShaderAsset>()}, // Vertex + Fragment
  461. {"Shaders/RHI/AsyncComputeLuminanceMap.azshader", azrtti_typeid<RPI::ShaderAsset>()}, // Vertex + Fragment
  462. {"Shaders/RHI/AsyncComputeLuminanceReduce.azshader", azrtti_typeid<RPI::ShaderAsset>()}, // Compute
  463. {"Shaders/RHI/AsyncComputeTonemapping.azshader", azrtti_typeid<RPI::ShaderAsset>()}, // Compute
  464. {"objects/shaderball_simple.fbx.azmodel", azrtti_typeid<AZ::RPI::ModelAsset>()}, // The model
  465. };
  466. // Configure the imgui progress list widget.
  467. auto onUserCancelledAction = [&]()
  468. {
  469. AZ_TracePrintf(AsyncCompute::sampleName, "Cancelled by user.\n");
  470. m_assetLoadManager->Cancel();
  471. SampleComponentManagerRequestBus::Broadcast(&SampleComponentManagerRequests::Reset);
  472. };
  473. m_imguiProgressList.OpenPopup("Waiting For Assets...", "Assets pending for processing:", {}, onUserCancelledAction, true /*automaticallyCloseOnAction*/, "Cancel");
  474. AZStd::for_each(assetList.begin(), assetList.end(),
  475. [&](const AssetCollectionAsyncLoader::AssetToLoadInfo& item) { m_imguiProgressList.AddItem(item.m_assetPath); });
  476. // Kickoff asynchronous asset loading, the activation will continue once all assets are available.
  477. m_assetLoadManager->LoadAssetsAsync(assetList, [&](AZStd::string_view assetName, [[maybe_unused]] bool success, size_t pendingAssetCount)
  478. {
  479. if (m_fullyActivated)
  480. {
  481. return;
  482. }
  483. AZ_Error(AsyncCompute::sampleName, success, "Error loading asset %s, a crash will occur when OnAllAssetsReadyActivate() is called!", assetName.data());
  484. AZ_TracePrintf(AsyncCompute::sampleName, "Asset %s loaded %s. Wait for %zu more assets before full activation\n", assetName.data(), success ? "successfully" : "UNSUCCESSFULLY", pendingAssetCount);
  485. m_imguiProgressList.RemoveItem(assetName);
  486. if (!pendingAssetCount)
  487. {
  488. OnAllAssetsReadyActivate();
  489. }
  490. });
  491. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScriptWithTimeout, 120.0f);
  492. }
  493. void AsyncComputeExampleComponent::OnAllAssetsReadyActivate()
  494. {
  495. AZ_Assert(!m_fullyActivated, "Full Activation should occur only once");
  496. CreateSceneRenderTargets();
  497. CreateQuad();
  498. LoadModel();
  499. LoadShaders();
  500. CreatePipelines();
  501. SetupScene();
  502. SetArcBallControllerParams();
  503. CreateLuminanceMapScope();
  504. CreateShadowScope();
  505. CreateLuminanceReduceScopes();
  506. CreateTonemappingScope();
  507. CreateForwardScope();
  508. CreateCopyTextureScope();
  509. m_imguiSidebar.Activate();
  510. AZ::RHI::RHISystemNotificationBus::Handler::BusConnect();
  511. ExampleComponentRequestBus::Handler::BusConnect(GetEntityId());
  512. AZ::TickBus::Handler::BusConnect();
  513. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  514. m_fullyActivated = true;
  515. }
  516. void AsyncComputeExampleComponent::Deactivate()
  517. {
  518. m_assetLoadManager->Cancel();
  519. m_fullyActivated = false;
  520. m_quadBufferPool = nullptr;
  521. m_quadInputAssemblyBuffer = nullptr;
  522. m_terrainPipelineStates.fill(nullptr);
  523. m_modelPipelineStates.fill(nullptr);
  524. m_model = nullptr;
  525. m_copyTexturePipelineState = nullptr;
  526. m_luminancePipelineState = nullptr;
  527. m_luminanceReducePipelineState = nullptr;
  528. m_tonemappingPipelineState = nullptr;
  529. m_shaderResourceGroups.fill(AZStd::vector<AZ::Data::Instance<AZ::RPI::ShaderResourceGroup>>());
  530. m_viewShaderResourceGroup = nullptr;
  531. m_shaders.fill(nullptr);
  532. m_imagePool = nullptr;
  533. m_sceneImages.fill(nullptr);
  534. m_scopeProducers.clear();
  535. m_windowContext = nullptr;
  536. m_imguiSidebar.Deactivate();
  537. ExampleComponentRequestBus::Handler::BusDisconnect();
  538. AZ::TickBus::Handler::BusDisconnect();
  539. AZ::RHI::RHISystemNotificationBus::Handler::BusDisconnect();
  540. }
  541. void AsyncComputeExampleComponent::SetupScene()
  542. {
  543. // Shader inputs
  544. const Name shaderInputImageWorldMatrix{ "m_worldMatrix" };
  545. const Name shaderInputImageViewProjectionMatrix{ "m_viewProjectionMatrix" };
  546. const Name shaderInputImageLightViewProjectionMatrix{ "m_lightViewProjectionMatrix" };
  547. const Name shaderInputImageLightPosition{ "m_lightPosition" };
  548. const Name shaderInputImageAmbientColor{ "m_ambientColor" };
  549. const Name shaderInputImageDiffuseColor{ "m_diffuseColor" };
  550. const Name shaderInputImageDepthMapTexture{ "m_depthMapTexture" };
  551. const Name textureInputImageTexture{ "m_texture" };
  552. const Name luminanceReduceInputImageTexture{ "m_inputTexture" };
  553. const Name luminanceReduceOutputImageTexture{ "m_outputTexture" };
  554. const Name tonemappingImageTexture{ "m_inOutTexture" };
  555. const Name tonemappingLuminanceImageTexture{ "m_luminanceTexture" };
  556. // These are the model matrices. They contain the rotation, translation and scale of the objects that we are going to draw.
  557. AZStd::vector<AZ::Matrix4x4> objectMatrices =
  558. {
  559. AZ::Matrix4x4::CreateScale(AZ::Vector3(12.0f)),
  560. AZ::Matrix4x4::CreateRotationZ(AZ::Constants::Pi),
  561. AZ::Matrix4x4::CreateFromQuaternionAndTranslation(AZ::Quaternion::CreateRotationZ(AZ::Constants::QuarterPi * 3.0f), AZ::Vector3(5.0f, 8.0f, 0.0f)),
  562. AZ::Matrix4x4::CreateFromQuaternionAndTranslation(AZ::Quaternion::CreateRotationZ(-AZ::Constants::QuarterPi * 3.0f), AZ::Vector3(-6.0f, 6.0f, 0.0f)) * AZ::Matrix4x4::CreateScale(AZ::Vector3(1.5f)),
  563. AZ::Matrix4x4::CreateFromQuaternionAndTranslation(AZ::Quaternion::CreateRotationZ(-AZ::Constants::QuarterPi * 3.0f), AZ::Vector3(-7.0f, -4.0f, 0.0f)) * AZ::Matrix4x4::CreateScale(AZ::Vector3(0.6f)),
  564. AZ::Matrix4x4::CreateFromQuaternionAndTranslation(AZ::Quaternion::CreateRotationZ(AZ::Constants::QuarterPi * 2.0), AZ::Vector3(4.0f, -4.0f, 0.0f)) * AZ::Matrix4x4::CreateScale(AZ::Vector3(1.3f))
  565. };
  566. const float zNear = 1.0f, zFar = 100.0f;
  567. const AZ::Vector3 up = AZ::Vector3(0.0f, 0.0f, 1.0f);
  568. const AZ::Vector3 lookAt = AZ::Vector3(0.0f, 0.0f, 0.0f);
  569. auto ambientColor = AZ::Vector4(0.15f, 0.15f, 0.15f, 1.0f);
  570. auto diffuseColor = AZ::Vector4(1.0f, 1.0f, 1.0f, 1.0f);
  571. // Camera
  572. float fieldOfView = AZ::Constants::Pi / 4.0f;
  573. float screenAspect = GetViewportWidth() / GetViewportHeight();
  574. MakePerspectiveFovMatrixRH(m_projectionMatrix, fieldOfView, screenAspect, zNear, zFar);
  575. // Light
  576. float fovY = AZ::Constants::Pi / 2.0f;
  577. float aspectRatio = 1.0f;
  578. auto lightPosition = AZ::Vector3(-5.0f, -12.0f, 8.0f);
  579. AZ::Matrix4x4 lightProjectMatrix;
  580. MakePerspectiveFovMatrixRH(lightProjectMatrix, fovY, aspectRatio, zNear, zFar);
  581. AZ::Matrix4x4 worldToLight = lightProjectMatrix * CreateViewMatrix(lightPosition, up, lookAt);
  582. // Shadow generation SRGs
  583. m_shaderResourceGroups[ShadowScope].reserve(objectMatrices.size());
  584. for (const AZ::Matrix4x4& objectMatrix : objectMatrices)
  585. {
  586. auto shaderResourceGroup = CreateShaderResourceGroup(m_shaders[ShadowScope], "DepthViewSrg", AsyncCompute::sampleName);
  587. RHI::ShaderInputConstantIndex viewProjectionMatrixInput;
  588. RHI::ShaderInputConstantIndex modelMatrixInput;
  589. FindShaderInputIndex(&viewProjectionMatrixInput, shaderResourceGroup, shaderInputImageViewProjectionMatrix, AsyncCompute::sampleName);
  590. FindShaderInputIndex(&modelMatrixInput, shaderResourceGroup, shaderInputImageWorldMatrix, AsyncCompute::sampleName);
  591. shaderResourceGroup->SetConstant(viewProjectionMatrixInput, worldToLight);
  592. shaderResourceGroup->SetConstant(modelMatrixInput, objectMatrix);
  593. shaderResourceGroup->Compile();
  594. m_shaderResourceGroups[ShadowScope].push_back(shaderResourceGroup);
  595. }
  596. // Forward scope SRGs
  597. m_shaderResourceGroups[ForwardScope].reserve(objectMatrices.size());
  598. for (const AZ::Matrix4x4& objectMatrix : objectMatrices)
  599. {
  600. auto shaderResourceGroup = CreateShaderResourceGroup(m_shaders[ForwardScope], "ShadowSrg", AsyncCompute::sampleName);
  601. AZStd::array<RHI::ShaderInputConstantIndex, 5> shaderInputIndices;
  602. FindShaderInputIndex(&shaderInputIndices[0], shaderResourceGroup, shaderInputImageWorldMatrix, AsyncCompute::sampleName);
  603. FindShaderInputIndex(&shaderInputIndices[1], shaderResourceGroup, shaderInputImageLightViewProjectionMatrix, AsyncCompute::sampleName);
  604. FindShaderInputIndex(&shaderInputIndices[2], shaderResourceGroup, shaderInputImageLightPosition, AsyncCompute::sampleName);
  605. FindShaderInputIndex(&shaderInputIndices[3], shaderResourceGroup, shaderInputImageAmbientColor, AsyncCompute::sampleName);
  606. FindShaderInputIndex(&shaderInputIndices[4], shaderResourceGroup, shaderInputImageDiffuseColor, AsyncCompute::sampleName);
  607. FindShaderInputIndex(&m_shaderInputImageIndex, shaderResourceGroup, shaderInputImageDepthMapTexture, AsyncCompute::sampleName);
  608. shaderResourceGroup->SetConstant(shaderInputIndices[0], objectMatrix);
  609. shaderResourceGroup->SetConstant(shaderInputIndices[1], worldToLight);
  610. shaderResourceGroup->SetConstant(shaderInputIndices[2], AZ::Vector4::CreateFromVector3AndFloat(lightPosition, 1.0f));
  611. shaderResourceGroup->SetConstant(shaderInputIndices[3], ambientColor);
  612. shaderResourceGroup->SetConstant(shaderInputIndices[4], diffuseColor);
  613. m_shaderResourceGroups[ForwardScope].push_back(shaderResourceGroup);
  614. // Do not compile now since this SRG is updated every frame with the image input.
  615. }
  616. {
  617. // Copy texture SRG
  618. auto shaderResourceGroup = CreateShaderResourceGroup(m_shaders[CopyTextureScope], "CopyQueueSrg", AsyncCompute::sampleName);
  619. FindShaderInputIndex(&m_copyTextureShaderInputImageIndex, shaderResourceGroup, textureInputImageTexture, AsyncCompute::sampleName);
  620. m_shaderResourceGroups[CopyTextureScope].push_back(shaderResourceGroup);
  621. }
  622. {
  623. // Luminance map SRG
  624. auto shaderResourceGroup = CreateShaderResourceGroup(m_shaders[LuminanceMapScope], "TextureInstanceSrg", AsyncCompute::sampleName);
  625. FindShaderInputIndex(&m_luminanceShaderInputImageIndex, shaderResourceGroup, textureInputImageTexture, AsyncCompute::sampleName);
  626. m_shaderResourceGroups[LuminanceMapScope].push_back(shaderResourceGroup);
  627. }
  628. {
  629. // Luminance reduce SRGs
  630. AZ_Assert(m_numThreads[LuminanceReduceScope].m_X == m_numThreads[LuminanceReduceScope].m_Y, "If the shader source changes, this logic should change too.");
  631. AZ_Assert(m_numThreads[LuminanceReduceScope].m_Z == 1, "If the shader source changes, this logic should change too.");
  632. const auto luminanceMapThreadGroupSize = m_numThreads[LuminanceReduceScope].m_X;
  633. for (uint32_t size = AsyncCompute::s_luminanceMapSize; size > 1; size = AZStd::max(size / (luminanceMapThreadGroupSize * 2), 1u))
  634. {
  635. auto shaderResourceGroup = CreateShaderResourceGroup(m_shaders[LuminanceReduceScope], "TexturesSrg", AsyncCompute::sampleName);
  636. FindShaderInputIndex(&m_luminanceReduceShaderInputImageIndex, shaderResourceGroup, luminanceReduceInputImageTexture, AsyncCompute::sampleName);
  637. FindShaderInputIndex(&m_luminanceReduceShaderOutputImageIndex, shaderResourceGroup, luminanceReduceOutputImageTexture, AsyncCompute::sampleName);
  638. m_shaderResourceGroups[LuminanceReduceScope].push_back(shaderResourceGroup);
  639. }
  640. }
  641. {
  642. // Tonemapping SRGs
  643. auto shaderResourceGroup = CreateShaderResourceGroup(m_shaders[TonemappingScope], "TexturesSrg", AsyncCompute::sampleName);
  644. FindShaderInputIndex(&m_tonemappingShaderImageIndex, shaderResourceGroup, tonemappingImageTexture, AsyncCompute::sampleName);
  645. FindShaderInputIndex(&m_tonemappingLuminanceImageIndex, shaderResourceGroup, tonemappingLuminanceImageTexture, AsyncCompute::sampleName);
  646. m_shaderResourceGroups[TonemappingScope].push_back(shaderResourceGroup);
  647. }
  648. }
  649. void AsyncComputeExampleComponent::SetArcBallControllerParams()
  650. {
  651. AZ::Debug::CameraControllerRequestBus::Event(m_cameraEntityId, &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  652. azrtti_typeid<AZ::Debug::ArcBallControllerComponent>());
  653. AZ::RPI::ViewPtr cameraView;
  654. // The RPI::View associated to this component can be obtained through the ViewProvider, by using Entity Id.
  655. AZ::RPI::ViewProviderBus::EventResult(cameraView, m_cameraEntityId, &AZ::RPI::ViewProvider::GetView);
  656. if (cameraView)
  657. {
  658. m_viewShaderResourceGroup = cameraView->GetShaderResourceGroup();
  659. }
  660. }
  661. void AsyncComputeExampleComponent::CreateCopyTextureScope()
  662. {
  663. const auto prepareFunction = [this](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData)
  664. {
  665. auto& source = m_sceneIds[m_previousSceneImageIndex];
  666. auto& destination = m_outputAttachmentId;
  667. {
  668. {
  669. RHI::ImageScopeAttachmentDescriptor descriptor;
  670. descriptor.m_attachmentId = destination;
  671. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Load;
  672. frameGraph.UseColorAttachment(descriptor);
  673. }
  674. {
  675. RHI::ImageScopeAttachmentDescriptor descriptor;
  676. descriptor.m_attachmentId = source;
  677. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Load;
  678. frameGraph.UseShaderAttachment(descriptor, RHI::ScopeAttachmentAccess::Read, RHI::ScopeAttachmentStage::FragmentShader);
  679. }
  680. }
  681. frameGraph.SetEstimatedItemCount(1);
  682. };
  683. const auto compileFunction = [this](const RHI::FrameGraphCompileContext& context, [[maybe_unused]] const ScopeData& scopeData)
  684. {
  685. auto& source = m_sceneIds[m_previousSceneImageIndex];
  686. auto& shaderResourceGroup = m_shaderResourceGroups[CopyTextureScope].front();
  687. const auto* imageView = context.GetImageView(source);
  688. shaderResourceGroup->SetImageView(m_copyTextureShaderInputImageIndex, imageView);
  689. shaderResourceGroup->Compile();
  690. };
  691. const auto executeFunction = [this](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  692. {
  693. RHI::CommandList* commandList = context.GetCommandList();
  694. commandList->SetViewports(&m_viewport, 1);
  695. commandList->SetScissors(&m_scissor, 1);
  696. {
  697. const RHI::DeviceShaderResourceGroup* shaderResourceGroups[] = { m_shaderResourceGroups[CopyTextureScope]
  698. .front()
  699. ->GetRHIShaderResourceGroup()
  700. ->GetDeviceShaderResourceGroup(
  701. context.GetDeviceIndex())
  702. .get() };
  703. RHI::DeviceDrawItem drawItem;
  704. drawItem.m_geometryView = m_geometryViews[CopyTextureScope].GetDeviceGeometryView(context.GetDeviceIndex());
  705. drawItem.m_streamIndices = m_geometryViews[CopyTextureScope].GetFullStreamBufferIndices();
  706. drawItem.m_pipelineState = m_copyTexturePipelineState->GetDevicePipelineState(context.GetDeviceIndex()).get();
  707. drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups));
  708. drawItem.m_shaderResourceGroups = shaderResourceGroups;
  709. commandList->Submit(drawItem);
  710. }
  711. };
  712. AZStd::string name = AZStd::string::format("CopyTextureToSwapchain");
  713. const RHI::ScopeId shadowScope(name);
  714. m_scopeProducers.emplace_back(aznew RHI::ScopeProducerFunction<
  715. ScopeData,
  716. decltype(prepareFunction),
  717. decltype(compileFunction),
  718. decltype(executeFunction)>(
  719. shadowScope,
  720. ScopeData{},
  721. prepareFunction,
  722. compileFunction,
  723. executeFunction));
  724. }
  725. void AsyncComputeExampleComponent::CreateShadowScope()
  726. {
  727. // Generate shadowmap texture.
  728. const auto prepareFunction = [this](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData)
  729. {
  730. // Create & Binds DepthStencil image
  731. {
  732. RHI::ImageScopeAttachmentDescriptor dsDesc;
  733. dsDesc.m_attachmentId = m_shadowAttachmentId;
  734. dsDesc.m_imageViewDescriptor.m_overrideFormat = RHI::Format::D32_FLOAT;
  735. dsDesc.m_loadStoreAction.m_clearValue = RHI::ClearValue::CreateDepthStencil(1.0f, 0);
  736. dsDesc.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Clear;
  737. frameGraph.UseDepthStencilAttachment(
  738. dsDesc, RHI::ScopeAttachmentAccess::ReadWrite,
  739. RHI::ScopeAttachmentStage::EarlyFragmentTest | RHI::ScopeAttachmentStage::LateFragmentTest);
  740. }
  741. frameGraph.SetEstimatedItemCount(static_cast<uint32_t>(m_shaderResourceGroups[ShadowScope].size()));
  742. };
  743. RHI::EmptyCompileFunction<ScopeData> compileFunction;
  744. const auto executeFunction = [this](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  745. {
  746. RHI::CommandList* commandList = context.GetCommandList();
  747. float shadowMapSizeFloat = static_cast<float>(AsyncCompute::s_shadowMapSize);
  748. int32_t shadowMapSizeInt = static_cast<int32_t>(AsyncCompute::s_shadowMapSize);
  749. RHI::Viewport viewport = RHI::Viewport(0, shadowMapSizeFloat, 0, shadowMapSizeFloat);
  750. RHI::Scissor scissor(0, 0, shadowMapSizeInt, shadowMapSizeInt);
  751. commandList->SetViewports(&viewport, 1);
  752. commandList->SetScissors(&scissor, 1);
  753. for(uint32_t i = context.GetSubmitRange().m_startIndex; i < context.GetSubmitRange().m_endIndex; ++i)
  754. {
  755. if (i == 0)
  756. {
  757. const RHI::DeviceShaderResourceGroup* shaderResourceGroups[] = { m_shaderResourceGroups[ShadowScope][0]
  758. ->GetRHIShaderResourceGroup()
  759. ->GetDeviceShaderResourceGroup(
  760. context.GetDeviceIndex())
  761. .get() };
  762. RHI::DeviceDrawItem drawItem;
  763. drawItem.m_geometryView = m_geometryViews[ShadowScope].GetDeviceGeometryView(context.GetDeviceIndex());
  764. drawItem.m_streamIndices = m_geometryViews[ShadowScope].GetFullStreamBufferIndices();
  765. drawItem.m_pipelineState = m_terrainPipelineStates[ShadowScope]->GetDevicePipelineState(context.GetDeviceIndex()).get();
  766. drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups));
  767. drawItem.m_shaderResourceGroups = shaderResourceGroups;
  768. commandList->Submit(drawItem, i);
  769. }
  770. else
  771. {
  772. // Models
  773. const RHI::DeviceShaderResourceGroup* shaderResourceGroups[] = { m_shaderResourceGroups[ShadowScope][i]
  774. ->GetRHIShaderResourceGroup()
  775. ->GetDeviceShaderResourceGroup(
  776. context.GetDeviceIndex())
  777. .get() };
  778. for (auto& mesh : m_model->GetLods()[0]->GetMeshes())
  779. {
  780. RHI::DeviceDrawItem drawItem;
  781. drawItem.m_geometryView = mesh.GetDeviceGeometryView(context.GetDeviceIndex());
  782. drawItem.m_streamIndices = m_modelStreamBufferIndices[ShadowScope];
  783. drawItem.m_pipelineState = m_modelPipelineStates[ShadowScope]->GetDevicePipelineState(context.GetDeviceIndex()).get();
  784. drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups));
  785. drawItem.m_shaderResourceGroups = shaderResourceGroups;
  786. commandList->Submit(drawItem, i);
  787. }
  788. }
  789. }
  790. };
  791. const RHI::ScopeId shadowScope("ShadowScope");
  792. m_scopeProducers.emplace_back(aznew RHI::ScopeProducerFunction<
  793. ScopeData,
  794. decltype(prepareFunction),
  795. decltype(compileFunction),
  796. decltype(executeFunction)>(
  797. shadowScope,
  798. ScopeData{},
  799. prepareFunction,
  800. compileFunction,
  801. executeFunction));
  802. }
  803. void AsyncComputeExampleComponent::CreateForwardScope()
  804. {
  805. // Render all objects with shadows.
  806. const auto prepareFunction = [this](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData)
  807. {
  808. // Binds the scene image. Clears it to black.
  809. {
  810. RHI::ImageScopeAttachmentDescriptor descriptor;
  811. descriptor.m_attachmentId = m_sceneIds[m_currentSceneImageIndex];
  812. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Clear;
  813. descriptor.m_loadStoreAction.m_clearValue = RHI::ClearValue::CreateVector4Float(0.f, 0.f, 0.f, 0.f);
  814. frameGraph.UseColorAttachment(descriptor);
  815. }
  816. // Binds depth buffer from depth pass
  817. {
  818. frameGraph.UseShaderAttachment(
  819. RHI::ImageScopeAttachmentDescriptor(m_shadowAttachmentId), RHI::ScopeAttachmentAccess::Read,
  820. RHI::ScopeAttachmentStage::FragmentShader);
  821. }
  822. // Binds DepthStencil image
  823. {
  824. RHI::Ptr<RHI::Device> device = Utils::GetRHIDevice();
  825. RHI::ImageScopeAttachmentDescriptor dsDesc;
  826. dsDesc.m_attachmentId = m_forwardDepthStencilId;
  827. dsDesc.m_imageViewDescriptor.m_overrideFormat = device->GetNearestSupportedFormat(RHI::Format::D24_UNORM_S8_UINT, AZ::RHI::FormatCapabilities::DepthStencil);
  828. dsDesc.m_loadStoreAction.m_clearValue = RHI::ClearValue::CreateDepthStencil(0, 0);
  829. dsDesc.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Clear;
  830. dsDesc.m_loadStoreAction.m_loadActionStencil = RHI::AttachmentLoadAction::Clear;
  831. frameGraph.UseDepthStencilAttachment(
  832. dsDesc, RHI::ScopeAttachmentAccess::Write, RHI::ScopeAttachmentStage::EarlyFragmentTest | RHI::ScopeAttachmentStage::LateFragmentTest);
  833. }
  834. frameGraph.SetEstimatedItemCount(static_cast<uint32_t>(m_shaderResourceGroups[ForwardScope].size()));
  835. };
  836. const auto compileFunction = [this](const RHI::FrameGraphCompileContext& context, [[maybe_unused]] const ScopeData& scopeData)
  837. {
  838. const auto* imageView = context.GetImageView(m_shadowAttachmentId);
  839. for (const auto& shaderResourceGroup : m_shaderResourceGroups[ForwardScope])
  840. {
  841. shaderResourceGroup->SetImageView(m_shaderInputImageIndex, imageView);
  842. shaderResourceGroup->Compile();
  843. }
  844. };
  845. const auto executeFunction = [this](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  846. {
  847. RHI::CommandList* commandList = context.GetCommandList();
  848. // Bind ViewSrg
  849. commandList->SetShaderResourceGroupForDraw(*m_viewShaderResourceGroup->GetRHIShaderResourceGroup()->GetDeviceShaderResourceGroup(context.GetDeviceIndex()).get());
  850. // Set persistent viewport and scissor state.
  851. const auto& imageSize = m_sceneImages[m_currentSceneImageIndex]->GetDescriptor().m_size;
  852. RHI::Viewport viewport(0, static_cast<float>(imageSize.m_width), 0, static_cast<float>(imageSize.m_height));
  853. RHI::Scissor scissor(0, 0, static_cast<int32_t>(imageSize.m_width), static_cast<int32_t>(imageSize.m_height));
  854. commandList->SetViewports(&viewport, 1);
  855. commandList->SetScissors(&scissor, 1);
  856. for (uint32_t i = context.GetSubmitRange().m_startIndex; i < context.GetSubmitRange().m_endIndex; ++i)
  857. {
  858. if (i == 0)
  859. {
  860. // Terrain
  861. const RHI::DeviceShaderResourceGroup* shaderResourceGroups[] = {
  862. m_shaderResourceGroups[ForwardScope][0]
  863. ->GetRHIShaderResourceGroup()
  864. ->GetDeviceShaderResourceGroup(context.GetDeviceIndex())
  865. .get(),
  866. m_viewShaderResourceGroup->GetRHIShaderResourceGroup()->GetDeviceShaderResourceGroup(context.GetDeviceIndex()).get()
  867. };
  868. RHI::DeviceDrawItem drawItem;
  869. drawItem.m_geometryView = m_geometryViews[ForwardScope].GetDeviceGeometryView(context.GetDeviceIndex());
  870. drawItem.m_streamIndices = m_geometryViews[ForwardScope].GetFullStreamBufferIndices();
  871. drawItem.m_pipelineState = m_terrainPipelineStates[ForwardScope]->GetDevicePipelineState(context.GetDeviceIndex()).get();
  872. drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups));
  873. drawItem.m_shaderResourceGroups = shaderResourceGroups;
  874. commandList->Submit(drawItem, i);
  875. }
  876. else
  877. {
  878. // Model
  879. const RHI::DeviceShaderResourceGroup* shaderResourceGroups[] = {
  880. m_shaderResourceGroups[ForwardScope][i]
  881. ->GetRHIShaderResourceGroup()
  882. ->GetDeviceShaderResourceGroup(context.GetDeviceIndex())
  883. .get(),
  884. m_viewShaderResourceGroup->GetRHIShaderResourceGroup()->GetDeviceShaderResourceGroup(context.GetDeviceIndex()).get()
  885. };
  886. for (auto& mesh : m_model->GetLods()[0]->GetMeshes())
  887. {
  888. RHI::DeviceDrawItem drawItem;
  889. drawItem.m_geometryView = mesh.GetDeviceGeometryView(context.GetDeviceIndex());
  890. drawItem.m_streamIndices = m_modelStreamBufferIndices[ForwardScope];
  891. drawItem.m_pipelineState = m_modelPipelineStates[ForwardScope]->GetDevicePipelineState(context.GetDeviceIndex()).get();
  892. drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups));
  893. drawItem.m_shaderResourceGroups = shaderResourceGroups;
  894. commandList->Submit(drawItem, i);
  895. }
  896. }
  897. }
  898. };
  899. const RHI::ScopeId forwardScope("ForwardScope");
  900. m_scopeProducers.emplace_back(
  901. aznew RHI::ScopeProducerFunction<
  902. ScopeData,
  903. decltype(prepareFunction),
  904. decltype(compileFunction),
  905. decltype(executeFunction)>(
  906. forwardScope,
  907. ScopeData{},
  908. prepareFunction,
  909. compileFunction,
  910. executeFunction));
  911. }
  912. void AsyncComputeExampleComponent::CreateTonemappingScope()
  913. {
  914. const auto prepareFunction = [this](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData)
  915. {
  916. {
  917. RHI::ImageScopeAttachmentDescriptor inputOuputDescriptor;
  918. inputOuputDescriptor.m_attachmentId = m_sceneIds[m_previousSceneImageIndex];
  919. inputOuputDescriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Load;
  920. frameGraph.UseShaderAttachment(
  921. inputOuputDescriptor, RHI::ScopeAttachmentAccess::ReadWrite, RHI::ScopeAttachmentStage::ComputeShader);
  922. RHI::ImageScopeAttachmentDescriptor luminanceDescriptor;
  923. luminanceDescriptor.m_attachmentId = m_averageLuminanceAttachmentId;
  924. luminanceDescriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Load;
  925. frameGraph.UseShaderAttachment(
  926. luminanceDescriptor, RHI::ScopeAttachmentAccess::Read, RHI::ScopeAttachmentStage::ComputeShader);
  927. }
  928. frameGraph.SetEstimatedItemCount(1);
  929. frameGraph.SetHardwareQueueClass(m_asyncComputeEnabled ? RHI::HardwareQueueClass::Compute : RHI::HardwareQueueClass::Graphics);
  930. };
  931. const auto compileFunction = [this](const RHI::FrameGraphCompileContext& context, [[maybe_unused]] const ScopeData& scopeData)
  932. {
  933. const auto* hdrSceneView = context.GetImageView(m_sceneIds[m_previousSceneImageIndex]);
  934. const auto* luminanceView = context.GetImageView(m_averageLuminanceAttachmentId);
  935. for (const auto& shaderResourceGroup : m_shaderResourceGroups[TonemappingScope])
  936. {
  937. shaderResourceGroup->SetImageView(m_tonemappingShaderImageIndex, hdrSceneView);
  938. shaderResourceGroup->SetImageView(m_tonemappingLuminanceImageIndex, luminanceView);
  939. shaderResourceGroup->Compile();
  940. }
  941. };
  942. const auto executeFunction = [this](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  943. {
  944. RHI::CommandList* commandList = context.GetCommandList();
  945. RHI::DeviceDispatchItem dispatchItem;
  946. decltype(dispatchItem.m_shaderResourceGroups) shaderResourceGroups = { { m_shaderResourceGroups[TonemappingScope][0]->GetRHIShaderResourceGroup()->GetDeviceShaderResourceGroup(context.GetDeviceIndex()).get() } };
  947. RHI::DispatchDirect dispatchArgs;
  948. dispatchArgs.m_totalNumberOfThreadsX = m_outputWidth;
  949. dispatchArgs.m_threadsPerGroupX = aznumeric_cast<uint16_t>(m_numThreads[TonemappingScope].m_X);
  950. dispatchArgs.m_totalNumberOfThreadsY = m_outputHeight;
  951. dispatchArgs.m_threadsPerGroupY = aznumeric_cast<uint16_t>(m_numThreads[TonemappingScope].m_Y);
  952. dispatchArgs.m_totalNumberOfThreadsZ = 1;
  953. dispatchArgs.m_threadsPerGroupZ = aznumeric_cast<uint16_t>(m_numThreads[TonemappingScope].m_Z);
  954. AZ_Assert(dispatchArgs.m_threadsPerGroupX == dispatchArgs.m_threadsPerGroupY, "If the shader source changes, this logic should change too.");
  955. AZ_Assert(dispatchArgs.m_threadsPerGroupZ == 1, "If the shader source changes, this logic should change too.");
  956. dispatchItem.m_arguments = dispatchArgs;
  957. dispatchItem.m_pipelineState = m_tonemappingPipelineState->GetDevicePipelineState(context.GetDeviceIndex()).get();
  958. dispatchItem.m_shaderResourceGroupCount = 1;
  959. dispatchItem.m_shaderResourceGroups = shaderResourceGroups;
  960. commandList->Submit(dispatchItem);
  961. };
  962. const RHI::ScopeId tonemappingScope("TonemappingScope");
  963. m_scopeProducers.emplace_back(
  964. aznew RHI::ScopeProducerFunction<
  965. ScopeData,
  966. decltype(prepareFunction),
  967. decltype(compileFunction),
  968. decltype(executeFunction)>(
  969. tonemappingScope,
  970. ScopeData{},
  971. prepareFunction,
  972. compileFunction,
  973. executeFunction));
  974. }
  975. void AsyncComputeExampleComponent::CreateLuminanceMapScope()
  976. {
  977. // Create a luminance map (that will be reduce) from the scene image.
  978. const auto prepareFunction = [this](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData)
  979. {
  980. {
  981. RHI::ImageScopeAttachmentDescriptor luminanceMapDesc;
  982. luminanceMapDesc.m_attachmentId = m_luminanceMapAttachmentId;
  983. luminanceMapDesc.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::DontCare;
  984. frameGraph.UseColorAttachment(luminanceMapDesc);
  985. RHI::ImageScopeAttachmentDescriptor sceneDescriptor;
  986. sceneDescriptor.m_attachmentId = m_sceneIds[m_previousSceneImageIndex];
  987. sceneDescriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Load;
  988. frameGraph.UseShaderAttachment(sceneDescriptor, RHI::ScopeAttachmentAccess::Read, RHI::ScopeAttachmentStage::FragmentShader);
  989. }
  990. frameGraph.SetEstimatedItemCount(1);
  991. };
  992. const auto compileFunction = [this](const RHI::FrameGraphCompileContext& context, [[maybe_unused]] const ScopeData& scopeData)
  993. {
  994. const auto* imageView = context.GetImageView(m_sceneIds[m_previousSceneImageIndex]);
  995. for (const auto& shaderResourceGroup : m_shaderResourceGroups[LuminanceMapScope])
  996. {
  997. shaderResourceGroup->SetImageView(m_luminanceShaderInputImageIndex, imageView);
  998. shaderResourceGroup->Compile();
  999. }
  1000. };
  1001. const auto executeFunction = [this](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  1002. {
  1003. RHI::CommandList* commandList = context.GetCommandList();
  1004. RHI::Viewport viewport(0, static_cast<float>(AsyncCompute::s_luminanceMapSize), 0, static_cast<float>(AsyncCompute::s_luminanceMapSize));
  1005. RHI::Scissor scissor(0, 0, AsyncCompute::s_luminanceMapSize, AsyncCompute::s_luminanceMapSize);
  1006. commandList->SetViewports(&viewport, 1);
  1007. commandList->SetScissors(&scissor, 1);
  1008. {
  1009. // Quad
  1010. const RHI::DeviceShaderResourceGroup* shaderResourceGroups[] = { m_shaderResourceGroups[LuminanceMapScope][0]
  1011. ->GetRHIShaderResourceGroup()
  1012. ->GetDeviceShaderResourceGroup(
  1013. context.GetDeviceIndex())
  1014. .get() };
  1015. RHI::DeviceDrawItem drawItem;
  1016. drawItem.m_geometryView = m_geometryViews[LuminanceMapScope].GetDeviceGeometryView(context.GetDeviceIndex());
  1017. drawItem.m_streamIndices = m_geometryViews[LuminanceMapScope].GetFullStreamBufferIndices();
  1018. drawItem.m_pipelineState = m_luminancePipelineState->GetDevicePipelineState(context.GetDeviceIndex()).get();
  1019. drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups));
  1020. drawItem.m_shaderResourceGroups = shaderResourceGroups;
  1021. commandList->Submit(drawItem);
  1022. }
  1023. };
  1024. const RHI::ScopeId shadowScope("LuminanceMapScope");
  1025. m_scopeProducers.emplace_back(aznew RHI::ScopeProducerFunction<
  1026. ScopeData,
  1027. decltype(prepareFunction),
  1028. decltype(compileFunction),
  1029. decltype(executeFunction)>(
  1030. shadowScope,
  1031. ScopeData{},
  1032. prepareFunction,
  1033. compileFunction,
  1034. executeFunction));
  1035. }
  1036. void AsyncComputeExampleComponent::CreateLuminanceReduceScopes()
  1037. {
  1038. // We reduce the luminance map texture using multiple chained compute scopes
  1039. // until we get the 1x1 texture.
  1040. RHI::AttachmentId inputAttachmentId = m_luminanceMapAttachmentId;
  1041. // By design, the luminance reduce shader uses the same size for X and Y.
  1042. // If the shader code changes this logic should change too, otherwise taking numThreads.m_X is enough
  1043. const auto luminanceMapThreadGroupSize = m_numThreads[LuminanceReduceScope].m_X;
  1044. for(uint32_t inputSize = AsyncCompute::s_luminanceMapSize, i = 0; inputSize > 1; ++i)
  1045. {
  1046. uint32_t outputSize = AZStd::max(inputSize / (luminanceMapThreadGroupSize * 2), 1u);
  1047. AZStd::string outputAttachmentString = AZStd::string::format("LuminanceReduce%d", static_cast<int>(outputSize));
  1048. RHI::AttachmentId outputAttachmentId(outputAttachmentString);
  1049. const auto prepareFunction = [this, outputSize, inputAttachmentId, outputAttachmentId](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData)
  1050. {
  1051. {
  1052. const RHI::ImageDescriptor imageDescriptor = RHI::ImageDescriptor::Create2D(
  1053. RHI::ImageBindFlags::ShaderReadWrite | RHI::ImageBindFlags::Color,
  1054. outputSize,
  1055. outputSize,
  1056. RHI::Format::R32_FLOAT);
  1057. frameGraph.GetAttachmentDatabase().CreateTransientImage(RHI::TransientImageDescriptor(outputAttachmentId, imageDescriptor));
  1058. }
  1059. {
  1060. RHI::ImageScopeAttachmentDescriptor inputDescriptor;
  1061. inputDescriptor.m_attachmentId = inputAttachmentId;
  1062. inputDescriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Load;
  1063. frameGraph.UseShaderAttachment(
  1064. inputDescriptor, RHI::ScopeAttachmentAccess::Read, RHI::ScopeAttachmentStage::ComputeShader);
  1065. RHI::ImageScopeAttachmentDescriptor outputDescriptor;
  1066. outputDescriptor.m_attachmentId = outputAttachmentId;
  1067. outputDescriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::DontCare;
  1068. frameGraph.UseShaderAttachment(
  1069. outputDescriptor, RHI::ScopeAttachmentAccess::ReadWrite, RHI::ScopeAttachmentStage::ComputeShader);
  1070. }
  1071. frameGraph.SetEstimatedItemCount(1);
  1072. frameGraph.SetHardwareQueueClass(m_asyncComputeEnabled ? RHI::HardwareQueueClass::Compute : RHI::HardwareQueueClass::Graphics);
  1073. };
  1074. const auto compileFunction = [this, inputAttachmentId, outputAttachmentId, i](const RHI::FrameGraphCompileContext& context, [[maybe_unused]] const ScopeData& scopeData)
  1075. {
  1076. const auto* inputView = context.GetImageView(inputAttachmentId);
  1077. const auto* outputView = context.GetImageView(outputAttachmentId);
  1078. const auto& shaderResourceGroup = m_shaderResourceGroups[LuminanceReduceScope][i];
  1079. shaderResourceGroup->SetImageView(m_luminanceReduceShaderInputImageIndex, inputView);
  1080. shaderResourceGroup->SetImageView(m_luminanceReduceShaderOutputImageIndex, outputView);
  1081. shaderResourceGroup->Compile();
  1082. };
  1083. const auto executeFunction = [this, i, outputSize](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  1084. {
  1085. RHI::CommandList* commandList = context.GetCommandList();
  1086. RHI::DeviceDispatchItem dispatchItem;
  1087. decltype(dispatchItem.m_shaderResourceGroups) shaderResourceGroups = { { m_shaderResourceGroups[LuminanceReduceScope][i]->GetRHIShaderResourceGroup()->GetDeviceShaderResourceGroup(context.GetDeviceIndex()).get() } };
  1088. RHI::DispatchDirect dispatchArgs;
  1089. dispatchArgs.m_threadsPerGroupX = aznumeric_cast<uint16_t>(m_numThreads[LuminanceReduceScope].m_X);
  1090. dispatchArgs.m_threadsPerGroupY = aznumeric_cast<uint16_t>(m_numThreads[LuminanceReduceScope].m_Y);
  1091. dispatchArgs.m_threadsPerGroupZ = aznumeric_cast<uint16_t>(m_numThreads[LuminanceReduceScope].m_Z);
  1092. AZ_Assert(dispatchArgs.m_threadsPerGroupZ == 1, "If the shader source changes, this logic should change too.");
  1093. dispatchArgs.m_totalNumberOfThreadsX = outputSize * dispatchArgs.m_threadsPerGroupX;
  1094. dispatchArgs.m_totalNumberOfThreadsY = outputSize * dispatchArgs.m_threadsPerGroupY;
  1095. dispatchArgs.m_totalNumberOfThreadsZ = 1;
  1096. dispatchItem.m_arguments = dispatchArgs;
  1097. dispatchItem.m_pipelineState = m_luminanceReducePipelineState->GetDevicePipelineState(context.GetDeviceIndex()).get();
  1098. dispatchItem.m_shaderResourceGroupCount = 1;
  1099. dispatchItem.m_shaderResourceGroups = shaderResourceGroups;
  1100. commandList->Submit(dispatchItem);
  1101. };
  1102. AZStd::string scopeName = AZStd::string::format("LuminanceReduce%d", static_cast<int>(outputSize));
  1103. const RHI::ScopeId tonemappingScope(scopeName);
  1104. m_scopeProducers.emplace_back(
  1105. aznew RHI::ScopeProducerFunction<
  1106. ScopeData,
  1107. decltype(prepareFunction),
  1108. decltype(compileFunction),
  1109. decltype(executeFunction)>(
  1110. tonemappingScope,
  1111. ScopeData{},
  1112. prepareFunction,
  1113. compileFunction,
  1114. executeFunction));
  1115. inputAttachmentId = outputAttachmentId;
  1116. inputSize = outputSize;
  1117. }
  1118. }
  1119. bool AsyncComputeExampleComponent::ReadInConfig(const AZ::ComponentConfig* baseConfig)
  1120. {
  1121. auto config = azrtti_cast<const SampleComponentConfig*>(baseConfig);
  1122. AZ_Assert(config && config->IsValid(), "SampleComponentConfig required for sample component configuration.");
  1123. m_cameraEntityId = config->m_cameraEntityId;
  1124. return BasicRHIComponent::ReadInConfig(baseConfig);
  1125. }
  1126. }