当前位置:   article > 正文

剖析虚幻渲染体系(11)- RDG_ue5 rdg

ue5 rdg

目录

11.1 本篇概述

RDG全称是Rendering Dependency Graph,意为渲染依赖性图表,是UE4.22开始引进的全新的渲染子系统,基于有向无环图(Directed Acyclic Graph,DAG)的调度系统,用于执行渲染管线的整帧优化。

它利用现代的图形API(DirectX 12、Vulkan和Metal 2),实现自动异步计算调度以及更高效的内存管理和屏障管理来提升性能。

传统的图形API(DirectX 11、OpenGL)要求驱动器调用复杂的启发法,以确定何时以及如何在GPU上执行关键的调度操作。例如清空缓存,管理和再使用内存,执行布局转换等等。由于接口存在即时模式特性,因此需要复杂的记录和状态跟踪才能处理各种极端情况。这些情况最终会对性能产生负面影响,并阻碍并行。

现代的图形API(DirectX 12、Vulkan和Metal 2)与传统图形API不同,将低级GPU管理的负担转移到应用程序。这使得应用程序可以利用渲染管线的高级情境来驱动调度,从而提高性能并且简化渲染堆栈。

RDG的理念不在GPU上立即执行Pass,而是先收集所有需要渲染的Pass,然后按照依赖的顺序对图表进行编译和执行,期间会执行各类裁剪和优化。

依赖性图表数据结构的整帧认知与现代图形API的能力相结合,使RDG能够在后台执行复杂的调度任务:

  • 执行异步计算通道的自动调度和隔离。
  • 在帧的不相交间隔期间,使资源之间的别名内存保持活跃状态。
  • 尽早启动屏障和布局转换,避免管线延迟。

此外,RDG利用依赖性图表在通道设置期间提供丰富的验证,对影响功能和性能的问题进行自动捕捉,从而改进开发流程。

RDG并非UE独创的概念和技术,早在2017年的GDC中,寒霜就已经实现并应用了Frame Graph(帧图)的技术。Frame Graph旨在将引擎的各类渲染功能(Feature)和上层渲染逻辑(Renderer)和下层资源(Shader、RenderContext、图形API等)隔离开来,以便做进一步的解耦、优化,其中最重要的就是多线程和并行渲染。

FrameGraph是高层级的Render Pass和资源的代表,包含了一帧中所用到的所有信息。Pass之间可以指定顺序和依赖关系,下图是其中的一个示例:

寒霜引擎采用帧图方式实现的延迟渲染的顺序和依赖图。

可以毫不夸张地说,UE的RDG正是基于Frame Graph之上定制和实现而成的。到了UE4.26,RDG已经被大量普及,包含场景渲染、后处理、光追等等模块都使用了RDG代替原本直接调用RHI命令的方式。

本篇主要阐述UE RDG的以下内容:

  • RDG的基本概念和类型。
  • RDG的使用方法。
  • RDG的内部机制和原理。

11.2 RDG基础

本章先阐述RDG涉及的主要类型、概念、接口等。

11.2.1 RDG基础类型

RDG基础类型和接口主要集中于RenderGraphUtils.h和RenderGraphDefinitions.h之中。部分解析如下:

  1. // Engine\Source\Runtime\RenderCore\Public\RenderGraphDefinitions.h
  2. // RDG Pass类型.
  3. enum class ERDGPassFlags : uint8
  4. {
  5. None = 0, // 用于无参数的AddPass函数.
  6. Raster = 1 << 0, // Pass在图形管道上使用光栅化.
  7. Compute = 1 << 1, // Pass在图形管道上使用compute.
  8. AsyncCompute = 1 << 2, // Pass在异步计算管道上使用compute
  9. Copy = 1 << 3, // Pass在图形管道上使用复制命令.
  10. NeverCull = 1 << 4, // 不被裁剪优化, 用于特殊pass.
  11. SkipRenderPass = 1 << 5, // 忽略BeginRenderPass/EndRenderPass, 留给用户去调用. 只在Raster绑定时有效. 将禁用Pass合并.
  12. UntrackedAccess = 1 << 6, // Pass访问原始的RHI资源,这些资源可能被注册到RDG中,但所有资源都保持在当前状态. 此标志阻止图形调度跨越通道的分割障碍。任何拆分都被延迟到pass执行之后。资源可能不会在pass执行过程中改变状态。影响性能的屏障。不能与AsyncCompute组合。
  13. Readback = Copy | NeverCull, // Pass使用复制命令,但写入暂存资源(staging resource).
  14. CommandMask = Raster | Compute | AsyncCompute | Copy, // 标志掩码,表示提交给pass的RHI命令的类型.
  15. ScopeMask = NeverCull | UntrackedAccess // 可由传递标志作用域使用的标志掩码
  16. };
  17. // Buffer标记.
  18. enum class ERDGBufferFlags : uint8
  19. {
  20. None = 0, // 无标记.
  21. MultiFrame = 1 << 0 // 存续于多帧.
  22. };
  23. // 纹理标记.
  24. enum class ERDGTextureFlags : uint8
  25. {
  26. None = 0,
  27. MultiFrame = 1 << 0, // 存续于多帧.
  28. MaintainCompression = 1 << 1, // 防止在此纹理上解压元数据.
  29. };
  30. // UAV标记.
  31. enum class ERDGUnorderedAccessViewFlags : uint8
  32. {
  33. None = 0,
  34. SkipBarrier = 1 << 0 // 忽略屏障.
  35. };
  36. // 父资源类型.
  37. enum class ERDGParentResourceType : uint8
  38. {
  39. Texture,
  40. Buffer,
  41. MAX
  42. };
  43. // 视图类型.
  44. enum class ERDGViewType : uint8
  45. {
  46. TextureUAV, // 纹理UAV(用于写入数据)
  47. TextureSRV, // 纹理SRV(用于读取数据)
  48. BufferUAV, // 缓冲UAV(用于写入数据)
  49. BufferSRV, // 缓冲SRV(用于读取数据)
  50. MAX
  51. };
  52. // 用于在创建视图时指定纹理元数据平面
  53. enum class ERDGTextureMetaDataAccess : uint8
  54. {
  55. None = 0, // 主平面默认压缩使用.
  56. CompressedSurface, // 主平面不压缩使用.
  57. Depth, // 深度平面默认压缩使用.
  58. Stencil, // 模板平面默认压缩使用.
  59. HTile, // HTile平面.
  60. FMask, // FMask平面.
  61. CMask // CMask平面.
  62. };
  63. // 简单的C++对象分配器, 用MemStack分配器追踪和销毁物体.
  64. class FRDGAllocator final
  65. {
  66. public:
  67. FRDGAllocator();
  68. ~FRDGAllocator();
  69. // 分配原始内存.
  70. FORCEINLINE void* Alloc(uint32 SizeInBytes, uint32 AlignInBytes)
  71. {
  72. return MemStack.Alloc(SizeInBytes, AlignInBytes);
  73. }
  74. // 分配POD内存而不跟踪析构函数.
  75. template <typename PODType>
  76. FORCEINLINE PODType* AllocPOD()
  77. {
  78. return reinterpret_cast<PODType*>(Alloc(sizeof(PODType), alignof(PODType)));
  79. }
  80. // 带析构追踪的C++对象分配.
  81. template <typename ObjectType, typename... TArgs>
  82. FORCEINLINE ObjectType* AllocObject(TArgs&&... Args)
  83. {
  84. TTrackedAlloc<ObjectType>* TrackedAlloc = new(MemStack) TTrackedAlloc<ObjectType>(Forward<TArgs&&>(Args)...);
  85. check(TrackedAlloc);
  86. TrackedAllocs.Add(TrackedAlloc);
  87. return TrackedAlloc->Get();
  88. }
  89. // 不带析构追踪的C++对象分配. (危险, 慎用)
  90. template <typename ObjectType, typename... TArgs>
  91. FORCEINLINE ObjectType* AllocNoDestruct(TArgs&&... Args)
  92. {
  93. return new (MemStack) ObjectType(Forward<TArgs&&>(Args)...);
  94. }
  95. // 释放全部已分配的内存.
  96. void ReleaseAll();
  97. private:
  98. class FTrackedAlloc
  99. {
  100. public:
  101. virtual ~FTrackedAlloc() = default;
  102. };
  103. template <typename ObjectType>
  104. class TTrackedAlloc : public FTrackedAlloc
  105. {
  106. public:
  107. template <typename... TArgs>
  108. FORCEINLINE TTrackedAlloc(TArgs&&... Args) : Object(Forward<TArgs&&>(Args)...) {}
  109. FORCEINLINE ObjectType* Get() { return &Object; }
  110. private:
  111. ObjectType Object;
  112. };
  113. // 分配器.
  114. FMemStackBase MemStack;
  115. // 所有已分配的对象.
  116. TArray<FTrackedAlloc*, SceneRenderingAllocator> TrackedAllocs;
  117. };
  118. // Engine\Source\Runtime\RenderCore\Public\RenderGraphUtils.h
  119. // 清理未使用的资源.
  120. extern RENDERCORE_API void ClearUnusedGraphResourcesImpl(const FShaderParameterBindings& ShaderBindings, ...);
  121. (......)
  122. // 注册外部纹理, 可附带备用实例.
  123. FRDGTextureRef RegisterExternalTextureWithFallback(FRDGBuilder& GraphBuilder, ...);
  124. inline FRDGTextureRef TryRegisterExternalTexture(FRDGBuilder& GraphBuilder, ...);
  125. inline FRDGBufferRef TryRegisterExternalBuffer(FRDGBuilder& GraphBuilder, ...);
  126. // 计算着色器的工具类.
  127. struct RENDERCORE_API FComputeShaderUtils
  128. {
  129. // 理想的组大小为8x8,在GCN上至少占据一个wave,在Nvidia上占据两个warp.
  130. static constexpr int32 kGolden2DGroupSize = 8;
  131. static FIntVector GetGroupCount(const int32 ThreadCount, const int32 GroupSize);
  132. // 派发计算着色器到RHI命令列表, 携带其参数.
  133. template<typename TShaderClass>
  134. static void Dispatch(FRHIComputeCommandList& RHICmdList, const TShaderRef<TShaderClass>& ComputeShader, const typename TShaderClass::FParameters& Parameters, FIntVector GroupCount);
  135. // 派发非直接的计算着色器到RHI命令列表, 携带其参数.
  136. template<typename TShaderClass>
  137. static void DispatchIndirect(FRHIComputeCommandList& RHICmdList, const TShaderRef<TShaderClass>& ComputeShader, const typename TShaderClass::FParameters& Parameters, FRHIVertexBuffer* IndirectArgsBuffer, uint32 IndirectArgOffset);
  138. // 派发计算着色器到render graph builder, 携带其参数.
  139. template<typename TShaderClass>
  140. static void AddPass(FRDGBuilder& GraphBuilder,FRDGEventName&& PassName,ERDGPassFlags PassFlags,const TShaderRef<TShaderClass>& ComputeShader,typename TShaderClass::FParameters* Parameters,FIntVector GroupCount);
  141. (......)
  142. // 清理UAV.
  143. static void ClearUAV(FRDGBuilder& GraphBuilder, FGlobalShaderMap* ShaderMap, FRDGBufferUAVRef UAV, uint32 ClearValue);
  144. static void ClearUAV(FRDGBuilder& GraphBuilder, FGlobalShaderMap* ShaderMap, FRDGBufferUAVRef UAV, FVector4 ClearValue);
  145. };
  146. // 增加拷贝纹理Pass.
  147. void AddCopyTexturePass(FRDGBuilder& GraphBuilder, FRDGTextureRef InputTexture, FRDGTextureRef OutputTexture, const FRHICopyTextureInfo& CopyInfo);
  148. (......)
  149. // 增加拷贝到解析目标的Pass.
  150. void AddCopyToResolveTargetPass(FRDGBuilder& GraphBuilder, FRDGTextureRef InputTexture, FRDGTextureRef OutputTexture, const FResolveParams& ResolveParams);
  151. // 清理各类资源的Pass.
  152. void AddClearUAVPass(FRDGBuilder& GraphBuilder, FRDGBufferUAVRef BufferUAV, uint32 Value);
  153. void AddClearUAVFloatPass(FRDGBuilder& GraphBuilder, FRDGBufferUAVRef BufferUAV, float Value);
  154. void AddClearUAVPass(FRDGBuilder& GraphBuilder, FRDGTextureUAVRef TextureUAV, const FUintVector4& ClearValues);
  155. void AddClearRenderTargetPass(FRDGBuilder& GraphBuilder, FRDGTextureRef Texture);
  156. void AddClearDepthStencilPass(FRDGBuilder& GraphBuilder,FRDGTextureRef Texture,bool bClearDepth,float Depth,bool bClearStencil,uint8 Stencil);
  157. void AddClearStencilPass(FRDGBuilder& GraphBuilder, FRDGTextureRef Texture);
  158. (......)
  159. // 增加回读纹理的Pass.
  160. void AddEnqueueCopyPass(FRDGBuilder& GraphBuilder, FRHIGPUTextureReadback* Readback, FRDGTextureRef SourceTexture, FResolveRect Rect = FResolveRect());
  161. // 增加回读缓冲区的Pass.
  162. void AddEnqueueCopyPass(FRDGBuilder& GraphBuilder, FRHIGPUBufferReadback* Readback, FRDGBufferRef SourceBuffer, uint32 NumBytes);
  163. // 创建资源.
  164. FRDGBufferRef CreateStructuredBuffer(FRDGBuilder& GraphBuilder, ...);
  165. FRDGBufferRef CreateVertexBuffer(FRDGBuilder& GraphBuilder, ...);
  166. // 无参数的Pass增加.
  167. template <typename ExecuteLambdaType>
  168. void AddPass(FRDGBuilder& GraphBuilder, FRDGEventName&& Name, ExecuteLambdaType&& ExecuteLambda);
  169. template <typename ExecuteLambdaType>
  170. void AddPass(FRDGBuilder& GraphBuilder, ExecuteLambdaType&& ExecuteLambda);
  171. // 其它特殊Pass
  172. void AddBeginUAVOverlapPass(FRDGBuilder& GraphBuilder);
  173. void AddEndUAVOverlapPass(FRDGBuilder& GraphBuilder);
  174. (......)

11.2.2 RDG资源

