RayTracingFeatureProcessor.h 16 KB

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