ComputeExampleComponent.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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/RHI/CommandList.h>
  9. #include <Atom/RHI/Factory.h>
  10. #include <Atom/RHI/FrameScheduler.h>
  11. #include <Atom/RHI/ScopeProducerFunction.h>
  12. #include <Atom/RHI.Reflect/InputStreamLayoutBuilder.h>
  13. #include <Atom/RHI.Reflect/RenderAttachmentLayoutBuilder.h>
  14. #include <Atom/RPI.Reflect/Shader/ShaderAsset.h>
  15. #include <AzCore/Math/Vector2.h>
  16. #include <AzCore/Math/Vector4.h>
  17. #include <AzCore/Serialization/SerializeContext.h>
  18. #include <RHI/ComputeExampleComponent.h>
  19. #include <SampleComponentConfig.h>
  20. #include <SampleComponentManager.h>
  21. #include <Utils/Utils.h>
  22. namespace AtomSampleViewer
  23. {
  24. const char* ComputeExampleComponent::s_computeExampleName = "ComputeExample";
  25. namespace ShaderInputs
  26. {
  27. static const char* const ShaderInputDimension{ "dimension" };
  28. static const char* const ShaderInputSeed{ "seed" };
  29. }
  30. void ComputeExampleComponent::Reflect(AZ::ReflectContext* context)
  31. {
  32. if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  33. {
  34. serializeContext->Class<ComputeExampleComponent, AZ::Component>()->Version(0);
  35. }
  36. }
  37. ComputeExampleComponent::ComputeExampleComponent()
  38. {
  39. m_supportRHISamplePipeline = true;
  40. }
  41. void ComputeExampleComponent::OnFramePrepare(AZ::RHI::FrameGraphBuilder& frameGraphBuilder)
  42. {
  43. m_dispatchSRGs[0]->SetConstant(m_dispatchSeedConstantIndex, AZ::Vector2(cosf(m_time), sin(m_time)));
  44. m_dispatchSRGs[0]->Compile();
  45. BasicRHIComponent::OnFramePrepare(frameGraphBuilder);
  46. }
  47. void ComputeExampleComponent::OnTick(float deltaTime, AZ::ScriptTimePoint time)
  48. {
  49. AZ_UNUSED(time);
  50. m_time += deltaTime;
  51. }
  52. void ComputeExampleComponent::Activate()
  53. {
  54. CreateInputAssemblyBuffersAndViews();
  55. CreateComputeBuffer();
  56. LoadComputeShader();
  57. LoadRasterShader();
  58. CreateComputeScope();
  59. CreateRasterScope();
  60. AZ::TickBus::Handler::BusConnect();
  61. AZ::RHI::RHISystemNotificationBus::Handler::BusConnect();
  62. }
  63. void ComputeExampleComponent::Deactivate()
  64. {
  65. m_inputAssemblyBuffer = nullptr;
  66. m_inputAssemblyBufferPool = nullptr;
  67. m_dispatchPipelineState = nullptr;
  68. m_drawPipelineState = nullptr;
  69. m_dispatchSRGs.fill(nullptr);
  70. m_drawSRGs.fill(nullptr);
  71. m_computeBufferPool = nullptr;
  72. m_computeBuffer = nullptr;
  73. m_computeBufferView = nullptr;
  74. m_scopeProducers.clear();
  75. m_windowContext = nullptr;
  76. AZ::TickBus::Handler::BusDisconnect();
  77. AZ::RHI::RHISystemNotificationBus::Handler::BusDisconnect();
  78. }
  79. void ComputeExampleComponent::CreateInputAssemblyBuffersAndViews()
  80. {
  81. using namespace AZ;
  82. RHI::Ptr<RHI::Device> device = Utils::GetRHIDevice();
  83. m_inputAssemblyBufferPool = aznew RHI::BufferPool();
  84. RHI::BufferPoolDescriptor bufferPoolDesc;
  85. bufferPoolDesc.m_bindFlags = RHI::BufferBindFlags::InputAssembly;
  86. bufferPoolDesc.m_heapMemoryLevel = RHI::HeapMemoryLevel::Device;
  87. m_inputAssemblyBufferPool->Init(RHI::MultiDevice::AllDevices, bufferPoolDesc);
  88. BufferData bufferData;
  89. SetFullScreenRect(bufferData.m_positions.data(), bufferData.m_uvs.data(), bufferData.m_indices.data());
  90. m_inputAssemblyBuffer = aznew RHI::Buffer();
  91. RHI::BufferInitRequest request;
  92. request.m_buffer = m_inputAssemblyBuffer.get();
  93. request.m_descriptor = RHI::BufferDescriptor{ RHI::BufferBindFlags::InputAssembly, sizeof(bufferData) };
  94. request.m_initialData = &bufferData;
  95. m_inputAssemblyBufferPool->InitBuffer(request);
  96. m_streamBufferViews[0] =
  97. {
  98. *m_inputAssemblyBuffer,
  99. offsetof(BufferData, m_positions),
  100. sizeof(BufferData::m_positions),
  101. sizeof(VertexPosition)
  102. };
  103. m_streamBufferViews[1] =
  104. {
  105. *m_inputAssemblyBuffer,
  106. offsetof(BufferData, m_uvs),
  107. sizeof(BufferData::m_uvs),
  108. sizeof(VertexUV)
  109. };
  110. m_indexBufferView =
  111. {
  112. *m_inputAssemblyBuffer,
  113. offsetof(BufferData, m_indices),
  114. sizeof(BufferData::m_indices),
  115. RHI::IndexFormat::Uint16
  116. };
  117. RHI::InputStreamLayoutBuilder layoutBuilder;
  118. layoutBuilder.AddBuffer()->Channel("POSITION", RHI::Format::R32G32B32_FLOAT);
  119. layoutBuilder.AddBuffer()->Channel("UV", RHI::Format::R32G32_FLOAT);
  120. m_inputStreamLayout = layoutBuilder.End();
  121. RHI::ValidateStreamBufferViews(m_inputStreamLayout, m_streamBufferViews);
  122. }
  123. void ComputeExampleComponent::LoadComputeShader()
  124. {
  125. using namespace AZ;
  126. const char* shaderFilePath = "Shaders/RHI/ComputeDispatch.azshader";
  127. const auto shader = LoadShader(shaderFilePath, s_computeExampleName);
  128. if (shader == nullptr)
  129. return;
  130. RHI::PipelineStateDescriptorForDispatch pipelineDesc;
  131. shader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId).ConfigurePipelineState(pipelineDesc);
  132. const auto& numThreads = shader->GetAsset()->GetAttribute(RHI::ShaderStage::Compute, Name("numthreads"));
  133. if (numThreads)
  134. {
  135. const RHI::ShaderStageAttributeArguments& args = *numThreads;
  136. m_numThreadsX = args[0].type() == azrtti_typeid<int>() ? AZStd::any_cast<int>(args[0]) : m_numThreadsX;
  137. m_numThreadsY = args[1].type() == azrtti_typeid<int>() ? AZStd::any_cast<int>(args[1]) : m_numThreadsY;
  138. m_numThreadsZ = args[2].type() == azrtti_typeid<int>() ? AZStd::any_cast<int>(args[2]) : m_numThreadsZ;
  139. }
  140. else
  141. {
  142. AZ_Error(s_computeExampleName, false, "Did not find expected numthreads attribute");
  143. }
  144. m_dispatchPipelineState = shader->AcquirePipelineState(pipelineDesc);
  145. if (!m_dispatchPipelineState)
  146. {
  147. AZ_Error(s_computeExampleName, false, "Failed to acquire default pipeline state for shader '%s'", shaderFilePath);
  148. return;
  149. }
  150. m_dispatchSRGs[0] = CreateShaderResourceGroup(shader, "ConstantSrg", s_computeExampleName);
  151. m_dispatchSRGs[1] = CreateShaderResourceGroup(shader, "BufferSrg", s_computeExampleName);
  152. FindShaderInputIndex(&m_dispatchDimensionConstantIndex, m_dispatchSRGs[0], AZ::Name{ShaderInputs::ShaderInputDimension}, s_computeExampleName);
  153. FindShaderInputIndex(&m_dispatchSeedConstantIndex, m_dispatchSRGs[0], AZ::Name{ShaderInputs::ShaderInputSeed}, s_computeExampleName);
  154. // This SRG will be compiled during the OnFramePrepare
  155. m_dispatchSRGs[0]->SetConstant(m_dispatchDimensionConstantIndex, AZ::Vector2(static_cast<float>(m_bufferWidth), static_cast<float>(m_bufferHeight)));
  156. }
  157. void ComputeExampleComponent::LoadRasterShader()
  158. {
  159. using namespace AZ;
  160. const char* shaderFilePath = "Shaders/RHI/ComputeDraw.azshader";
  161. auto shader = LoadShader(shaderFilePath, s_computeExampleName);
  162. if (shader == nullptr)
  163. return;
  164. RHI::PipelineStateDescriptorForDraw pipelineDesc;
  165. shader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId).ConfigurePipelineState(pipelineDesc);
  166. pipelineDesc.m_inputStreamLayout = m_inputStreamLayout;
  167. RHI::RenderAttachmentLayoutBuilder attachmentsBuilder;
  168. attachmentsBuilder.AddSubpass()
  169. ->RenderTargetAttachment(m_outputFormat);
  170. [[maybe_unused]] RHI::ResultCode result = attachmentsBuilder.End(pipelineDesc.m_renderAttachmentConfiguration.m_renderAttachmentLayout);
  171. AZ_Assert(result == RHI::ResultCode::Success, "Failed to create render attachment layout");
  172. m_drawPipelineState = shader->AcquirePipelineState(pipelineDesc);
  173. if (!m_drawPipelineState)
  174. {
  175. AZ_Error(s_computeExampleName, false, "Failed to acquire default pipeline state for shader '%s'", shaderFilePath);
  176. return;
  177. }
  178. m_drawSRGs[0] = CreateShaderResourceGroup(shader, "ConstantSrg", s_computeExampleName);
  179. m_drawSRGs[1] = CreateShaderResourceGroup(shader, "BufferSrg", s_computeExampleName);
  180. FindShaderInputIndex(&m_drawDimensionConstantIndex, m_drawSRGs[0], AZ::Name{ShaderInputs::ShaderInputDimension}, s_computeExampleName);
  181. m_drawSRGs[0]->SetConstant(m_drawDimensionConstantIndex, AZ::Vector2(static_cast<float>(m_bufferWidth), static_cast<float>(m_bufferHeight)));
  182. m_drawSRGs[0]->Compile();
  183. }
  184. void ComputeExampleComponent::CreateComputeBuffer()
  185. {
  186. using namespace AZ;
  187. RHI::Ptr<RHI::Device> device = Utils::GetRHIDevice();
  188. [[maybe_unused]] RHI::ResultCode result = RHI::ResultCode::Success;
  189. m_computeBufferPool = aznew RHI::BufferPool();
  190. RHI::BufferPoolDescriptor bufferPoolDesc;
  191. bufferPoolDesc.m_bindFlags = RHI::BufferBindFlags::ShaderReadWrite;
  192. bufferPoolDesc.m_heapMemoryLevel = RHI::HeapMemoryLevel::Device;
  193. bufferPoolDesc.m_hostMemoryAccess = RHI::HostMemoryAccess::Write;
  194. result = m_computeBufferPool->Init(RHI::MultiDevice::AllDevices, bufferPoolDesc);
  195. AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialized compute buffer pool");
  196. m_computeBuffer = aznew RHI::Buffer();
  197. uint32_t bufferSize = m_bufferWidth * m_bufferHeight * RHI::GetFormatSize(RHI::Format::R32G32B32A32_FLOAT);
  198. RHI::BufferInitRequest request;
  199. request.m_buffer = m_computeBuffer.get();
  200. request.m_descriptor = RHI::BufferDescriptor{ RHI::BufferBindFlags::ShaderReadWrite, bufferSize };
  201. result = m_computeBufferPool->InitBuffer(request);
  202. AZ_Assert(result == RHI::ResultCode::Success, "Failed to initialized compute buffer");
  203. m_bufferViewDescriptor = RHI::BufferViewDescriptor::CreateStructured(0, m_bufferWidth * m_bufferHeight, RHI::GetFormatSize(RHI::Format::R32G32B32A32_FLOAT));
  204. m_computeBufferView = m_computeBuffer->BuildBufferView(m_bufferViewDescriptor);
  205. if(!m_computeBufferView.get())
  206. {
  207. AZ_Assert(false, "Failed to initialized compute buffer view");
  208. }
  209. AZ_Assert(m_computeBufferView->GetDeviceBufferView(RHI::MultiDevice::DefaultDeviceIndex)->IsFullView(), "compute Buffer View initialization failed to cover in full the Compute Buffer");
  210. }
  211. void ComputeExampleComponent::CreateComputeScope()
  212. {
  213. using namespace AZ;
  214. struct ScopeData
  215. {
  216. //UserDataParam - Empty for this samples
  217. };
  218. const auto prepareFunction = [this](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData)
  219. {
  220. // attach compute buffer
  221. {
  222. [[maybe_unused]] RHI::ResultCode result = frameGraph.GetAttachmentDatabase().ImportBuffer(m_bufferAttachmentId, m_computeBuffer);
  223. AZ_Error(s_computeExampleName, result == RHI::ResultCode::Success, "Failed to import compute buffer with error %d", result);
  224. RHI::BufferScopeAttachmentDescriptor desc;
  225. desc.m_attachmentId = m_bufferAttachmentId;
  226. desc.m_bufferViewDescriptor = m_bufferViewDescriptor;
  227. desc.m_loadStoreAction.m_clearValue = AZ::RHI::ClearValue::CreateVector4Float(0.0f, 0.0f, 0.0f, 0.0f);
  228. frameGraph.UseShaderAttachment(desc, RHI::ScopeAttachmentAccess::ReadWrite, RHI::ScopeAttachmentStage::ComputeShader);
  229. const Name computeBufferId{ "m_computeBuffer" };
  230. RHI::ShaderInputBufferIndex computeBufferIndex = m_dispatchSRGs[1]->FindShaderInputBufferIndex(computeBufferId);
  231. AZ_Error(s_computeExampleName, computeBufferIndex.IsValid(), "Failed to find shader input buffer %s.", computeBufferId.GetCStr());
  232. m_dispatchSRGs[1]->SetBufferView(computeBufferIndex, m_computeBufferView.get());
  233. m_dispatchSRGs[1]->Compile();
  234. }
  235. frameGraph.SetEstimatedItemCount(1);
  236. };
  237. RHI::EmptyCompileFunction<ScopeData> compileFunction;
  238. const auto executeFunction = [this](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  239. {
  240. RHI::CommandList* commandList = context.GetCommandList();
  241. // Set persistent viewport and scissor state.
  242. commandList->SetViewports(&m_viewport, 1);
  243. commandList->SetScissors(&m_scissor, 1);
  244. AZStd::array<const RHI::DeviceShaderResourceGroup*, 8> shaderResourceGroups;
  245. shaderResourceGroups[0] = m_dispatchSRGs[0]->GetRHIShaderResourceGroup()->GetDeviceShaderResourceGroup(context.GetDeviceIndex()).get();
  246. shaderResourceGroups[1] = m_dispatchSRGs[1]->GetRHIShaderResourceGroup()->GetDeviceShaderResourceGroup(context.GetDeviceIndex()).get();
  247. RHI::DeviceDispatchItem dispatchItem;
  248. RHI::DispatchDirect dispatchArgs;
  249. dispatchArgs.m_threadsPerGroupX = aznumeric_cast<uint16_t>(m_numThreadsX);
  250. dispatchArgs.m_threadsPerGroupY = aznumeric_cast<uint16_t>(m_numThreadsY);
  251. dispatchArgs.m_threadsPerGroupZ = aznumeric_cast<uint16_t>(m_numThreadsZ);
  252. dispatchArgs.m_totalNumberOfThreadsX = m_bufferWidth;
  253. dispatchArgs.m_totalNumberOfThreadsY = m_bufferHeight;
  254. dispatchArgs.m_totalNumberOfThreadsZ = 1;
  255. dispatchItem.m_arguments = dispatchArgs;
  256. dispatchItem.m_pipelineState = m_dispatchPipelineState->GetDevicePipelineState(context.GetDeviceIndex()).get();
  257. dispatchItem.m_shaderResourceGroupCount = 2;
  258. dispatchItem.m_shaderResourceGroups = shaderResourceGroups;
  259. commandList->Submit(dispatchItem);
  260. };
  261. m_scopeProducers.emplace_back(
  262. aznew RHI::ScopeProducerFunction<
  263. ScopeData,
  264. decltype(prepareFunction),
  265. decltype(compileFunction),
  266. decltype(executeFunction)>(
  267. RHI::ScopeId{"Compute"},
  268. ScopeData{},
  269. prepareFunction,
  270. compileFunction,
  271. executeFunction));
  272. }
  273. void ComputeExampleComponent::CreateRasterScope()
  274. {
  275. using namespace AZ;
  276. struct ScopeData
  277. {
  278. RPI::WindowContext* m_windowContext;
  279. };
  280. const auto prepareFunction = [this](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] ScopeData& scopeData)
  281. {
  282. // Binds the swap chain as a color attachment. Clears it to white.
  283. {
  284. RHI::ImageScopeAttachmentDescriptor descriptor;
  285. descriptor.m_attachmentId = m_outputAttachmentId;
  286. descriptor.m_loadStoreAction.m_clearValue = RHI::ClearValue::CreateVector4Float(1.0f, 1.0, 1.0, 0.0);
  287. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Clear;
  288. frameGraph.UseColorAttachment(descriptor);
  289. }
  290. // attach compute buffer
  291. {
  292. RHI::BufferScopeAttachmentDescriptor desc;
  293. desc.m_attachmentId = m_bufferAttachmentId;
  294. desc.m_bufferViewDescriptor = m_bufferViewDescriptor;
  295. desc.m_loadStoreAction.m_clearValue = AZ::RHI::ClearValue::CreateVector4Float(0.0f, 0.0f, 0.0f, 0.0f);
  296. frameGraph.UseShaderAttachment(desc, RHI::ScopeAttachmentAccess::ReadWrite, RHI::ScopeAttachmentStage::FragmentShader);
  297. const Name computeBufferId{ "m_computeBuffer" };
  298. RHI::ShaderInputBufferIndex computeBufferIndex = m_drawSRGs[1]->FindShaderInputBufferIndex(computeBufferId);
  299. AZ_Error(s_computeExampleName, computeBufferIndex.IsValid(), "Failed to find shader input buffer %s.", computeBufferId.GetCStr());
  300. m_drawSRGs[1]->SetBufferView(computeBufferIndex, m_computeBufferView.get());
  301. m_drawSRGs[1]->Compile();
  302. }
  303. // We will submit a single draw item.
  304. frameGraph.SetEstimatedItemCount(1);
  305. };
  306. RHI::EmptyCompileFunction<ScopeData> compileFunction;
  307. const auto executeFunction = [this](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  308. {
  309. RHI::CommandList* commandList = context.GetCommandList();
  310. // Set persistent viewport and scissor state.
  311. commandList->SetViewports(&m_viewport, 1);
  312. commandList->SetScissors(&m_scissor, 1);
  313. RHI::DrawIndexed drawIndexed;
  314. drawIndexed.m_indexCount = 6;
  315. drawIndexed.m_instanceCount = 1;
  316. const RHI::DeviceShaderResourceGroup* shaderResourceGroups[] = {
  317. m_drawSRGs[0]->GetRHIShaderResourceGroup()->GetDeviceShaderResourceGroup(context.GetDeviceIndex()).get(),
  318. m_drawSRGs[1]->GetRHIShaderResourceGroup()->GetDeviceShaderResourceGroup(context.GetDeviceIndex()).get()
  319. };
  320. RHI::DeviceDrawItem drawItem;
  321. drawItem.m_arguments = drawIndexed;
  322. drawItem.m_pipelineState = m_drawPipelineState->GetDevicePipelineState(context.GetDeviceIndex()).get();
  323. auto deviceIndexBufferView{m_indexBufferView.GetDeviceIndexBufferView(context.GetDeviceIndex())};
  324. drawItem.m_indexBufferView = &deviceIndexBufferView;
  325. drawItem.m_streamBufferViewCount = static_cast<uint8_t>(m_streamBufferViews.size());
  326. AZStd::array<AZ::RHI::DeviceStreamBufferView, 2> deviceStreamBufferViews{
  327. m_streamBufferViews[0].GetDeviceStreamBufferView(context.GetDeviceIndex()),
  328. m_streamBufferViews[1].GetDeviceStreamBufferView(context.GetDeviceIndex())
  329. };
  330. drawItem.m_streamBufferViews = deviceStreamBufferViews.data();
  331. drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups));
  332. drawItem.m_shaderResourceGroups = shaderResourceGroups;
  333. // Submit the triangle draw item.
  334. commandList->Submit(drawItem);
  335. };
  336. m_scopeProducers.emplace_back(
  337. aznew RHI::ScopeProducerFunction<
  338. ScopeData,
  339. decltype(prepareFunction),
  340. decltype(compileFunction),
  341. decltype(executeFunction)>(
  342. RHI::ScopeId{"Raster"},
  343. ScopeData{},
  344. prepareFunction,
  345. compileFunction,
  346. executeFunction));
  347. }
  348. }