RayTracingFeatureProcessor.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. #pragma once
  9. #include <Atom/Feature/RayTracing/RayTracingFeatureProcessorInterface.h>
  10. #include <Atom/Feature/RayTracing/RayTracingIndexList.h>
  11. #include <Atom/Feature/TransformService/TransformServiceFeatureProcessorInterface.h>
  12. #include <Atom/RHI/DeviceBufferView.h>
  13. #include <Atom/RHI/DeviceImageView.h>
  14. #include <Atom/RHI/IndexBufferView.h>
  15. #include <Atom/RHI/RayTracingAccelerationStructure.h>
  16. #include <Atom/RHI/RayTracingBufferPools.h>
  17. #include <Atom/RHI/RayTracingCompactionQueryPool.h>
  18. #include <Atom/RHI/StreamBufferView.h>
  19. #include <Atom/RPI.Public/Buffer/RingBuffer.h>
  20. #include <Atom/RPI.Public/Shader/Shader.h>
  21. #include <Atom/RPI.Reflect/Image/Image.h>
  22. #include <Atom/Utils/StableDynamicArray.h>
  23. #include <AzCore/Math/Aabb.h>
  24. #include <AzCore/Math/Color.h>
  25. #include <AzCore/Math/Transform.h>
  26. #include <RayTracing/RayTracingResourceList.h>
  27. // this define specifies that the mesh buffers and material textures are stored in the Bindless Srg
  28. // Note1: The previous implementation using separate unbounded arrays is preserved since it demonstrates a TDR caused by
  29. // the RHI unbounded array allocation. This define and the previous codepath can be removed once the TDR is
  30. // investigated and resolved.
  31. // Note2: There are corresponding USE_BINDLESS_SRG defines in the RayTracingSceneSrg.azsli and RayTracingMaterialSrg.azsli
  32. // shader files that must match the setting of this define.
  33. #define USE_BINDLESS_SRG 1
  34. namespace AZ
  35. {
  36. namespace Render
  37. {
  38. //! This feature processor manages ray tracing data for a Scene
  39. class RayTracingFeatureProcessor
  40. : public RayTracingFeatureProcessorInterface
  41. {
  42. public:
  43. AZ_CLASS_ALLOCATOR(RayTracingFeatureProcessor, AZ::SystemAllocator)
  44. AZ_RTTI(AZ::Render::RayTracingFeatureProcessor, "{5017EFD3-A996-44B0-9ED2-C47609A2EE8D}", AZ::Render::RayTracingFeatureProcessorInterface);
  45. static void Reflect(AZ::ReflectContext* context);
  46. RayTracingFeatureProcessor() = default;
  47. virtual ~RayTracingFeatureProcessor() = default;
  48. // FeatureProcessor overrides
  49. void Activate() override;
  50. void Deactivate() override;
  51. // RayTracingFeatureProcessorInterface overrides
  52. ProceduralGeometryTypeHandle RegisterProceduralGeometryType(
  53. const AZStd::string& name,
  54. const Data::Instance<RPI::Shader>& intersectionShader,
  55. const AZStd::string& intersectionShaderName,
  56. const AZStd::unordered_map<int, uint32_t>& bindlessBufferIndices = {}) override;
  57. void SetProceduralGeometryTypeBindlessBufferIndex(
  58. ProceduralGeometryTypeWeakHandle geometryTypeHandle, const AZStd::unordered_map<int, uint32_t>& bindlessBufferIndices) override;
  59. void AddProceduralGeometry(
  60. ProceduralGeometryTypeWeakHandle geometryTypeHandle,
  61. const Uuid& uuid,
  62. const Aabb& aabb,
  63. const SubMeshMaterial& material,
  64. RHI::RayTracingAccelerationStructureInstanceInclusionMask instanceMask,
  65. uint32_t localInstanceIndex) override;
  66. void SetProceduralGeometryTransform(
  67. const Uuid& uuid, const Transform& transform, const Vector3& nonUniformScale = Vector3::CreateOne()) override;
  68. void SetProceduralGeometryLocalInstanceIndex(const Uuid& uuid, uint32_t localInstanceIndex) override;
  69. void SetProceduralGeometryMaterial(const Uuid& uuid, const SubMeshMaterial& material) override;
  70. void RemoveProceduralGeometry(const Uuid& uuid) override;
  71. int GetProceduralGeometryCount(ProceduralGeometryTypeWeakHandle geometryTypeHandle) const override;
  72. const ProceduralGeometryTypeList& GetProceduralGeometryTypes() const override { return m_proceduralGeometryTypes; }
  73. const ProceduralGeometryList& GetProceduralGeometries() const override { return m_proceduralGeometry; }
  74. void AddMesh(const AZ::Uuid& uuid, const Mesh& rayTracingMesh, const SubMeshVector& subMeshes) override;
  75. void RemoveMesh(const AZ::Uuid& uuid) override;
  76. void SetMeshTransform(const AZ::Uuid& uuid, const AZ::Transform transform, const AZ::Vector3 nonUniformScale) override;
  77. void SetMeshReflectionProbe(const AZ::Uuid& uuid, const Mesh::ReflectionProbe& reflectionProbe) override;
  78. void SetMeshMaterials(const AZ::Uuid& uuid, const SubMeshMaterialVector& subMeshMaterials) override;
  79. const SubMeshVector& GetSubMeshes() const override { return m_subMeshes; }
  80. SubMeshVector& GetSubMeshes() override { return m_subMeshes; }
  81. const MeshMap& GetMeshMap() override { return m_meshes; }
  82. uint32_t GetSubMeshCount() const override { return m_subMeshCount; }
  83. uint32_t GetSkinnedMeshCount() const override { return m_skinnedMeshCount; }
  84. Data::Instance<RPI::ShaderResourceGroup> GetRayTracingSceneSrg() const override { return m_rayTracingSceneSrg; }
  85. Data::Instance<RPI::ShaderResourceGroup> GetRayTracingMaterialSrg() const override { return m_rayTracingMaterialSrg; }
  86. const Data::Instance<RPI::Buffer> GetMeshInfoGpuBuffer() const override { return m_meshInfoGpuBuffer.GetCurrentBuffer(); }
  87. const Data::Instance<RPI::Buffer> GetMaterialInfoGpuBuffer() const override { return m_materialInfoGpuBuffer.GetCurrentBuffer(); }
  88. void Render(const RenderPacket&) override;
  89. void BeginFrame(int deviceIndex) override;
  90. uint32_t GetRevision() const override { return m_revision; }
  91. uint32_t GetBuiltRevision(int deviceIndex) const override;
  92. void SetBuiltRevision(int deviceIndex, uint32_t revision) override;
  93. uint32_t GetProceduralGeometryTypeRevision() const override { return m_proceduralGeometryTypeRevision; }
  94. RHI::RayTracingBufferPools& GetBufferPools() override { return *m_bufferPools; }
  95. void UpdateRayTracingSrgs() override;
  96. const RHI::Ptr<RHI::RayTracingTlas>& GetTlas() const override { return m_tlas; }
  97. RHI::Ptr<RHI::RayTracingTlas>& GetTlas() override{ return m_tlas; }
  98. RHI::AttachmentId GetTlasAttachmentId() const override { return m_tlasAttachmentId; }
  99. BlasInstanceMap& GetBlasInstances() override { return m_blasInstanceMap; }
  100. AZStd::mutex& GetBlasBuiltMutex() override { return m_blasBuiltMutex; }
  101. BlasBuildList& GetBlasBuildList(int deviceIndex) override { return m_blasToBuild[deviceIndex]; }
  102. const BlasBuildList& GetSkinnedMeshBlasList() override { return m_skinnedBlasIds; };
  103. BlasBuildList& GetBlasCompactionList(int deviceIndex) override { return m_blasToCompact[deviceIndex]; }
  104. const void MarkBlasInstanceForCompaction(int deviceIndex, Data::AssetId assetId) override;
  105. const void MarkBlasInstanceAsCompactionEnqueued(int deviceIndex, Data::AssetId assetId) override;
  106. bool HasMeshGeometry() const override { return m_subMeshCount != 0; }
  107. bool HasProceduralGeometry() const override { return !m_proceduralGeometry.empty(); }
  108. bool HasGeometry() const override { return HasMeshGeometry() || HasProceduralGeometry(); }
  109. RHI::MultiDevice::DeviceMask GetDeviceMask() const override { return m_deviceMask; }
  110. private:
  111. AZ_DISABLE_COPY_MOVE(RayTracingFeatureProcessor);
  112. void UpdateBlasInstances();
  113. void UpdateMeshInfoBuffer();
  114. void UpdateProceduralGeometryInfoBuffer();
  115. void UpdateMaterialInfoBuffer();
  116. void UpdateIndexLists();
  117. void UpdateRayTracingSceneSrg();
  118. void UpdateRayTracingMaterialSrg();
  119. void RemoveBlasInstance(Data::AssetId id);
  120. static RHI::RayTracingAccelerationStructureBuildFlags CreateRayTracingAccelerationStructureBuildFlags(bool isSkinnedMesh);
  121. // flag indicating if RayTracing is enabled, currently based on device support
  122. bool m_rayTracingEnabled = false;
  123. // mesh data for meshes that should be included in ray tracing operations,
  124. // this is a map of the mesh UUID to the ray tracing data for the sub-meshes
  125. MeshMap m_meshes;
  126. SubMeshVector m_subMeshes;
  127. // buffer pools used in ray tracing operations
  128. RHI::Ptr<RHI::RayTracingBufferPools> m_bufferPools;
  129. // ray tracing acceleration structure (TLAS)
  130. RHI::Ptr<RHI::RayTracingTlas> m_tlas;
  131. // RayTracingScene and RayTracingMaterial asset and Srgs
  132. Data::Asset<RPI::ShaderAsset> m_rayTracingSrgAsset;
  133. Data::Instance<RPI::ShaderResourceGroup> m_rayTracingSceneSrg;
  134. Data::Instance<RPI::ShaderResourceGroup> m_rayTracingMaterialSrg;
  135. // current revision number of ray tracing data
  136. uint32_t m_revision = 0;
  137. // Currently built revision by device
  138. AZStd::unordered_map<int, uint32_t> m_builtRevisions;
  139. // latest tlas revision number
  140. uint32_t m_tlasRevision = 0;
  141. uint32_t m_proceduralGeometryTypeRevision = 0;
  142. // total number of ray tracing sub-meshes
  143. uint32_t m_subMeshCount = 0;
  144. // TLAS attachmentId
  145. RHI::AttachmentId m_tlasAttachmentId;
  146. // cached TransformServiceFeatureProcessor
  147. TransformServiceFeatureProcessorInterface* m_transformServiceFeatureProcessor = nullptr;
  148. // mutex for the mesh and BLAS lists
  149. AZStd::mutex m_mutex;
  150. // mutex for the m_blasBuilt flag manipulation
  151. AZStd::mutex m_blasBuiltMutex;
  152. // structure for data in the m_meshInfoBuffer, shaders that use the buffer must match this type
  153. struct MeshInfo
  154. {
  155. // byte offsets into the mesh buffer views
  156. uint32_t m_indexByteOffset = 0;
  157. uint32_t m_positionByteOffset = 0;
  158. uint32_t m_normalByteOffset = 0;
  159. uint32_t m_tangentByteOffset = 0;
  160. uint32_t m_bitangentByteOffset = 0;
  161. uint32_t m_uvByteOffset = 0;
  162. RayTracingSubMeshBufferFlags m_bufferFlags = RayTracingSubMeshBufferFlags::None;
  163. uint32_t m_bufferStartIndex = 0;
  164. AZStd::array<float, 12> m_worldInvTranspose; // float3x4
  165. };
  166. // vector of MeshInfo, transferred to the meshInfoGpuBuffer
  167. using MeshInfoVector = AZStd::vector<MeshInfo>;
  168. AZStd::unordered_map<int, MeshInfoVector> m_meshInfos;
  169. RPI::RingBuffer m_meshInfoGpuBuffer{ "RayTracingMeshInfo", RPI::CommonBufferPoolType::ReadOnly, sizeof(MeshInfo) };
  170. RPI::RingBuffer m_proceduralGeometryInfoGpuBuffer{ "ProceduralGeometryInfo", RPI::CommonBufferPoolType::ReadOnly, RHI::Format::R32G32_UINT };
  171. // structure for data in the m_materialInfoBuffer, shaders that use the buffer must match this type
  172. struct alignas(16) MaterialInfo
  173. {
  174. AZStd::array<float, 4> m_baseColor; // float4
  175. AZStd::array<float, 4> m_irradianceColor; // float4
  176. AZStd::array<float, 3> m_emissiveColor; // float3
  177. float m_metallicFactor = 0.0f;
  178. float m_roughnessFactor = 0.0f;
  179. RayTracingSubMeshTextureFlags m_textureFlags = RayTracingSubMeshTextureFlags::None;
  180. uint32_t m_textureStartIndex = InvalidIndex;
  181. uint32_t m_reflectionProbeCubeMapIndex = InvalidIndex;
  182. // reflection probe data, must match the structure in ReflectionProbeData.azlsi
  183. struct alignas(16) ReflectionProbeData
  184. {
  185. AZStd::array<float, 12> m_modelToWorld; // float3x4
  186. AZStd::array<float, 12> m_modelToWorldInverse; // float3x4
  187. AZStd::array<float, 3> m_outerObbHalfLengths; // float3
  188. float m_exposure = 0.0f;
  189. AZStd::array<float, 3> m_innerObbHalfLengths; // float3
  190. uint32_t m_useReflectionProbe = 0;
  191. uint32_t m_useParallaxCorrection = 0;
  192. AZStd::array<float, 3> m_padding;
  193. };
  194. ReflectionProbeData m_reflectionProbeData;
  195. };
  196. // vector of MaterialInfo, transferred to the materialInfoGpuBuffer
  197. using MaterialInfoVector = AZStd::vector<MaterialInfo>;
  198. AZStd::unordered_map<int, MaterialInfoVector> m_materialInfos;
  199. AZStd::unordered_map<int, MaterialInfoVector> m_proceduralGeometryMaterialInfos;
  200. RPI::RingBuffer m_materialInfoGpuBuffer{ "RayTracingMaterialInfo", RPI::CommonBufferPoolType::ReadOnly, sizeof(MaterialInfo) };
  201. // update flags
  202. bool m_meshInfoBufferNeedsUpdate = false;
  203. bool m_proceduralGeometryInfoBufferNeedsUpdate = false;
  204. bool m_materialInfoBufferNeedsUpdate = false;
  205. bool m_indexListNeedsUpdate = false;
  206. // side list for looking up existing BLAS objects so they can be re-used when the same mesh is added multiple times
  207. BlasInstanceMap m_blasInstanceMap;
  208. BlasBuildList m_blasToCreate;
  209. AZStd::unordered_map<int, BlasBuildList> m_blasToBuild;
  210. AZStd::unordered_map<int, BlasBuildList> m_blasToCompact;
  211. BlasBuildList m_skinnedBlasIds;
  212. struct BlasFrameEvent
  213. {
  214. int m_frameIndex = -1;
  215. };
  216. // List of Blas instances that are enqueued for compaction
  217. // The frame index corresponds to the frame where the compaction query is ready
  218. AZStd::unordered_map<int, AZStd::unordered_map<Data::AssetId, BlasFrameEvent>> m_blasEnqueuedForCompact;
  219. // List of Blas instances where the compacted Blas is already built
  220. // The frame index corresponds to the frame where the uncompacted Blas is no longer needed and can be deleted
  221. AZStd::unordered_map<int, AZStd::unordered_map<Data::AssetId, BlasFrameEvent>> m_uncompactedBlasEnqueuedForDeletion;
  222. int m_frameIndex = 0;
  223. int m_updatedFrameIndex = 0;
  224. #if !USE_BINDLESS_SRG
  225. // Mesh buffer and material texture resources are managed with a RayTracingResourceList, which contains an internal
  226. // indirection list. This allows resource entries to be swapped inside the RayTracingResourceList when removing entries,
  227. // without invalidating the indices held here in the m_meshBufferIndices and m_materialTextureIndices lists.
  228. // mesh buffer and material texture resource lists, accessed by the shader through an unbounded array
  229. RayTracingResourceList<RHI::BufferView> m_meshBuffers;
  230. RayTracingResourceList<const RHI::ImageView> m_materialTextures;
  231. #endif
  232. // RayTracingIndexList implements an internal freelist chain stored inside the list itself, allowing entries to be
  233. // reused after elements are removed.
  234. // mesh buffer and material texture index lists, which contain the array indices of the mesh resources
  235. static const uint32_t NumMeshBuffersPerMesh = 6;
  236. AZStd::unordered_map<int, RayTracingIndexList<NumMeshBuffersPerMesh>> m_meshBufferIndices;
  237. static const uint32_t NumMaterialTexturesPerMesh = 5;
  238. AZStd::unordered_map<int, RayTracingIndexList<NumMaterialTexturesPerMesh>> m_materialTextureIndices;
  239. // Gpu buffers for the mesh and material index lists
  240. RPI::RingBuffer m_meshBufferIndicesGpuBuffer{ "RayTracingMeshBufferIndices", RPI::CommonBufferPoolType::ReadOnly, RHI::Format::R32_UINT };
  241. RPI::RingBuffer m_materialTextureIndicesGpuBuffer{ "RayTracingMaterialTextureIndices", RPI::CommonBufferPoolType::ReadOnly, RHI::Format::R32_UINT };
  242. uint32_t m_skinnedMeshCount = 0;
  243. ProceduralGeometryTypeList m_proceduralGeometryTypes;
  244. ProceduralGeometryList m_proceduralGeometry;
  245. AZStd::unordered_map<Uuid, size_t> m_proceduralGeometryLookup;
  246. RHI::Ptr<RHI::RayTracingCompactionQueryPool> m_compactionQueryPool;
  247. RHI::MultiDevice::DeviceMask m_deviceMask = {};
  248. void ConvertMaterial(MaterialInfo& materialInfo, const SubMeshMaterial& subMeshMaterial, int deviceIndex);
  249. };
  250. }
  251. }