RDG资源并不是直接用RHI资源,而是包裹了RHI资源引用,然后针对不同类型的资源各自封装,且增加了额外的信息。部分RDG的定义如下:

  1. // Engine\Source\Runtime\RenderCore\Public\RenderGraphResources.h
  2. class FRDGResource
  3. {
  4. public:
  5. // 删除拷贝构造函数.
  6. FRDGResource(const FRDGResource&) = delete;
  7. virtual ~FRDGResource() = default;
  8. //
  9. // 下面的接口只能被RDG的Pass执行期间调用.
  10. // 标记此资源是否被使用, 若非, 则会被清理掉.
  11. #if RDG_ENABLE_DEBUG
  12. virtual void MarkResourceAsUsed();
  13. #else
  14. inline void MarkResourceAsUsed() {}
  15. #endif
  16. // 获取RDG的RHI资源引用.
  17. FRHIResource* GetRHI() const
  18. {
  19. ValidateRHIAccess();
  20. return ResourceRHI;
  21. }
  22. //
  23. protected:
  24. FRDGResource(const TCHAR* InName);
  25. // 将此资源分配为RHI资源的简单直通容器.
  26. void SetPassthroughRHI(FRHIResource* InResourceRHI)
  27. {
  28. ResourceRHI = InResourceRHI;
  29. #if RDG_ENABLE_DEBUG
  30. DebugData.bAllowRHIAccess = true;
  31. DebugData.bPassthrough = true;
  32. #endif
  33. }
  34. bool IsPassthrough() const
  35. {
  36. #if RDG_ENABLE_DEBUG
  37. return DebugData.bPassthrough;
  38. #else
  39. return false;
  40. #endif
  41. }
  42. /** Verify that the RHI resource can be accessed at a pass execution. */
  43. void ValidateRHIAccess() const
  44. {
  45. #if RDG_ENABLE_DEBUG
  46. checkf(DebugData.bAllowRHIAccess,
  47. TEXT("Accessing the RHI resource of %s at this time is not allowed. If you hit this check in pass, ")
  48. TEXT("that is due to this resource not being referenced in the parameters of your pass."),
  49. Name);
  50. #endif
  51. }
  52. FRHIResource* GetRHIUnchecked() const
  53. {
  54. return ResourceRHI;
  55. }
  56. // RHI资源引用.
  57. FRHIResource* ResourceRHI = nullptr;
  58. private:
  59. // 调试信息.
  60. #if RDG_ENABLE_DEBUG
  61. class FDebugData
  62. {
  63. private:
  64. // 在运行时跟踪资源是否被pass的lambda实际使用,以检测对pass不必要的资源依赖.
  65. bool bIsActuallyUsedByPass = false;
  66. // 追踪Pass执行期间, 底层的RHI自已是否允许被访问.
  67. bool bAllowRHIAccess = false;
  68. // 如果为true,则该资源不附加到任何构建器,而是作为一个虚拟容器存在,用于将代码暂存到RDG.
  69. bool bPassthrough = false;
  70. } DebugData;
  71. #endif
  72. };
  73. class FRDGUniformBuffer : public FRDGResource
  74. {
  75. public:
  76. // 获取RHI.
  77. FRHIUniformBuffer* GetRHI() const
  78. {
  79. return static_cast<FRHIUniformBuffer*>(FRDGResource::GetRHI());
  80. }
  81. (......)
  82. protected:
  83. template <typename TParameterStruct>
  84. explicit FRDGUniformBuffer(TParameterStruct* InParameters, const TCHAR* InName)
  85. : FRDGResource(InName)
  86. , ParameterStruct(InParameters)
  87. , bGlobal(ParameterStruct.HasStaticSlot());
  88. private:
  89. // 参数结构体.
  90. const FRDGParameterStruct ParameterStruct;
  91. // RHI资源.
  92. TRefCountPtr<FRHIUniformBuffer> UniformBufferRHI;
  93. // RDG句柄.
  94. FRDGUniformBufferHandle Handle;
  95. // 全局绑定或局部绑定.
  96. uint8 bGlobal : 1;
  97. };
  98. // RDGUniformBuffer模板类.
  99. template <typename ParameterStructType>
  100. class TRDGUniformBuffer : public FRDGUniformBuffer
  101. {
  102. public:
  103. const TRDGParameterStruct<ParameterStructType>& GetParameters() const;
  104. TUniformBufferRef<ParameterStructType> GetRHIRef() const;
  105. const ParameterStructType* operator->() const;
  106. (......)
  107. };
  108. // 一种由图跟踪分配生命周期的渲染图资源。可能有引用它的子资源(例如视图)
  109. class FRDGParentResource : public FRDGResource
  110. {
  111. public:
  112. // 父资源类型.
  113. const ERDGParentResourceType Type;
  114. bool IsExternal() const;
  115. protected:
  116. FRDGParentResource(const TCHAR* InName, ERDGParentResourceType InType);
  117. // 是否外部资源.
  118. uint8 bExternal : 1;
  119. // 是否被提取的资源.
  120. uint8 bExtracted : 1;
  121. // 此资源是否需要acquire / discard.
  122. uint8 bTransient : 1;
  123. // 是否最后的拥有者分配的.
  124. uint8 bLastOwner : 1;
  125. // 将被裁剪.
  126. uint8 bCulled : 1;
  127. // 是否被异步计算Pass使用.
  128. uint8 bUsedByAsyncComputePass : 1;
  129. private:
  130. // 引用数量.
  131. uint16 ReferenceCount = 0;
  132. // 用户分配的资源的初始和最终状态(如果已知)
  133. ERHIAccess AccessInitial = ERHIAccess::Unknown;
  134. ERHIAccess AccessFinal = ERHIAccess::Unknown;
  135. FRDGPassHandle AcquirePass;
  136. FRDGPassHandle FirstPass;
  137. FRDGPassHandle LastPass;
  138. (......)
  139. };
  140. // 创建渲染纹理的描述信息.
  141. struct RENDERCORE_API FRDGTextureDesc
  142. {
  143. static FRDGTextureDesc Create2D(...);
  144. static FRDGTextureDesc Create2DArray(...);
  145. static FRDGTextureDesc Create3D(...);
  146. static FRDGTextureDesc CreateCube(...);
  147. static FRDGTextureDesc CreateCubeArray(...);
  148. bool IsTexture2D() const;
  149. bool IsTexture3D() const;
  150. bool IsTextureCube() const;
  151. bool IsTextureArray() const;
  152. bool IsMipChain() const;
  153. bool IsMultisample() const;
  154. FIntVector GetSize() const;
  155. // 子资源的布局.
  156. FRDGTextureSubresourceLayout GetSubresourceLayout() const;
  157. bool IsValid() const;
  158. // 清理值.
  159. FClearValueBinding ClearValue;
  160. ETextureDimension Dimension = ETextureDimension::Texture2D;
  161. // 清理标记.
  162. ETextureCreateFlags Flags = TexCreate_None;
  163. // 像素格式.
  164. EPixelFormat Format = PF_Unknown;
  165. // 纹理在x和y中的范围
  166. FIntPoint Extent = FIntPoint(1, 1);
  167. // 3D纹理的深度.
  168. uint16 Depth = 1;
  169. uint16 ArraySize = 1;
  170. // 纹理层级数.
  171. uint8 NumMips = 1;
  172. // 采样数.
  173. uint8 NumSamples = 1;
  174. };
  175. // 将池内的RT描述转成RDG纹理描述.
  176. inline FRDGTextureDesc Translate(const FPooledRenderTargetDesc& InDesc, ERenderTargetTexture InTexture = ERenderTargetTexture::Targetable);
  177. // 将RDG纹理描述转成池内的RT描述.
  178. inline FPooledRenderTargetDesc Translate(const FRDGTextureDesc& InDesc);
  179. // 池内的纹理.
  180. class RENDERCORE_API FRDGPooledTexture
  181. {
  182. public:
  183. // 描述.
  184. const FRDGTextureDesc Desc;
  185. // 引用计数.
  186. uint32 GetRefCount() const;
  187. uint32 AddRef() const;
  188. uint32 Release() const;
  189. private:
  190. FRDGPooledTexture(FRHITexture* InTexture, const FRDGTextureDesc& InDesc, const FUnorderedAccessViewRHIRef& FirstMipUAV);
  191. // 初始化缓存的UAV.
  192. void InitViews(const FUnorderedAccessViewRHIRef& FirstMipUAV);
  193. void Finalize();
  194. void Reset();
  195. // 对应的RHI纹理.
  196. FRHITexture* Texture = nullptr;
  197. // 所在的纹理对象.
  198. FRDGTexture* Owner = nullptr;
  199. // 子资源布局.
  200. FRDGTextureSubresourceLayout Layout;
  201. // 子资源状态.
  202. FRDGTextureSubresourceState State;
  203. // 为RHI纹理缓存的UAV/SRV.
  204. TArray<FUnorderedAccessViewRHIRef, TInlineAllocator<1>> MipUAVs;
  205. TArray<TPair<FRHITextureSRVCreateInfo, FShaderResourceViewRHIRef>, TInlineAllocator<1>> SRVs;
  206. FUnorderedAccessViewRHIRef HTileUAV;
  207. FShaderResourceViewRHIRef HTileSRV;
  208. FUnorderedAccessViewRHIRef StencilUAV;
  209. FShaderResourceViewRHIRef FMaskSRV;
  210. FShaderResourceViewRHIRef CMaskSRV;
  211. mutable uint32 RefCount = 0;
  212. };
  213. // RDG纹理.
  214. class RENDERCORE_API FRDGTexture final : public FRDGParentResource
  215. {
  216. public:
  217. // 为还未传到RDG的Pass创建一个适用于用RDG参数填充RHI统一缓冲区的直通纹理.
  218. static FRDGTextureRef GetPassthrough(const TRefCountPtr<IPooledRenderTarget>& PooledRenderTarget);
  219. // 描述和标记.
  220. const FRDGTextureDesc Desc;
  221. const ERDGTextureFlags Flags;
  222. //
  223. //! The following methods may only be called during pass execution.
  224. IPooledRenderTarget* GetPooledRenderTarget() const
  225. FRHITexture* GetRHI() const
  226. //
  227. FRDGTextureSubresourceLayout GetSubresourceLayout() const;
  228. FRDGTextureSubresourceRange GetSubresourceRange() const;
  229. FRDGTextureSubresourceRange GetSubresourceRangeSRV() const;
  230. private:
  231. FRDGTexture(const TCHAR* InName, const FRDGTextureDesc& InDesc, ERDGTextureFlags InFlags, ERenderTargetTexture InRenderTargetTexture);
  232. void SetRHI(FPooledRenderTarget* PooledRenderTarget, FRDGTextureRef& OutPreviousOwner);
  233. void Finalize();
  234. FRHITexture* GetRHIUnchecked() const;
  235. bool IsLastOwner() const;
  236. FRDGTextureSubresourceState& GetState();
  237. const ERenderTargetTexture RenderTargetTexture;
  238. // 用于促进子资源转换的布局.
  239. FRDGTextureSubresourceLayout Layout;
  240. // 在执行期间拥有PooledTexture分配的下一个纹理.
  241. FRDGTextureHandle NextOwner;
  242. // 已注册到构建器的句柄.
  243. FRDGTextureHandle Handle;
  244. // 池内纹理.
  245. IPooledRenderTarget* PooledRenderTarget = nullptr;
  246. FRDGPooledTexture* PooledTexture = nullptr;
  247. // 从池纹理缓存的状态指针
  248. FRDGTextureSubresourceState* State = nullptr;
  249. // 当持有强引用时严格有效,
  250. TRefCountPtr<IPooledRenderTarget> Allocation;
  251. // 在构建图时跟踪合并的子资源状态
  252. FRDGTextureTransientSubresourceStateIndirect MergeState;
  253. // 在图的构建过程中,追踪传递每个子资源的生产者.
  254. TRDGTextureSubresourceArray<FRDGPassHandle> LastProducers;
  255. };
  256. // 池化的缓冲区.
  257. class RENDERCORE_API FRDGPooledBuffer
  258. {
  259. public:
  260. const FRDGBufferDesc Desc;
  261. FRHIUnorderedAccessView* GetOrCreateUAV(FRDGBufferUAVDesc UAVDesc);
  262. FRHIShaderResourceView* GetOrCreateSRV(FRDGBufferSRVDesc SRVDesc);
  263. FRHIVertexBuffer* GetVertexBufferRHI() const;
  264. FRHIIndexBuffer* GetIndexBufferRHI() const;
  265. FRHIStructuredBuffer* GetStructuredBufferRHI() const;
  266. uint32 GetRefCount() const;
  267. uint32 AddRef() const;
  268. uint32 Release() const;
  269. (......)
  270. private:
  271. FRDGPooledBuffer(const FRDGBufferDesc& InDesc);
  272. // 顶点/索引/结构体缓冲.
  273. FVertexBufferRHIRef VertexBuffer;
  274. FIndexBufferRHIRef IndexBuffer;
  275. FStructuredBufferRHIRef StructuredBuffer;
  276. // UAV/SRV.
  277. TMap<FRDGBufferUAVDesc, FUnorderedAccessViewRHIRef, FDefaultSetAllocator, TUAVFuncs<FRDGBufferUAVDesc, FUnorderedAccessViewRHIRef>> UAVs;
  278. TMap<FRDGBufferSRVDesc, FShaderResourceViewRHIRef, FDefaultSetAllocator, TSRVFuncs<FRDGBufferSRVDesc, FShaderResourceViewRHIRef>> SRVs;
  279. void Reset();
  280. void Finalize();
  281. const TCHAR* Name = nullptr;
  282. // 拥有者.
  283. FRDGBufferRef Owner = nullptr;
  284. FRDGSubresourceState State;
  285. mutable uint32 RefCount = 0;
  286. uint32 LastUsedFrame = 0;
  287. };
  288. // 渲染图追踪的缓冲区.
  289. class RENDERCORE_API FRDGBuffer final : public FRDGParentResource
  290. {
  291. public:
  292. const FRDGBufferDesc Desc;
  293. const ERDGBufferFlags Flags;
  294. //
  295. //! The following methods may only be called during pass execution.
  296. // 获取RHI资源.
  297. FRHIVertexBuffer* GetIndirectRHICallBuffer() const
  298. FRHIVertexBuffer* GetRHIVertexBuffer() const
  299. FRHIStructuredBuffer* GetRHIStructuredBuffer() const
  300. //
  301. private:
  302. FRDGBuffer(const TCHAR* InName, const FRDGBufferDesc& InDesc, ERDGBufferFlags InFlags);
  303. // 设置RHI资源.
  304. void SetRHI(FRDGPooledBuffer* InPooledBuffer, FRDGBufferRef& OutPreviousOwner);
  305. void Finalize();
  306. FRDGSubresourceState& GetState() const
  307. // RDG句柄.
  308. FRDGBufferHandle Handle;
  309. // 最后处理此资源的人.
  310. FRDGPassHandle LastProducer;
  311. // 下一个拥有者.
  312. FRDGBufferHandle NextOwner;
  313. // 赋予的池化缓冲区.
  314. FRDGPooledBuffer* PooledBuffer = nullptr;
  315. // 子资源状态.
  316. FRDGSubresourceState* State = nullptr;
  317. TRefCountPtr<FRDGPooledBuffer> Allocation;
  318. FRDGSubresourceState* MergeState = nullptr;
  319. };
  320. (......)

在RDG系统中,基本上对所有的RHI资源进行了封装和包裹,以便进一步控制、管理RHI资源,精准控制它们的生命周期、引用关系及调试信息等,进一步可以优化、裁剪它们,提升渲染性能。

11.2.3 RDG Pass

