AlphaToCoverageExampleComponent.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 <AzCore/Math/MatrixUtils.h>
  9. #include <Atom/RHI/CommandList.h>
  10. #include <Atom/RPI.Public/Shader/Shader.h>
  11. #include <Atom/RHI.Reflect/InputStreamLayoutBuilder.h>
  12. #include <Atom/RHI.Reflect/RenderAttachmentLayoutBuilder.h>
  13. #include <Atom/RPI.Reflect/Shader/ShaderAsset.h>
  14. #include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
  15. #include <AzCore/Serialization/SerializeContext.h>
  16. #include <AzCore/std/createdestroy.h>
  17. #include <RHI/AlphaToCoverageExampleComponent.h>
  18. #include <SampleComponentManager.h>
  19. #include <Utils/Utils.h>
  20. namespace AtomSampleViewer
  21. {
  22. namespace AlphaToCoverage
  23. {
  24. const char* SampleName = "AlphaToCoverageExample";
  25. const char* ShaderFilePath = "Shaders/RHI/TexturedSurface.azshader";
  26. const char* TextureFilePath = "TestData/Textures/Foliage_Leaves_0_BaseColor.dds.streamingimage";
  27. }
  28. void AlphaToCoverageExampleComponent::Reflect(AZ::ReflectContext* context)
  29. {
  30. if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  31. {
  32. serializeContext->Class<AlphaToCoverageExampleComponent, AZ::Component>()
  33. ->Version(0)
  34. ;
  35. }
  36. }
  37. AlphaToCoverageExampleComponent::AlphaToCoverageExampleComponent()
  38. {
  39. m_supportRHISamplePipeline = true;
  40. }
  41. void AlphaToCoverageExampleComponent::Activate()
  42. {
  43. using namespace AZ;
  44. RHI::Ptr<RHI::Device> device = Utils::GetRHIDevice();
  45. m_inputAssemblyBufferPool = aznew RHI::BufferPool();
  46. RHI::BufferPoolDescriptor bufferPoolDesc;
  47. bufferPoolDesc.m_bindFlags = RHI::BufferBindFlags::InputAssembly;
  48. bufferPoolDesc.m_heapMemoryLevel = RHI::HeapMemoryLevel::Device;
  49. m_inputAssemblyBufferPool->Init(bufferPoolDesc);
  50. m_depthImageAttachmentId = RHI::AttachmentId("A2C_Depth");
  51. m_multisamleDepthImageAttachmentId = RHI::AttachmentId("A2C_MSAA_Depth");
  52. m_resolveImageAttachmentId = RHI::AttachmentId("A2C_Resolve");
  53. CreateResources();
  54. CreateScopeResources(BlendType::SrcOver);
  55. CreateScopeResources(BlendType::AlphaTest);
  56. CreateScopeResources(BlendType::A2C_MSAA);
  57. // render A2C_MSAA first since it contains resolve
  58. CreateRectangleScopeProducer(BlendType::A2C_MSAA);
  59. CreateRectangleScopeProducer(BlendType::SrcOver);
  60. CreateRectangleScopeProducer(BlendType::AlphaTest);
  61. AZ::TickBus::Handler::BusConnect();
  62. AZ::RHI::RHISystemNotificationBus::Handler::BusConnect();
  63. }
  64. void AlphaToCoverageExampleComponent::Deactivate()
  65. {
  66. m_rectangleInputAssemblyBuffer = nullptr;
  67. m_inputAssemblyBufferPool = nullptr;
  68. m_pipelineStates.fill(nullptr);
  69. AZStd::for_each(m_shaderResourceGroups.begin(), m_shaderResourceGroups.end(), [](auto& srgs)
  70. {
  71. srgs.fill(nullptr);
  72. });
  73. AZ::RHI::RHISystemNotificationBus::Handler::BusDisconnect();
  74. m_windowContext = nullptr;
  75. m_scopeProducers.clear();
  76. }
  77. void AlphaToCoverageExampleComponent::OnTick(float deltaTime, AZ::ScriptTimePoint time)
  78. {
  79. AZ_UNUSED(time);
  80. m_time += deltaTime;
  81. }
  82. void AlphaToCoverageExampleComponent::OnFramePrepare(AZ::RHI::FrameGraphBuilder& frameGraphBuilder)
  83. {
  84. using namespace AZ;
  85. const float baseAngle = fmod(m_time * AZ::Constants::TwoPi / 16, AZ::Constants::TwoPi); // 1 rotate for 16 seconds.
  86. const auto rotate0 = AZ::Matrix4x4::CreateRotationY(-baseAngle);
  87. const auto rotate1 = AZ::Matrix4x4::CreateRotationY(-baseAngle + AZ::Constants::HalfPi);
  88. const float rectHeight = 2 * m_targetDepth * tanf(m_fieldOfView / 2);
  89. const float rectWidth = rectHeight / 3;
  90. const auto scale = AZ::Matrix4x4::CreateScale(AZ::Vector3(rectWidth / 2, rectHeight / 2, rectWidth / 2));
  91. for (int32_t blendIndex = 0; blendIndex < s_numBlendTypes; ++blendIndex)
  92. {
  93. const auto translate = AZ::Matrix4x4::CreateTranslation(AZ::Vector3((blendIndex - 1) * rectWidth, 0.f, 0.f));
  94. const auto worldMatrix0 = translate * rotate0 * scale;
  95. const auto worldMatrix1 = translate * rotate1 * scale;
  96. auto& srg0 = m_shaderResourceGroups[blendIndex][0];
  97. auto& srg1 = m_shaderResourceGroups[blendIndex][1];
  98. if(srg0)
  99. {
  100. srg0->SetConstant(m_worldMatrixIndex, worldMatrix0);
  101. srg0->Compile();
  102. }
  103. if (srg1)
  104. {
  105. srg1->SetConstant(m_worldMatrixIndex, worldMatrix1);
  106. srg1->Compile();
  107. }
  108. }
  109. BasicRHIComponent::OnFramePrepare(frameGraphBuilder);
  110. }
  111. void AlphaToCoverageExampleComponent::CreateResources()
  112. {
  113. using namespace AZ;
  114. RHI::InputStreamLayoutBuilder layoutBuilder;
  115. layoutBuilder.AddBuffer()->Channel("POSITION", RHI::Format::R32G32B32_FLOAT);
  116. layoutBuilder.AddBuffer()->Channel("UV", RHI::Format::R32G32_FLOAT);
  117. m_rectangleInputStreamLayout = layoutBuilder.End();
  118. RectangleBufferData bufferData;
  119. SetFullScreenRect(bufferData.m_positions.data(), bufferData.m_uvs.data(), bufferData.m_indices.data());
  120. m_rectangleInputAssemblyBuffer = aznew RHI::Buffer();
  121. RHI::ResultCode result = RHI::ResultCode::Success;
  122. RHI::BufferInitRequest request;
  123. request.m_buffer = m_rectangleInputAssemblyBuffer.get();
  124. request.m_descriptor = RHI::BufferDescriptor{RHI::BufferBindFlags::InputAssembly, sizeof(bufferData)};
  125. request.m_initialData = &bufferData;
  126. result = m_inputAssemblyBufferPool->InitBuffer(request);
  127. if (result != RHI::ResultCode::Success)
  128. {
  129. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to initialize position buffer with error code %d", result);
  130. return;
  131. }
  132. m_geometryView.SetDrawArguments(RHI::DrawIndexed(0, 6, 0));
  133. m_geometryView.SetIndexBufferView({
  134. *m_rectangleInputAssemblyBuffer,
  135. offsetof(RectangleBufferData, m_indices),
  136. sizeof(RectangleBufferData::m_indices),
  137. RHI::IndexFormat::Uint16
  138. });
  139. m_geometryView.AddStreamBufferView({
  140. *m_rectangleInputAssemblyBuffer,
  141. offsetof(RectangleBufferData, m_positions),
  142. sizeof(RectangleBufferData::m_positions),
  143. sizeof(VertexPosition)
  144. });
  145. m_geometryView.AddStreamBufferView({
  146. *m_rectangleInputAssemblyBuffer,
  147. offsetof(RectangleBufferData, m_uvs),
  148. sizeof(RectangleBufferData::m_uvs),
  149. sizeof(VertexUV)
  150. });
  151. RHI::ValidateStreamBufferViews(m_rectangleInputStreamLayout, m_geometryView, m_geometryView.GetFullStreamBufferIndices());
  152. m_shader = LoadShader(AlphaToCoverage::ShaderFilePath, AlphaToCoverage::SampleName);
  153. if (!m_shader)
  154. {
  155. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to load shader.");
  156. return;
  157. }
  158. for (uint32_t blendIndex = 0; blendIndex < s_numBlendTypes; ++blendIndex)
  159. {
  160. for (uint32_t rectIndex = 0; rectIndex < s_numRectangles; ++rectIndex)
  161. {
  162. m_shaderResourceGroups[blendIndex][rectIndex] = CreateShaderResourceGroup(m_shader, "TexturedSurfaceSrg", AlphaToCoverage::SampleName);
  163. }
  164. }
  165. m_worldMatrixIndex.Reset();
  166. m_viewProjectionMatrixIndex.Reset();
  167. m_alphaTestRefValueIndex.Reset();
  168. const AZ::Vector3 upVector{0.f, 1.f, 0.f};
  169. const AZ::Vector3 lookAtPos{0.f, 0.f, 0.f};
  170. const float zNear = 0.1f, zFar = 10.f;
  171. const float screenAspect = 1.f;
  172. const AZ::Vector3 eyePosition{0.f, 0.f, m_targetDepth};
  173. Matrix4x4 projectionMatrix;
  174. MakePerspectiveFovMatrixRH(projectionMatrix, m_fieldOfView, screenAspect, zNear, zFar);
  175. const auto viewMatrix = CreateViewMatrix(eyePosition, upVector, lookAtPos);
  176. const auto viewProjectionMatrix = projectionMatrix * viewMatrix;
  177. const Name albedoMapId{"m_albedoMap"};
  178. AZ::RHI::ShaderInputImageIndex albedMapImageIndex;
  179. FindShaderInputIndex(&albedMapImageIndex, m_shaderResourceGroups[0][0], albedoMapId, AlphaToCoverage::SampleName);
  180. auto textureIamge = LoadStreamingImage(AlphaToCoverage::TextureFilePath, AlphaToCoverage::SampleName);
  181. if (!textureIamge)
  182. {
  183. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to load texture image.");
  184. }
  185. constexpr float alphaTestRefValue = 0.1f;
  186. for (uint32_t blendIndex = 0; blendIndex < s_numBlendTypes; ++blendIndex)
  187. {
  188. float alphaRefValue = blendIndex == static_cast<int32_t>(BlendType::AlphaTest) ? alphaTestRefValue : 0.f;
  189. for (uint32_t rectIndex = 0; rectIndex < s_numRectangles; ++rectIndex)
  190. {
  191. if (!m_shaderResourceGroups[blendIndex][rectIndex]->SetImage(albedMapImageIndex, textureIamge))
  192. {
  193. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to set image into shader resource group.");
  194. return;
  195. }
  196. if (!m_shaderResourceGroups[blendIndex][rectIndex]->SetConstant(m_viewProjectionMatrixIndex, viewProjectionMatrix))
  197. {
  198. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to set view projection matrix into shader resource group.");
  199. return;
  200. }
  201. if (!m_shaderResourceGroups[blendIndex][rectIndex]->SetConstant(m_alphaTestRefValueIndex, alphaRefValue))
  202. {
  203. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to set alpha test reference value into shader resource group.");
  204. return;
  205. }
  206. }
  207. }
  208. }
  209. void AlphaToCoverageExampleComponent::CreateScopeResources(BlendType type)
  210. {
  211. using namespace AZ;
  212. if(!m_shader)
  213. {
  214. return;
  215. }
  216. const bool useDepth = (type == BlendType::AlphaTest) || (type == BlendType::A2C_MSAA);
  217. const bool useResolve = (type == BlendType::A2C_MSAA);
  218. AZ::RHI::PipelineStateDescriptorForDraw pipelineStateDescriptor;
  219. pipelineStateDescriptor.m_inputStreamLayout = m_rectangleInputStreamLayout;
  220. auto shaderVariant = m_shader->GetVariant(RPI::ShaderAsset::RootShaderVariantStableId);
  221. shaderVariant.ConfigurePipelineState(pipelineStateDescriptor);
  222. RHI::RenderAttachmentLayoutBuilder attachmentsBuilder;
  223. auto* subpass = attachmentsBuilder.AddSubpass();
  224. subpass->RenderTargetAttachment(m_outputFormat, useResolve);
  225. if (useDepth)
  226. {
  227. subpass->DepthStencilAttachment(s_depthFormat);
  228. }
  229. [[maybe_unused]] RHI::ResultCode result = attachmentsBuilder.End(pipelineStateDescriptor.m_renderAttachmentConfiguration.m_renderAttachmentLayout);
  230. AZ_Assert(result == RHI::ResultCode::Success, "Failed to create render attachment layout");
  231. pipelineStateDescriptor.m_renderStates.m_depthStencilState.m_depth.m_enable = useDepth;
  232. pipelineStateDescriptor.m_renderStates.m_depthStencilState.m_depth.m_func = RHI::ComparisonFunc::LessEqual;
  233. pipelineStateDescriptor.m_renderStates.m_multisampleState.m_samples = useResolve ? s_sampleCount : 1;
  234. pipelineStateDescriptor.m_renderStates.m_rasterState.m_cullMode = RHI::CullMode::None;
  235. pipelineStateDescriptor.m_renderStates.m_blendState.m_alphaToCoverageEnable = pipelineStateDescriptor.m_renderStates.m_multisampleState.m_samples > 1;
  236. RHI::TargetBlendState& targetBlendState = pipelineStateDescriptor.m_renderStates.m_blendState.m_targets[0];
  237. if (type == BlendType::SrcOver)
  238. {
  239. targetBlendState.m_enable = true;
  240. targetBlendState.m_blendSource = RHI::BlendFactor::AlphaSource;
  241. targetBlendState.m_blendDest = RHI::BlendFactor::AlphaSourceInverse;
  242. targetBlendState.m_blendOp = RHI::BlendOp::Add;
  243. targetBlendState.m_blendAlphaSource = RHI::BlendFactor::One;
  244. targetBlendState.m_blendAlphaDest = RHI::BlendFactor::AlphaSourceInverse;
  245. targetBlendState.m_blendAlphaOp = RHI::BlendOp::Add;
  246. }
  247. auto& pipeline = m_pipelineStates[static_cast<uint32_t>(type)];
  248. pipeline = m_shader->AcquirePipelineState(pipelineStateDescriptor);
  249. if (!pipeline)
  250. {
  251. AZ_Error(AlphaToCoverage::SampleName, false, "Failed to acquire default pipeline state for shader '%s'", AlphaToCoverage::ShaderFilePath);
  252. return;
  253. }
  254. }
  255. void AlphaToCoverageExampleComponent::CreateRectangleScopeProducer(BlendType type)
  256. {
  257. using namespace AZ;
  258. const uint32_t typeIndex = static_cast<uint32_t>(type);
  259. // Creates a scope for blend type.
  260. const auto prepareFunction = [this, type](RHI::FrameGraphInterface frameGraph, [[maybe_unused]] const ScopeData& scopeData)
  261. {
  262. // Bind the color attachment
  263. {
  264. RHI::ImageScopeAttachmentDescriptor descriptor;
  265. if (type == BlendType::A2C_MSAA)
  266. {
  267. auto colorImageDesc = RHI::ImageDescriptor::Create2D(
  268. RHI::ImageBindFlags::Color | RHI::ImageBindFlags::ShaderRead,
  269. m_outputWidth,
  270. m_outputHeight,
  271. m_outputFormat);
  272. colorImageDesc.m_multisampleState = RHI::MultisampleState(s_sampleCount, 0);
  273. frameGraph.GetAttachmentDatabase().CreateTransientImage(RHI::TransientImageDescriptor(m_resolveImageAttachmentId, colorImageDesc));
  274. descriptor.m_attachmentId = m_resolveImageAttachmentId;
  275. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Clear;
  276. descriptor.m_loadStoreAction.m_clearValue = RHI::ClearValue::CreateVector4Float(1.f, 1.f, 1.f, 0.f);
  277. descriptor.m_loadStoreAction.m_storeAction = RHI::AttachmentStoreAction::DontCare;
  278. }
  279. else
  280. {
  281. descriptor.m_attachmentId = m_outputAttachmentId;
  282. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Load;
  283. descriptor.m_loadStoreAction.m_storeAction = RHI::AttachmentStoreAction::Store;
  284. }
  285. frameGraph.UseColorAttachment(descriptor);
  286. }
  287. // Bind the depth attachment
  288. if (type == BlendType::AlphaTest || type == BlendType::A2C_MSAA)
  289. {
  290. RHI::AttachmentId depthAttachmentId = (type == BlendType::AlphaTest) ? m_depthImageAttachmentId : m_multisamleDepthImageAttachmentId;
  291. auto depthImageDesc = RHI::ImageDescriptor::Create2D(
  292. RHI::ImageBindFlags::DepthStencil,
  293. m_outputWidth,
  294. m_outputHeight,
  295. s_depthFormat);
  296. depthImageDesc.m_multisampleState.m_samples = (type == BlendType::A2C_MSAA) ? s_sampleCount : 1;
  297. frameGraph.GetAttachmentDatabase().CreateTransientImage(RHI::TransientImageDescriptor(depthAttachmentId, depthImageDesc));
  298. RHI::ImageScopeAttachmentDescriptor descriptor;
  299. descriptor.m_attachmentId = depthAttachmentId;
  300. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::Clear;
  301. descriptor.m_loadStoreAction.m_clearValue = RHI::ClearValue::CreateDepth(1.f);
  302. descriptor.m_loadStoreAction.m_storeAction = RHI::AttachmentStoreAction::Store;
  303. frameGraph.UseDepthStencilAttachment(
  304. descriptor, RHI::ScopeAttachmentAccess::ReadWrite,
  305. AZ::RHI::ScopeAttachmentStage::EarlyFragmentTest | AZ::RHI::ScopeAttachmentStage::LateFragmentTest);
  306. }
  307. // Bind the resolve attachment
  308. if (type == BlendType::A2C_MSAA)
  309. {
  310. RHI::ResolveScopeAttachmentDescriptor descriptor;
  311. descriptor.m_attachmentId = m_outputAttachmentId;
  312. descriptor.m_loadStoreAction.m_loadAction = RHI::AttachmentLoadAction::DontCare;
  313. descriptor.m_loadStoreAction.m_storeAction = RHI::AttachmentStoreAction::Store;
  314. descriptor.m_resolveAttachmentId = m_resolveImageAttachmentId;
  315. frameGraph.UseResolveAttachment(descriptor);
  316. }
  317. // We will submit two draw item.
  318. frameGraph.SetEstimatedItemCount(2);
  319. };
  320. RHI::EmptyCompileFunction<ScopeData> compileFunction;
  321. const auto executeFunction = [this, typeIndex](const RHI::FrameGraphExecuteContext& context, [[maybe_unused]] const ScopeData& scopeData)
  322. {
  323. RHI::CommandList* commandList = context.GetCommandList();
  324. // Set persistent viewport and scissor state.
  325. commandList->SetViewports(&m_viewport, 1);
  326. commandList->SetScissors(&m_scissor, 1);
  327. for (uint32_t rectIndex = context.GetSubmitRange().m_startIndex; rectIndex < context.GetSubmitRange().m_endIndex; ++rectIndex)
  328. {
  329. const RHI::DeviceShaderResourceGroup* shaderResourceGroups[] = { m_shaderResourceGroups[typeIndex][rectIndex]
  330. ->GetRHIShaderResourceGroup()
  331. ->GetDeviceShaderResourceGroup(
  332. context.GetDeviceIndex())
  333. .get() };
  334. RHI::DeviceDrawItem drawItem;
  335. drawItem.m_geometryView = m_geometryView.GetDeviceGeometryView(context.GetDeviceIndex());
  336. drawItem.m_streamIndices = m_geometryView.GetFullStreamBufferIndices();
  337. drawItem.m_pipelineState = m_pipelineStates[typeIndex]->GetDevicePipelineState(context.GetDeviceIndex()).get();
  338. drawItem.m_shaderResourceGroupCount = static_cast<uint8_t>(RHI::ArraySize(shaderResourceGroups));
  339. drawItem.m_shaderResourceGroups = shaderResourceGroups;
  340. // Submit the rectangle draw item.
  341. commandList->Submit(drawItem);
  342. }
  343. };
  344. const auto name = AZStd::string::format("BlendType_%d", typeIndex);
  345. const AZ::RHI::ScopeId rectangleScopeId(name);
  346. m_scopeProducers.emplace_back(
  347. aznew RHI::ScopeProducerFunction<
  348. ScopeData,
  349. decltype(prepareFunction),
  350. decltype(compileFunction),
  351. decltype(executeFunction)>(
  352. rectangleScopeId,
  353. ScopeData{},
  354. prepareFunction,
  355. compileFunction,
  356. executeFunction));
  357. }
  358. } // namespace AtomSampleViewer