StreamBufferViewsBuilder.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 "StreamBufferViewsBuilder.h"
  9. namespace AZ
  10. {
  11. namespace Render
  12. {
  13. #define DEBUG_LOG_BUFFERVIEWS (0)
  14. class ShaderStreamBufferViews final : public ShaderStreamBufferViewsInterface
  15. {
  16. public:
  17. AZ_RTTI(
  18. AZ::Render::ShaderStreamBufferViews,
  19. "{35C88638-C8F8-4124-B7AD-269ED7BFE6BE}",
  20. AZ::Render::ShaderStreamBufferViewsInterface);
  21. ShaderStreamBufferViews() = delete;
  22. explicit ShaderStreamBufferViews(uint32_t lodIndex, uint32_t meshIndex)
  23. : m_lodIndex(lodIndex), m_meshIndex(meshIndex)
  24. {
  25. }
  26. ~ShaderStreamBufferViews() = default;
  27. ////////////////////////////////////////////////////////////
  28. // ShaderStreamBufferViewsInterface overrides Start...
  29. const AZ::RHI::Ptr<AZ::RHI::BufferView>& GetVertexIndicesBufferView() const override
  30. {
  31. return m_vertexIndicesBufferView;
  32. }
  33. const AZ::RHI::IndexBufferView& GetVertexIndicesIndexBufferView() const override
  34. {
  35. return m_vertexIndicesIndexBufferView;
  36. }
  37. uint32_t GetVertexIndicesBindlessReadIndex(int deviceIndex) const override
  38. {
  39. if (!m_vertexIndicesBufferView)
  40. {
  41. return AZ::RHI::DeviceBufferView::InvalidBindlessIndex;
  42. }
  43. uint32_t readIndex = AZ::RHI::DeviceBufferView::InvalidBindlessIndex;
  44. m_vertexIndicesBufferView->GetBindlessIndices(deviceIndex, &readIndex);
  45. return readIndex;
  46. }
  47. AZStd::unordered_map<int, uint32_t> GetVertexIndicesBindlessReadIndex() const override
  48. {
  49. if (!m_vertexIndicesBufferView)
  50. {
  51. AZStd::unordered_map<int, uint32_t> empty;
  52. return empty;
  53. }
  54. return m_vertexIndicesBufferView->GetBindlessReadIndex();
  55. }
  56. const AZ::RHI::Ptr<AZ::RHI::BufferView>& GetBufferView(const AZ::RHI::ShaderSemantic& shaderSemantic) const override
  57. {
  58. static AZ::RHI::Ptr<AZ::RHI::BufferView> InvalidBufferView;
  59. if (!m_bufferViewsBySemantic.contains(shaderSemantic))
  60. {
  61. return InvalidBufferView;
  62. }
  63. return m_bufferViewsBySemantic.at(shaderSemantic);
  64. }
  65. const AZ::RHI::Ptr<AZ::RHI::BufferView>& GetBufferView(const char* semanticName) const override
  66. {
  67. return GetBufferView(AZ::RHI::ShaderSemantic::Parse(semanticName));
  68. }
  69. const AZ::RHI::StreamBufferView* GetStreamBufferView(const AZ::RHI::ShaderSemantic& shaderSemantic) const override
  70. {
  71. if (!m_streamBufferViewsBySemantic.contains(shaderSemantic))
  72. {
  73. return nullptr;
  74. }
  75. return &(m_streamBufferViewsBySemantic.at(shaderSemantic));
  76. }
  77. const AZ::RHI::StreamBufferView* GetStreamBufferView(const char* semanticName) const override
  78. {
  79. return GetStreamBufferView(AZ::RHI::ShaderSemantic::Parse(semanticName));
  80. }
  81. uint32_t GetStreamBufferViewBindlessReadIndex(int deviceIndex, const AZ::RHI::ShaderSemantic& shaderSemantic) const override
  82. {
  83. if (!m_bufferViewsBySemantic.contains(shaderSemantic))
  84. {
  85. return AZ::RHI::DeviceBufferView::InvalidBindlessIndex;
  86. }
  87. uint32_t readIndex = AZ::RHI::DeviceBufferView::InvalidBindlessIndex;
  88. m_bufferViewsBySemantic.at(shaderSemantic)->GetBindlessIndices(deviceIndex, &readIndex);
  89. return readIndex;
  90. }
  91. uint32_t GetStreamBufferViewBindlessReadIndex(int deviceIndex, const char* semanticName) const override
  92. {
  93. return GetStreamBufferViewBindlessReadIndex(deviceIndex, AZ::RHI::ShaderSemantic::Parse(semanticName));
  94. }
  95. AZStd::unordered_map<int, uint32_t> GetStreamBufferViewBindlessReadIndex(
  96. const AZ::RHI::ShaderSemantic& shaderSemantic) const override
  97. {
  98. if (!m_bufferViewsBySemantic.contains(shaderSemantic))
  99. {
  100. AZStd::unordered_map<int, uint32_t> empty;
  101. return empty;
  102. }
  103. return m_bufferViewsBySemantic.at(shaderSemantic)->GetBindlessReadIndex();
  104. }
  105. AZStd::unordered_map<int, uint32_t> GetStreamBufferViewBindlessReadIndex(const char* semanticName) const override
  106. {
  107. return GetStreamBufferViewBindlessReadIndex(AZ::RHI::ShaderSemantic::Parse(semanticName));
  108. }
  109. uint32_t GetLodIndex() const override
  110. {
  111. return m_lodIndex;
  112. }
  113. uint32_t GetMeshIndex() const override
  114. {
  115. return m_meshIndex;
  116. }
  117. // ShaderStreamBufferViewsInterface overrides End...
  118. ////////////////////////////////////////////////////////////
  119. private:
  120. friend class ShaderStreamBufferViewsBuilder;
  121. uint32_t m_lodIndex; //Kept for informational purposes.
  122. uint32_t m_meshIndex; //Kept for informational purposes.
  123. // This represents a View to the buffer that contains all the vertex indices of a single mesh
  124. // in GPU memory. If the BindlessSrg is enabled, which typically is the case,
  125. // you can query its BindlessSrg Read index.
  126. // REMARK: Typically this BufferView will be the same for all subMeshes because
  127. // we always map the whole range as defined in its AZ::RHI::Buffer, and this is done
  128. // because most RHI backends require the Offset of a bufferView to be aligned to 16 bytes, which
  129. // is not often the case for a SubMesh. The workaround is to map the whole buffer with offset 0,
  130. // and the developer must feed the offset as a shader constant. The actual offset can be queried
  131. // from @m_vertexIndicesIndexBufferView.
  132. AZ::RHI::Ptr<AZ::RHI::BufferView> m_vertexIndicesBufferView;
  133. // This works as a descriptor of Offset, number of bytes, etc, which is necessary
  134. // when (@m_meshIndex > 0) because the Offset within @m_vertexIndicesBufferView is different than zero.
  135. // Typically the offset returned by @m_vertexIndicesIndexBufferView.GetOffset() must be loaded as a shader constant
  136. // so the shader code knows how to read the indices at the correct offset from a ByteAddressBuffer.
  137. AZ::RHI::IndexBufferView m_vertexIndicesIndexBufferView;
  138. // This is the main dictionary of BufferViews which typically will be the same across all sub meshes.
  139. // The reason it is the same across all sub meshes is because most RHI backends require the Offset
  140. // of a bufferView to be aligned to 16 bytes, which is not often the case for a SubMesh.
  141. // The workaround is to map the whole buffer with offset 0,
  142. // and the developer must feed the offset as a shader constant. The actual offset can be queried
  143. // from @m_streamBufferViewsBySemantic.
  144. using BufferViewsBySemantic = AZStd::unordered_map<AZ::RHI::ShaderSemantic, AZ::RHI::Ptr<AZ::RHI::BufferView>>;
  145. BufferViewsBySemantic m_bufferViewsBySemantic;
  146. // This works as a descriptor of Offset, number of bytes, etc, which is necessary
  147. // when (@m_meshIndex > 0) because the Offset within @m_bufferViewsBySemantic is different than zero.
  148. // Typically the offset returned by @m_streamBufferViewsBySemantic.GetOffset() must be loaded as a shader constant
  149. // so the shader code knows how to read the indices at the correct offset from a ByteAddressBuffer.
  150. using StreamBufferViewsBySemantic = AZStd::unordered_map<AZ::RHI::ShaderSemantic, AZ::RHI::StreamBufferView>;
  151. StreamBufferViewsBySemantic m_streamBufferViewsBySemantic;
  152. }; // class ShaderStreamBufferViews
  153. ShaderStreamBufferViewsBuilder::ShaderStreamBufferViewsBuilder(const AZ::Render::MeshFeatureProcessorInterface::MeshHandle& meshHandle)
  154. : m_meshHandle(&meshHandle)
  155. {
  156. }
  157. ////////////////////////////////////////////////////////////
  158. // StreamBufferViewsBuilderInterface overrides Start...
  159. bool ShaderStreamBufferViewsBuilder::AddStream(const char* semanticName, AZ::RHI::Format streamFormat, bool isOptional)
  160. {
  161. if (m_shaderInputContract)
  162. {
  163. AZ_Error(LogWindow, false, "Can not add stream '%s' because the ShaderInputContract was finalized!", semanticName);
  164. return false;
  165. }
  166. auto it = std::find_if(
  167. m_streamsList.cbegin(),
  168. m_streamsList.cend(),
  169. [semanticName](const StreamInfo& item) -> bool
  170. {
  171. return strcmp(item.m_semanticName, semanticName) == 0;
  172. });
  173. if (it != m_streamsList.end())
  174. {
  175. AZ_Error(LogWindow, false, "%s. A stream with name '%s' already exists!", __FUNCTION__, semanticName);
  176. return false;
  177. }
  178. m_streamsList.emplace_back(semanticName, streamFormat, isOptional);
  179. return true;
  180. }
  181. AZ::u8 ShaderStreamBufferViewsBuilder::GetStreamCount() const
  182. {
  183. return aznumeric_caster(m_streamsList.size());
  184. }
  185. AZStd::unique_ptr<ShaderStreamBufferViewsInterface> ShaderStreamBufferViewsBuilder::BuildShaderStreamBufferViews(
  186. uint32_t lodIndex, uint32_t meshIndex)
  187. {
  188. if (!m_shaderInputContract)
  189. {
  190. FinalizeShaderInputContract();
  191. }
  192. AZStd::unique_ptr<ShaderStreamBufferViews> shaderStreamBufferViews = AZStd::make_unique<ShaderStreamBufferViews>(lodIndex, meshIndex);
  193. const auto& modelInstance = (*m_meshHandle)->GetModel();
  194. if (!modelInstance)
  195. {
  196. // A valid MeshHandle, when the Mesh Asset is being loaded, may temporary not have a model instance.
  197. return shaderStreamBufferViews;
  198. }
  199. const auto& modelLods = modelInstance->GetLods();
  200. const auto& modelLod = modelLods[lodIndex];
  201. const auto& modelLodMeshList = modelLod->GetMeshes();
  202. const auto& modelLodMesh = modelLodMeshList[meshIndex];
  203. shaderStreamBufferViews->m_vertexIndicesBufferView =
  204. BuildShaderIndexBufferView(modelLodMesh, shaderStreamBufferViews->m_vertexIndicesIndexBufferView);
  205. // retrieve the material
  206. const AZ::Render::CustomMaterialId customMaterialId(lodIndex, modelLodMesh.m_materialSlotStableId);
  207. // This is a private function!
  208. const auto& customMaterialInfo = (*m_meshHandle)->GetCustomMaterialWithFallback(customMaterialId);
  209. const auto& material = customMaterialInfo.m_material ? customMaterialInfo.m_material : modelLodMesh.m_material;
  210. // retrieve vertex/index buffers
  211. AZ::RHI::InputStreamLayout inputStreamLayout;
  212. AZ::RHI::StreamBufferIndices streamIndices;
  213. [[maybe_unused]] bool result = modelLod->GetStreamsForMesh(
  214. inputStreamLayout,
  215. streamIndices,
  216. nullptr,
  217. *m_shaderInputContract.get(),
  218. meshIndex,
  219. customMaterialInfo.m_uvMapping,
  220. material->GetAsset()->GetMaterialTypeAsset()->GetUvNameMap());
  221. AZ_Assert(result, "Failed to retrieve mesh stream buffer views");
  222. const AZ::u8 streamCount = GetStreamCount();
  223. auto streamIter = modelLodMesh.CreateStreamIterator(streamIndices);
  224. auto streamChannels = inputStreamLayout.GetStreamChannels();
  225. for (AZ::u8 streamIdx = 0; streamIdx < streamCount; streamIdx++)
  226. {
  227. auto shaderSemantic = streamChannels[streamIdx].m_semantic;
  228. AZ::RHI::Buffer* rhiBuffer = const_cast<AZ::RHI::Buffer*>(streamIter[streamIdx].GetBuffer());
  229. // REMARK: The reason we are not doing this, is that most RHIs need the Offset in a BufferView to be aligned to 16 bytes,
  230. // which is not case for most sub meshes. To avoid this potential error, we map the whole buffer,
  231. // and expect the developer to use ShaderStreamBufferViews::GetStreamBufferView() to get the actual offset and feed it as a shader constant.
  232. // const uint32_t streamByteOffset = streamIter[streamIdx].GetByteOffset();
  233. // const uint32_t streamByteCount = streamIter[streamIdx].GetByteCount();
  234. const uint32_t streamByteOffset = 0;
  235. const uint32_t streamByteCount = static_cast<uint32_t>(rhiBuffer->GetDescriptor().m_byteCount);
  236. auto bufferViewDescriptor = AZ::RHI::BufferViewDescriptor::CreateRaw(streamByteOffset, streamByteCount);
  237. auto ptrBufferView = rhiBuffer->GetBufferView(bufferViewDescriptor);
  238. shaderStreamBufferViews->m_bufferViewsBySemantic.emplace(shaderSemantic, ptrBufferView);
  239. shaderStreamBufferViews->m_streamBufferViewsBySemantic.emplace(shaderSemantic, streamIter[streamIdx]);
  240. #if DEBUG_LOG_BUFFERVIEWS
  241. AZ_Printf(
  242. "ShaderStreamBufferViewsBuilder",
  243. "subMesh[%u] semantic[%s] viewByteOffset=%u, viewByteCount=%u, bufferByteCount=%u.\n",
  244. meshIndex,
  245. shaderSemantic.ToString().c_str(),
  246. streamIter[streamIdx].GetByteOffset(),
  247. streamIter[streamIdx].GetByteCount(),
  248. streamByteCount);
  249. #endif
  250. }
  251. return shaderStreamBufferViews;
  252. }
  253. const MeshFeatureProcessorInterface::MeshHandle& ShaderStreamBufferViewsBuilder::GetMeshHandle() const
  254. {
  255. return *m_meshHandle;
  256. }
  257. // StreamBufferViewsBuilderInterface overrides End...
  258. ////////////////////////////////////////////////////////////
  259. void ShaderStreamBufferViewsBuilder::FinalizeShaderInputContract()
  260. {
  261. AZ_Assert(!m_shaderInputContract, "ShaderInputContract was already finalized.");
  262. m_shaderInputContract = AZStd::make_unique<AZ::RPI::ShaderInputContract>();
  263. for (const auto& streamInfo : m_streamsList)
  264. {
  265. AZ::RPI::ShaderInputContract::StreamChannelInfo streamChannelInfo;
  266. streamChannelInfo.m_semantic = AZ::RHI::ShaderSemantic::Parse(streamInfo.m_semanticName);
  267. streamChannelInfo.m_componentCount = AZ::RHI::GetFormatComponentCount(streamInfo.m_streamFormat);
  268. streamChannelInfo.m_isOptional = streamInfo.m_isOptional;
  269. m_shaderInputContract->m_streamChannels.emplace_back(streamChannelInfo);
  270. }
  271. }
  272. AZ::RHI::Ptr<AZ::RHI::BufferView> ShaderStreamBufferViewsBuilder::BuildShaderIndexBufferView(
  273. const AZ::RPI::ModelLod::Mesh& modelLodMesh, AZ::RHI::IndexBufferView& indexBufferViewOut) const
  274. {
  275. AZ_Assert(modelLodMesh.GetDrawArguments().m_type == AZ::RHI::DrawType::Indexed, "We only support indexed geometry!");
  276. const AZ::RHI::IndexBufferView& indexBufferView = modelLodMesh.GetIndexBufferView();
  277. indexBufferViewOut = indexBufferView;
  278. uint32_t indexElementSize = indexBufferView.GetIndexFormat() == AZ::RHI::IndexFormat::Uint16 ? 2 : 4;
  279. // REMARK: The reason we are not doing this, is that most RHIs need the Offset in a BufferView to be aligned to 16 bytes,
  280. // which is not case for most sub meshes. To avoid this potential error, we map the whole buffer,
  281. // and expect the developer to use @indexBufferViewOut to get the actual offset and feed it as a shader constant.
  282. // uint32_t indexElementOffset = indexBufferView.GetByteOffset() / indexElementSize;
  283. // uint32_t indexElementCount = indexBufferView.GetByteCount() / indexElementSize;
  284. uint32_t indexElementOffset = 0;
  285. uint32_t indexElementCount = (uint32_t)indexBufferView.GetBuffer()->GetDescriptor().m_byteCount / indexElementSize;
  286. AZ::RHI::BufferViewDescriptor indexBufferDescriptor;
  287. indexBufferDescriptor.m_elementOffset = indexElementOffset;
  288. indexBufferDescriptor.m_elementCount = indexElementCount;
  289. indexBufferDescriptor.m_elementSize = indexElementSize;
  290. indexBufferDescriptor.m_elementFormat =
  291. indexBufferView.GetIndexFormat() == AZ::RHI::IndexFormat::Uint16 ? AZ::RHI::Format::R16_UINT : AZ::RHI::Format::R32_UINT;
  292. auto* rhiBuffer = const_cast<AZ::RHI::Buffer*>(indexBufferView.GetBuffer());
  293. #if DEBUG_LOG_BUFFERVIEWS
  294. AZ_Printf(
  295. "ShaderStreamBufferViewsBuilder",
  296. "Index buffer viewByteOffset=%u, viewByteCount=%u, elementCount=%u, elementSize=%u.\n",
  297. indexBufferView.GetByteOffset(),
  298. indexBufferView.GetByteCount(),
  299. indexElementCount,
  300. indexElementSize);
  301. #endif
  302. return rhiBuffer->GetBufferView(indexBufferDescriptor);
  303. }
  304. } // namespace Render
  305. } // namespace AZ