RDG Pass模块涉及了屏障、资源转换、RDGPass等概念:

  1. // Engine\Source\Runtime\RHI\Public\RHI.h
  2. // 用于表示RHI中挂起的资源转换的不透明数据结构.
  3. struct FRHITransition
  4. {
  5. public:
  6. template <typename T>
  7. inline T* GetPrivateData()
  8. {
  9. uintptr_t Addr = Align(uintptr_t(this + 1), GRHITransitionPrivateData_AlignInBytes);
  10. return reinterpret_cast<T*>(Addr);
  11. }
  12. template <typename T>
  13. inline const T* GetPrivateData() const
  14. {
  15. return const_cast<FRHITransition*>(this)->GetPrivateData<T>();
  16. }
  17. private:
  18. FRHITransition(const FRHITransition&) = delete;
  19. FRHITransition(FRHITransition&&) = delete;
  20. FRHITransition(ERHIPipeline SrcPipelines, ERHIPipeline DstPipelines);
  21. ~FRHITransition();
  22. // 获取总的分配尺寸.
  23. static uint64 GetTotalAllocationSize()
  24. // 获取对齐字节数.
  25. static uint64 GetAlignment();
  26. // 开始标记.
  27. inline void MarkBegin(ERHIPipeline Pipeline) const
  28. {
  29. int8 Mask = int8(Pipeline);
  30. int8 PreviousValue = FPlatformAtomics::InterlockedAnd(&State, ~Mask);
  31. if (PreviousValue == Mask)
  32. {
  33. Cleanup();
  34. }
  35. }
  36. // 结束标记.
  37. inline void MarkEnd(ERHIPipeline Pipeline) const
  38. {
  39. int8 Mask = int8(Pipeline) << int32(ERHIPipeline::Num);
  40. int8 PreviousValue = FPlatformAtomics::InterlockedAnd(&State, ~Mask);
  41. if (PreviousValue == Mask)
  42. {
  43. Cleanup();
  44. }
  45. }
  46. // 清理转换资源, 包含RHI转换和分配的内存.
  47. inline void Cleanup() const;
  48. mutable int8 State;
  49. #if DO_CHECK
  50. mutable ERHIPipeline AllowedSrc;
  51. mutable ERHIPipeline AllowedDst;
  52. #endif
  53. #if ENABLE_RHI_VALIDATION
  54. // 栅栏.
  55. RHIValidation::FFence* Fence = nullptr;
  56. // 挂起的开始操作.
  57. RHIValidation::FOperationsList PendingOperationsBegin;
  58. // 挂起的结束操作.
  59. RHIValidation::FOperationsList PendingOperationsEnd;
  60. #endif
  61. };
  62. // Engine\Source\Runtime\RenderCore\Public\RenderGraphPass.h
  63. // RDG屏障批
  64. class RENDERCORE_API FRDGBarrierBatch
  65. {
  66. public:
  67. FRDGBarrierBatch(const FRDGBarrierBatch&) = delete;
  68. bool IsSubmitted() const
  69. FString GetName() const;
  70. protected:
  71. FRDGBarrierBatch(const FRDGPass* InPass, const TCHAR* InName);
  72. void SetSubmitted();
  73. ERHIPipeline GetPipeline() const
  74. private:
  75. bool bSubmitted = false;
  76. // Graphics或AsyncCompute
  77. ERHIPipeline Pipeline;
  78. #if RDG_ENABLE_DEBUG
  79. const FRDGPass* Pass;
  80. const TCHAR* Name;
  81. #endif
  82. };
  83. // 屏障批开始
  84. class RENDERCORE_API FRDGBarrierBatchBegin final : public FRDGBarrierBatch
  85. {
  86. public:
  87. FRDGBarrierBatchBegin(const FRDGPass* InPass, const TCHAR* InName, TOptional<ERHIPipeline> InOverridePipelineForEnd = {});
  88. ~FRDGBarrierBatchBegin();
  89. // 增加资源转换到批次.
  90. void AddTransition(FRDGParentResourceRef Resource, const FRHITransitionInfo& Info);
  91. const FRHITransition* GetTransition() const;
  92. bool IsTransitionValid() const;
  93. void SetUseCrossPipelineFence();
  94. // 提交屏障/资源转换.
  95. void Submit(FRHIComputeCommandList& RHICmdList);
  96. private:
  97. TOptional<ERHIPipeline> OverridePipelineToEnd;
  98. bool bUseCrossPipelineFence = false;
  99. // 提交后存储的资源转换, 它在结束批处理时被赋回null.
  100. const FRHITransition* Transition = nullptr;
  101. // 要执行的异步资源转换数组.
  102. TArray<FRHITransitionInfo, TInlineAllocator<1, SceneRenderingAllocator>> Transitions;
  103. #if RDG_ENABLE_DEBUG
  104. // 与Transitions数组匹配的RDG资源数组, 仅供调试.
  105. TArray<FRDGParentResource*, SceneRenderingAllocator> Resources;
  106. #endif
  107. };
  108. // 屏障批结束
  109. class RENDERCORE_API FRDGBarrierBatchEnd final : public FRDGBarrierBatch
  110. {
  111. public:
  112. FRDGBarrierBatchEnd(const FRDGPass* InPass, const TCHAR* InName);
  113. ~FRDGBarrierBatchEnd();
  114. // 预留内存.
  115. void ReserveMemory(uint32 ExpectedDependencyCount);
  116. // 在开始批处理上插入依赖项, 开始批可以插入多个结束批.
  117. void AddDependency(FRDGBarrierBatchBegin* BeginBatch);
  118. // 提交资源转换.
  119. void Submit(FRHIComputeCommandList& RHICmdList);
  120. private:
  121. // 此结束批完成后可以唤起的开始批转换.
  122. TArray<FRDGBarrierBatchBegin*, TInlineAllocator<1, SceneRenderingAllocator>> Dependencies;
  123. };
  124. // RGD通道基础类.
  125. class RENDERCORE_API FRDGPass
  126. {
  127. public:
  128. FRDGPass(FRDGEventName&& InName, FRDGParameterStruct InParameterStruct, ERDGPassFlags InFlags);
  129. FRDGPass(const FRDGPass&) = delete;
  130. virtual ~FRDGPass() = default;
  131. // 通道数据接口.
  132. const TCHAR* GetName() const;
  133. FORCEINLINE const FRDGEventName& GetEventName() const;
  134. FORCEINLINE ERDGPassFlags GetFlags() const;
  135. FORCEINLINE ERHIPipeline GetPipeline() const;
  136. // RDG Pass参数.
  137. FORCEINLINE FRDGParameterStruct GetParameters() const;
  138. FORCEINLINE FRDGPassHandle GetHandle() const;
  139. bool IsMergedRenderPassBegin() const;
  140. bool IsMergedRenderPassEnd() const;
  141. bool SkipRenderPassBegin() const;
  142. bool SkipRenderPassEnd() const;
  143. bool IsAsyncCompute() const;
  144. bool IsAsyncComputeBegin() const;
  145. bool IsAsyncComputeEnd() const;
  146. bool IsGraphicsFork() const;
  147. bool IsGraphicsJoin() const;
  148. // 生产者句柄.
  149. const FRDGPassHandleArray& GetProducers() const;
  150. // 跨管线生产者.
  151. FRDGPassHandle GetCrossPipelineProducer() const;
  152. // 跨管线消费者.
  153. FRDGPassHandle GetCrossPipelineConsumer() const;
  154. // 分叉Pass.
  155. FRDGPassHandle GetGraphicsForkPass() const;
  156. // 合并Pass.
  157. FRDGPassHandle GetGraphicsJoinPass() const;
  158. #if RDG_CPU_SCOPES
  159. FRDGCPUScopes GetCPUScopes() const;
  160. #endif
  161. #if RDG_GPU_SCOPES
  162. FRDGGPUScopes GetGPUScopes() const;
  163. #endif
  164. private:
  165. // 前序屏障.
  166. FRDGBarrierBatchBegin& GetPrologueBarriersToBegin(FRDGAllocator& Allocator);
  167. FRDGBarrierBatchEnd& GetPrologueBarriersToEnd(FRDGAllocator& Allocator);
  168. // 后序屏障.
  169. FRDGBarrierBatchBegin& GetEpilogueBarriersToBeginForGraphics(FRDGAllocator& Allocator);
  170. FRDGBarrierBatchBegin& GetEpilogueBarriersToBeginForAsyncCompute(FRDGAllocator& Allocator);
  171. FRDGBarrierBatchBegin& GetEpilogueBarriersToBeginFor(FRDGAllocator& Allocator, ERHIPipeline PipelineForEnd);
  172. //
  173. //! User Methods to Override
  174. // 执行实现.
  175. virtual void ExecuteImpl(FRHIComputeCommandList& RHICmdList) = 0;
  176. //
  177. // 执行.
  178. void Execute(FRHIComputeCommandList& RHICmdList);
  179. // Pass数据.
  180. const FRDGEventName Name;
  181. const FRDGParameterStruct ParameterStruct;
  182. const ERDGPassFlags Flags;
  183. const ERHIPipeline Pipeline;
  184. FRDGPassHandle Handle;
  185. // Pass标记.
  186. union
  187. {
  188. struct
  189. {
  190. uint32 bSkipRenderPassBegin : 1;
  191. uint32 bSkipRenderPassEnd : 1;
  192. uint32 bAsyncComputeBegin : 1;
  193. uint32 bAsyncComputeEnd : 1;
  194. uint32 bAsyncComputeEndExecute : 1;
  195. uint32 bGraphicsFork : 1;
  196. uint32 bGraphicsJoin : 1;
  197. uint32 bUAVAccess : 1;
  198. IF_RDG_ENABLE_DEBUG(uint32 bFirstTextureAllocated : 1);
  199. };
  200. uint32 PackedBits = 0;
  201. };
  202. // 最新的跨管道生产者的句柄.
  203. FRDGPassHandle CrossPipelineProducer;
  204. // 最早的跨管线消费者的句柄.
  205. FRDGPassHandle CrossPipelineConsumer;
  206. // (仅限AsyncCompute)Graphics pass,该通道是异步计算间隔的fork / join.
  207. FRDGPassHandle GraphicsForkPass;
  208. FRDGPassHandle GraphicsJoinPass;
  209. // 处理此通道的前序/后续屏障的通道.
  210. FRDGPassHandle PrologueBarrierPass;
  211. FRDGPassHandle EpilogueBarrierPass;
  212. // 生产者Pass列表.
  213. FRDGPassHandleArray Producers;
  214. // 纹理状态.
  215. struct FTextureState
  216. {
  217. FRDGTextureTransientSubresourceState State;
  218. FRDGTextureTransientSubresourceStateIndirect MergeState;
  219. uint16 ReferenceCount = 0;
  220. };
  221. // 缓冲区状态.
  222. struct FBufferState
  223. {
  224. FRDGSubresourceState State;
  225. FRDGSubresourceState* MergeState = nullptr;
  226. uint16 ReferenceCount = 0;
  227. };
  228. // 将纹理/缓冲区映射到Pass中如何使用的信息。
  229. TSortedMap<FRDGTexture*, FTextureState, SceneRenderingAllocator> TextureStates;
  230. TSortedMap<FRDGBuffer*, FBufferState, SceneRenderingAllocator> BufferStates;
  231. // 在执行此Pass期间,计划开始的Pass参数列表.
  232. TArray<FRDGPass*, TInlineAllocator<1, SceneRenderingAllocator>> ResourcesToBegin;
  233. TArray<FRDGPass*, TInlineAllocator<1, SceneRenderingAllocator>> ResourcesToEnd;
  234. // 在acquire完成*之后**在丢弃*之前*获取的纹理列表. 获取适用于所有分配的纹理.
  235. TArray<FRHITexture*, SceneRenderingAllocator> TexturesToAcquire;
  236. // 在Pass完成*之后*,获得(acquires)*之后*,丢弃的纹理列表. 丢弃仅适用于标记为瞬态(transient)的纹理,并且纹理的最后一个别名(alia)使用自动丢弃行为(为了支持更干净的切换到用户或返回池).
  237. TArray<FRHITexture*, SceneRenderingAllocator> TexturesToDiscard;
  238. FRDGBarrierBatchBegin* PrologueBarriersToBegin = nullptr;
  239. FRDGBarrierBatchEnd* PrologueBarriersToEnd = nullptr;
  240. FRDGBarrierBatchBegin* EpilogueBarriersToBeginForGraphics = nullptr;
  241. FRDGBarrierBatchBegin* EpilogueBarriersToBeginForAsyncCompute = nullptr;
  242. EAsyncComputeBudget AsyncComputeBudget = EAsyncComputeBudget::EAll_4;
  243. };
  244. // RDG Pass Lambda执行函数.
  245. template <typename ParameterStructType, typename ExecuteLambdaType>
  246. class TRDGLambdaPass : public FRDGPass
  247. {
  248. (......)
  249. TRDGLambdaPass(FRDGEventName&& InName, const ParameterStructType* InParameterStruct, ERDGPassFlags InPassFlags, ExecuteLambdaType&& InExecuteLambda);
  250. private:
  251. // 执行实现.
  252. void ExecuteImpl(FRHIComputeCommandList& RHICmdList) override
  253. {
  254. check(!kSupportsRaster || RHICmdList.IsImmediate());
  255. // 调用Lambda实例.
  256. ExecuteLambda(static_cast<TRHICommandList&>(RHICmdList));
  257. }
  258. Lambda实例.
  259. ExecuteLambdaType ExecuteLambda;
  260. };
  261. // 附带空Lambda的Pass.
  262. template <typename ExecuteLambdaType>
  263. class TRDGEmptyLambdaPass : public TRDGLambdaPass<FEmptyShaderParameters, ExecuteLambdaType>
  264. {
  265. public:
  266. TRDGEmptyLambdaPass(FRDGEventName&& InName, ERDGPassFlags InPassFlags, ExecuteLambdaType&& InExecuteLambda);
  267. private:
  268. FEmptyShaderParameters EmptyShaderParameters;
  269. };
  270. // 用于前序/后序Pass.
  271. class FRDGSentinelPass final : public FRDGPass
  272. {
  273. public:
  274. FRDGSentinelPass(FRDGEventName&& Name);
  275. private:
  276. void ExecuteImpl(FRHIComputeCommandList&) override;
  277. FEmptyShaderParameters EmptyShaderParameters;
  278. };

以上显示RDG的Pass比较复杂,是RDG体系中最核心的类型之一,涉及了消费者、生产者、转换依赖、各类资源状态等等数据和处理。RDG的Pass有以下几种类型:

FRDGPass

TRDGLambdaPass

FRDGSentinelPass

RDG Pass和渲染Pass并非一一对应关系,有可能多个合并成一个渲染Pass,详见后面章节。RDG Pass最复杂莫过于多线程处理、资源状态转换以及依赖处理,不过本节先不涉及,后续章节再详细探讨。

11.2.4 FRDGBuilder

FRDGBuilder是RDG体系的心脏和发动机,也是个大管家,负责收集渲染Pass和参数,编译Pass、数据,处理资源依赖,裁剪和优化各类数据,还有提供执行接口。它的声明如下:

  1. class RENDERCORE_API FRDGBuilder
  2. {
  3. public:
  4. FRDGBuilder(FRHICommandListImmediate& InRHICmdList, FRDGEventName InName = {}, const char* UnaccountedCSVStat = kDefaultUnaccountedCSVStat);
  5. FRDGBuilder(const FRDGBuilder&) = delete;
  6. // 查找外部纹理, 若找不到返回null.
  7. FRDGTextureRef FindExternalTexture(FRHITexture* Texture) const;
  8. FRDGTextureRef FindExternalTexture(IPooledRenderTarget* ExternalPooledTexture, ERenderTargetTexture Texture) const;
  9. // 注册外部池内RTRDG, 以便RDG追踪之. 池内RT可能包含两种RHI纹理: MSAA和非MSAA.
  10. FRDGTextureRef RegisterExternalTexture(
  11. const TRefCountPtr<IPooledRenderTarget>& ExternalPooledTexture,
  12. ERenderTargetTexture Texture = ERenderTargetTexture::ShaderResource,
  13. ERDGTextureFlags Flags = ERDGTextureFlags::None);
  14. FRDGTextureRef RegisterExternalTexture(
  15. const TRefCountPtr<IPooledRenderTarget>& ExternalPooledTexture,
  16. const TCHAR* NameIfNotRegistered,
  17. ERenderTargetTexture RenderTargetTexture = ERenderTargetTexture::ShaderResource,
  18. ERDGTextureFlags Flags = ERDGTextureFlags::None);
  19. // 注册外部缓冲区到RDG, 以便RDG追踪之.
  20. FRDGBufferRef RegisterExternalBuffer(const TRefCountPtr<FRDGPooledBuffer>& ExternalPooledBuffer, ERDGBufferFlags Flags = ERDGBufferFlags::None);
  21. FRDGBufferRef RegisterExternalBuffer(const TRefCountPtr<FRDGPooledBuffer>& ExternalPooledBuffer, ERDGBufferFlags Flags, ERHIAccess AccessFinal);
  22. FRDGBufferRef RegisterExternalBuffer(
  23. const TRefCountPtr<FRDGPooledBuffer>& ExternalPooledBuffer,
  24. const TCHAR* NameIfNotRegistered,
  25. ERDGBufferFlags Flags = ERDGBufferFlags::None);
  26. // 资源创建接口.
  27. FRDGTextureRef CreateTexture(const FRDGTextureDesc& Desc, const TCHAR* Name, ERDGTextureFlags Flags = ERDGTextureFlags::None);
  28. FRDGBufferRef CreateBuffer(const FRDGBufferDesc& Desc, const TCHAR* Name, ERDGBufferFlags Flags = ERDGBufferFlags::None);
  29. FRDGTextureSRVRef CreateSRV(const FRDGTextureSRVDesc& Desc);
  30. FRDGBufferSRVRef CreateSRV(const FRDGBufferSRVDesc& Desc);
  31. FORCEINLINE FRDGBufferSRVRef CreateSRV(FRDGBufferRef Buffer, EPixelFormat Format);
  32. FRDGTextureUAVRef CreateUAV(const FRDGTextureUAVDesc& Desc, ERDGUnorderedAccessViewFlags Flags = ERDGUnorderedAccessViewFlags::None);
  33. FORCEINLINE FRDGTextureUAVRef CreateUAV(FRDGTextureRef Texture, ERDGUnorderedAccessViewFlags Flags = ERDGUnorderedAccessViewFlags::None);
  34. FRDGBufferUAVRef CreateUAV(const FRDGBufferUAVDesc& Desc, ERDGUnorderedAccessViewFlags Flags = ERDGUnorderedAccessViewFlags::None);
  35. FORCEINLINE FRDGBufferUAVRef CreateUAV(FRDGBufferRef Buffer, EPixelFormat Format, ERDGUnorderedAccessViewFlags Flags = ERDGUnorderedAccessViewFlags::None);
  36. template <typename ParameterStructType>
  37. TRDGUniformBufferRef<ParameterStructType> CreateUniformBuffer(ParameterStructType* ParameterStruct);
  38. // 分配内存, 内存由RDG管理生命周期.
  39. void* Alloc(uint32 SizeInBytes, uint32 AlignInBytes);
  40. template <typename PODType>
  41. PODType* AllocPOD();
  42. template <typename ObjectType, typename... TArgs>
  43. ObjectType* AllocObject(TArgs&&... Args);
  44. template <typename ParameterStructType>
  45. ParameterStructType* AllocParameters();
  46. // 增加附带参数和LambdaPass.
  47. template <typename ParameterStructType, typename ExecuteLambdaType>
  48. FRDGPassRef AddPass(FRDGEventName&& Name, const ParameterStructType* ParameterStruct, ERDGPassFlags Flags, ExecuteLambdaType&& ExecuteLambda);
  49. // 增加没有参数只有LambdaPass.
  50. template <typename ExecuteLambdaType>
  51. FRDGPassRef AddPass(FRDGEventName&& Name, ERDGPassFlags Flags, ExecuteLambdaType&& ExecuteLambda);
  52. // 在Builder执行末期, 提取池内纹理到指定的指针. 对于RDG创建的资源, 这将延长GPU资源的生命周期,直到执行,指针被填充. 如果指定,纹理将转换为AccessFinal状态, 否则将转换为kDefaultAccessFinal状态.
  53. void QueueTextureExtraction(FRDGTextureRef Texture, TRefCountPtr<IPooledRenderTarget>* OutPooledTexturePtr);
  54. void QueueTextureExtraction(FRDGTextureRef Texture, TRefCountPtr<IPooledRenderTarget>* OutPooledTexturePtr, ERHIAccess AccessFinal);
  55. // 在Builder执行末期, 提取缓冲区到指定的指针.
  56. void QueueBufferExtraction(FRDGBufferRef Buffer, TRefCountPtr<FRDGPooledBuffer>* OutPooledBufferPtr);
  57. void QueueBufferExtraction(FRDGBufferRef Buffer, TRefCountPtr<FRDGPooledBuffer>* OutPooledBufferPtr, ERHIAccess AccessFinal);
  58. // 预分配资源. 只对RDG创建的资源, 会强制立即分配底层池内资源, 有效地将其推广到外部资源. 这将增加内存压力,但允许使用GetPooled{Texture, Buffer}查询池中的资源. 主要用于增量地将代码移植到RDG.
  59. void PreallocateTexture(FRDGTextureRef Texture);
  60. void PreallocateBuffer(FRDGBufferRef Buffer);
  61. // 立即获取底层资源, 只允许用于注册或预分配的资源.
  62. const TRefCountPtr<IPooledRenderTarget>& GetPooledTexture(FRDGTextureRef Texture) const;
  63. const TRefCountPtr<FRDGPooledBuffer>& GetPooledBuffer(FRDGBufferRef Buffer) const;
  64. // 设置执行之后的状态.
  65. void SetTextureAccessFinal(FRDGTextureRef Texture, ERHIAccess Access);
  66. void SetBufferAccessFinal(FRDGBufferRef Buffer, ERHIAccess Access);
  67. void RemoveUnusedTextureWarning(FRDGTextureRef Texture);
  68. void RemoveUnusedBufferWarning(FRDGBufferRef Buffer);
  69. // 执行队列Pass,管理渲染目标(RHI RenderPasses)的设置,资源转换和队列纹理提取.
  70. void Execute();
  71. // 渲染图形资源池的每帧更新.
  72. static void TickPoolElements();
  73. // RDG使用的命令列表.
  74. FRHICommandListImmediate& RHICmdList;
  75. private:
  76. static const ERHIAccess kDefaultAccessInitial = ERHIAccess::Unknown;
  77. static const ERHIAccess kDefaultAccessFinal = ERHIAccess::SRVMask;
  78. static const char* const kDefaultUnaccountedCSVStat;
  79. // RDG使用的AsyncCompute命令列表.
  80. FRHIAsyncComputeCommandListImmediate& RHICmdListAsyncCompute;
  81. FRDGAllocator Allocator;
  82. const FRDGEventName BuilderName;
  83. ERDGPassFlags OverridePassFlags(const TCHAR* PassName, ERDGPassFlags Flags, bool bAsyncComputeSupported);
  84. FORCEINLINE FRDGPassHandle GetProloguePassHandle() const;
  85. FORCEINLINE FRDGPassHandle GetEpiloguePassHandle() const;
  86. // RDG对象注册表.
  87. FRDGPassRegistry Passes;
  88. FRDGTextureRegistry Textures;
  89. FRDGBufferRegistry Buffers;
  90. FRDGViewRegistry Views;
  91. FRDGUniformBufferRegistry UniformBuffers;
  92. // 已被裁剪的Pass.
  93. FRDGPassBitArray PassesToCull;
  94. // 没有参数的Pass.
  95. FRDGPassBitArray PassesWithEmptyParameters;
  96. // 跟踪外部资源到已注册的渲染图对应项,以进行重复数据删除.
  97. TSortedMap<FRHITexture*, FRDGTexture*, TInlineAllocator<4, SceneRenderingAllocator>> ExternalTextures;
  98. TSortedMap<const FRDGPooledBuffer*, FRDGBuffer*, TInlineAllocator<4, SceneRenderingAllocator>> ExternalBuffers;
  99. FRDGPass* ProloguePass = nullptr;
  100. FRDGPass* EpiloguePass = nullptr;
  101. // 待提取资源的列表.
  102. TArray<TPair<FRDGTextureRef, TRefCountPtr<IPooledRenderTarget>*>, TInlineAllocator<4, SceneRenderingAllocator>> ExtractedTextures;
  103. TArray<TPair<FRDGBufferRef, TRefCountPtr<FRDGPooledBuffer>*>, TInlineAllocator<4, SceneRenderingAllocator>> ExtractedBuffers;
  104. // 用于中间操作的纹理状态, 保存在这里以避免重新分配.
  105. FRDGTextureTransientSubresourceStateIndirect ScratchTextureState;
  106. EAsyncComputeBudget AsyncComputeBudgetScope = EAsyncComputeBudget::EAll_4;
  107. // 编译.
  108. void Compile();
  109. // 清理.
  110. void Clear();
  111. // 开始资源转换.
  112. void BeginResourceRHI(FRDGUniformBuffer* UniformBuffer);
  113. void BeginResourceRHI(FRDGPassHandle, FRDGTexture* Texture);
  114. void BeginResourceRHI(FRDGPassHandle, FRDGTextureSRV* SRV);
  115. void BeginResourceRHI(FRDGPassHandle, FRDGTextureUAV* UAV);
  116. void BeginResourceRHI(FRDGPassHandle, FRDGBuffer* Buffer);
  117. void BeginResourceRHI(FRDGPassHandle, FRDGBufferSRV* SRV);
  118. void BeginResourceRHI(FRDGPassHandle, FRDGBufferUAV* UAV);
  119. // 结束资源转换.
  120. void EndResourceRHI(FRDGPassHandle, FRDGTexture* Texture, uint32 ReferenceCount);
  121. void EndResourceRHI(FRDGPassHandle, FRDGBuffer* Buffer, uint32 ReferenceCount);
  122. // Pass接口.
  123. void SetupPassInternal(FRDGPass* Pass, FRDGPassHandle PassHandle, ERHIPipeline PassPipeline);
  124. void SetupPass(FRDGPass* Pass);
  125. void SetupEmptyPass(FRDGPass* Pass);
  126. void ExecutePass(FRDGPass* Pass);
  127. // Pass前序后序.
  128. void ExecutePassPrologue(FRHIComputeCommandList& RHICmdListPass, FRDGPass* Pass);
  129. void ExecutePassEpilogue(FRHIComputeCommandList& RHICmdListPass, FRDGPass* Pass);
  130. // 收集资源和屏障.
  131. void CollectPassResources(FRDGPassHandle PassHandle);
  132. void CollectPassBarriers(FRDGPassHandle PassHandle, FRDGPassHandle& LastUntrackedPassHandle);
  133. // 增加Pass依赖.
  134. void AddPassDependency(FRDGPassHandle ProducerHandle, FRDGPassHandle ConsumerHandle);
  135. // 增加后序转换.
  136. void AddEpilogueTransition(FRDGTextureRef Texture, FRDGPassHandle LastUntrackedPassHandle);
  137. void AddEpilogueTransition(FRDGBufferRef Buffer, FRDGPassHandle LastUntrackedPassHandle);
  138. // 增加普通转换.
  139. void AddTransition(FRDGPassHandle PassHandle, FRDGTextureRef Texture, const FRDGTextureTransientSubresourceStateIndirect& StateAfter, FRDGPassHandle LastUntrackedPassHandle);
  140. void AddTransition(FRDGPassHandle PassHandle, FRDGBufferRef Buffer, FRDGSubresourceState StateAfter, FRDGPassHandle LastUntrackedPassHandle);
  141. void AddTransitionInternal(
  142. FRDGParentResource* Resource,
  143. FRDGSubresourceState StateBefore,
  144. FRDGSubresourceState StateAfter,
  145. FRDGPassHandle LastUntrackedPassHandle,
  146. const FRHITransitionInfo& TransitionInfo);
  147. // 获取渲染Pass信息.
  148. FRHIRenderPassInfo GetRenderPassInfo(const FRDGPass* Pass) const;
  149. // 分配子资源.
  150. FRDGSubresourceState* AllocSubresource(const FRDGSubresourceState& Other);
  151. #if RDG_ENABLE_DEBUG
  152. void VisualizePassOutputs(const FRDGPass* Pass);
  153. void ClobberPassOutputs(const FRDGPass* Pass);
  154. #endif
  155. };

作为RDG系统的驱动器,FRDGBuilder负责存储数据、处理状态转换、自动管理资源生命周期和屏障、裁剪无效资源,以及收集、编译、执行Pass,提取纹理或缓冲等等功能。它的内部执行机制比较复杂,后续的章节会详尽地剖析之。

11.3 RDG机制

本节将主要阐述RDG的工作机制、过程和原理,以及它在渲染方面的优势和特性。

有的同学如果只想学习如何使用RDG,则可以跳过本章而直接阅读11.4 RDG开发。

11.3.1 RDG机制概述

渲染依赖图框架(Rendering Dependency Graph Framework),它设置Lambda范围,该范围设计为Pass,利用延迟执行向RHI发出GPU命令。它们是通过FRDGBuilder::AddPass()创建的。当创建一个Pass时,它需要Shader参数。 可以是任何着色器参数,但框架最感兴趣的是渲染图形资源。

保存所有Pass参数的结构应该使用FRDGBuilder::AllocParameters()分配,以确保正确的生命周期,因为Lambda的执行是被延迟的。

用FRDGBuilder::CreateTexture()或FRDGBuilder::CreateBuffer()创建的一个渲染图资源只记录资源描述符。当资源需要时,将按图表进行分配。渲染图将跟踪资源的生命周期,并在剩余的Pass不再引用它时释放和重用内存。

Pass使用的所有渲染图资源必须在FRDGBuilder::AddPass()给出的Pass参数中,因为渲染图需要知道每个Pass正在使用哪些资源。

只保证在执行Pass时分配资源。 因此,访问它们应该只在使用FRDGBuilder::AddPass()创建的Pass的Lambda范围内完成。未列出Pass使用的一些资源可能会导致问题。

重要的是不要在参数中引用比Pass需要的更多的图资源,因为这人为地增加了关于该资源生命周期的图信息。这可能会导致内存使用的增加或防止Pass的重叠地执行。一个例子是ClearUnusedGraphResources(),它可以自动清除Shader中没有使用的资源引用。如果资源在Pass中没有被使用,则会发出警告。

Pass执行的lambda范围可能发生在FRDGBuilder::AddPass()之后的任何时候。出于调试的目的,它可能直接发生在具有Immediate模式的AddPass()中。当在传递执行过程中发生错误时,立即模式允许您使用可能包含错误源原因的Pass设置的调用堆栈。Immediate模式可以通过命令行命令-rdgimmediate或控制台变量r.RDG.ImmediateMode=1来启用。

由遗留代码生成的池管理资源纹理FPooledRenderTarget可以通过使用FRDGBuilder::RegisterExternalTexture()在渲染图中使用。

有了Pass依赖关系的信息,执行可能会对不同的硬件目标进行优先级排序,例如对内存压力或Pass GPU执行并发进行优先级排序。因此,不能保证Pass的执行顺序。Pass的执行顺序只能保证将在中间资源上执行工作,就像立即模式在GPU上执行工作一样。

渲染图通道不应该修改外部数据结构的状态,因为这可能会根据Pass的执行顺序导致边界情况。应该使用FRDGBuilder::QueueTextureExtraction()提取执行完成后幸存的渲染图资源(例如viewport back buffer、TAA历史记录…)。如果检测到一个Pass对生成任何计划提取的资源或修改外部纹理没有用处,这个Pass甚至可能不会执行警告。

除非是出于强大的技术原因(比如为VR一次性渲染多个视图的立体渲染),否则不要在同一Pass中将多个工作捆绑在不同的资源上。这将最终在一组工作上创建更多的依赖关系,单个工作可能只需要这些依赖关系的一个子集。调度程序可能会将其中的一部分与其它GPU工作重叠。这也可能保留分配的瞬态资源更长的时间,潜在地增加整帧的最高内存压力峰值。

虽然AddPass()只希望lambda范围有延迟执行,但这并不意味着我们需要编写一个。通过使用一个更简单的工具箱(如FComputeShaderUtils、FPixelShaderUtils)就可以满足大多数情况的需求了。

11.3.2 FRDGBuilder::AddPass

FRDGBuilder::AddPass是向RDG系统增加一个包含Pass参数和Lambda的Pass,其具体的逻辑如下:

  1. // Engine\Source\Runtime\RenderCore\Public\RenderGraphBuilder.inl
  2. template <typename ParameterStructType, typename ExecuteLambdaType>
  3. FRDGPassRef FRDGBuilder::AddPass(FRDGEventName&& Name, const ParameterStructType* ParameterStruct, ERDGPassFlags Flags, ExecuteLambdaType&& ExecuteLambda)
  4. {
  5. using LambdaPassType = TRDGLambdaPass<ParameterStructType, ExecuteLambdaType>;
  6. (......)
  7. // 分配RDG Pass实例.
  8. FRDGPass* Pass = Allocator.AllocObject<LambdaPassType>(
  9. MoveTemp(Name),
  10. ParameterStruct,
  11. OverridePassFlags(Name.GetTCHAR(), Flags, LambdaPassType::kSupportsAsyncCompute),
  12. MoveTemp(ExecuteLambda));
  13. // 加入Pass列表.
  14. Passes.Insert(Pass);
  15. // 设置Pass.
  16. SetupPass(Pass);
  17. return Pass;
  18. }

AddPass的逻辑比较简单,将传入的数据构造一个FRDGPass实例,然后加入列表并设置Pass数据。下面是SetupPass的具体逻辑:

  1. void FRDGBuilder::SetupPass(FRDGPass* Pass)
  2. {
  3. // 获取Pass数据.
  4. const FRDGParameterStruct PassParameters = Pass->GetParameters();
  5. const FRDGPassHandle PassHandle = Pass->GetHandle();
  6. const ERDGPassFlags PassFlags = Pass->GetFlags();
  7. const ERHIPipeline PassPipeline = Pass->GetPipeline();
  8. bool bPassUAVAccess = false;
  9. // ----处理纹理状态----
  10. Pass->TextureStates.Reserve(PassParameters.GetTextureParameterCount() + (PassParameters.HasRenderTargets() ? (MaxSimultaneousRenderTargets + 1) : 0));
  11. // 遍历所有纹理, 对每个纹理执行状态/数据/引用等处理.
  12. EnumerateTextureAccess(PassParameters, PassFlags, [&](FRDGViewRef TextureView, FRDGTextureRef Texture, ERHIAccess Access, FRDGTextureSubresourceRange Range)
  13. {
  14. const FRDGViewHandle NoUAVBarrierHandle = GetHandleIfNoUAVBarrier(TextureView);
  15. const EResourceTransitionFlags TransitionFlags = GetTextureViewTransitionFlags(TextureView, Texture);
  16. auto& PassState = Pass->TextureStates.FindOrAdd(Texture);
  17. PassState.ReferenceCount++;
  18. const bool bWholeTextureRange = Range.IsWholeResource(Texture->GetSubresourceLayout());
  19. bool bWholePassState = IsWholeResource(PassState.State);
  20. // Convert the pass state to subresource dimensionality if we've found a subresource range.
  21. if (!bWholeTextureRange && bWholePassState)
  22. {
  23. InitAsSubresources(PassState.State, Texture->Layout);
  24. bWholePassState = false;
  25. }
  26. const auto AddSubresourceAccess = [&](FRDGSubresourceState& State)
  27. {
  28. State.Access = MakeValidAccess(State.Access | Access);
  29. State.Flags |= TransitionFlags;
  30. State.NoUAVBarrierFilter.AddHandle(NoUAVBarrierHandle);
  31. State.Pipeline = PassPipeline;
  32. };
  33. if (bWholePassState)
  34. {
  35. AddSubresourceAccess(GetWholeResource(PassState.State));
  36. }
  37. else
  38. {
  39. EnumerateSubresourceRange(PassState.State, Texture->Layout, Range, AddSubresourceAccess);
  40. }
  41. bPassUAVAccess |= EnumHasAnyFlags(Access, ERHIAccess::UAVMask);
  42. });
  43. // ----处理缓冲区状态----
  44. Pass->BufferStates.Reserve(PassParameters.GetBufferParameterCount());
  45. // 遍历所有缓冲区, 对每个缓冲区执行状态/数据/引用等处理.
  46. EnumerateBufferAccess(PassParameters, PassFlags, [&](FRDGViewRef BufferView, FRDGBufferRef Buffer, ERHIAccess Access)
  47. {
  48. const FRDGViewHandle NoUAVBarrierHandle = GetHandleIfNoUAVBarrier(BufferView);
  49. auto& PassState = Pass->BufferStates.FindOrAdd(Buffer);
  50. PassState.ReferenceCount++;
  51. PassState.State.Access = MakeValidAccess(PassState.State.Access | Access);
  52. PassState.State.NoUAVBarrierFilter.AddHandle(NoUAVBarrierHandle);
  53. PassState.State.Pipeline = PassPipeline;
  54. bPassUAVAccess |= EnumHasAnyFlags(Access, ERHIAccess::UAVMask);
  55. });
  56. Pass->bUAVAccess = bPassUAVAccess;
  57. const bool bEmptyParameters = !Pass->TextureStates.Num() && !Pass->BufferStates.Num();
  58. PassesWithEmptyParameters.Add(bEmptyParameters);
  59. // 在Graphics管线, Pass可以开始/结束Pass自己的资源. 异步计算则在编译期间编排.
  60. if (PassPipeline == ERHIPipeline::Graphics && !bEmptyParameters)
  61. {
  62. Pass->ResourcesToBegin.Add(Pass);
  63. Pass->ResourcesToEnd.Add(Pass);
  64. }
  65. // 内部设置Pass.
  66. SetupPassInternal(Pass, PassHandle, PassPipeline);
  67. }

下面继续解析SetupPassInternal:

  1. void FRDGBuilder::SetupPassInternal(FRDGPass* Pass, FRDGPassHandle PassHandle, ERHIPipeline PassPipeline)
  2. {
  3. // 设置各种Pass为自身句柄.
  4. Pass->GraphicsJoinPass = PassHandle;
  5. Pass->GraphicsForkPass = PassHandle;
  6. Pass->PrologueBarrierPass = PassHandle;
  7. Pass->EpilogueBarrierPass = PassHandle;
  8. (......)
  9. // 如果是立即模式且非后序Pass,
  10. if (GRDGImmediateMode && Pass != EpiloguePass)
  11. {
  12. // 简单地将merge状态重定向成pass状态,因为不会编译图.
  13. // 纹理的Merge状态.
  14. for (auto& TexturePair : Pass->TextureStates)
  15. {
  16. auto& PassState = TexturePair.Value;
  17. const uint32 SubresourceCount = PassState.State.Num();
  18. PassState.MergeState.SetNum(SubresourceCount);
  19. for (uint32 Index = 0; Index < SubresourceCount; ++Index)
  20. {
  21. if (PassState.State[Index].Access != ERHIAccess::Unknown)
  22. {
  23. PassState.MergeState[Index] = &PassState.State[Index];
  24. PassState.MergeState[Index]->SetPass(PassHandle);
  25. }
  26. }
  27. }
  28. // 缓冲区的Merge状态.
  29. for (auto& BufferPair : Pass->BufferStates)
  30. {
  31. auto& PassState = BufferPair.Value;
  32. PassState.MergeState = &PassState.State;
  33. PassState.MergeState->SetPass(PassHandle);
  34. }
  35. FRDGPassHandle LastUntrackedPassHandle = GetProloguePassHandle();
  36. // 收集Pass资源.
  37. CollectPassResources(PassHandle);
  38. // 收集Pass屏障.
  39. CollectPassBarriers(PassHandle, LastUntrackedPassHandle);
  40. // 直接执行Pass.
  41. ExecutePass(Pass);
  42. }
  43. }

总结起来,AddPass会根据传入的参数构建一个RDG Pass的实例,然后设置该Pass的纹理和缓冲区数据,接着用内部设置Pass的依赖Pass等句柄,如果是立即模式,会重定向纹理和缓冲区的Merge状态成Pass状态,并且直接执行。

11.3.3 FRDGBuilder::Compile

FRDGBuilder的编译逻辑非常复杂,执行了很多处理和优化,具体如下:

  1. void FRDGBuilder::Compile()
  2. {
  3. uint32 RasterPassCount = 0;
  4. uint32 AsyncComputePassCount = 0;
  5. // Pass标记位.
  6. FRDGPassBitArray PassesOnAsyncCompute(false, Passes.Num());
  7. FRDGPassBitArray PassesOnRaster(false, Passes.Num());
  8. FRDGPassBitArray PassesWithUntrackedOutputs(false, Passes.Num());
  9. FRDGPassBitArray PassesToNeverCull(false, Passes.Num());
  10. const FRDGPassHandle ProloguePassHandle = GetProloguePassHandle();
  11. const FRDGPassHandle EpiloguePassHandle = GetEpiloguePassHandle();
  12. const auto IsCrossPipeline = [&](FRDGPassHandle A, FRDGPassHandle B)
  13. {
  14. return PassesOnAsyncCompute[A] != PassesOnAsyncCompute[B];
  15. };
  16. const auto IsSortedBefore = [&](FRDGPassHandle A, FRDGPassHandle B)
  17. {
  18. return A < B;
  19. };
  20. const auto IsSortedAfter = [&](FRDGPassHandle A, FRDGPassHandle B)
  21. {
  22. return A > B;
  23. };
  24. // 在图中构建生产者/消费者依赖关系,并构建打包的元数据位数组,以便在搜索符合特定条件的Pass时获得更好的缓存一致性.
  25. // 搜索根也被用来进行筛选. 携带了不跟踪的RHI输出(e.g. SHADER_PARAMETER_{BUFFER, TEXTURE}_UAV)的Pass不能被裁剪, 也不能写入外部资源的任何Pass.
  26. // 资源提取将生命周期延长到尾声(epilogue)Pass,尾声Pass总是图的根。前言和尾声是辅助Pass,因此永远不会被淘汰。
  27. {
  28. SCOPED_NAMED_EVENT(FRDGBuilder_Compile_Culling_Dependencies, FColor::Emerald);
  29. // 增加裁剪依赖.
  30. const auto AddCullingDependency = [&](FRDGPassHandle& ProducerHandle, FRDGPassHandle PassHandle, ERHIAccess Access)
  31. {
  32. if (Access != ERHIAccess::Unknown)
  33. {
  34. if (ProducerHandle.IsValid())
  35. {
  36. // 增加Pass依赖.
  37. AddPassDependency(ProducerHandle, PassHandle);
  38. }
  39. // 如果可写, 则存储新的生产者.
  40. if (IsWritableAccess(Access))
  41. {
  42. ProducerHandle = PassHandle;
  43. }
  44. }
  45. };
  46. // 遍历所有Pass, 处理每个Pass的纹理和缓冲区状态等.
  47. for (FRDGPassHandle PassHandle = Passes.Begin(); PassHandle != Passes.End(); ++PassHandle)
  48. {
  49. FRDGPass* Pass = Passes[PassHandle];
  50. bool bUntrackedOutputs = Pass->GetParameters().HasExternalOutputs();
  51. // 处理Pass的所有纹理状态.
  52. for (auto& TexturePair : Pass->TextureStates)
  53. {
  54. FRDGTextureRef Texture = TexturePair.Key;
  55. auto& LastProducers = Texture->LastProducers;
  56. auto& PassState = TexturePair.Value.State;
  57. const bool bWholePassState = IsWholeResource(PassState);
  58. const bool bWholeProducers = IsWholeResource(LastProducers);
  59. // 生产者数组需要至少和pass状态数组一样大.
  60. if (bWholeProducers && !bWholePassState)
  61. {
  62. InitAsSubresources(LastProducers, Texture->Layout);
  63. }
  64. // 增加裁剪依赖.
  65. for (uint32 Index = 0, Count = LastProducers.Num(); Index < Count; ++Index)
  66. {
  67. AddCullingDependency(LastProducers[Index], PassHandle, PassState[bWholePassState ? 0 : Index].Access);
  68. }
  69. bUntrackedOutputs |= Texture->bExternal;
  70. }
  71. // 处理Pass的所有缓冲区状态.
  72. for (auto& BufferPair : Pass->BufferStates)
  73. {
  74. FRDGBufferRef Buffer = BufferPair.Key;
  75. AddCullingDependency(Buffer->LastProducer, PassHandle, BufferPair.Value.State.Access);
  76. bUntrackedOutputs |= Buffer->bExternal;
  77. }
  78. // 处理Pass的其它标记和数据.
  79. const ERDGPassFlags PassFlags = Pass->GetFlags();
  80. const bool bAsyncCompute = EnumHasAnyFlags(PassFlags, ERDGPassFlags::AsyncCompute);
  81. const bool bRaster = EnumHasAnyFlags(PassFlags, ERDGPassFlags::Raster);
  82. const bool bNeverCull = EnumHasAnyFlags(PassFlags, ERDGPassFlags::NeverCull);
  83. PassesOnRaster[PassHandle] = bRaster;
  84. PassesOnAsyncCompute[PassHandle] = bAsyncCompute;
  85. PassesToNeverCull[PassHandle] = bNeverCull;
  86. PassesWithUntrackedOutputs[PassHandle] = bUntrackedOutputs;
  87. AsyncComputePassCount += bAsyncCompute ? 1 : 0;
  88. RasterPassCount += bRaster ? 1 : 0;
  89. }
  90. // prologue/epilogue设置为不追踪, 它们分别负责外部资源的导入/导出.
  91. PassesWithUntrackedOutputs[ProloguePassHandle] = true;
  92. PassesWithUntrackedOutputs[EpiloguePassHandle] = true;
  93. // 处理提取纹理的裁剪依赖.
  94. for (const auto& Query : ExtractedTextures)
  95. {
  96. FRDGTextureRef Texture = Query.Key;
  97. for (FRDGPassHandle& ProducerHandle : Texture->LastProducers)
  98. {
  99. AddCullingDependency(ProducerHandle, EpiloguePassHandle, Texture->AccessFinal);
  100. }
  101. Texture->ReferenceCount++;
  102. }
  103. // 处理提取缓冲区的裁剪依赖.
  104. for (const auto& Query : ExtractedBuffers)
  105. {
  106. FRDGBufferRef Buffer = Query.Key;
  107. AddCullingDependency(Buffer->LastProducer, EpiloguePassHandle, Buffer->AccessFinal);
  108. Buffer->ReferenceCount++;
  109. }
  110. }
  111. // -------- 处理Pass裁剪 --------
  112. if (GRDGCullPasses)
  113. {
  114. TArray<FRDGPassHandle, TInlineAllocator<32, SceneRenderingAllocator>> PassStack;
  115. // 所有Pass初始化为剔除.
  116. PassesToCull.Init(true, Passes.Num());
  117. // 收集Pass的根列表, 符合条件的是那些不追踪的输出或标记为永不剔除的Pass.
  118. for (FRDGPassHandle PassHandle = Passes.Begin(); PassHandle != Passes.End(); ++PassHandle)
  119. {
  120. if (PassesWithUntrackedOutputs[PassHandle] || PassesToNeverCull[PassHandle])
  121. {
  122. PassStack.Add(PassHandle);
  123. }
  124. }
  125. // 非递归循环的栈遍历, 采用深度优先搜索方式, 标记每个根可达的Pass节点为不裁剪.
  126. while (PassStack.Num())
  127. {
  128. const FRDGPassHandle PassHandle = PassStack.Pop();
  129. if (PassesToCull[PassHandle])
  130. {
  131. PassesToCull[PassHandle] = false;
  132. PassStack.Append(Passes[PassHandle]->Producers);
  133. #if STATS
  134. --GRDGStatPassCullCount;
  135. #endif
  136. }
  137. }
  138. }
  139. else // 不启用Pass裁剪, 所有Pass初始化为不裁剪.
  140. {
  141. PassesToCull.Init(false, Passes.Num());
  142. }
  143. // -------- 处理Pass屏障 --------
  144. // 遍历经过筛选的图,并为每个子资源编译屏障, 某些过渡是多余的, 例如read-to-read。
  145. // RDG采用了保守的启发式,选择不合并不一定意味着就要执行转换.
  146. // 它们是两个不同的步骤。合并状态跟踪第一次和最后一次的Pass间隔. Pass的引用也会累积到每个资源上.
  147. // 必须在剔除后发生,因为剔除后的Pass不能提供引用.
  148. {
  149. SCOPED_NAMED_EVENT(FRDGBuilder_Compile_Barriers, FColor::Emerald);
  150. for (FRDGPassHandle PassHandle = Passes.Begin(); PassHandle != Passes.End(); ++PassHandle)
  151. {
  152. // 跳过被裁剪或无参数的Pass.
  153. if (PassesToCull[PassHandle] || PassesWithEmptyParameters[PassHandle])
  154. {
  155. continue;
  156. }
  157. // 合并子资源状态.
  158. const auto MergeSubresourceStates = [&](ERDGParentResourceType ResourceType, FRDGSubresourceState*& PassMergeState, FRDGSubresourceState*& ResourceMergeState, const FRDGSubresourceState& PassState)
  159. {
  160. // 跳过未知状态的资源合并.
  161. if (PassState.Access == ERHIAccess::Unknown)
  162. {
  163. return;
  164. }
  165. if (!ResourceMergeState || !FRDGSubresourceState::IsMergeAllowed(ResourceType, *ResourceMergeState, PassState))
  166. {
  167. // 跨管线、不可合并的状态改变需要一个新的pass依赖项来进行防护.
  168. if (ResourceMergeState && ResourceMergeState->Pipeline != PassState.Pipeline)
  169. {
  170. AddPassDependency(ResourceMergeState->LastPass, PassHandle);
  171. }
  172. // 分配一个新的挂起的合并状态,并将其分配给pass状态.
  173. ResourceMergeState = AllocSubresource(PassState);
  174. ResourceMergeState->SetPass(PassHandle);
  175. }
  176. else
  177. {
  178. // 合并Pass状态进合并后的状态.
  179. ResourceMergeState->Access |= PassState.Access;
  180. ResourceMergeState->LastPass = PassHandle;
  181. }
  182. PassMergeState = ResourceMergeState;
  183. };
  184. const bool bAsyncComputePass = PassesOnAsyncCompute[PassHandle];
  185. // 获取当前处理的Pass实例.
  186. FRDGPass* Pass = Passes[PassHandle];
  187. // 处理当前Pass的纹理状态.
  188. for (auto& TexturePair : Pass->TextureStates)
  189. {
  190. FRDGTextureRef Texture = TexturePair.Key;
  191. auto& PassState = TexturePair.Value;
  192. // 增加引用数量.
  193. Texture->ReferenceCount += PassState.ReferenceCount;
  194. Texture->bUsedByAsyncComputePass |= bAsyncComputePass;
  195. const bool bWholePassState = IsWholeResource(PassState.State);
  196. const bool bWholeMergeState = IsWholeResource(Texture->MergeState);
  197. // 为简单起见,合并/Pass状态维度应该匹配.
  198. if (bWholeMergeState && !bWholePassState)
  199. {
  200. InitAsSubresources(Texture->MergeState, Texture->Layout);
  201. }
  202. else if (!bWholeMergeState && bWholePassState)
  203. {
  204. InitAsWholeResource(Texture->MergeState);
  205. }
  206. const uint32 SubresourceCount = PassState.State.Num();
  207. PassState.MergeState.SetNum(SubresourceCount);
  208. // 合并子资源状态.
  209. for (uint32 Index = 0; Index < SubresourceCount; ++Index)
  210. {
  211. MergeSubresourceStates(ERDGParentResourceType::Texture, PassState.MergeState[Index], Texture->MergeState[Index], PassState.State[Index]);
  212. }
  213. }
  214. // 处理当前Pass的缓冲区状态.
  215. for (auto& BufferPair : Pass->BufferStates)
  216. {
  217. FRDGBufferRef Buffer = BufferPair.Key;
  218. auto& PassState = BufferPair.Value;
  219. Buffer->ReferenceCount += PassState.ReferenceCount;
  220. Buffer->bUsedByAsyncComputePass |= bAsyncComputePass;
  221. MergeSubresourceStates(ERDGParentResourceType::Buffer, PassState.MergeState, Buffer->MergeState, PassState.State);
  222. }
  223. }
  224. }
  225. // 处理异步计算Pass.
  226. if (AsyncComputePassCount > 0)
  227. {
  228. SCOPED_NAMED_EVENT(FRDGBuilder_Compile_AsyncCompute, FColor::Emerald);
  229. FRDGPassBitArray PassesWithCrossPipelineProducer(false, Passes.Num());
  230. FRDGPassBitArray PassesWithCrossPipelineConsumer(false, Passes.Num());
  231. // 遍历正在执行的活动Pass,以便为每个Pass找到最新的跨管道生产者和最早的跨管道消费者, 以便后续构建异步计算重叠区域时缩小搜索空间.
  232. for (FRDGPassHandle PassHandle = Passes.Begin(); PassHandle != Passes.End(); ++PassHandle)
  233. {
  234. if (PassesToCull[PassHandle] || PassesWithEmptyParameters[PassHandle])
  235. {
  236. continue;
  237. }
  238. FRDGPass* Pass = Passes[PassHandle];
  239. // 遍历生产者, 处理生产者和消费者的引用关系.
  240. for (FRDGPassHandle ProducerHandle : Pass->GetProducers())
  241. {
  242. const FRDGPassHandle ConsumerHandle = PassHandle;
  243. if (!IsCrossPipeline(ProducerHandle, ConsumerHandle))
  244. {
  245. continue;
  246. }
  247. FRDGPass* Consumer = Pass;
  248. FRDGPass* Producer = Passes[ProducerHandle];
  249. // 为生产者查找另一个管道上最早的消费者.
  250. if (Producer->CrossPipelineConsumer.IsNull() || IsSortedBefore(ConsumerHandle, Producer->CrossPipelineConsumer))
  251. {
  252. Producer->CrossPipelineConsumer = PassHandle;
  253. PassesWithCrossPipelineConsumer[ProducerHandle] = true;
  254. }
  255. // 为消费者查找另一个管道上的最新生产者.
  256. if (Consumer->CrossPipelineProducer.IsNull() || IsSortedAfter(ProducerHandle, Consumer->CrossPipelineProducer))
  257. {
  258. Consumer->CrossPipelineProducer = ProducerHandle;
  259. PassesWithCrossPipelineProducer[ConsumerHandle] = true;
  260. }
  261. }
  262. }
  263. // 为异步计算建立fork / join重叠区域, 用于栅栏及资源分配/回收. 在fork/join完成之前,异步计算Pass不能分配/释放它们的资源引用,因为两个管道是并行运行的。因此,异步计算的所有资源生命周期都被扩展到整个异步区域。
  264. const auto IsCrossPipelineProducer = [&](FRDGPassHandle A)
  265. {
  266. return PassesWithCrossPipelineConsumer[A];
  267. };
  268. const auto IsCrossPipelineConsumer = [&](FRDGPassHandle A)
  269. {
  270. return PassesWithCrossPipelineProducer[A];
  271. };
  272. // 查找跨管道生产者.
  273. const auto FindCrossPipelineProducer = [&](FRDGPassHandle PassHandle)
  274. {
  275. FRDGPassHandle LatestProducerHandle = ProloguePassHandle;
  276. FRDGPassHandle ConsumerHandle = PassHandle;
  277. // 期望在其它管道上找到最新的生产者,以便建立一个分叉点. 因为可以用N个生产者通道消耗N个资源,所以只关心最后一个.
  278. while (ConsumerHandle != Passes.Begin())
  279. {
  280. if (!PassesToCull[ConsumerHandle] && !IsCrossPipeline(ConsumerHandle, PassHandle) && IsCrossPipelineConsumer(ConsumerHandle))
  281. {
  282. const FRDGPass* Consumer = Passes[ConsumerHandle];
  283. if (IsSortedAfter(Consumer->CrossPipelineProducer, LatestProducerHandle))
  284. {
  285. LatestProducerHandle = Consumer->CrossPipelineProducer;
  286. }
  287. }
  288. --ConsumerHandle;
  289. }
  290. return LatestProducerHandle;
  291. };
  292. // 查找跨管道消费者.
  293. const auto FindCrossPipelineConsumer = [&](FRDGPassHandle PassHandle)
  294. {
  295. check(PassHandle != EpiloguePassHandle);
  296. FRDGPassHandle EarliestConsumerHandle = EpiloguePassHandle;
  297. FRDGPassHandle ProducerHandle = PassHandle;
  298. // 期望找到另一个管道上最早的使用者,因为这在管道之间建立了连接点。因为可以在另一个管道上为N个消费者生产,所以只关心第一个执行的消费者.
  299. while (ProducerHandle != Passes.End())
  300. {
  301. if (!PassesToCull[ProducerHandle] && !IsCrossPipeline(ProducerHandle, PassHandle) && IsCrossPipelineProducer(ProducerHandle))
  302. {
  303. const FRDGPass* Producer = Passes[ProducerHandle];
  304. if (IsSortedBefore(Producer->CrossPipelineConsumer, EarliestConsumerHandle))
  305. {
  306. EarliestConsumerHandle = Producer->CrossPipelineConsumer;
  307. }
  308. }
  309. ++ProducerHandle;
  310. }
  311. return EarliestConsumerHandle;
  312. };
  313. // 将图形Pass插入到异步计算Pass的分叉中.
  314. const auto InsertGraphicsToAsyncComputeFork = [&](FRDGPass* GraphicsPass, FRDGPass* AsyncComputePass)
  315. {
  316. FRDGBarrierBatchBegin& EpilogueBarriersToBeginForAsyncCompute = GraphicsPass->GetEpilogueBarriersToBeginForAsyncCompute(Allocator);
  317. GraphicsPass->bGraphicsFork = 1;
  318. EpilogueBarriersToBeginForAsyncCompute.SetUseCrossPipelineFence();
  319. AsyncComputePass->bAsyncComputeBegin = 1;
  320. AsyncComputePass->GetPrologueBarriersToEnd(Allocator).AddDependency(&EpilogueBarriersToBeginForAsyncCompute);
  321. };
  322. // 将异步计算Pass插入到图形Pass的合并中.
  323. const auto InsertAsyncToGraphicsComputeJoin = [&](FRDGPass* AsyncComputePass, FRDGPass* GraphicsPass)
  324. {
  325. FRDGBarrierBatchBegin& EpilogueBarriersToBeginForGraphics = AsyncComputePass->GetEpilogueBarriersToBeginForGraphics(Allocator);
  326. AsyncComputePass->bAsyncComputeEnd = 1;
  327. EpilogueBarriersToBeginForGraphics.SetUseCrossPipelineFence();
  328. GraphicsPass->bGraphicsJoin = 1;
  329. GraphicsPass->GetPrologueBarriersToEnd(Allocator).AddDependency(&EpilogueBarriersToBeginForGraphics);
  330. };
  331. FRDGPass* PrevGraphicsForkPass = nullptr;
  332. FRDGPass* PrevGraphicsJoinPass = nullptr;
  333. FRDGPass* PrevAsyncComputePass = nullptr;
  334. // 遍历所有Pass, 扩展资源的生命周期, 处理图形Pass和异步计算Pass的交叉和合并节点.
  335. for (FRDGPassHandle PassHandle = Passes.Begin(); PassHandle != Passes.End(); ++PassHandle)
  336. {
  337. if (!PassesOnAsyncCompute[PassHandle] || PassesToCull[PassHandle])
  338. {
  339. continue;
  340. }
  341. FRDGPass* AsyncComputePass = Passes[PassHandle];
  342. // 找到分叉Pass和合并Pass.
  343. const FRDGPassHandle GraphicsForkPassHandle = FindCrossPipelineProducer(PassHandle);
  344. const FRDGPassHandle GraphicsJoinPassHandle = FindCrossPipelineConsumer(PassHandle);
  345. AsyncComputePass->GraphicsForkPass = GraphicsForkPassHandle;
  346. AsyncComputePass->GraphicsJoinPass = GraphicsJoinPassHandle;
  347. FRDGPass* GraphicsForkPass = Passes[GraphicsForkPassHandle];
  348. FRDGPass* GraphicsJoinPass = Passes[GraphicsJoinPassHandle];
  349. // 将异步计算中使用的资源的生命周期延长到fork/join图形Pass。
  350. GraphicsForkPass->ResourcesToBegin.Add(AsyncComputePass);
  351. GraphicsJoinPass->ResourcesToEnd.Add(AsyncComputePass);
  352. // 将图形分叉Pass插入到异步计算分叉Pass.
  353. if (PrevGraphicsForkPass != GraphicsForkPass)
  354. {
  355. InsertGraphicsToAsyncComputeFork(GraphicsForkPass, AsyncComputePass);
  356. }
  357. // 将异步计算合并Pass插入到图形合并Pass.
  358. if (PrevGraphicsJoinPass != GraphicsJoinPass && PrevAsyncComputePass)
  359. {
  360. InsertAsyncToGraphicsComputeJoin(PrevAsyncComputePass, PrevGraphicsJoinPass);
  361. }
  362. PrevAsyncComputePass = AsyncComputePass;
  363. PrevGraphicsForkPass = GraphicsForkPass;
  364. PrevGraphicsJoinPass = GraphicsJoinPass;
  365. }
  366. // 图中的最后一个异步计算Pass需要手动连接回epilogue pass.
  367. if (PrevAsyncComputePass)
  368. {
  369. InsertAsyncToGraphicsComputeJoin(PrevAsyncComputePass, EpiloguePass);
  370. PrevAsyncComputePass->bAsyncComputeEndExecute = 1;
  371. }
  372. }
  373. // 遍历所有图形管道Pass, 并且合并所有具有相同RT的光栅化Pass到同一个RHI渲染Pass中.
  374. if (GRDGMergeRenderPasses && RasterPassCount > 0)
  375. {
  376. SCOPED_NAMED_EVENT(FRDGBuilder_Compile_RenderPassMerge, FColor::Emerald);
  377. TArray<FRDGPassHandle, SceneRenderingAllocator> PassesToMerge;
  378. FRDGPass* PrevPass = nullptr;
  379. const FRenderTargetBindingSlots* PrevRenderTargets = nullptr;
  380. const auto CommitMerge = [&]
  381. {
  382. if (PassesToMerge.Num())
  383. {
  384. const FRDGPassHandle FirstPassHandle = PassesToMerge[0];
  385. const FRDGPassHandle LastPassHandle = PassesToMerge.Last();
  386. // 给定一个Pass的间隔合并成一个单一的渲染Pass: [B, X, X, X, X, E], 开始Pass(B)和结束Pass(E)会分别调用BeginRenderPass/EndRenderPass.
  387. // 另外,begin将处理整个合并间隔的所有序言屏障,end将处理所有尾声屏障, 这可以避免渲染通道内的资源转换,并更有效地批量处理资源转换.
  388. // 假设已经在遍历期间完成了过滤来自合并集的Pass之间的依赖关系.
  389. // (B)是合并序列里的首个Pass.
  390. {
  391. FRDGPass* Pass = Passes[FirstPassHandle];
  392. Pass->bSkipRenderPassEnd = 1;
  393. Pass->EpilogueBarrierPass = LastPassHandle;
  394. }
  395. // (X)是中间Pass.
  396. for (int32 PassIndex = 1, PassCount = PassesToMerge.Num() - 1; PassIndex < PassCount; ++PassIndex)
  397. {
  398. const FRDGPassHandle PassHandle = PassesToMerge[PassIndex];
  399. FRDGPass* Pass = Passes[PassHandle];
  400. Pass->bSkipRenderPassBegin = 1;
  401. Pass->bSkipRenderPassEnd = 1;
  402. Pass->PrologueBarrierPass = FirstPassHandle;
  403. Pass->EpilogueBarrierPass = LastPassHandle;
  404. }
  405. // (E)是合并序列里的最后Pass.
  406. {
  407. FRDGPass* Pass = Passes[LastPassHandle];
  408. Pass->bSkipRenderPassBegin = 1;
  409. Pass->PrologueBarrierPass = FirstPassHandle;
  410. }
  411. #if STATS
  412. GRDGStatRenderPassMergeCount += PassesToMerge.Num();
  413. #endif
  414. }
  415. PassesToMerge.Reset();
  416. PrevPass = nullptr;
  417. PrevRenderTargets = nullptr;
  418. };
  419. // 遍历所有光栅Pass, 合并所有相同RT的Pass到同一个渲染Pass中.
  420. for (FRDGPassHandle PassHandle = Passes.Begin(); PassHandle != Passes.End(); ++PassHandle)
  421. {
  422. // 跳过已被裁剪的Pass.
  423. if (PassesToCull[PassHandle])
  424. {
  425. continue;
  426. }
  427. // 是光栅Pass才处理.
  428. if (PassesOnRaster[PassHandle])
  429. {
  430. FRDGPass* NextPass = Passes[PassHandle];
  431. // 用户控制渲染Pass的Pass不能与其他Pass合并,光栅UAV的Pass由于潜在的相互依赖也不能合并.
  432. if (EnumHasAnyFlags(NextPass->GetFlags(), ERDGPassFlags::SkipRenderPass) || NextPass->bUAVAccess)
  433. {
  434. CommitMerge();
  435. continue;
  436. }
  437. // 图形分叉Pass不能和之前的光栅Pass合并.
  438. if (NextPass->bGraphicsFork)
  439. {
  440. CommitMerge();
  441. }
  442. const FRenderTargetBindingSlots& RenderTargets = NextPass->GetParameters().GetRenderTargets();
  443. if (PrevPass)
  444. {
  445. // 对比RT, 以判定是否可以合并.
  446. if (PrevRenderTargets->CanMergeBefore(RenderTargets)
  447. #if WITH_MGPU
  448. && PrevPass->GPUMask == NextPass->GPUMask
  449. #endif
  450. )
  451. {
  452. // 如果可以, 添加Pass到PassesToMerge列表.
  453. if (!PassesToMerge.Num())
  454. {
  455. PassesToMerge.Add(PrevPass->GetHandle());
  456. }
  457. PassesToMerge.Add(PassHandle);
  458. }
  459. else
  460. {
  461. CommitMerge();
  462. }
  463. }
  464. PrevPass = NextPass;
  465. PrevRenderTargets = &RenderTargets;
  466. }
  467. else if (!PassesOnAsyncCompute[PassHandle])
  468. {
  469. // 图形管道上的非光栅Pass将使RT合并无效.
  470. CommitMerge();
  471. }
  472. }
  473. CommitMerge();
  474. }
  475. }

以上代码显示RDG编译期间的逻辑非常复杂,步骤繁多,先后经历构建生产者和消费者的依赖关系,确定Pass的裁剪等各类标记,调整资源的生命周期,裁剪Pass,处理Pass的资源转换和屏障,处理异步计算Pass的依赖和引用关系,查找并建立分叉和合并Pass节点,合并所有具体相同渲染目标的光栅化Pass等步骤。

以上代码还涉及了一些重要接口,下面一一分析之:

  1. // 增加Pass依赖, 将生产者(ProducerHandle)加入到消费者(ConsumerHandle)的生产者列表(Producers)中.
  2. void FRDGBuilder::AddPassDependency(FRDGPassHandle ProducerHandle, FRDGPassHandle ConsumerHandle)
  3. {
  4. FRDGPass* Consumer = Passes[ConsumerHandle];
  5. auto& Producers = Consumer->Producers;
  6. if (Producers.Find(ProducerHandle) == INDEX_NONE)
  7. {
  8. Producers.Add(ProducerHandle);
  9. }
  10. };
  11. // 初始化为子资源.
  12. template <typename ElementType, typename AllocatorType>
  13. inline void InitAsSubresources(TRDGTextureSubresourceArray<ElementType, AllocatorType>& SubresourceArray, const FRDGTextureSubresourceLayout& Layout, const ElementType& Element = {})
  14. {
  15. const uint32 SubresourceCount = Layout.GetSubresourceCount();
  16. SubresourceArray.SetNum(SubresourceCount, false);
  17. for (uint32 SubresourceIndex = 0; SubresourceIndex < SubresourceCount; ++SubresourceIndex)
  18. {
  19. SubresourceArray[SubresourceIndex] = Element;
  20. }
  21. }
  22. // 初始化为整资源.
  23. template <typename ElementType, typename AllocatorType>
  24. FORCEINLINE void InitAsWholeResource(TRDGTextureSubresourceArray<ElementType, AllocatorType>& SubresourceArray, const ElementType& Element = {})
  25. {
  26. SubresourceArray.SetNum(1, false);
  27. SubresourceArray[0] = Element;
  28. }
  29. // 分配子资源.
  30. FRDGSubresourceState* FRDGBuilder::AllocSubresource(const FRDGSubresourceState& Other)
  31. {
  32. FRDGSubresourceState* State = Allocator.AllocPOD<FRDGSubresourceState>();
  33. *State = Other;
  34. return State;
  35. }

11.3.4 FRDGBuilder::Execute

经过前述的收集Pass(AddPass)、编译渲染图之后,便可以执行渲染图了,由FRDGBuilder::Execute承担:

  1. void FRDGBuilder::Execute()
  2. {
  3. SCOPED_NAMED_EVENT(FRDGBuilder_Execute, FColor::Emerald);
  4. // 在编译之前,在图的末尾创建epilogue pass.
  5. EpiloguePass = Passes.Allocate<FRDGSentinelPass>(Allocator, RDG_EVENT_NAME("Graph Epilogue"));
  6. SetupEmptyPass(EpiloguePass);
  7. const FRDGPassHandle ProloguePassHandle = GetProloguePassHandle();
  8. const FRDGPassHandle EpiloguePassHandle = GetEpiloguePassHandle();
  9. FRDGPassHandle LastUntrackedPassHandle = ProloguePassHandle;
  10. // 非立即模式.
  11. if (!GRDGImmediateMode)
  12. {
  13. // 执行之前先编译, 具体见11.3.3章节.
  14. Compile();
  15. {
  16. SCOPE_CYCLE_COUNTER(STAT_RDG_CollectResourcesTime);
  17. // 收集Pass资源.
  18. for (FRDGPassHandle PassHandle = Passes.Begin(); PassHandle != Passes.End(); ++PassHandle)
  19. {
  20. if (!PassesToCull[PassHandle])
  21. {
  22. CollectPassResources(PassHandle);
  23. }
  24. }
  25. // 结束纹理提取.
  26. for (const auto& Query : ExtractedTextures)
  27. {
  28. EndResourceRHI(EpiloguePassHandle, Query.Key, 1);
  29. }
  30. // 结束缓冲区提取.
  31. for (const auto& Query : ExtractedBuffers)
  32. {
  33. EndResourceRHI(EpiloguePassHandle, Query.Key, 1);
  34. }
  35. }
  36. // 收集Pass的屏障.
  37. {
  38. SCOPE_CYCLE_COUNTER(STAT_RDG_CollectBarriersTime);
  39. for (FRDGPassHandle PassHandle = Passes.Begin(); PassHandle != Passes.End(); ++PassHandle)
  40. {
  41. if (!PassesToCull[PassHandle])
  42. {
  43. CollectPassBarriers(PassHandle, LastUntrackedPassHandle);
  44. }
  45. }
  46. }
  47. }
  48. // 遍历所有纹理, 每个纹理增加尾声转换.
  49. for (FRDGTextureHandle TextureHandle = Textures.Begin(); TextureHandle != Textures.End(); ++TextureHandle)
  50. {
  51. FRDGTextureRef Texture = Textures[TextureHandle];
  52. if (Texture->GetRHIUnchecked())
  53. {
  54. AddEpilogueTransition(Texture, LastUntrackedPassHandle);
  55. Texture->Finalize();
  56. }
  57. }
  58. // 遍历所有缓冲区, 每个缓冲区增加尾声转换.
  59. for (FRDGBufferHandle BufferHandle = Buffers.Begin(); BufferHandle != Buffers.End(); ++BufferHandle)
  60. {
  61. FRDGBufferRef Buffer = Buffers[BufferHandle];
  62. if (Buffer->GetRHIUnchecked())
  63. {
  64. AddEpilogueTransition(Buffer, LastUntrackedPassHandle);
  65. Buffer->Finalize();
  66. }
  67. }
  68. // 执行Pass.
  69. if (!GRDGImmediateMode)
  70. {
  71. QUICK_SCOPE_CYCLE_COUNTER(STAT_FRDGBuilder_Execute_Passes);
  72. for (FRDGPassHandle PassHandle = Passes.Begin(); PassHandle != Passes.End(); ++PassHandle)
  73. {
  74. // 执行非裁剪的Pass.
  75. if (!PassesToCull[PassHandle])
  76. {
  77. ExecutePass(Passes[PassHandle]);
  78. }
  79. }
  80. }
  81. else
  82. {
  83. ExecutePass(EpiloguePass);
  84. }
  85. RHICmdList.SetGlobalUniformBuffers({});
  86. #if WITH_MGPU
  87. (......)
  88. #endif
  89. // 执行纹理提取.
  90. for (const auto& Query : ExtractedTextures)
  91. {
  92. *Query.Value = Query.Key->PooledRenderTarget;
  93. }
  94. // 执行缓冲区提取.
  95. for (const auto& Query : ExtractedBuffers)
  96. {
  97. *Query.Value = Query.Key->PooledBuffer;
  98. }
  99. // 清理.
  100. Clear();
  101. }

在执行过程中涉及到了执行Pass的接口ExecutePass,其逻辑如下:

  1. void FRDGBuilder::ExecutePass(FRDGPass* Pass)
  2. {
  3. QUICK_SCOPE_CYCLE_COUNTER(STAT_FRDGBuilder_ExecutePass);
  4. SCOPED_GPU_MASK(RHICmdList, Pass->GPUMask);
  5. IF_RDG_CPU_SCOPES(CPUScopeStacks.BeginExecutePass(Pass));
  6. // 使用GPU范围.
  7. #if RDG_GPU_SCOPES
  8. const bool bUsePassEventScope = Pass != EpiloguePass && Pass != ProloguePass;
  9. if (bUsePassEventScope)
  10. {
  11. GPUScopeStacks.BeginExecutePass(Pass);
  12. }
  13. #endif
  14. #if WITH_MGPU
  15. if (!bWaitedForTemporalEffect && NameForTemporalEffect != NAME_None)
  16. {
  17. RHICmdList.WaitForTemporalEffect(NameForTemporalEffect);
  18. bWaitedForTemporalEffect = true;
  19. }
  20. #endif
  21. // 执行pass的顺序: 1.prologue -> 2.pass主体 -> 3.epilogue.
  22. // 整个过程使用指定管道上的命令列表执行.
  23. FRHIComputeCommandList& RHICmdListPass = (Pass->GetPipeline() == ERHIPipeline::AsyncCompute)
  24. ? static_cast<FRHIComputeCommandList&>(RHICmdListAsyncCompute)
  25. : RHICmdList;
  26. // 1.执行prologue
  27. ExecutePassPrologue(RHICmdListPass, Pass);
  28. // 2.执行pass主体
  29. Pass->Execute(RHICmdListPass);
  30. // 3.执行epilogue
  31. ExecutePassEpilogue(RHICmdListPass, Pass);
  32. #if RDG_GPU_SCOPES
  33. if (bUsePassEventScope)
  34. {
  35. GPUScopeStacks.EndExecutePass(Pass);
  36. }
  37. #endif
  38. // 异步计算完成, 则立即派发.
  39. if (Pass->bAsyncComputeEnd)
  40. {
  41. FRHIAsyncComputeCommandListImmediate::ImmediateDispatch(RHICmdListAsyncCompute);
  42. }
  43. // 如果是调试模式且非异步计算,则提交命令并刷新到GPU, 然后等待GPU处理完成.
  44. if (GRDGDebugFlushGPU && !GRDGAsyncCompute)
  45. {
  46. RHICmdList.SubmitCommandsAndFlushGPU();
  47. RHICmdList.BlockUntilGPUIdle();
  48. }
  49. }

执行Pass主要有3个步骤:1. prologue、2. pass主体、3. epilogue,它们的执行逻辑如下:

  1. // 1. prologue
  2. void FRDGBuilder::ExecutePassPrologue(FRHIComputeCommandList& RHICmdListPass, FRDGPass* Pass)
  3. {
  4. // 提交前序开始屏障.
  5. if (Pass->PrologueBarriersToBegin)
  6. {
  7. Pass->PrologueBarriersToBegin->Submit(RHICmdListPass);
  8. }
  9. // 提交前序结束屏障.
  10. if (Pass->PrologueBarriersToEnd)
  11. {
  12. Pass->PrologueBarriersToEnd->Submit(RHICmdListPass);
  13. }
  14. // 由于访问检查将允许在RDG资源上调用GetRHI,所以在第一次使用时将初始化统一缓冲区.
  15. Pass->GetParameters().EnumerateUniformBuffers([&](FRDGUniformBufferRef UniformBuffer)
  16. {
  17. BeginResourceRHI(UniformBuffer);
  18. });
  19. // 设置异步计算预算(Budget).
  20. if (Pass->GetPipeline() == ERHIPipeline::AsyncCompute)
  21. {
  22. RHICmdListPass.SetAsyncComputeBudget(Pass->AsyncComputeBudget);
  23. }
  24. const ERDGPassFlags PassFlags = Pass->GetFlags();
  25. if (EnumHasAnyFlags(PassFlags, ERDGPassFlags::Raster))
  26. {
  27. if (!EnumHasAnyFlags(PassFlags, ERDGPassFlags::SkipRenderPass) && !Pass->SkipRenderPassBegin())
  28. {
  29. // 调用命令队列的BeginRenderPass接口.
  30. static_cast<FRHICommandList&>(RHICmdListPass).BeginRenderPass(Pass->GetParameters().GetRenderPassInfo(), Pass->GetName());
  31. }
  32. }
  33. }
  34. // 2. pass主体
  35. void FRDGPass::Execute(FRHIComputeCommandList& RHICmdList)
  36. {
  37. QUICK_SCOPE_CYCLE_COUNTER(STAT_FRDGPass_Execute);
  38. // 设置统一缓冲区.
  39. RHICmdList.SetGlobalUniformBuffers(ParameterStruct.GetGlobalUniformBuffers());
  40. // 执行Pass的实现.
  41. ExecuteImpl(RHICmdList);
  42. }
  43. void TRDGLambdaPass::ExecuteImpl(FRHIComputeCommandList& RHICmdList) override
  44. {
  45. // 执行Lambda.
  46. ExecuteLambda(static_cast<TRHICommandList&>(RHICmdList));
  47. }
  48. // 3. epilogue
  49. void FRDGBuilder::ExecutePassEpilogue(FRHIComputeCommandList& RHICmdListPass, FRDGPass* Pass)
  50. {
  51. QUICK_SCOPE_CYCLE_COUNTER(STAT_FRDGBuilder_ExecutePassEpilogue);
  52. const ERDGPassFlags PassFlags = Pass->GetFlags();
  53. // 调用命令队列的EndRenderPass.
  54. if (EnumHasAnyFlags(PassFlags, ERDGPassFlags::Raster) && !EnumHasAnyFlags(PassFlags, ERDGPassFlags::SkipRenderPass) && !Pass->SkipRenderPassEnd())
  55. {
  56. static_cast<FRHICommandList&>(RHICmdListPass).EndRenderPass();
  57. }
  58. // 放弃资源转换.
  59. for (FRHITexture* Texture : Pass->TexturesToDiscard)
  60. {
  61. RHIDiscardTransientResource(Texture);
  62. }
  63. // 获取(Acquire)转换资源.
  64. for (FRHITexture* Texture : Pass->TexturesToAcquire)
  65. {
  66. RHIAcquireTransientResource(Texture);
  67. }
  68. const FRDGParameterStruct PassParameters = Pass->GetParameters();
  69. // 提交用于图形管线的尾声屏障.
  70. if (Pass->EpilogueBarriersToBeginForGraphics)
  71. {
  72. Pass->EpilogueBarriersToBeginForGraphics->Submit(RHICmdListPass);
  73. }
  74. // 提交用于异步计算的尾声屏障.
  75. if (Pass->EpilogueBarriersToBeginForAsyncCompute)
  76. {
  77. Pass->EpilogueBarriersToBeginForAsyncCompute->Submit(RHICmdListPass);
  78. }
  79. }

由上可知,执行期间,会先编译所有Pass,然后依次执行Pass的前序、主体和后续,相当于将命令队列的BeginRenderPass、执行渲染代码、EndRenderPass分散在它们之间。Pass执行主体实际很简单,就是调用该Pass的Lambda实例,传入使用的命令队列实例。

执行的最后阶段是清理,见下面的分析:

  1. void FRDGBuilder::Clear()
  2. {
  3. // 清理外部资源.
  4. ExternalTextures.Empty();
  5. ExternalBuffers.Empty();
  6. // 清理提取资源.
  7. ExtractedTextures.Empty();
  8. ExtractedBuffers.Empty();
  9. // 清理主体数据.
  10. Passes.Clear();
  11. Views.Clear();
  12. Textures.Clear();
  13. Buffers.Clear();
  14. // 清理统一缓冲区和分配器.
  15. UniformBuffers.Clear();
  16. Allocator.ReleaseAll();
  17. }

11.3.5 RDG机制总结

UE的RDG体系默认执行于渲染线程,虽然会合并具有相同RT的RDG Pass,但不意味着它们会被并行地执行,而是被串行地执行。在普通情况下,每个Pass执行的末期不会立即提交并等待GPU完成,但如果是调试模式且非异步计算,则会。

FRDGBuilder并没有全局唯一的实例,通常是将它声明为局部变量,在一定生命周期内完成Pass的收集、编译和执行的整套流程。声明FRDGBuilder实例的模块有:距离场、渲染纹理、场景渲染器、场景捕捉器、光线追踪、后处理、毛发、虚拟纹理等等。

FRDGBuilder的执行周期可划分为4个阶段:收集Pass、编译Pass、执行Pass和清理。

收集Pass阶段,主要是收集渲染模块的所有能够产生RHI渲染指令的Pass(Lambda),收集之后并非立即执行,将被延迟执行。AddPass的步骤是先创建FRDGPass的实例,并加入到Pass列表,随后执行SetupPass。SetupPass的过程主要是处理纹理和缓冲区的状态、引用、依赖和标记等。

编译Pass阶段,则比较复杂,步骤甚多。主要包含构建生产者和消费者的依赖关系,确定Pass的裁剪等各类标记,调整资源的生命周期,裁剪Pass,处理Pass的资源转换和屏障,处理异步计算Pass的依赖和引用关系,查找并建立分叉和合并Pass节点,合并所有具体相同渲染目标的光栅化Pass等步骤。

执行Pass阶段,首先会执行编译,再根据编译结果执行所有符合条件的Pass。执行单个Pass时依次执行前序、主体和后续,相当于执行命令队列的BeginRenderPass、执行Pass主体(Lambda)渲染代码、EndRenderPass。执行Pass主体时过程简洁,就是调用该Pass的Lambda实例。

最后便是清理阶段,将清理或重置FRDGBuilder实例内的所有数据和内存。

在FRDGBuilder执行的整个过程中,和直接使用RHICommandList相比,FRDGBuilder的特性和优化措施如下:

  • RDG Pass引用的资源都应该由RDG分配或管理,即便是外部注册的资源,也应该在RDG期间保证生命周期。RDG会自动管理资源的生命周期,延迟它们在交叉、合并Pass期间的生命周期,并在使用完无引用时释放并重用之。

  • 资源的分配并非即时响应,而是在初次被使用时才分配或创建。

  • 拥有子资源(Subresource)的概念,通过合理的布局将它们整合成大的资源块,可以派发一个子资源到另外一个,也可以自动创建子资源的视图(View)和别名(Aliase),创建由未来渲染Pass创建的资源别名。进而有效地管理资源的分配、释放、重用,减少内存总体占用和内存碎片,减少CPU和GPU的IO,提升内存使用效率。

  • 以FRDGBuilder的实例为单位管理RDG Pass,自动排序、引用、分叉和合并Pass,处理Pass的资源引用和依赖,裁剪无用的Pass和资源。RDG也可以正确处理Graphics Pass和Async Compute Pass之间的依赖和引用,将它们有序地按照DAG图串联起来,并正确地处理它们的资源交叉使用和状态转换。

  • RDG能够合并RDG Pass的渲染,前提是这些RDG Pass使用了相同的渲染纹理。这样可以减少RHI层的Begin/EndRenderPass的调用,减少RHI渲染命令和资源状态的转换。

  • RDG能够自动处理Pass之间的资源依赖、屏障和状态转换,摒弃无效的状态转换(如read-to-read、write-to-write),并且可以合并、批量转换资源的状态,进一步减少渲染指令的数量。

  • RDG Pass的执行是在渲染线程中发生,并且是串行,而没有使用TaskGraph并行地执行。

    理论上是可以并行执行的,不过这只是猜想,是否可行还需要实践验证。

  • RDG拥有丰富的调试模式和信息,支持即时执行模式,协助开发人员快速定位问题,减少Bug查复时间和难度。

当然,FRDGBuilder也存在一些副作用:

  • 在渲染体系增加了一层概念和封装,提高渲染层的复杂性,增加学习成本。

  • 增加开发复杂度,由于是延时执行,有些bug不能得到即时反馈。

  • 某些Pass或资源的生命周期可能被额外延长。

来自Frostbite异步计算示意图。其中SSAO、SSAO Filter的Pass放入到异步队列,它们会写入和读取Raw AO的纹理,即便在同步点之前结束,但Raw AO的生命周期依然会被延长到同步点。

11.4 RDG开发

本章主要阐述如何使用UE的RDG系统。

11.4.1 创建RDG资源

创建RDG资源(纹理、缓冲区、UAV、SRV等)的示例代码如下:

  1. // ---- 创建RDG纹理示范 ----
  2. // 创建RDG纹理描述
  3. FRDGTextureDesc TextureDesc = Input.Texture->Desc;
  4. TextureDesc.Reset();
  5. TextureDesc.Format = PF_FloatRGBA;
  6. TextureDesc.ClearValue = FClearValueBinding::None;
  7. TextureDesc.Flags &= ~TexCreate_DepthStencilTargetable;
  8. TextureDesc.Flags |= TexCreate_RenderTargetable;
  9. TextureDesc.Extent = OutputViewport.Extent;
  10. // 创建RDG纹理.
  11. FRDGTextureRef MyRDGTexture = GraphBuilder.CreateTexture(TextureDesc, TEXT("MyRDGTexture"));
  12. // ---- 创建RDG纹理UAV示范 ----
  13. FRDGTextureUAVRef MyRDGTextureUAV = GraphBuilder.CreateUAV(MyRDGTexture);
  14. // ---- 创建RDG纹理SRV示范 ----
  15. FRDGTextureSRVRef MyRDGTextureSRV = GraphBuilder.CreateSRV(FRDGTextureSRVDesc::CreateWithPixelFormat(MyRDGTexture, PF_FloatRGBA));

创建纹理等资源前需要创建资源的描述符,而创建资源的UAV和SRV时,可以用之前创建的资源作为实例传进去,从而达到复用的目的。创建SRV需要将资源实例作为描述符的参数,创建描述符后再创建SRV。

上述代码以创建纹理的相关资源为例,缓冲区的创建也类似,不再举例。

11.4.2 注册外部资源

上一节的资源由RDG创建和管理,资源的生命周期也由RDG负责。如果我们已有非RDG创建的资源,可以在RDG使用么?答案是可以,通过FRDGBuilder::RegisterExternalXXX接口可以完成将外部资源注册到RDG系统中。下面以注册纹理为例:

  1. // 在RDG外创建RHI资源.
  2. FRHIResourceCreateInfo CreateInfo;
  3. FTexture2DRHIRef MyRHITexture = RHICreateTexture2D(1024, 768, PF_B8G8R8A8, 1, 1, TexCreate_CPUReadback, CreateInfo);
  4. // 将外部创建的RHI资源注册成RDG资源.
  5. FRDGTextureRef MyExternalRDGTexture = GraphBuilder.RegisterExternalTexture(MyRHITexture);

需要注意的是,外部注册的资源,RDG无法控制和管理其生命周期,需要保证RDG使用期间外部资源的生命周期处于正常状态,否则将引发异常甚至程序崩溃。

如果想从RDG资源获取RHI资源的实例,以下代码可达成:

FRHITexture* MyRHITexture = MyRDGTexture.GetRHI();

用图例展示RHI资源和RDG资源之间的转换关系:

FRDGBuilder::RegisterExternalXXX

FRDGResource::GetRHI

FRHIResource

FRDGResource

上述代码以注册纹理的相关资源为例,缓冲区的注册也类似。

11.4.3 提取资源

上一章RDG机制中已经提到了,RDG收集Pass之后并非立即执行,而是延迟执行(包括资源被延迟创建或分配),这就导致了一个问题:如果想将渲染后的资源赋值给某个变量,无法使用立即模式,需要适配延迟执行模式。这种适配延迟执行的资源提取是通过以下接口来实现的:

  • FRDGBuilder::QueueTextureExtraction
  • FRDGBuilder::QueueBufferExtraction

使用示例如下:

  1. // 创建RDG纹理.
  2. FRDGTextureRef MyRDGTexture;
  3. FRDGTextureDesc MyTextureDesc = FRDGTextureDesc::Create2D(OutputExtent, HistoryPixelFormat, FClearValueBinding::Black, TexCreate_ShaderResource | TexCreate_UAV);
  4. MyRDGTexture = GraphBuilder.CreateTexture(MyTextureDesc, "MyRDGTexture", ERDGTextureFlags::MultiFrame);
  5. // 创建UAV并作为Pass的shader参数.
  6. (......)
  7. PassParameters->MyRDGTextureUAV = GraphBuilder.CreateUAV(MyRDGTexture);
  8. (......)
  9. // 增加Pass, 以便渲染图像到MyRDGTextureUAV.
  10. FComputeShaderUtils::AddPass(GraphBuilder, RDG_EVENT_NAME("MyCustomPass", ...), ComputeShader, PassParameters, FComputeShaderUtils::GetGroupCount(8, 8));
  11. // 入队提取资源.
  12. TRefCountPtr<IPooledRenderTarget>* OutputRT;
  13. GraphBuilder.QueueTextureExtraction(MyRDGTexture, &OutputRT);
  14. // 对提取的OutputRT进行后续操作.
  15. (......)

不过需要注意的是,由于Pass、资源创建和提取都是被延迟的,意味着提取的资源仅可返回,提供给下一帧使用。

小思考:如果要在本帧使用提取后的资源,增加特殊的无参数Pass对提取后的资源进行操作可行吗?为什么?

11.4.4 增加Pass

整个RDG体系执行的单位是RDG Pass,它们的依赖、引用、输入、输出都是通过FRDGBuilder::AddPass完成,以下是其中一个示例:

  1. // 创建Pass的shader参数.
  2. FMyPS::FParameters* PassParameters = GraphBuilder.AllocParameters<FMyPS::FParameters>();
  3. PassParameters->InputTexture = InputTexture;
  4. PassParameters->RenderTargets = FRenderTargetBinding(InputTexture, InputTextureLoadAction);
  5. PassParameters->InputSampler = BilinearSampler;
  6. // 处理着色器.
  7. TShaderMapRef<FScreenPassVS> VertexShader(View.ShaderMap);
  8. TShaderMapRef<FMyPS> PixelShader(View.ShaderMap);
  9. const FScreenPassPipelineState PipelineState(VertexShader, PixelShader, AdditiveBlendState);
  10. // 增加RDG Pass.
  11. GraphBuilder.AddPass(
  12. RDG_EVENT_NAME("MyRDGPass"),
  13. PassParameters,
  14. ERDGPassFlags::Raster,
  15. // Pass的Lambda
  16. [PixelShader, PassParameters, PipelineState] (FRHICommandListImmediate& RHICmdList)
  17. {
  18. // 设置视口.
  19. RHICmdList.SetViewport(0, 0, 0.0f, 1024, 768, 1.0f);
  20. // 设置PSO.
  21. SetScreenPassPipelineState(RHICmdList, PipelineState);
  22. // 设置着色器参数.
  23. SetShaderParameters(RHICmdList, PixelShader, PixelShader.GetPixelShader(), *PassParameters);
  24. // 绘制矩形区域.
  25. DrawRectangle(RHICmdList, 0, 0, 1024, 768, 0, 0, 1.0f, 1.0f, FIntPoint(1024, 768), FIntPoint(1024, 768), PipelineState.VertexShader, EDRF_Default);
  26. });

向RDG系统增加的Pass可以是传统的Graphics Pass,也可以是Compute Shader,还可以是无参数的Pass。RDG Pass和RHI Pass并非一一对应关系,若干个RDG Pass可能合并成一个RHI Pass执行。具体见上一章节11.3.4 FRDGBuilder::Execute

11.4.5 创建FRDGBuilder

创建和使用FRDGBuilder的代码非常简单,如下所示:

  1. void RenderMyStuff(FRHICommandListImmediate& RHICmdList)
  2. {
  3. // ----创建FRDGBuilder的局部对象----
  4. FRDGBuilder GraphBuilder(RHICmdList, RDG_EVENT_NAME("GraphBuilder_RenderMyStuff"));
  5. (......)
  6. // ----增加Pass----
  7. GraphBuilder.AddPass(...);
  8. (......)
  9. GraphBuilder.AddPass(...);
  10. (......)
  11. // ----增加资源提取----
  12. GraphBuilder.QueueTextureExtraction(...);
  13. (......)
  14. // ---- 执行FRDGBuilder ----
  15. GraphBuilder.Execute();
  16. }

需要特别指出的是,FRDGBuilder的实例通常都是局部的,在UE体系中存在若干个FRDGBuilder的实例,主要用于比较独立的模块,例如场景渲染器、后处理、光线追踪等等模块。

FRDGBuilder执行实际有三个步骤:收集Pass、编译Pass、执行Pass,不过FRDGBuilder::Execute已经包含了编译和执行Pass,所以我们不再需要显示地调用FRDGBuilder::Compile接口。

11.4.6 RDG调试

RDG系统存在一些控制台命令,其名称和描述如下:

控制台变量描述
r.RDG.AsyncCompute控制异步计算策略:0-禁用;1-为异步计算Pass启用标记(默认);2-开启所有使用compute命令列表的计算通道。
r.RDG.Breakpoint当满足某些条件时,断点到调试器的断点位置。0-禁用,1~4-不同的特殊调试模式。
r.RDG.ClobberResources在分配时间用指定的清理颜色清除所有渲染目标和纹理/缓冲UAV。用于调试。
r.RDG.CullPassesRDG是否开启裁剪无用的Pass。0-禁用,1-开启(默认)。
r.RDG.Debug允许输出在连接和执行过程中发现的效率低下的警告。
r.RDG.Debug.FlushGPU开启每次Pass执行后刷新指令到GPU。当设置(r.RDG.AsyncCompute=0)时禁用异步计算。
r.RDG.Debug.GraphFilter将某些调试事件过滤到特定的图中。
r.RDG.Debug.PassFilter将某些调试事件过滤到特定的Pass。
r.RDG.Debug.ResourceFilter将某些调试事件过滤到特定的资源。
r.RDG.DumpGraph将多个可视化日志转储到磁盘。0-禁用,1-显示生产者、消费者Pass依赖,2-显示资源状态和转换,3-显示图形、异步计算的重叠。
r.RDG.ExtendResourceLifetimesRDG将把资源生命周期扩展到图的全部长度。会增加内存的占用。
r.RDG.ImmediateMode在创建Pass时执行Pass。当在Pass的Lambda中崩溃时,连接代码的调用堆栈非常有用。
r.RDG.MergeRenderPasses图形将合并相同的、连续的渲染通道到一个单一的渲染通道。0-禁用,1-开启(默认)。
r.RDG.OverlapUAVsRDG将在需要时重叠UAV的工作。如果禁用,UAV屏障总是插入。
r.RDG.TransitionLog输出资源转换到控制台。
r.RDG.VerboseCSVStats控制RDG的CSV分析统计的详细程度。0-为图形执行生成一个CSV配置文件,1-为图形执行的每个阶段生成一个CSV文件。

除了以上列出的RDG控制台,还有一些命令可以显示RDG系统运行过程中的有用信息。

vis列出所有有效的纹理,输入之后可能显示如下所示的信息:

  1. VisualizeTexture/Vis <CheckpointName> [<Mode>] [PIP/UV0/UV1/UV2] [BMP] [FRAC/SAT] [FULL]:
  2. Mode (examples):
  3. RGB = RGB in range 0..1 (default)
  4. *8 = RGB * 8
  5. A = alpha channel in range 0..1
  6. R = red channel in range 0..1
  7. G = green channel in range 0..1
  8. B = blue channel in range 0..1
  9. A*16 = Alpha * 16
  10. RGB/2 = RGB / 2
  11. SubResource:
  12. MIP5 = Mip level 5 (0 is default)
  13. INDEX5 = Array Element 5 (0 is default)
  14. InputMapping:
  15. PIP = like UV1 but as picture in picture with normal rendering (default)
  16. UV0 = UV in left top
  17. UV1 = full texture
  18. UV2 = pixel perfect centered
  19. Flags:
  20. BMP = save out bitmap to the screenshots folder (not on console, normalized)
  21. STENCIL = Stencil normally displayed in alpha channel of depth. This option is used for BMP to get a stencil only BMP.
  22. FRAC = use frac() in shader (default)
  23. SAT = use saturate() in shader
  24. FULLLIST = show full list, otherwise we hide some textures in the printout
  25. BYNAME = sort list by name
  26. BYSIZE = show list by size
  27. TextureId:
  28. 0 = <off>
  29. LogConsoleResponse: 13 = (2D 1x1 PF_DepthStencil) DepthDummy 1 KB
  30. LogConsoleResponse: 18 = (2D 976x492 PF_FloatRGBA RT) SceneColor 3752 KB
  31. LogConsoleResponse: 19 = (2D 128x32 PF_G16R16) PreintegratedGF 16 KB
  32. LogConsoleResponse: 23 = (2D 64x64 PF_FloatRGBA VRam) LTCMat 32 KB VRamInKB(Start/Size):<NONE>
  33. LogConsoleResponse: 24 = (2D 64x64 PF_G16R16F VRam) LTCAmp 16 KB VRamInKB(Start/Size):<NONE>
  34. LogConsoleResponse: 26 = (2D 976x492 PF_FloatRGBA UAV) SSRTemporalAA 3752 KB
  35. LogConsoleResponse: 27 = (2D 976x492 PF_FloatR11G11B10 RT UAV) SSGITemporalAccumulation0 1876 KB
  36. LogConsoleResponse: 29 = (2D 976x492 PF_R32_UINT RT UAV) DenoiserMetadata0 1876 KB
  37. LogConsoleResponse: 30 = (2D 976x492 PF_FloatRGBA RT UAV VRam) SceneColorDeferred 3752 KB VRamInKB(Start/Size):<NONE>
  38. LogConsoleResponse: 31 = (2D 976x492 PF_DepthStencil VRam) SceneDepthZ 2345 KB VRamInKB(Start/Size):<NONE>
  39. LogConsoleResponse: 37 = (3D 64x64x16 PF_FloatRGBA UAV) HairLUT 512 KB
  40. LogConsoleResponse: 38 = (3D 64x64x16 PF_FloatRGBA UAV) HairLUT 512 KB
  41. LogConsoleResponse: 39 = (2D 64x64 PF_R32_FLOAT UAV) HairCoverageLUT 16 KB
  42. LogConsoleResponse: 47 = (2D 98x64 PF_A16B16G16R16) SSProfiles 49 KB
  43. LogConsoleResponse: 48 = (2D 256x64 PF_FloatRGBA RT) AtmosphereTransmittance 128 KB
  44. LogConsoleResponse: 49 = (2D 64x16 PF_FloatRGBA RT) AtmosphereIrradiance 8 KB
  45. LogConsoleResponse: 50 = (2D 64x16 PF_FloatRGBA RT) AtmosphereDeltaE 8 KB
  46. LogConsoleResponse: 51 = (3D 256x128x2 PF_FloatRGBA RT) AtmosphereInscatter 512 KB
  47. LogConsoleResponse: 52 = (3D 256x128x2 PF_FloatRGBA RT) AtmosphereDeltaSR 512 KB
  48. LogConsoleResponse: 53 = (3D 256x128x2 PF_FloatRGBA RT) AtmosphereDeltaSM 512 KB
  49. LogConsoleResponse: 54 = (3D 256x128x2 PF_FloatRGBA RT) AtmosphereDeltaJ 512 KB
  50. LogConsoleResponse: 55 = (2D 1x1 PF_A32B32G32R32F RT UAV) EyeAdaptation 1 KB
  51. LogConsoleResponse: 56 = (3D 32x32x32 PF_A2B10G10R10 RT VRam) CombineLUTs 128 KB VRamInKB(Start/Size):<NONE>
  52. LogConsoleResponse: 68 = (2D 976x492 PF_R8G8 RT UAV) SSGITemporalAccumulation1 938 KB
  53. LogConsoleResponse: 89 = (2D 976x246 PF_R32_UINT RT UAV) QuadOverdrawBuffer 938 KB
  54. LogConsoleResponse: 91 = (2D 976x492 PF_FloatRGBA RT UAV) LightAccumulation 3752 KB
  55. LogConsoleResponse: 92 = (Cube[2] 128 PF_FloatRGBA) ReflectionEnvs 2048 KB
  56. LogConsoleResponse: 93 = (3D 64x64x64 PF_FloatRGBA RT UAV) TranslucentVolumeDir2 2048 KB
  57. LogConsoleResponse: 95 = (2D 1x1 PF_A32B32G32R32F RT UAV) EyeAdaptation 1 KB
  58. LogConsoleResponse: 96 = (3D 64x64x64 PF_FloatRGBA RT UAV) TranslucentVolume2 2048 KB
  59. LogConsoleResponse: 97 = (3D 64x64x64 PF_FloatRGBA RT UAV) TranslucentVolumeDir1 2048 KB
  60. LogConsoleResponse: 98 = (3D 64x64x64 PF_FloatRGBA RT UAV) TranslucentVolume1 2048 KB
  61. LogConsoleResponse: 99 = (3D 64x64x64 PF_FloatRGBA RT UAV) TranslucentVolumeDir0 2048 KB
  62. LogConsoleResponse: 101 = (3D 64x64x64 PF_FloatRGBA RT UAV) TranslucentVolume0 2048 KB
  63. LogConsoleResponse: 102 = (2D 976x492 PF_G8 RT UAV) ScreenSpaceAO 469 KB
  64. LogConsoleResponse: 106 = (2D 488x246 PF_DepthStencil) SmallDepthZ 1173 KB
  65. LogConsoleResponse: 107 = (2D 1x1 PF_A32B32G32R32F RT UAV) EyeAdaptation 1 KB
  66. LogConsoleResponse: CheckpointName (what was rendered this frame, use <Name>@<Number> to get intermediate versions):
  67. LogConsoleResponse: Pool: 43/112 MB (referenced/allocated)

11.5 本篇总结

本篇主要阐述了UE的RDG的、基础概念、使用方法、渲染流程和主要机制,使得读者对RDG有着大致的理解,至于更多技术细节和原理,需要读者自己去研读UE源码发掘。有很多RDG的使用细节本篇没有涉及,可以阅读官方的RDG 101: A Crash Cours弥补。

11.5.1 本篇思考

按惯例,本篇也布置一些小思考,以助理解和加深RDG的掌握和理解:

  • RDG的步骤有哪些?每个步骤的作用是什么?各有什么特点?
  • RDG的资源和RHI的资源有什么区别和联系?如何相互转换?
  • 利用RDG实现自定义的CS和PS绘制代码。

特别说明

  • 感谢所有参考文献的作者,部分图片来自参考文献和网络,侵删。
  • 本系列文章为笔者原创,只发表在博客园上,欢迎分享本文链接,但未经同意,不允许转载
  • 系列文章,未完待续,完整目录请戳内容纲目
  • 系列文章,未完待续,完整目录请戳内容纲目
  • 系列文章,未完待续,完整目录请戳内容纲目

参考文献

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/133182
推荐阅读
相关标签
  

闽ICP备14008679号