浏览代码

Merge pull request #878 from Unity-Technologies/Branch_RTRefactoring

Refactoring of HDRP render texture usage using RTHandles
/main
GitHub 7 年前
当前提交
a6688080
共有 51 个文件被更改,包括 1533 次插入1034 次删除
  1. 78
      ScriptableRenderPipeline/Core/CoreRP/CoreUtils.cs
  2. 466
      ScriptableRenderPipeline/Core/CoreRP/RTHandle.cs
  3. 2
      ScriptableRenderPipeline/Core/CoreRP/Resources/GPUCopy.compute
  4. 2
      ScriptableRenderPipeline/Core/CoreRP/Resources/GPUCopyAsset.cs
  5. 10
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Common.hlsl
  6. 53
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs
  7. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugColorPicker.shader
  8. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs
  9. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugFullScreen.shader
  10. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/LightingDebugPanel.cs
  11. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraEditor.cs
  12. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDAssetFactory.cs
  13. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/LightLoopSettingsUI.cs
  14. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/RenderPipelineSettingsUI.cs
  15. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/SerializedRenderPipelineSettings.cs
  16. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDCustomSamplerId.cs
  17. 688
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
  18. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.asset
  19. 43
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs
  20. 193
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs
  21. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/DeferredDirectionalShadow.compute
  22. 80
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  23. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopSettings.cs
  24. 28
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-clustered.compute
  25. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionSystemInternal.cs
  26. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Builtin/BuiltinData.cs
  27. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs
  28. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.cs
  29. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl
  30. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/RenderPipelineMaterial.cs
  31. 105
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs
  32. 13
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipeline/FrameSettings.cs
  33. 24
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipeline/RenderPipelineSettings.cs
  34. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/Blit.shader
  35. 251
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/BufferPyramid.cs
  36. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset
  37. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/RenderPipelineResources.cs
  38. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariables.hlsl
  39. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariablesFunctions.hlsl
  40. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISkyRenderer.cs
  41. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSkyRenderer.cs
  42. 19
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyManager.cs
  43. 77
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyRenderingContext.cs
  44. 57
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/MRTBufferManager.cs
  45. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/MRTBufferManager.cs.meta
  46. 63
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DBufferManager.cs
  47. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DBufferManager.cs.meta
  48. 71
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GBufferManager.cs
  49. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GBufferManager.cs.meta
  50. 59
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CopyDepthBuffer.shader
  51. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CopyDepthBuffer.shader.meta

78
ScriptableRenderPipeline/Core/CoreRP/CoreUtils.cs


}
}
public static void ClearRenderTarget(CommandBuffer cmd, ClearFlag clearFlag, Color clearColor)
{
if (clearFlag != ClearFlag.None)
cmd.ClearRenderTarget((clearFlag & ClearFlag.Depth) != 0, (clearFlag & ClearFlag.Color) != 0, clearColor);
}
if (clearFlag != ClearFlag.None)
cmd.ClearRenderTarget((clearFlag & ClearFlag.Depth) != 0, (clearFlag & ClearFlag.Color) != 0, clearColor);
ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier buffer, ClearFlag clearFlag = ClearFlag.None, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)

public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
cmd.SetRenderTarget(colorBuffer, depthBuffer, miplevel, cubemapFace, depthSlice);
if (clearFlag != ClearFlag.None)
cmd.ClearRenderTarget((clearFlag & ClearFlag.Depth) != 0, (clearFlag & ClearFlag.Color) != 0, clearColor);
ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthBuffer)

public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, Color clearColor)
{
cmd.SetRenderTarget(colorBuffers, depthBuffer);
if (clearFlag != ClearFlag.None)
cmd.ClearRenderTarget((clearFlag & ClearFlag.Depth) != 0, (clearFlag & ClearFlag.Color) != 0, clearColor);
}
public static RenderTexture CreateRenderTexture(RenderTextureDescriptor baseDesc, int depthBufferBits, RenderTextureFormat format,
RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default)
{
baseDesc.depthBufferBits = depthBufferBits;
baseDesc.colorFormat = format;
baseDesc.sRGB = (readWrite != RenderTextureReadWrite.Linear);
// Depth-only needs bindMS in order to use with CopyTexture
if ((format == RenderTextureFormat.Depth) && (baseDesc.msaaSamples > 1))
baseDesc.bindMS = true;
return new RenderTexture(baseDesc);
}
public static void CreateCmdTemporaryRT(CommandBuffer cmd, int nameID, RenderTextureDescriptor baseDesc,
int depthBufferBits, FilterMode filter, RenderTextureFormat format,
RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default, int msaaSamplesOverride = 0, bool enableRandomWrite = false)
{
if (msaaSamplesOverride > 0)
UpdateRenderTextureDescriptor(ref baseDesc, depthBufferBits, format, readWrite, msaaSamplesOverride, enableRandomWrite);
else
UpdateRenderTextureDescriptor(ref baseDesc, depthBufferBits, format, readWrite, baseDesc.msaaSamples, enableRandomWrite);
cmd.GetTemporaryRT(nameID, baseDesc, filter);
}
public static void UpdateRenderTextureDescriptor(ref RenderTextureDescriptor baseDesc, int depthBufferBits, RenderTextureFormat format, RenderTextureReadWrite readWrite, int msaaSamples, bool enableRandomWrite)
{
baseDesc.depthBufferBits = depthBufferBits;
baseDesc.colorFormat = format;
baseDesc.sRGB = (readWrite != RenderTextureReadWrite.Linear);
Debug.Assert(!enableRandomWrite || (msaaSamples == 1));
baseDesc.msaaSamples = msaaSamples;
baseDesc.enableRandomWrite = enableRandomWrite;
}
public static void ClearCubemap(CommandBuffer cmd, RenderTargetIdentifier buffer, Color clearColor)
{
// We should have the option to clear mip maps here, but since RenderTargetIdentifier, we can't know the number to clear...
// So for now, we won't do it.
for (int i = 0; i < 6; ++i)
SetRenderTarget(cmd, buffer, ClearFlag.Color, clearColor, 0, (CubemapFace)i);
ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void ClearCubemap(CommandBuffer cmd, RenderTexture renderTexture, Color clearColor, bool clearMips = false)

mesh.triangles = triangles;
return mesh;
}
public static void ResizeHTile(ref RenderTexture hTile, ref RenderTargetIdentifier hTileRT, RenderTextureDescriptor desc)
{
// We must use a RenderTexture and not GetTemporaryRT() as currently Unity only aloow to bind a RenderTexture for a UAV in a pixel shader
// We use 8x8 tiles in order to match the native GCN HTile as closely as possible.
desc.width = (desc.width + 7) / 8;
desc.height = (desc.height + 7) / 8;
// TODO: This fails allocation with MSAA enabled?
hTile = CreateRenderTexture(desc, 0, RenderTextureFormat.R8, RenderTextureReadWrite.Linear); // DXGI_FORMAT_R8_UINT is not supported by Unity
hTile.filterMode = FilterMode.Point;
hTile.enableRandomWrite = true;
hTile.Create();
hTileRT = new RenderTargetIdentifier(hTile);
}
}
}

466
ScriptableRenderPipeline/Core/CoreRP/RTHandle.cs


public class RTHandle
{
public static int s_MaxWidth { get; private set; }
public static int s_MaxHeight { get; private set; }
enum RTCategory
{
Regular = 0,
MSAA = 1,
Count
}
static List<RTHandle> s_AutoSizedRTs;
// Static management.
public static int s_MaxWidth { get { return s_MaxWidths[(int)RTCategory.Regular]; } }
public static int s_MaxHeight { get { return s_MaxHeights[(int)RTCategory.Regular]; } }
public RenderTexture rt { get; private set; }
public RenderTargetIdentifier nameID;
public static int s_MaxWidthMSAAA { get { return s_MaxWidths[(int)RTCategory.MSAA]; } }
public static int s_MaxHeightMSAA { get { return s_MaxHeights[(int)RTCategory.MSAA]; } }
Vector2 scaleFactor = Vector2.one;
ScaleFunc scaleFunc;
private static int GetMaxWith(RTCategory category) { return s_MaxWidths[(int)category]; }
private static int GetMaxHeight(RTCategory category) { return s_MaxHeights[(int)category]; }
// Parameters for auto-scaled Render Textures
static bool s_ScaledRTSupportsMSAA = false;
static MSAASamples s_ScaledRTCurrentMSAASamples = MSAASamples.None;
static List<RTHandle> s_AutoSizedRTs;
static RTCategory s_ScaledRTCurrentCategory = RTCategory.Regular;
static int[] s_MaxWidths = new int[(int)RTCategory.Count];
static int[] s_MaxHeights = new int[(int)RTCategory.Count];
public static int maxWidth { get { return GetMaxWith(s_ScaledRTCurrentCategory); } }
public static int maxHeight { get { return GetMaxHeight(s_ScaledRTCurrentCategory); } }
s_MaxWidth = 1;
s_MaxHeight = 1;
for (int i = 0; i < (int)RTCategory.Count; ++i)
{
s_MaxWidths[i] = 1;
s_MaxHeights[i] = 1;
}
RTHandle(RenderTexture rt)
// Call this once to set the initial size and allow msaa targets or not.
public static void Initialize(int width, int height, bool scaledRTsupportsMSAA, MSAASamples scaledRTMSAASamples)
this.rt = rt;
nameID = new RenderTargetIdentifier(rt);
}
Debug.Assert(s_AutoSizedRTs.Count == 0, "RTHandle.Initialize should only be called once before allocating any Render Texture.");
for (int i = 0; i < (int)RTCategory.Count; ++i)
{
s_MaxWidths[i] = width;
s_MaxHeights[i] = height;
}
public void Release()
{
s_AutoSizedRTs.Remove(this);
CoreUtils.Destroy(rt);
rt = null;
nameID = BuiltinRenderTextureType.None;
s_ScaledRTSupportsMSAA = scaledRTsupportsMSAA;
s_ScaledRTCurrentMSAASamples = scaledRTMSAASamples;
rth.Release();
if(rth != null)
rth.Release();
public static void SetReferenceSize(int width, int height)
public static void SetReferenceSize(int width, int height, bool msaa, MSAASamples msaaSamples)
// Technically, the enum could be passed as argument directly but let's not pollute public API with unnecessary complexity for now.
RTCategory category = msaa ? RTCategory.MSAA : RTCategory.Regular;
if (width > s_MaxWidth || height > s_MaxHeight)
Resize(width, height);
bool msaaSamplesChanged = msaa && (msaaSamples != s_ScaledRTCurrentMSAASamples);
if (width > GetMaxWith(category) || height > GetMaxHeight(category) || msaaSamplesChanged)
Resize(width, height, category, msaaSamples);
public static void ResetReferenceSize(int width, int height)
public static void ResetReferenceSize(int width, int height, bool msaa, MSAASamples msaaSamples)
// Technically, the enum could be passed as argument directly but let's not pollute public API with unnecessary complexity for now.
RTCategory category = msaa ? RTCategory.MSAA : RTCategory.Regular;
if (width != s_MaxWidth || height != s_MaxHeight)
Resize(width, height);
bool msaaSamplesChanged = msaa && (msaaSamples != s_ScaledRTCurrentMSAASamples);
if (width != GetMaxWith(category) || height != GetMaxHeight(category) || msaaSamplesChanged)
Resize(width, height, category, msaaSamples);
static void Resize(int width, int height)
static void Resize(int width, int height, RTCategory category, MSAASamples msaaSamples)
s_MaxWidth = width;
s_MaxHeight = height;
var maxSize = new Vector2Int(s_MaxWidth, s_MaxHeight);
s_MaxWidths[(int)category] = width;
s_MaxHeights[(int)category] = height;
s_ScaledRTCurrentMSAASamples = msaaSamples;
var maxSize = new Vector2Int(width, height);
s_ScaledRTCurrentCategory = category;
var rt = rth.rt;
rt.Release();
var rt = rth.m_RTs[(int)category];
// This can happen if you create a RTH for MSAA. By default we only create the MSAA version of the target.
// Missing version will be created when needed in the getter.
if (rt != null)
{
rt.Release();
Vector2Int scaledSize = rth.GetScaledSize(maxSize);
Vector2Int scaledSize;
rt.width = Mathf.Max(scaledSize.x, 1);
rt.height = Mathf.Max(scaledSize.y, 1);
if (rth.scaleFunc != null)
{
scaledSize = rth.scaleFunc(maxSize);
if (category == RTCategory.MSAA)
rt.antiAliasing = (int)s_ScaledRTCurrentMSAASamples;
rt.Create();
else
{
scaledSize = new Vector2Int(
x: Mathf.RoundToInt(rth.scaleFactor.x * s_MaxWidth),
y: Mathf.RoundToInt(rth.scaleFactor.y * s_MaxHeight)
);
}
rt.width = Mathf.Max(scaledSize.x, 1);
rt.height = Mathf.Max(scaledSize.y, 1);
rt.Create();
// This method wraps around regular RenderTexture creation.
// There is no specific logic applied to RenderTextures created this way.
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
bool enableMSAA = msaaSamples != MSAASamples.None;
if (!enableMSAA && bindTextureMS == true)
{
Debug.LogWarning("RTHandle allocated without MSAA but with bindMS set to true, forcing bindMS to false.");
bindTextureMS = false;
}
var rt = new RenderTexture(width, height, (int)depthBufferBits, colorFormat, sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.HideAndDontSave,

};
rt.Create();
return new RTHandle(rt);
RTCategory category = enableMSAA ? RTCategory.MSAA : RTCategory.Regular;
var newRT = new RTHandle();
newRT.SetRenderTexture(rt, category);
newRT.useScaling = false;
newRT.m_EnableRandomWrite = enableRandomWrite;
newRT.m_EnableMSAA = enableMSAA;
return newRT;
// Next two methods are used to allocate RenderTexture that depend on the frame settings (resolution and msaa for now)
// RenderTextures allocated this way are meant to be defined by a scale of camera resolution (full/half/quarter resolution for example).
// The idea is that internally the system will scale up the size of all render texture so that it amortizes with time and not reallocate when a smaller size is required (which is what happens with TemporaryRTs).
// Since MSAA cannot be changed on the fly for a given RenderTexture, a separate instance will be created if the user requires it. This instance will be the one used after the next call of SetReferenceSize if MSAA is required.
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
bool enableMSAA = false,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
int width = Mathf.Max(Mathf.RoundToInt(scaleFactor.x * s_MaxWidth), 1);
int height = Mathf.Max(Mathf.RoundToInt(scaleFactor.y * s_MaxHeight), 1);
bool allocForMSAA = s_ScaledRTSupportsMSAA ? enableMSAA : false;
RTCategory category = allocForMSAA ? RTCategory.MSAA : RTCategory.Regular;
int width = Mathf.Max(Mathf.RoundToInt(scaleFactor.x * GetMaxWith(category)), 1);
int height = Mathf.Max(Mathf.RoundToInt(scaleFactor.y * GetMaxHeight(category)), 1);
var rth = Alloc(width,
var rth = AllocAutoSizedRenderTexture(width,
height,
1,
depthBufferBits,

autoGenerateMips,
anisoLevel,
mipMapBias,
msaaSamples,
enableMSAA,
bindTextureMS,
useDynamicScale,
vrUsage,

rth.scaleFactor = scaleFactor;
s_AutoSizedRTs.Add(rth);
return rth;
}

//
public static RTHandle Alloc(
ScaleFunc scaleFunc,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
bool enableMSAA = false,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
var scaleFactor = scaleFunc(new Vector2Int(s_MaxWidth, s_MaxHeight));
bool allocForMSAA = s_ScaledRTSupportsMSAA ? enableMSAA : false;
RTCategory category = allocForMSAA ? RTCategory.MSAA : RTCategory.Regular;
var scaleFactor = scaleFunc(new Vector2Int(GetMaxWith(category), GetMaxHeight(category)));
var rth = Alloc(width,
var rth = AllocAutoSizedRenderTexture(width,
height,
1,
depthBufferBits,

autoGenerateMips,
anisoLevel,
mipMapBias,
msaaSamples,
enableMSAA,
bindTextureMS,
useDynamicScale,
vrUsage,

rth.scaleFunc = scaleFunc;
return rth;
}
static RTHandle AllocAutoSizedRenderTexture(
int width,
int height,
int slices,
DepthBits depthBufferBits,
RenderTextureFormat colorFormat,
FilterMode filterMode,
TextureWrapMode wrapMode,
TextureDimension dimension,
bool sRGB,
bool enableRandomWrite,
bool useMipMap,
bool autoGenerateMips,
int anisoLevel,
float mipMapBias,
bool enableMSAA,
bool bindTextureMS,
bool useDynamicScale,
VRTextureUsage vrUsage,
RenderTextureMemoryless memoryless
)
{
// Here user made a mistake in setting up msaa/bindMS, hence the warning
if (!enableMSAA && bindTextureMS == true)
{
Debug.LogWarning("RTHandle allocated without MSAA but with bindMS set to true, forcing bindMS to false.");
bindTextureMS = false;
}
bool allocForMSAA = s_ScaledRTSupportsMSAA ? enableMSAA : false;
// Here we purposefully disable MSAA so we just force the bindMS param to false.
if (!allocForMSAA)
{
bindTextureMS = false;
}
// MSAA Does not support random read/write.
if (allocForMSAA && enableRandomWrite == true)
{
Debug.LogWarning("RTHandle allocated with MSAA can't be enableRandomWrite.");
enableRandomWrite = false;
}
int msaaSamples = allocForMSAA ? (int)s_ScaledRTCurrentMSAASamples : 1;
bool UAV = enableRandomWrite;
RTCategory category = allocForMSAA ? RTCategory.MSAA : RTCategory.Regular;
var rt = new RenderTexture(width, height, (int)depthBufferBits, colorFormat, sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.HideAndDontSave,
volumeDepth = slices,
filterMode = filterMode,
wrapMode = wrapMode,
dimension = dimension,
enableRandomWrite = UAV,
useMipMap = useMipMap,
autoGenerateMips = autoGenerateMips,
anisoLevel = anisoLevel,
mipMapBias = mipMapBias,
antiAliasing = msaaSamples,
bindTextureMS = bindTextureMS,
useDynamicScale = useDynamicScale,
vrUsage = vrUsage,
memorylessMode = memoryless
};
rt.Create();
RTHandle rth = new RTHandle();
rth.SetRenderTexture(rt, category);
rth.m_EnableMSAA = enableMSAA;
rth.m_EnableRandomWrite = enableRandomWrite;
rth.useScaling = true;
s_AutoSizedRTs.Add(rth);
return rth;
}

public static implicit operator RenderTargetIdentifier(RTHandle handle)
{
return handle.nameID;
}
public static string DumpRTInfo()
{
string result = "";
for (int i = 0; i < s_AutoSizedRTs.Count; ++i)
{
RenderTexture rt = s_AutoSizedRTs[i].rt;
result = string.Format("{0}\nRT ({1})\t Format: {2} W: {3} H {4}\n", result, i, rt.format, rt.width, rt.height );
}
return result;
}
// Instance data
RenderTexture[] m_RTs = new RenderTexture[2];
RenderTargetIdentifier[] m_NameIDs = new RenderTargetIdentifier[2];
bool m_EnableMSAA = false;
bool m_EnableRandomWrite = false;
Vector2 scaleFactor = Vector2.one;
ScaleFunc scaleFunc;
public bool useScaling { get; private set; }
public RenderTexture rt
{
get
{
if(!useScaling)
{
return m_EnableMSAA ? m_RTs[(int)RTCategory.MSAA] : m_RTs[(int)RTCategory.Regular];
}
else
{
RTCategory category = (m_EnableMSAA && s_ScaledRTCurrentCategory == RTCategory.MSAA) ? RTCategory.MSAA : RTCategory.Regular;
CreateIfNeeded(category);
return m_RTs[(int)category];
}
}
}
public RenderTargetIdentifier nameID
{
get
{
if (!useScaling)
{
return m_EnableMSAA ? m_NameIDs[(int)RTCategory.MSAA] : m_RTs[(int)RTCategory.Regular];
}
else
{
RTCategory category = (m_EnableMSAA && s_ScaledRTCurrentCategory == RTCategory.MSAA) ? RTCategory.MSAA : RTCategory.Regular;
CreateIfNeeded(category);
return m_NameIDs[(int)category];
}
}
}
// Keep constructor private
RTHandle()
{
}
void SetRenderTexture(RenderTexture rt, RTCategory category)
{
m_RTs[(int)category] = rt;
m_NameIDs[(int)category] = new RenderTargetIdentifier(rt);
}
void CreateIfNeeded(RTCategory category)
{
// If a RT was first created for MSAA then the regular one might be null, in this case we create it.
// That's why we never test the MSAA version: It should always be there if RT was declared correctly.
if(category == RTCategory.Regular && m_RTs[(int)RTCategory.Regular] == null)
{
RenderTexture refRT = m_RTs[(int)RTCategory.MSAA];
Debug.Assert(refRT != null);
Vector2Int scaledSize = GetScaledSize(new Vector2Int(s_MaxWidth, s_MaxHeight));
RenderTexture newRT = new RenderTexture(scaledSize.x, scaledSize.y, refRT.depth, refRT.format, refRT.sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.HideAndDontSave,
volumeDepth = refRT.volumeDepth,
filterMode = refRT.filterMode,
wrapMode = refRT.wrapMode,
dimension = refRT.dimension,
enableRandomWrite = m_EnableRandomWrite, // We cannot take the info from the msaa rt since we force it to 1
useMipMap = refRT.useMipMap,
autoGenerateMips = refRT.autoGenerateMips,
anisoLevel = refRT.anisoLevel,
mipMapBias = refRT.mipMapBias,
antiAliasing = 1, // No MSAA for the regular version of the texture.
bindTextureMS = refRT.bindTextureMS,
useDynamicScale = refRT.useDynamicScale,
vrUsage = refRT.vrUsage,
memorylessMode = refRT.memorylessMode
};
newRT.Create();
m_RTs[(int)RTCategory.Regular] = newRT;
m_NameIDs[(int)RTCategory.Regular] = new RenderTargetIdentifier(newRT);
}
}
public void Release()
{
s_AutoSizedRTs.Remove(this);
for (int i = 0; i < (int)RTCategory.Count; ++i)
{
CoreUtils.Destroy(m_RTs[i]);
m_NameIDs[i] = BuiltinRenderTextureType.None;
m_RTs[i] = null;
}
}
public Vector2Int GetScaledSize(Vector2Int refSize)
{
if (scaleFunc != null)
{
return scaleFunc(refSize);
}
else
{
return new Vector2Int(
x: Mathf.RoundToInt(scaleFactor.x * refSize.x),
y: Mathf.RoundToInt(scaleFactor.y * refSize.y)
);
}
}
}
}

2
ScriptableRenderPipeline/Core/CoreRP/Resources/GPUCopy.compute


[numthreads(8, 8, 1)]
void KSampleCopy4_1_x(uint2 dispatchThreadId : SV_DispatchThreadID)
{
_Result1[dispatchThreadId] = SAMPLE_TEXTURE2D_LOD(_Source4, sampler_LinearClamp, float2(dispatchThreadId) * _Size.zw, 0.0).x;
_Result1[dispatchThreadId] = LOAD_TEXTURE2D(_Source4, dispatchThreadId).x;
}

2
ScriptableRenderPipeline/Core/CoreRP/Resources/GPUCopyAsset.cs


k_KernelSize.ToString(), k_KernelSize.ToString()));
cck.AppendLine(string.Format(@"void {0}(uint2 dispatchThreadId : SV_DispatchThreadID)", kernelName));
cck.AppendLine("{");
cck.AppendLine(string.Format(" _Result{0}[dispatchThreadId] = SAMPLE_TEXTURE2D_LOD(_Source{1}, sampler_LinearClamp, float2(dispatchThreadId) * _Size.zw, 0.0).{2};",
cck.AppendLine(string.Format(" _Result{0}[dispatchThreadId] = LOAD_TEXTURE2D(_Source{1}, dispatchThreadId).{2};",
o.targetChannel.ToString(), o.sourceChannel.ToString(), o.subscript));
cck.AppendLine("}");
cck.AppendLine();

10
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Common.hlsl


struct PositionInputs
{
float3 positionWS; // World space position (could be camera-relative)
float2 positionNDC; // Normalized screen UVs : [0, 1) (with the half-pixel offset)
uint2 positionSS; // Screen space pixel coordinates : [0, NumPixels)
uint2 tileCoord; // Screen tile coordinates : [0, NumTiles)
float deviceDepth; // Depth from the depth buffer : [0, 1] (typically reversed)
float linearDepth; // View space Z coordinate : [Near, Far]
float2 positionNDC; // Normalized screen coordinates within the viewport : [0, 1) (with the half-pixel offset)
uint2 positionSS; // Screen space pixel coordinates : [0, NumPixels)
uint2 tileCoord; // Screen tile coordinates : [0, NumTiles)
float deviceDepth; // Depth from the depth buffer : [0, 1] (typically reversed)
float linearDepth; // View space Z coordinate : [Near, Far]
};
// This function is use to provide an easy way to sample into a screen texture, either from a pixel or a compute shaders.

53
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs


}
}
// This is the size actually used for this camera (as it can be altered by VR for example)
int m_ActualWidth;
int m_ActualHeight;
// This is the scale and bias of the camera viewport compared to the reference size of our Render Targets (RHandle.maxSize)
Vector2 m_CameraScaleBias;
// Current mssa sample
MSAASamples m_msaaSamples;
public int actualWidth { get { return m_ActualWidth; } }
public int actualHeight { get { return m_ActualHeight; } }
public Vector2 scaleBias { get { return m_CameraScaleBias; } }
public MSAASamples msaaSamples { get { return m_msaaSamples; } }
public Matrix4x4 viewProjMatrix
{
get { return projMatrix * viewMatrix; }

{
get { return nonJitteredProjMatrix * viewMatrix; }
}
public RenderTextureDescriptor renderTextureDesc { get; private set; }
// Always true for cameras that just got added to the pool - needed for previous matrices to
// avoid one-frame jumps/hiccups with temporal effects (motion blur, TAA...)

m_LastFrameActive = Time.frameCount;
RenderTextureDescriptor tempDesc;
m_ActualWidth = camera.pixelWidth;
m_ActualHeight = camera.pixelHeight;
screenSize = new Vector4(XRSettings.eyeTextureWidth, XRSettings.eyeTextureHeight, 1.0f / XRSettings.eyeTextureWidth, 1.0f / XRSettings.eyeTextureHeight);
tempDesc = XRSettings.eyeTextureDesc;
m_ActualWidth = XRSettings.eyeTextureWidth;
m_ActualHeight = XRSettings.eyeTextureHeight;
else
{
screenSize = new Vector4(camera.pixelWidth, camera.pixelHeight, 1.0f / camera.pixelWidth, 1.0f / camera.pixelHeight);
tempDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
}
// Unfortunately sometime (like in the HDCameraEditor) HDUtils.hdrpSettings can be null because of scripts that change the current pipeline...
m_msaaSamples = HDUtils.hdrpSettings != null ? HDUtils.hdrpSettings.msaaSampleCount : MSAASamples.None;
RTHandle.SetReferenceSize(m_ActualWidth, m_ActualHeight, frameSettings.enableMSAA, m_msaaSamples);
if (frameSettings.enableMSAA)
{
// this is already pre-validated to be a valid sample count by InitializeFrameSettings
var sampleCount = (int)frameSettings.msaaSampleCount;
tempDesc.msaaSamples = sampleCount;
}
else
{
tempDesc.msaaSamples = 1;
}
tempDesc.depthBufferBits = 0;
tempDesc.autoGenerateMips = false;
tempDesc.useMipMap = false;
tempDesc.enableRandomWrite = false;
tempDesc.memoryless = RenderTextureMemoryless.None;
int maxWidth = RTHandle.maxWidth;
int maxHeight = RTHandle.maxHeight;
m_CameraScaleBias.x = (float)m_ActualWidth / maxWidth;
m_CameraScaleBias.y = (float)m_ActualHeight / maxHeight;
renderTextureDesc = tempDesc;
screenSize = new Vector4(m_ActualWidth, m_ActualHeight, 1.0f / m_ActualWidth, 1.0f / m_ActualHeight);
}
// Warning: different views can use the same camera!

cmd.SetGlobalVector(HDShaderIDs._ViewParam, viewParam);
cmd.SetGlobalVector(HDShaderIDs._InvProjParam, invProjParam);
cmd.SetGlobalVector(HDShaderIDs._ScreenSize, screenSize);
cmd.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, scaleBias);
cmd.SetGlobalMatrix(HDShaderIDs._PrevViewProjMatrix, prevViewProjMatrix);
cmd.SetGlobalVectorArray(HDShaderIDs._FrustumPlanes, frustumPlaneEquations);
cmd.SetGlobalInt(HDShaderIDs._TaaFrameIndex, (int)taaFrameIndex);

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugColorPicker.shader


{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID);
output.texcoord = GetNormalizedFullScreenTriangleTexCoord(input.vertexID);
return output;
}

{
if (_RequireToFlipInputTexture > 0.0)
{
input.texcoord.y = 1.0 - input.texcoord.y;
input.texcoord.y = 1.0 * _ScreenToTargetScale.y - input.texcoord.y;
}
float4 result = SAMPLE_TEXTURE2D(_DebugColorPickerTexture, sampler_DebugColorPickerTexture, input.texcoord);

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs


public float debugOverlayRatio = 0.33f;
public FullScreenDebugMode fullScreenDebugMode = FullScreenDebugMode.None;
public float fullscreenDebugMip = 0;
public float fullscreenDebugMip = 0.0f;
public MaterialDebugSettings materialDebugSettings = new MaterialDebugSettings();
public LightingDebugSettings lightingDebugSettings = new LightingDebugSettings();

DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(kShadowMinValueDebug, () => lightingDebugSettings.shadowMinValue, (value) => lightingDebugSettings.shadowMinValue = (float)value);
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(kShadowMaxValueDebug, () => lightingDebugSettings.shadowMaxValue, (value) => lightingDebugSettings.shadowMaxValue = (float)value);
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, int>(kFullScreenDebugMode, () => (int)fullScreenDebugMode, (value) => fullScreenDebugMode = (FullScreenDebugMode)value, DebugItemFlag.None, new DebugItemHandlerIntEnum(DebugDisplaySettings.lightingFullScreenDebugStrings, DebugDisplaySettings.lightingFullScreenDebugValues));
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, uint>(
kFullScreenDebugMip,
() =>
{

break;
}
var size = Shader.GetGlobalVector(id);
var lodCount = Mathf.FloorToInt(Mathf.Log(Mathf.Min(size.x, size.y), 2f));
var lodCount = size.z;
return (uint)(fullscreenDebugMip * lodCount);
},

break;
}
var size = Shader.GetGlobalVector(id);
var lodCount = Mathf.Floor(Mathf.Log(Mathf.Min(size.x, size.y), 2f));
var lodCount = size.z;
fullscreenDebugMip = (float)Convert.ChangeType(value, typeof(Single)) / lodCount;
},
DebugItemFlag.None,

break;
}
var size = Shader.GetGlobalVector(id);
var lodCount = Mathf.FloorToInt(Mathf.Log(Mathf.Min(size.x, size.y), 2f));
var lodCount = size.z;
return (uint)lodCount;
})
);

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugFullScreen.shader


{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID);
output.texcoord = GetNormalizedFullScreenTriangleTexCoord(input.vertexID);
return output;
}

{
if (_RequireToFlipInputTexture > 0.0)
{
input.texcoord.y = 1.0 - input.texcoord.y;
// Texcoord are already scaled by _ScreenToTargetScale but we need to account for the flip here anyway.
input.texcoord.y = 1.0 * _ScreenToTargetScale.y - input.texcoord.y;
}
// SSAO

if (_FullScreenDebugMode == FULLSCREENDEBUGMODE_NAN_TRACKER)
{
float4 color = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, s_point_clamp_sampler, input.texcoord);
if (AnyIsNan(color) || any(isinf(color)))
{
color = float4(1.0, 0.0, 0.0, 1.0);

{
arrow_coord.y = 1.0 - arrow_coord.y;
}
arrow_coord *= _ScreenToTargetScale;
float2 mv_arrow = SampleMotionVectors(arrow_coord);

if (_FullScreenDebugMode == FULLSCREENDEBUGMODE_DEFERRED_SHADOWS)
{
float4 color = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, s_point_clamp_sampler, input.texcoord);
return float4(color.rgb, 0.0);
return float4(color.rrr, 0.0);
}
if (_FullScreenDebugMode == FULLSCREENDEBUGMODE_PRE_REFRACTION_COLOR_PYRAMID
|| _FullScreenDebugMode == FULLSCREENDEBUGMODE_FINAL_COLOR_PYRAMID)

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/LightingDebugPanel.cs


break;
}
default:
fullScreenDebugMipHandler.SetValue(0f);
fullScreenDebugMipHandler.SetValue(0);
break;
}

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraEditor.cs


if (m_PreviewTexture != null)
m_PreviewTexture.Release();
var baseDesc = m_PreviewHDCamera.renderTextureDesc;
baseDesc.width = width;
baseDesc.height = height;
CoreUtils.UpdateRenderTextureDescriptor(ref baseDesc, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear, 1, true);
m_PreviewTexture = new RenderTexture(baseDesc);
m_PreviewTexture = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
m_PreviewTexture.enableRandomWrite = true;
m_PreviewTexture.Create();
}
return m_PreviewTexture;
}

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDAssetFactory.cs


// General
newAsset.cameraMotionVectors = Load<Shader>(HDRenderPipelinePath + "RenderPipelineResources/CameraMotionVectors.shader");
newAsset.copyStencilBuffer = Load<Shader>(HDRenderPipelinePath + "RenderPipelineResources/CopyStencilBuffer.shader");
newAsset.copyDepthBuffer = Load<Shader>(HDRenderPipelinePath + "RenderPipelineResources/CopyDepthBuffer.shader");
newAsset.blit = Load<Shader>(HDRenderPipelinePath + "RenderPipelineResources/Blit.shader");
// Sky

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/LightLoopSettingsUI.cs


if (EditorGUILayout.BeginFadeGroup(s.isSectionExpandedEnableTileAndCluster.faded))
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(p.isFptlEnabled, _.GetContent("Enable FPTL"));
EditorGUILayout.PropertyField(p.enableFptlForForwardOpaque, _.GetContent("Enable FPTL For Forward Opaque"));
EditorGUILayout.PropertyField(p.enableBigTilePrepass, _.GetContent("Enable Big Tile Prepass"));
EditorGUILayout.PropertyField(p.enableComputeLightEvaluation, _.GetContent("Enable Compute Light Evaluation"));

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/RenderPipelineSettingsUI.cs


EditorGUILayout.PropertyField(d.supportSSR, _.GetContent("Support SSR"));
EditorGUILayout.PropertyField(d.supportSSAO, _.GetContent("Support SSAO"));
EditorGUILayout.PropertyField(d.supportDBuffer, _.GetContent("Support Decal Buffer"));
EditorGUILayout.PropertyField(d.msaaSampleCount, _.GetContent("MSAA Sample Count"));
EditorGUILayout.PropertyField(d.supportMSAA, _.GetContent("Support Multi Sampling Anti-Aliasing"));
EditorGUILayout.PropertyField(d.MSAASampleCount, _.GetContent("MSAA Sample Count"));
EditorGUILayout.PropertyField(d.supportForwardOnly, _.GetContent("Support Forward Only"));
EditorGUILayout.PropertyField(d.supportMotionVectors, _.GetContent("Support Motion Vectors"));
EditorGUILayout.PropertyField(d.supportStereo, _.GetContent("Support Stereo Rendering"));
--EditorGUI.indentLevel;
}
}

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/SerializedRenderPipelineSettings.cs


public SerializedProperty supportSSR;
public SerializedProperty supportSSAO;
public SerializedProperty supportDBuffer;
public SerializedProperty msaaSampleCount;
public SerializedProperty supportMSAA;
public SerializedProperty MSAASampleCount;
public SerializedProperty supportForwardOnly;
public SerializedProperty supportMotionVectors;
public SerializedProperty supportStereo;
public SerializedGlobalLightLoopSettings lightLoopSettings;
public SerializedShadowInitParameters shadowInitParams;

supportSSR = root.Find((RenderPipelineSettings s) => s.supportSSR);
supportSSAO = root.Find((RenderPipelineSettings s) => s.supportSSAO);
supportDBuffer = root.Find((RenderPipelineSettings s) => s.supportDBuffer);
msaaSampleCount = root.Find((RenderPipelineSettings s) => s.msaaSampleCount);
supportMSAA = root.Find((RenderPipelineSettings s) => s.supportMSAA);
MSAASampleCount = root.Find((RenderPipelineSettings s) => s.msaaSampleCount);
supportForwardOnly = root.Find((RenderPipelineSettings s) => s.supportForwardOnly);
supportMotionVectors = root.Find((RenderPipelineSettings s) => s.supportMotionVectors);
supportStereo = root.Find((RenderPipelineSettings s) => s.supportStereo);
lightLoopSettings = new SerializedGlobalLightLoopSettings(root.Find((RenderPipelineSettings s) => s.lightLoopSettings));
shadowInitParams = new SerializedShadowInitParameters(root.Find((RenderPipelineSettings s) => s.shadowInitParams));

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDCustomSamplerId.cs


PyramidDepth,
PostProcessing,
RenderDebug,
InitAndClearBuffer,
InitGBuffersAndClearDepthStencil,
ClearBuffers,
ClearDepthStencil,
ClearSSSDiffuseTarget,
ClearSSSFilteringTarget,
ClearAndCopyStencilTexture,

HDRenderPipelineRender,
CullResultsCull,
CopyDepthForSceneView,
// Profile sampler for tile pass
TPPrepareLightsForGPU,

688
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
文件差异内容过多而无法显示
查看文件

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.asset


enableBigTilePrepass: 1
isFptlEnabled: 1
renderPipelineSettings:
supportShadowMask: 1
supportShadowMask: 0
supportsForwardOnly: 0
supportMSAA: 0
supportMSAAAntiAliasing: 0
msaaSampleCount: 1
supportsMotionVectors: 1
supportsStereo: 0
lightLoopSettings:
spotCookieSize: 128
cookieTexArraySize: 16

43
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs


public static readonly int g_mScrProjection = Shader.PropertyToID("g_mScrProjection");
public static readonly int g_mInvScrProjection = Shader.PropertyToID("g_mInvScrProjection");
public static readonly int g_iLog2NumClusters = Shader.PropertyToID("g_iLog2NumClusters");
public static readonly int g_screenSize = Shader.PropertyToID("g_screenSize");
public static readonly int g_iNumSamplesMSAA = Shader.PropertyToID("g_iNumSamplesMSAA");
public static readonly int g_fNearPlane = Shader.PropertyToID("g_fNearPlane");
public static readonly int g_fFarPlane = Shader.PropertyToID("g_fFarPlane");
public static readonly int g_fClustScale = Shader.PropertyToID("g_fClustScale");

public static readonly int _StencilRef = Shader.PropertyToID("_StencilRef");
public static readonly int _StencilCmp = Shader.PropertyToID("_StencilCmp");
public static readonly int _InputDepth = Shader.PropertyToID("_InputDepthTexture");
public static readonly int _SrcBlend = Shader.PropertyToID("_SrcBlend");
public static readonly int _DstBlend = Shader.PropertyToID("_DstBlend");

public static readonly int _ViewParam = Shader.PropertyToID("_ViewParam");
public static readonly int _InvProjParam = Shader.PropertyToID("_InvProjParam");
public static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize");
public static readonly int _ScreenToTargetScale = Shader.PropertyToID("_ScreenToTargetScale");
public static readonly int _PrevViewProjMatrix = Shader.PropertyToID("_PrevViewProjMatrix");
public static readonly int _FrustumPlanes = Shader.PropertyToID("_FrustumPlanes");
public static readonly int _TaaFrameIndex = Shader.PropertyToID("_TaaFrameIndex");

public static readonly int _GaussianPyramidColorTexture = Shader.PropertyToID("_GaussianPyramidColorTexture");
public static readonly int _PyramidDepthTexture = Shader.PropertyToID("_PyramidDepthTexture");
public static readonly int _GaussianPyramidColorMipSize = Shader.PropertyToID("_GaussianPyramidColorMipSize");
public static readonly int[] _GaussianPyramidColorMips =
{
Shader.PropertyToID("_GaussianColorMip0"),
Shader.PropertyToID("_GaussianColorMip1"),
Shader.PropertyToID("_GaussianColorMip2"),
Shader.PropertyToID("_GaussianColorMip3"),
Shader.PropertyToID("_GaussianColorMip4"),
Shader.PropertyToID("_GaussianColorMip5"),
Shader.PropertyToID("_GaussianColorMip6"),
Shader.PropertyToID("_GaussianColorMip7"),
Shader.PropertyToID("_GaussianColorMip8"),
Shader.PropertyToID("_GaussianColorMip9"),
Shader.PropertyToID("_GaussianColorMip10"),
Shader.PropertyToID("_GaussianColorMip11"),
Shader.PropertyToID("_GaussianColorMip12"),
Shader.PropertyToID("_GaussianColorMip13"),
Shader.PropertyToID("_GaussianColorMip14"),
};
public static readonly int[] _DepthPyramidMips =
{
Shader.PropertyToID("_DepthPyramidMip0"),
Shader.PropertyToID("_DepthPyramidMip1"),
Shader.PropertyToID("_DepthPyramidMip2"),
Shader.PropertyToID("_DepthPyramidMip3"),
Shader.PropertyToID("_DepthPyramidMip4"),
Shader.PropertyToID("_DepthPyramidMip5"),
Shader.PropertyToID("_DepthPyramidMip6"),
Shader.PropertyToID("_DepthPyramidMip7"),
Shader.PropertyToID("_DepthPyramidMip8"),
Shader.PropertyToID("_DepthPyramidMip9"),
Shader.PropertyToID("_DepthPyramidMip10"),
Shader.PropertyToID("_DepthPyramidMip11"),
Shader.PropertyToID("_DepthPyramidMip12"),
Shader.PropertyToID("_DepthPyramidMip13"),
Shader.PropertyToID("_DepthPyramidMip14"),
};
public static readonly int _DebugColorPickerTexture = Shader.PropertyToID("_DebugColorPickerTexture");
public static readonly int _ColorPickerParam = Shader.PropertyToID("_ColorPickerParam");

public static readonly int _DebugFullScreenTexture = Shader.PropertyToID("_DebugFullScreenTexture");
public static readonly int _BlitTexture = Shader.PropertyToID("_BlitTexture");
public static readonly int _BlitScaleBias = Shader.PropertyToID("_BlitScaleBias");
public static readonly int _BlitMipLevel = Shader.PropertyToID("_BlitMipLevel");
public static readonly int _WorldScales = Shader.PropertyToID("_WorldScales");
public static readonly int _FilterKernels = Shader.PropertyToID("_FilterKernels");

193
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

public const RendererConfiguration k_RendererConfigurationBakedLightingWithShadowMask = k_RendererConfigurationBakedLighting | RendererConfiguration.PerObjectOcclusionProbe | RendererConfiguration.PerObjectOcclusionProbeProxyVolume | RendererConfiguration.PerObjectShadowMask;
public static Material GetBlitMaterial()
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (hdPipeline != null)
{
return hdPipeline.GetBlitMaterial();
}
return null;
}
public static RenderPipelineSettings hdrpSettings
{
get
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (hdPipeline != null)
{
return hdPipeline.renderPipelineSettings;
}
return null;
}
}
static MaterialPropertyBlock s_PropertyBlock = new MaterialPropertyBlock();
public static List<RenderPipelineMaterial> GetRenderPipelineMaterialList()
{

// Transpose for HLSL.
return Matrix4x4.Transpose(worldToViewMatrix.transpose * viewSpaceRasterTransform);
}
// This set of RenderTarget management methods is supposed to be used when rendering into a camera dependent render texture.
// This will automatically set the viewport based on the camera size and the RTHandle scaling info.
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RTHandle buffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
cmd.SetRenderTarget(buffer, miplevel, cubemapFace, depthSlice);
SetViewport(cmd, camera, buffer);
CoreUtils.ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RTHandle buffer, ClearFlag clearFlag = ClearFlag.None, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
SetRenderTarget(cmd, camera, buffer, clearFlag, CoreUtils.clearColorAllBlack, miplevel, cubemapFace, depthSlice);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RTHandle colorBuffer, RTHandle depthBuffer, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
SetRenderTarget(cmd, camera, colorBuffer, depthBuffer, ClearFlag.None, CoreUtils.clearColorAllBlack, miplevel, cubemapFace, depthSlice);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RTHandle colorBuffer, RTHandle depthBuffer, ClearFlag clearFlag, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
SetRenderTarget(cmd, camera, colorBuffer, depthBuffer, clearFlag, CoreUtils.clearColorAllBlack, miplevel, cubemapFace, depthSlice);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RTHandle colorBuffer, RTHandle depthBuffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
CoreUtils.SetRenderTarget(cmd, colorBuffer, depthBuffer, miplevel, cubemapFace, depthSlice);
SetViewport(cmd, camera, colorBuffer);
CoreUtils.ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier[] colorBuffers, RTHandle depthBuffer)
{
CoreUtils.SetRenderTarget(cmd, colorBuffers, depthBuffer, ClearFlag.None, CoreUtils.clearColorAllBlack);
SetViewport(cmd, camera, depthBuffer);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier[] colorBuffers, RTHandle depthBuffer, ClearFlag clearFlag = ClearFlag.None)
{
CoreUtils.SetRenderTarget(cmd, colorBuffers, depthBuffer); // Don't clear here, viewport needs to be set before we do.
SetViewport(cmd, camera, depthBuffer);
CoreUtils.ClearRenderTarget(cmd, clearFlag, CoreUtils.clearColorAllBlack);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier[] colorBuffers, RTHandle depthBuffer, ClearFlag clearFlag, Color clearColor)
{
cmd.SetRenderTarget(colorBuffers, depthBuffer);
SetViewport(cmd, camera, depthBuffer);
CoreUtils.ClearRenderTarget(cmd, clearFlag, clearColor);
}
// Scaling viewport is done for auto-scaling render targets.
// In the context of HDRP, every auto-scaled RT is scaled against the maximum RTHandles reference size (that can only grow).
// When we render using a camera whose viewport is smaller than the RTHandles reference size (and thus smaller than the RT actual size), we need to set it explicitly (otherwise, native code will set the viewport at the size of the RT)
// For auto-scaled RTs (like for example a half-resolution RT), we need to scale this viewport accordingly.
// For non scaled RTs we just do nothing, the native code will set the viewport at the size of the RT anyway.
public static void SetViewport(CommandBuffer cmd, HDCamera camera, RTHandle target)
{
if (target.useScaling)
{
Debug.Assert(camera != null, "Missing HDCamera when setting up Render Target with auto-scale and Viewport.");
Vector2Int scaledViewportSize = target.GetScaledSize(new Vector2Int(camera.actualWidth, camera.actualHeight));
cmd.SetViewport(new Rect(0.0f, 0.0f, scaledViewportSize.x, scaledViewportSize.y));
}
}
public static void BlitTexture(CommandBuffer cmd, RTHandle source, RTHandle destination, Vector4 scaleBias, float mipLevel, bool bilinear)
{
s_PropertyBlock.SetTexture(HDShaderIDs._BlitTexture, source);
s_PropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, scaleBias);
s_PropertyBlock.SetFloat(HDShaderIDs._BlitMipLevel, mipLevel);
cmd.DrawProcedural(Matrix4x4.identity, GetBlitMaterial(), bilinear ? 1 : 0, MeshTopology.Triangles, 3, 1, s_PropertyBlock);
}
// In the context of HDRP, the internal render targets used during the render loop are the same for all cameras, no matter the size of the camera.
// It means that we can end up rendering inside a partial viewport for one of these "camera space" rendering.
// In this case, we need to make sure than when we blit from one such camera texture to another, we only blit the necessary portion corresponding to the camera viewport.
// Here, both source and destination are camera-scaled.
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination, float mipLevel = 0.0f, bool bilinear = false)
{
// Will set the correct camera viewport as well.
SetRenderTarget(cmd, camera, destination);
BlitTexture(cmd, source, destination, camera.scaleBias, mipLevel, bilinear);
}
// This case, both source and destination are camera-scaled but we want to override the scale/bias parameter.
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination, Vector4 scaleBias, float mipLevel = 0.0f, bool bilinear = false)
{
// Will set the correct camera viewport as well.
SetRenderTarget(cmd, camera, destination);
BlitTexture(cmd, source, destination, scaleBias, mipLevel, bilinear);
}
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination, Rect destViewport, float mipLevel = 0.0f, bool bilinear = false)
{
SetRenderTarget(cmd, camera, destination);
cmd.SetViewport(destViewport);
BlitTexture(cmd, source, destination, camera.scaleBias, mipLevel, bilinear);
}
// This particular case is for blitting a camera-scaled texture into a non scaling texture. So we setup the full viewport (implicit in cmd.Blit) but have to scale the input UVs.
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RTHandle source, RenderTargetIdentifier destination)
{
cmd.Blit(source, destination, new Vector2(camera.scaleBias.x, camera.scaleBias.y), Vector2.zero);
}
// This particular case is for blitting a camera-scaled texture into a non scaling texture. So we setup the full viewport (implicit in cmd.Blit) but have to scale the input UVs.
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier source, RTHandle destination)
{
// Will set the correct camera viewport as well.
SetRenderTarget(cmd, camera, destination);
cmd.SetGlobalTexture(HDShaderIDs._BlitTexture, source);
cmd.SetGlobalVector(HDShaderIDs._BlitScaleBias, new Vector4(1.0f, 1.0f, 0.0f, 0.0f));
cmd.SetGlobalFloat(HDShaderIDs._BlitMipLevel, 0.0f);
// Wanted to make things clean and not use SetGlobalXXX APIs but can't use MaterialPropertyBlock with RenderTargetIdentifier so YEY
//s_PropertyBlock.SetTexture(HDShaderIDs._BlitTexture, source);
//s_PropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, camera.scaleBias);
cmd.DrawProcedural(Matrix4x4.identity, GetBlitMaterial(), 0, MeshTopology.Triangles, 3, 1);
}
// These method should be used to render full screen triangles sampling auto-scaling RTs.
// This will set the proper viewport and UV scale.
public static void DrawFullScreen( CommandBuffer commandBuffer, HDCamera camera, Material material,
RTHandle colorBuffer,
MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
HDUtils.SetRenderTarget(commandBuffer, camera, colorBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}
public static void DrawFullScreen( CommandBuffer commandBuffer, HDCamera camera, Material material,
RTHandle colorBuffer, RTHandle depthStencilBuffer,
MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
HDUtils.SetRenderTarget(commandBuffer, camera, colorBuffer, depthStencilBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}
public static void DrawFullScreen( CommandBuffer commandBuffer, HDCamera camera, Material material,
RenderTargetIdentifier[] colorBuffers, RTHandle depthStencilBuffer,
MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
HDUtils.SetRenderTarget(commandBuffer, camera, colorBuffers, depthStencilBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}
public static void DrawFullScreen( CommandBuffer commandBuffer, HDCamera camera, Material material,
RenderTargetIdentifier colorBuffer,
MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
CoreUtils.SetRenderTarget(commandBuffer, colorBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}
// Returns mouse coordinates: (x,y) in pixels and (z,w) normalized inside the render target (not the viewport)
public static Vector4 GetMouseCoordinates(HDCamera camera)
{
Vector2 mousePixelCoord = MousePositionDebug.instance.GetMousePosition(camera.screenSize.y);
return new Vector4(mousePixelCoord.x, mousePixelCoord.y, camera.scaleBias.x * mousePixelCoord.x / camera.screenSize.x, camera.scaleBias.y * mousePixelCoord.y / camera.screenSize.y);
}
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/DeferredDirectionalShadow.compute


float sampleStep = ((i + 1) * step + step * dither);
// UVs for the current sample
float2 sampleUV = startUV + rayUV * sampleStep;
float2 sampleUV = (startUV + rayUV * sampleStep) * _ScreenToTargetScale.xy;
// Ray depth for this sample
float raySampleDepth = startDepth + rayDepth * sampleStep;

80
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs


using System.Collections.Generic;
using UnityEngine.Experimental.Rendering.HDPipeline.Internal;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering.PostProcessing;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

}
}
int GetNumTileFtplX(Camera camera)
int GetNumTileFtplX(HDCamera hdCamera)
return (camera.pixelWidth + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
return (hdCamera.actualWidth + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
int GetNumTileFtplY(Camera camera)
int GetNumTileFtplY(HDCamera hdCamera)
return (camera.pixelHeight + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
return (hdCamera.actualHeight + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
int GetNumTileClusteredX(Camera camera)
int GetNumTileClusteredX(HDCamera hdCamera)
return (camera.pixelWidth + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
return (hdCamera.actualWidth + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
int GetNumTileClusteredY(Camera camera)
int GetNumTileClusteredY(HDCamera hdCamera)
return (camera.pixelHeight + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
return (hdCamera.actualHeight + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
}
public bool GetFeatureVariantsEnabled()

return (uint)logVolume << 20 | (uint)lightVolumeType << 17 | listType << 16 | ((uint)probeIndex & 0xFFFF);
}
void VoxelLightListGeneration(CommandBuffer cmd, Camera camera, Matrix4x4 projscr, Matrix4x4 invProjscr, RenderTargetIdentifier cameraDepthBufferRT)
void VoxelLightListGeneration(CommandBuffer cmd, HDCamera hdCamera, Matrix4x4 projscr, Matrix4x4 invProjscr, RenderTargetIdentifier cameraDepthBufferRT)
Camera camera = hdCamera.camera;
// clear atomic offset index
cmd.SetComputeBufferParam(buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, s_GlobalLightListAtomic);
cmd.DispatchCompute(buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, 1, 1, 1);

cmd.SetComputeMatrixParam(buildPerVoxelLightListShader, HDShaderIDs.g_mInvScrProjection, invProjscr);
cmd.SetComputeIntParam(buildPerVoxelLightListShader, HDShaderIDs.g_iLog2NumClusters, k_Log2NumClusters);
cmd.SetComputeVectorParam(buildPerVoxelLightListShader, HDShaderIDs.g_screenSize, hdCamera.screenSize);
cmd.SetComputeIntParam(buildPerVoxelLightListShader, HDShaderIDs.g_iNumSamplesMSAA, (int)hdCamera.msaaSamples);
//Vector4 v2_near = invProjscr * new Vector4(0.0f, 0.0f, 0.0f, 1.0f);
//Vector4 v2_far = invProjscr * new Vector4(0.0f, 0.0f, 1.0f, 1.0f);

cmd.SetComputeBufferParam(buildPerVoxelLightListShader, s_GenListPerVoxelKernel, HDShaderIDs._LightVolumeData, s_LightVolumeDataBuffer);
cmd.SetComputeBufferParam(buildPerVoxelLightListShader, s_GenListPerVoxelKernel, HDShaderIDs.g_data, s_ConvexBoundsBuffer);
var numTilesX = GetNumTileClusteredX(camera);
var numTilesY = GetNumTileClusteredY(camera);
var numTilesX = GetNumTileClusteredX(hdCamera);
var numTilesY = GetNumTileClusteredY(hdCamera);
cmd.DispatchCompute(buildPerVoxelLightListShader, s_GenListPerVoxelKernel, numTilesX, numTilesY, 1);
}

cmd.DispatchCompute(buildPerBigTileLightListShader, s_GenListPerBigTileKernel, numBigTilesX, numBigTilesY, 1);
}
var numTilesX = GetNumTileFtplX(camera);
var numTilesY = GetNumTileFtplY(camera);
var numTilesX = GetNumTileFtplX(hdCamera);
var numTilesY = GetNumTileFtplY(hdCamera);
var numTiles = numTilesX * numTilesY;
bool enableFeatureVariants = GetFeatureVariantsEnabled();

}
// Cluster
VoxelLightListGeneration(cmd, camera, projscr, invProjscr, cameraDepthBufferRT);
VoxelLightListGeneration(cmd, hdCamera, projscr, invProjscr, cameraDepthBufferRT);
if (enableFeatureVariants)
{

cmd.SetRenderTarget(BuiltinRenderTextureType.None);
BuildGPULightListsCommon(hdCamera, cmd, cameraDepthBufferRT, stencilTextureRT, skyEnabled);
PushGlobalParams(hdCamera.camera, cmd);
PushGlobalParams(hdCamera, cmd);
}
public GPUFence BuildGPULightListsAsyncBegin(HDCamera hdCamera, ScriptableRenderContext renderContext, RenderTargetIdentifier cameraDepthBufferRT, RenderTargetIdentifier stencilTextureRT, GPUFence startFence, bool skyEnabled)

return completeFence;
}
public void BuildGPULightListAsyncEnd(Camera camera, CommandBuffer cmd, GPUFence doneFence)
public void BuildGPULightListAsyncEnd(HDCamera hdCamera, CommandBuffer cmd, GPUFence doneFence)
PushGlobalParams(camera, cmd);
PushGlobalParams(hdCamera, cmd);
}
private void UpdateDataBuffers()

return add;
}
void PushGlobalParams(Camera camera, CommandBuffer cmd)
void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd)
Camera camera = hdCamera.camera;
// Shadows
m_ShadowMgr.SyncData();
m_ShadowMgr.BindResources(cmd, null, 0);

cmd.SetGlobalInt(HDShaderIDs._EnvLightCount, m_lightList.envLights.Count);
cmd.SetGlobalBuffer(HDShaderIDs._ShadowDatas, s_shadowDatas);
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplX, GetNumTileFtplX(camera));
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplY, GetNumTileFtplY(camera));
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplX, GetNumTileFtplX(hdCamera));
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplY, GetNumTileFtplY(hdCamera));
cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredX, GetNumTileClusteredX(camera));
cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredY, GetNumTileClusteredY(camera));
cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredX, GetNumTileClusteredX(hdCamera));
cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredY, GetNumTileClusteredY(hdCamera));
if (m_FrameSettings.lightLoopSettings.enableBigTilePrepass)
cmd.SetGlobalBuffer(HDShaderIDs.g_vBigTileLightList, s_BigTileLightList);

cmd.SetGlobalFloat(HDShaderIDs.g_fNearPlane, camera.nearClipPlane);
cmd.SetGlobalFloat(HDShaderIDs.g_fFarPlane, camera.farClipPlane);
cmd.SetGlobalInt(HDShaderIDs.g_iLog2NumClusters, k_Log2NumClusters);
cmd.SetGlobalInt(HDShaderIDs.g_isLogBaseBufferEnabled, k_UseDepthBuffer ? 1 : 0);
cmd.SetGlobalBuffer(HDShaderIDs.g_vLayeredOffsetsBuffer, s_PerVoxelOffset);

public bool outputSplitLighting;
}
public void RenderDeferredDirectionalShadow(HDCamera hdCamera, RenderTargetIdentifier deferredShadowRT, RenderTargetIdentifier depthTexture, CommandBuffer cmd)
public void RenderDeferredDirectionalShadow(HDCamera hdCamera, RTHandle deferredShadowRT, RenderTargetIdentifier depthTexture, CommandBuffer cmd)
{
cmd.SetGlobalTexture(HDShaderIDs._DeferredShadowTexture, RuntimeUtilities.blackTexture);
}
using (new ProfilingSample(cmd, "Deferred Directional Shadow", CustomSamplerId.TPDeferredDirectionalShadow.GetSampler()))
{

cmd.SetComputeTextureParam(deferredDirectionalShadowComputeShader, kernel, HDShaderIDs._MainDepthTexture, depthTexture);
int deferredShadowTileSize = 16; // Must match DeferreDirectionalShadow.compute
int numTilesX = (hdCamera.camera.pixelWidth + (deferredShadowTileSize - 1)) / deferredShadowTileSize;
int numTilesY = (hdCamera.camera.pixelHeight + (deferredShadowTileSize - 1)) / deferredShadowTileSize;
int numTilesX = (hdCamera.actualWidth + (deferredShadowTileSize - 1)) / deferredShadowTileSize;
int numTilesY = (hdCamera.actualHeight + (deferredShadowTileSize - 1)) / deferredShadowTileSize;
cmd.SetGlobalTexture(HDShaderIDs._DeferredShadowTexture, deferredShadowRT);
}
}

cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._MainDepthTexture, depthTexture);
// TODO: Should remove this setting but can't remove it else get error: Property (_AmbientOcclusionTexture) at kernel index (32) is not set. Check why
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._AmbientOcclusionTexture, HDShaderIDs._AmbientOcclusionTexture);
// TODO: Is it possible to setup this outside the loop ? Can figure out how, get this: Property (specularLightingUAV) at kernel index (21) is not set
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs.specularLightingUAV, colorBuffers[0]);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs.diffuseLightingUAV, colorBuffers[1]);

if (lightingDebug.tileClusterDebug != LightLoop.TileClusterDebug.None)
{
int w = hdCamera.camera.pixelWidth;
int h = hdCamera.camera.pixelHeight;
int w = hdCamera.actualWidth;
int h = hdCamera.actualHeight;
Vector2 mousePixelCoord = MousePositionDebug.instance.GetMousePosition(hdCamera.screenSize.y);
// Debug tiles
if (lightingDebug.tileClusterDebug == LightLoop.TileClusterDebug.MaterialFeatureVariants)

// featureVariants
m_DebugViewTilesMaterial.SetInt(HDShaderIDs._NumTiles, numTiles);
m_DebugViewTilesMaterial.SetInt(HDShaderIDs._ViewTilesFlags, (int)lightingDebug.tileClusterDebugByCategory);
m_DebugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, mousePixelCoord);
m_DebugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(hdCamera));
m_DebugViewTilesMaterial.SetBuffer(HDShaderIDs.g_TileList, s_TileList);
m_DebugViewTilesMaterial.SetBuffer(HDShaderIDs.g_DispatchIndirectBuffer, s_DispatchIndirectBuffer);
m_DebugViewTilesMaterial.EnableKeyword("USE_FPTL_LIGHTLIST");

// lightCategories
m_DebugViewTilesMaterial.SetInt(HDShaderIDs._ViewTilesFlags, (int)lightingDebug.tileClusterDebugByCategory);
m_DebugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, mousePixelCoord);
m_DebugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(hdCamera));
m_DebugViewTilesMaterial.SetBuffer(HDShaderIDs.g_vLightListGlobal, bUseClustered ? s_PerVoxelLightLists : s_LightList);
m_DebugViewTilesMaterial.EnableKeyword(bUseClustered ? "USE_CLUSTERED_LIGHTLIST" : "USE_FPTL_LIGHTLIST");
m_DebugViewTilesMaterial.DisableKeyword(!bUseClustered ? "USE_CLUSTERED_LIGHTLIST" : "USE_FPTL_LIGHTLIST");

for (uint i = 0; i < faceCount; ++i)
{
m_ShadowMgr.DisplayShadow(cmd, index, i, x, y, overlaySize, overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.camera.pixelWidth);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.actualWidth);
}
}
}

HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.camera.pixelWidth);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.actualWidth);
}
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopSettings.cs


[Serializable]
public class LightLoopSettings
{
public static string kEnableFptlForForwardOpaque = "Enable Fptl for Forward Opaque";
public static string kEnableTileCluster = "Enable Tile/Cluster";
public static string kEnableBigTile = "Enable Big Tile";
public static string kEnableComputeLighting = "Enable Compute Lighting";

static public void RegisterDebug(String menuName, LightLoopSettings lightLoopSettings)
{
DebugMenuManager.instance.AddDebugItem<bool>(menuName, kEnableFptlForForwardOpaque, () => lightLoopSettings.enableFptlForForwardOpaque, (value) => lightLoopSettings.enableFptlForForwardOpaque = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>(menuName, kEnableTileCluster, () => lightLoopSettings.enableTileAndCluster, (value) => lightLoopSettings.enableTileAndCluster = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>(menuName, kEnableBigTile, () => lightLoopSettings.enableBigTilePrepass, (value) => lightLoopSettings.enableBigTilePrepass = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>(menuName, kEnableComputeLighting, () => lightLoopSettings.enableComputeLightEvaluation, (value) => lightLoopSettings.enableComputeLightEvaluation = (bool)value);

28
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-clustered.compute


float g_fNearPlane;
float g_fFarPlane;
int g_iLog2NumClusters; // numClusters = (1<<g_iLog2NumClusters)
float4 g_screenSize;
int g_iNumSamplesMSAA;
CBUFFER_END
#include "ClusteredUtils.hlsl"

uint2 tileIDX = u3GroupID.xy;
uint t=threadID;
uint iWidth;
uint iHeight;
#ifdef MSAA_ENABLED
uint iNumSamplesMSAA;
g_depth_tex.GetDimensions(iWidth, iHeight, iNumSamplesMSAA);
#else
g_depth_tex.GetDimensions(iWidth, iHeight);
#endif
uint nrTilesX = (iWidth+(TILE_SIZE_CLUSTERED-1))>>log2TileSize;
uint nrTilesY = (iHeight+(TILE_SIZE_CLUSTERED-1))>>log2TileSize;
uint nrTilesX = ((uint)g_screenSize.x +(TILE_SIZE_CLUSTERED-1))>>log2TileSize;
uint nrTilesY = ((uint)g_screenSize.y +(TILE_SIZE_CLUSTERED-1))>>log2TileSize;
uint2 viTilUR = min( viTilLL+uint2(TILE_SIZE_CLUSTERED,TILE_SIZE_CLUSTERED), uint2(iWidth, iHeight) ); // not width and height minus 1 since viTilUR represents the end of the tile corner.
uint2 viTilUR = min( viTilLL+uint2(TILE_SIZE_CLUSTERED,TILE_SIZE_CLUSTERED), uint2(g_screenSize.x, g_screenSize.y) ); // not width and height minus 1 since viTilUR represents the end of the tile corner.
if(t==0)
{

for(int idx=t; idx<(TILE_SIZE_CLUSTERED*TILE_SIZE_CLUSTERED); idx+=NR_THREADS)
{
uint2 uPixCrd = min( uint2(viTilLL.x+(idx&(TILE_SIZE_CLUSTERED-1)), viTilLL.y+(idx>>log2TileSize)), uint2(iWidth-1, iHeight-1) );
uint2 uPixCrd = min( uint2(viTilLL.x+(idx&(TILE_SIZE_CLUSTERED-1)), viTilLL.y+(idx>>log2TileSize)), uint2(g_screenSize.x-1, g_screenSize.y-1) );
for(uint i=0; i<iNumSamplesMSAA; i++)
for(uint i=0; i<g_iNumSamplesMSAA; i++)
{
const float fDpth = FetchDepthMSAA(g_depth_tex, uPixCrd, i);
#else

if(dpt_ma<=0.0) dpt_ma = VIEWPORT_SCALE_Z; // assume sky pixel
#endif
float2 vTileLL = float2(viTilLL.x/(float) iWidth, viTilLL.y/(float) iHeight);
float2 vTileUR = float2(viTilUR.x/(float) iWidth, viTilUR.y/(float) iHeight);
float2 vTileLL = float2(viTilLL.x/g_screenSize.x, viTilLL.y/g_screenSize.y);
float2 vTileUR = float2(viTilUR.x/g_screenSize.x, viTilUR.y/g_screenSize.y);
// build coarse list using AABB
#ifdef USE_TWO_PASS_TILED_LIGHTING

int iNrCoarseLights = min(lightOffs,MAX_NR_COARSE_ENTRIES);
#ifdef PERFORM_SPHERICAL_INTERSECTION_TESTS
iNrCoarseLights = SphericalIntersectionTests( t, iNrCoarseLights, float2(min(viTilLL.xy+uint2(TILE_SIZE_CLUSTERED/2,TILE_SIZE_CLUSTERED/2), uint2(iWidth-1, iHeight-1))) );
iNrCoarseLights = SphericalIntersectionTests( t, iNrCoarseLights, float2(min(viTilLL.xy+uint2(TILE_SIZE_CLUSTERED/2,TILE_SIZE_CLUSTERED/2), uint2(g_screenSize.x-1, g_screenSize.y-1))) );
#endif
#ifdef ENABLE_DEPTH_TEXTURE_BACKPLANE

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionSystemInternal.cs


public RenderTexture NewRenderTarget(PlanarReflectionProbe probe)
{
var desc = GetRenderHDCamera(probe).renderTextureDesc;
desc.width = m_Parameters.planarReflectionProbeSize;
desc.height = m_Parameters.planarReflectionProbeSize;
desc.colorFormat = RenderTextureFormat.ARGBHalf;
desc.useMipMap = true;
var rt = new RenderTexture(desc);
var rt = new RenderTexture(m_Parameters.planarReflectionProbeSize, m_Parameters.planarReflectionProbeSize, 0, RenderTextureFormat.ARGBHalf);
rt.useMipMap = true;
rt.autoGenerateMips = false;
rt.Create();
return rt;
}

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Builtin/BuiltinData.cs


return RenderTextureFormat.ARGB32;
}
public static RenderTextureReadWrite GetShadowMaskBufferReadWrite()
public static bool GetShadowMaskSRGBFlag()
return RenderTextureReadWrite.Linear;
return false;
}
public static RenderTextureFormat GetVelocityBufferFormat()

public static RenderTextureReadWrite GetVelocityBufferReadWrite()
public static bool GetVelocityBufferSRGBFlag()
return RenderTextureReadWrite.Linear;
return false;
}
public static RenderTextureFormat GetDistortionBufferFormat()

}
public static RenderTextureReadWrite GetDistortionBufferReadWrite()
public static bool GetDistortionBufferSRGBFlag()
return RenderTextureReadWrite.Linear;
return false;
}
}
}

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs


static public int GetMaterialDBufferCount() { return (int)DBufferMaterial.Count; }
static RenderTextureFormat[] m_RTFormat = { RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32 };
static RenderTextureReadWrite[] m_RTReadWrite = { RenderTextureReadWrite.sRGB, RenderTextureReadWrite.Linear, RenderTextureReadWrite.Linear };
static bool[] m_sRGBFlags= { true, false, false };
static public void GetMaterialDBufferDescription(out RenderTextureFormat[] RTFormat, out RenderTextureReadWrite[] RTReadWrite)
static public void GetMaterialDBufferDescription(out RenderTextureFormat[] RTFormat, out bool[] sRGBFlags)
RTReadWrite = m_RTReadWrite;
sRGBFlags = m_sRGBFlags;
}
}
}

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.cs


public override int GetMaterialGBufferCount() { return (int)GBufferMaterial.Count; }
RenderTextureFormat[] m_RTFormat4 = { RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32, RenderTextureFormat.RGB111110Float };
RenderTextureReadWrite[] m_RTReadWrite4 = { RenderTextureReadWrite.sRGB, RenderTextureReadWrite.Linear, RenderTextureReadWrite.Linear, RenderTextureReadWrite.Linear };
bool[] m_RTsRGBFlag4 = { true, false, false, false };
public override void GetMaterialGBufferDescription(out RenderTextureFormat[] RTFormat, out RenderTextureReadWrite[] RTReadWrite)
public override void GetMaterialGBufferDescription(out RenderTextureFormat[] RTFormat, out bool[] sRGBFlag)
RTReadWrite = m_RTReadWrite4;
sRGBFlag = m_RTsRGBFlag4;
}
//-----------------------------------------------------------------------------

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl


TEXTURE2D(_PyramidDepthTexture);
CBUFFER_START(UnityGaussianPyramidParameters)
float4 _GaussianPyramidColorMipSize;
float4 _GaussianPyramidColorMipSize; // (x,y) = PyramidToScreenScale, z = lodCount
float4 _PyramidDepthMipSize;
CBUFFER_END

}
// Map the roughness to the correct mip map level of the color pyramid
lighting.specularTransmitted = SAMPLE_TEXTURE2D_LOD(_GaussianPyramidColorTexture, s_trilinear_clamp_sampler, refractedBackPointNDC, preLightData.transparentSSMipLevel).rgb;
lighting.specularTransmitted = SAMPLE_TEXTURE2D_LOD(_GaussianPyramidColorTexture, s_trilinear_clamp_sampler, refractedBackPointNDC * _GaussianPyramidColorMipSize.xy, preLightData.transparentSSMipLevel).rgb;
// Beer-Lamber law for absorption
lighting.specularTransmitted *= preLightData.transparentTransmittance;

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/RenderPipelineMaterial.cs


{
// GBuffer management
public virtual int GetMaterialGBufferCount() { return 0; }
public virtual void GetMaterialGBufferDescription(out RenderTextureFormat[] RTFormat, out RenderTextureReadWrite[] RTReadWrite)
public virtual void GetMaterialGBufferDescription(out RenderTextureFormat[] RTFormat, out bool[] sRGBFlag)
RTReadWrite = null;
sRGBFlag = null;
}
// Regular interface

105
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs


// Currently we only support SSSBuffer with one buffer. If the shader code change, it may require to update the shader manager
public const int k_MaxSSSBuffer = 1;
readonly int m_SSSBuffer0;
readonly RenderTargetIdentifier m_SSSBuffer0RT;
RenderTargetIdentifier[] m_ColorMRTs;
RenderTargetIdentifier[] m_RTIDs = new RenderTargetIdentifier[k_MaxSSSBuffer];
RTHandle[] m_ColorMRTs = new RTHandle[k_MaxSSSBuffer];
bool[] m_ExternalBuffer = new bool[k_MaxSSSBuffer];
// Disney SSS Model
ComputeShader m_SubsurfaceScatteringCS;

RenderTexture m_HTile;
RenderTargetIdentifier m_HTileRT;
RTHandle m_HTile;
// End Disney SSS Model
// Jimenez SSS Model

// Jimenez need an extra buffer and Disney need one for some platform
readonly int m_CameraFilteringBuffer;
readonly RenderTargetIdentifier m_CameraFilteringBufferRT;
RTHandle m_CameraFilteringBuffer;
// This is use to be able to read stencil value in compute shader
Material m_CopyStencilForSplitLighting;

m_SSSBuffer0 = HDShaderIDs._SSSBufferTexture[0];
m_SSSBuffer0RT = new RenderTargetIdentifier(m_SSSBuffer0);
// Use with Jimenez
m_CameraFilteringBuffer = HDShaderIDs._CameraFilteringBuffer;
m_CameraFilteringBufferRT = new RenderTargetIdentifier(m_CameraFilteringBuffer);
// In case of deferred, we must be in sync with SubsurfaceScattering.hlsl and lit.hlsl files and setup the correct buffers
// for SSS
public void InitSSSBuffersFromGBuffer(GBufferManager gbufferManager)
public void InitSSSBuffers(GBufferManager gbufferManager, RenderPipelineSettings settings)
m_RTIDs[0] = gbufferManager.GetGBuffers()[0]; // Note: This buffer must be sRGB (which is the case with Lit.shader)
}
// TODO: For MSAA, at least initially, we can only support Jimenez, because we can't create MSAA + UAV render targets.
if (settings.supportForwardOnly)
{
// In case of full forward we must allocate the render target for forward SSS (or reuse one already existing)
// TODO: Provide a way to reuse a render target
m_ColorMRTs[0] = RTHandle.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGB32, sRGB: true);
m_ExternalBuffer[0] = false;
}
else
{
// In case of deferred, we must be in sync with SubsurfaceScattering.hlsl and lit.hlsl files and setup the correct buffers
m_ColorMRTs[0] = gbufferManager.GetBuffer(0); // Note: This buffer must be sRGB (which is the case with Lit.shader)
m_ExternalBuffer[0] = true;
}
// In case of full forward we must allocate the render target for forward SSS (or reuse one already existing)
// TODO: Provide a way to reuse a render target
public void InitSSSBuffers(RenderTextureDescriptor desc, CommandBuffer cmd)
{
m_RTIDs[0] = m_SSSBuffer0RT;
if (ShaderConfig.k_UseDisneySSS == 0 || NeedTemporarySubsurfaceBuffer())
{
// Caution: must be same format as m_CameraSssDiffuseLightingBuffer
m_CameraFilteringBuffer = RTHandle.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.RGB111110Float, sRGB: false, enableRandomWrite: true, enableMSAA: true); // Enable UAV
}
desc.depthBufferBits = 0;
desc.colorFormat = RenderTextureFormat.ARGB32;
desc.sRGB = true; // Note: This buffer must be sRGB to match deferred case (which is the case with Lit.shader)
cmd.ReleaseTemporaryRT(m_SSSBuffer0);
cmd.GetTemporaryRT(m_SSSBuffer0, desc, FilterMode.Point);
// We use 8x8 tiles in order to match the native GCN HTile as closely as possible.
m_HTile = RTHandle.Alloc(size => new Vector2Int((size.x + 7) / 8, (size.y + 7) / 8), filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.R8, sRGB: false, enableRandomWrite: true); // Enable UAV
public RenderTargetIdentifier GetSSSBuffers(int index)
public RTHandle GetSSSBuffer(int index)
return m_RTIDs[index];
return m_ColorMRTs[index];
}
public void Build(HDRenderPipelineAsset hdAsset)

CoreUtils.Destroy(m_SssVerticalFilterPass);
CoreUtils.Destroy(m_SssHorizontalFilterAndCombinePass);
CoreUtils.Destroy(m_CopyStencilForSplitLighting);
}
public void Resize(HDCamera hdCamera)
{
CoreUtils.ResizeHTile(ref m_HTile, ref m_HTileRT, hdCamera.renderTextureDesc);
for (int i = 0; i < k_MaxSSSBuffer; ++i)
{
if (!m_ExternalBuffer[i])
{
RTHandle.Release(m_ColorMRTs[i]);
}
}
RTHandle.Release(m_CameraFilteringBuffer);
RTHandle.Release(m_HTile);
}
public void PushGlobalParams(CommandBuffer cmd, DiffusionProfileSettings sssParameters, FrameSettings frameSettings)

// Combines specular lighting and diffuse lighting with subsurface scattering.
public void SubsurfaceScatteringPass(HDCamera hdCamera, CommandBuffer cmd, DiffusionProfileSettings sssParameters, FrameSettings frameSettings,
RenderTargetIdentifier colorBufferRT, RenderTargetIdentifier diffuseBufferRT, RenderTargetIdentifier depthStencilBufferRT, RenderTargetIdentifier depthTextureRT)
RTHandle colorBufferRT, RTHandle diffuseBufferRT, RTHandle depthStencilBufferRT, RTHandle depthTextureRT)
{
if (sssParameters == null || !frameSettings.enableSubsurfaceScattering)
return;

// For Jimenez we always need an extra buffer, for Disney it depends on platform
if (ShaderConfig.k_UseDisneySSS == 0 || NeedTemporarySubsurfaceBuffer())
{
// Caution: must be same format as m_CameraSssDiffuseLightingBuffer
cmd.ReleaseTemporaryRT(m_CameraFilteringBuffer);
if (frameSettings.enableMSAA)
CoreUtils.CreateCmdTemporaryRT(cmd, m_CameraFilteringBuffer, hdCamera.renderTextureDesc, 0, FilterMode.Point, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear); // no UAV
else
CoreUtils.CreateCmdTemporaryRT(cmd, m_CameraFilteringBuffer, hdCamera.renderTextureDesc, 0, FilterMode.Point, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear, 1, true); // Enable UAV
CoreUtils.SetRenderTarget(cmd, m_CameraFilteringBufferRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraFilteringBuffer, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}
}

{
// Currently, Unity does not offer a way to access the GCN HTile even on PS4 and Xbox One.
// Therefore, it's computed in a pixel shader, and optimized to only contain the SSS bit.
CoreUtils.SetRenderTarget(cmd, m_HTileRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
HDUtils.SetRenderTarget(cmd, hdCamera, m_HTile, ClearFlag.Color, CoreUtils.clearColorAllBlack);
CoreUtils.SetRenderTarget(cmd, depthStencilBufferRT); // No need for color buffer here
HDUtils.SetRenderTarget(cmd, hdCamera, depthStencilBufferRT); // No need for color buffer here
CoreUtils.DrawFullScreen(cmd, m_CopyStencilForSplitLighting, null, 2);
cmd.ClearRandomWriteTargets();
}

cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._ShapeParams, sssParameters.shapeParams);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._DepthTexture, depthTextureRT);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._SSSHTile, m_HTileRT);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._SSSHTile, m_HTile);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._SSSBufferTexture[i], GetSSSBuffers(i));
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._SSSBufferTexture[i], GetSSSBuffer(i));
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._CameraFilteringBuffer, m_CameraFilteringBufferRT);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._CameraFilteringBuffer, m_CameraFilteringBuffer);
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraFilteringBufferRT); // Cannot set a RT on a material
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraFilteringBuffer); // Cannot set a RT on a material
// Additively blend diffuse and specular lighting into 'm_CameraColorBufferRT'.
CoreUtils.DrawFullScreen(cmd, m_CombineLightingPass, colorBufferRT, depthStencilBufferRT);

{
for (int i = 0; i < sssBufferCount; ++i)
{
cmd.SetGlobalTexture(HDShaderIDs._SSSBufferTexture[i], GetSSSBuffers(i));
cmd.SetGlobalTexture(HDShaderIDs._SSSBufferTexture[i], GetSSSBuffer(i));
}
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, diffuseBufferRT); // Cannot set a RT on a material

CoreUtils.DrawFullScreen(cmd, m_SssVerticalFilterPass, m_CameraFilteringBufferRT, depthStencilBufferRT);
CoreUtils.DrawFullScreen(cmd, m_SssVerticalFilterPass, m_CameraFilteringBuffer, depthStencilBufferRT);
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraFilteringBufferRT); // Cannot set a RT on a material
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraFilteringBuffer); // Cannot set a RT on a material
m_SssHorizontalFilterAndCombinePass.SetVectorArray(HDShaderIDs._FilterKernelsBasic, sssParameters.filterKernelsBasic);
m_SssHorizontalFilterAndCombinePass.SetVectorArray(HDShaderIDs._HalfRcpWeightedVariances, sssParameters.halfRcpWeightedVariances);
// Perform the horizontal SSS filtering pass, and combine diffuse and specular lighting into 'm_CameraColorBufferRT'.

13
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipeline/FrameSettings.cs


frameSettings.enablePostprocess = this.enablePostprocess;
frameSettings.enableStereo = this.enableStereo;
frameSettings.enableForwardRenderingOnly = this.enableForwardRenderingOnly;
frameSettings.enableOpaqueObjects = this.enableOpaqueObjects;
frameSettings.enableTransparentObjects = this.enableTransparentObjects;

// We have to fall back to forward-only rendering when scene view is using wireframe rendering mode
// as rendering everything in wireframe + deferred do not play well together
aggregate.enableForwardRenderingOnly = srcFrameSettings.enableForwardRenderingOnly || GL.wireframe;
aggregate.enableForwardRenderingOnly = srcFrameSettings.enableForwardRenderingOnly || GL.wireframe || renderPipelineSettings.supportForwardOnly;
aggregate.enableMotionVectors = camera.cameraType != CameraType.Reflection && srcFrameSettings.enableMotionVectors;
aggregate.enableObjectMotionVectors = camera.cameraType != CameraType.Reflection && srcFrameSettings.enableObjectMotionVectors;
aggregate.enableMotionVectors = camera.cameraType != CameraType.Reflection && srcFrameSettings.enableMotionVectors && renderPipelineSettings.supportMotionVectors;
aggregate.enableObjectMotionVectors = camera.cameraType != CameraType.Reflection && srcFrameSettings.enableObjectMotionVectors && renderPipelineSettings.supportMotionVectors;
aggregate.enableDBuffer = srcFrameSettings.enableDBuffer && renderPipelineSettings.supportDBuffer;
aggregate.enableAtmosphericScattering = srcFrameSettings.enableAtmosphericScattering;
aggregate.enableRoughRefraction = srcFrameSettings.enableRoughRefraction;

// Planar and real time cubemap doesn't need post process and render in FP16
aggregate.enablePostprocess = camera.cameraType != CameraType.Reflection && srcFrameSettings.enablePostprocess;
aggregate.enableStereo = camera.cameraType != CameraType.Reflection && srcFrameSettings.enableStereo && XRSettings.isDeviceActive && (camera.stereoTargetEye == StereoTargetEyeMask.Both);
aggregate.enableStereo = camera.cameraType != CameraType.Reflection && srcFrameSettings.enableStereo && XRSettings.isDeviceActive && (camera.stereoTargetEye == StereoTargetEyeMask.Both) && renderPipelineSettings.supportStereo;
// Force forward if we request stereo. TODO: We should not enforce that, users should be able to chose deferred
aggregate.enableForwardRenderingOnly = aggregate.enableForwardRenderingOnly || aggregate.enableStereo;

aggregate.enableTransparentObjects = srcFrameSettings.enableTransparentObjects;
aggregate.enableMSAA = srcFrameSettings.enableMSAA && ((int)renderPipelineSettings.msaaSampleCount > 1);
aggregate.msaaSampleCount = aggregate.enableMSAA ? renderPipelineSettings.msaaSampleCount : MSAASamples.None;
aggregate.enableMSAA = srcFrameSettings.enableMSAA && renderPipelineSettings.supportMSAA;
aggregate.ConfigureMSAADependentSettings();
aggregate.enableShadowMask = srcFrameSettings.enableShadowMask && renderPipelineSettings.supportShadowMask;

24
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipeline/RenderPipelineSettings.cs


// RenderPipelineSettings define settings that can't be change during runtime. It is equivalent to the GraphicsSettings of Unity (Tiers + shader variant removal).
// This allow to allocate resource or not for a given feature.
// FrameSettings control within a frame what is enable or not(enableShadow, enableStereo, enableDistortion...).
// HDRenderPipelineAsset reference the current RenderPipelineSettings use, there is one per supported platform(Currently this feature is not implemented and only one GlobalFrameSettings is available).
// A Camera with HDAdditionalData have one FrameSettings that configure how it will render.For example a camera use for reflection will disable distortion and postprocess.
// Additionally on a Camera there is another FrameSettings call ActiveFrameSettings that is created on the fly based on FrameSettings and allow modification for debugging purpose at runtime without being serialized on disk.
// The ActiveFrameSettings is register in the debug windows at the creation of the camera.
// A Camera with HDAdditionalData have a RenderPath that define if it use a "Default" FrameSettings, a preset of FrameSettings or a custom one.
// HDRenderPipelineAsset contain a "Default" FrameSettings that can be reference by any camera with RenderPath.Defaut or when the camera don't have HDAdditionalData like the camera of the Editor.
// It also contain a DefaultActiveFrameSettings
// HDRenderPipelineAsset reference the current RenderPipelineSettings used, there is one per supported platform(Currently this feature is not implemented and only one GlobalFrameSettings is available).
// A Camera with HDAdditionalData has one FrameSettings that configures how it will render. For example a camera used for reflection will disable distortion and post-process.
// Additionally, on a Camera there is another FrameSettings called ActiveFrameSettings that is created on the fly based on FrameSettings and allows modifications for debugging purpose at runtime without being serialized on disk.
// The ActiveFrameSettings is registered in the debug windows at the creation of the camera.
// A Camera with HDAdditionalData has a RenderPath that defines if it uses a "Default" FrameSettings, a preset of FrameSettings or a custom one.
// HDRenderPipelineAsset contains a "Default" FrameSettings that can be referenced by any camera with RenderPath.Defaut or when the camera doesn't have HDAdditionalData like the camera of the Editor.
// It also contains a DefaultActiveFrameSettings
// RenderPipelineSettings represent settings that are immutable at runtime.
// RenderPipelineSettings represents settings that are immutable at runtime.
// There is a dedicated RenderPipelineSettings for each platform
[Serializable]
public class RenderPipelineSettings

public bool supportSSR = true;
public bool supportSSAO = true;
public bool supportSubsurfaceScattering = true;
public bool supportForwardOnly = false;
public bool supportDBuffer = false;
public MSAASamples msaaSampleCount = MSAASamples.None;
public bool supportDBuffer = false;
public bool supportMSAA = false;
public MSAASamples msaaSampleCount = MSAASamples.None;
public bool supportMotionVectors = true;
public bool supportStereo = false;
public GlobalLightLoopSettings lightLoopSettings = new GlobalLightLoopSettings();
public ShadowInitParameters shadowInitParams = new ShadowInitParameters();

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/Blit.shader


TEXTURE2D(_BlitTexture);
SamplerState sampler_PointClamp;
SamplerState sampler_LinearClamp;
uniform float4 _BlitScaleBias;
uniform float _BlitMipLevel;
struct Attributes
{

{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID);
output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID) * _BlitScaleBias.xy + _BlitScaleBias.zw;
return SAMPLE_TEXTURE2D(_BlitTexture, sampler_PointClamp, input.texcoord);
return SAMPLE_TEXTURE2D_LOD(_BlitTexture, sampler_PointClamp, input.texcoord, _BlitMipLevel);
return SAMPLE_TEXTURE2D(_BlitTexture, sampler_LinearClamp, input.texcoord);
return SAMPLE_TEXTURE2D_LOD(_BlitTexture, sampler_LinearClamp, input.texcoord, _BlitMipLevel);
}
ENDHLSL

251
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/BufferPyramid.cs


using UnityEngine.Rendering;
using System.Collections.Generic;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

GPUCopy m_GPUCopy;
ComputeShader m_ColorPyramidCS;
RenderTextureDescriptor m_ColorRenderTextureDescriptor;
int[] m_ColorPyramidMips = new int[0];
RTHandle m_ColorPyramidBuffer;
List<RTHandle> m_ColorPyramidMips = new List<RTHandle>();
RenderTextureDescriptor m_DepthRenderTextureDescriptor;
int[] m_DepthPyramidMips = new int[0];
RTHandle m_DepthPyramidBuffer;
List<RTHandle> m_DepthPyramidMips = new List<RTHandle>();
public RenderTextureDescriptor colorRenderTextureDescriptor { get { return m_ColorRenderTextureDescriptor; } }
public int colorUsedMipMapCount { get { return Mathf.Min(colorBufferMipMapCount, m_ColorPyramidMips.Length); } }
public int colorBufferMipMapCount
public RTHandle colorPyramid { get { return m_ColorPyramidBuffer; } }
public RTHandle depthPyramid { get { return m_DepthPyramidBuffer; } }
public BufferPyramid(
ComputeShader colorPyramidCS,
ComputeShader depthPyramidCS, GPUCopy gpuCopy)
{
m_ColorPyramidCS = colorPyramidCS;
m_ColorPyramidKernel = m_ColorPyramidCS.FindKernel("KMain");
m_DepthPyramidCS = depthPyramidCS;
m_GPUCopy = gpuCopy;
m_DepthPyramidKernel_8 = m_DepthPyramidCS.FindKernel("KMain_8");
m_DepthPyramidKernel_1 = m_DepthPyramidCS.FindKernel("KMain_1");
}
float GetXRscale()
{
// for stereo double-wide, each half of the texture will represent a single eye's pyramid
float scale = 1.0f;
//if (m_Asset.renderPipelineSettings.supportsStereo && (desc.dimension != TextureDimension.Tex2DArray))
// scale = 2.0f; // double-wide
return scale;
}
public void CreateBuffers()
get
m_ColorPyramidBuffer = RTHandle.Alloc(size => CalculatePyramidSize(size), filterMode: FilterMode.Trilinear, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, useMipMap: true, autoGenerateMips: false);
m_DepthPyramidBuffer = RTHandle.Alloc(size => CalculatePyramidSize(size), filterMode: FilterMode.Trilinear, colorFormat: RenderTextureFormat.RFloat, sRGB: false, useMipMap: true, autoGenerateMips: false, enableRandomWrite: true); // Need randomReadWrite because we downsample the first mip with a compute shader.
}
public void DestroyBuffers()
{
RTHandle.Release(m_ColorPyramidBuffer);
RTHandle.Release(m_DepthPyramidBuffer);
foreach (var rth in m_ColorPyramidMips)
{
RTHandle.Release(rth);
}
foreach (var rth in m_DepthPyramidMips)
var minSize = Mathf.Min(colorRenderTextureDescriptor.width, colorRenderTextureDescriptor.height);
return Mathf.FloorToInt(Mathf.Log(minSize, 2f));
RTHandle.Release(rth);
public RenderTextureDescriptor depthRenderTextureDescriptor { get { return m_DepthRenderTextureDescriptor; } }
public int depthUsedMipMapCount { get { return Mathf.Min(depthBufferMipMapCount, m_DepthPyramidMips.Length); } }
public int depthBufferMipMapCount
public int GetPyramidLodCount(HDCamera camera)
get
var minSize = Mathf.Min(camera.actualWidth, camera.actualHeight);
return Mathf.FloorToInt(Mathf.Log(minSize, 2f));
}
Vector2Int CalculatePyramidMipSize(Vector2Int baseMipSize, int mipIndex)
{
return new Vector2Int(baseMipSize.x >> mipIndex, baseMipSize.y >> mipIndex);
}
Vector2Int CalculatePyramidSize(Vector2Int size)
{
// Instead of using the screen size, we round up to the next power of 2 because currently some platforms don't support NPOT Render Texture with mip maps (PS4 for example)
// Then we render in a Screen Sized viewport.
// Note that even if PS4 supported POT Mips, the buffers would be padded to the next power of 2 anyway (TODO: check with other platforms...)
int pyramidSize = (int)Mathf.NextPowerOfTwo(Mathf.Max(size.x, size.y));
return new Vector2Int((int)(pyramidSize * GetXRscale()), pyramidSize);
}
void UpdatePyramidMips(HDCamera camera, RenderTextureFormat format, List<RTHandle> mipList, int lodCount)
{
int currentLodCount = mipList.Count;
if (lodCount > currentLodCount)
var minSize = Mathf.Min(depthRenderTextureDescriptor.width, depthRenderTextureDescriptor.height);
return Mathf.FloorToInt(Mathf.Log(minSize, 2f));
for (int i = currentLodCount; i < lodCount; ++i)
{
int mipIndexCopy = i + 1; // Don't remove this copy! It's important for the value to be correctly captured by the lambda.
RTHandle newMip = RTHandle.Alloc(size => CalculatePyramidMipSize(CalculatePyramidSize(size), mipIndexCopy), colorFormat: format, sRGB: false, enableRandomWrite: true, useMipMap: false, filterMode: FilterMode.Bilinear);
mipList.Add(newMip);
}
public BufferPyramid(
ComputeShader colorPyramidCS, int[] colorMipIds,
ComputeShader depthPyramidCS, GPUCopy gpuCopy, int[] depthMipIds)
public Vector2 GetPyramidToScreenScale(HDCamera camera)
m_ColorPyramidCS = colorPyramidCS;
m_ColorPyramidKernel = m_ColorPyramidCS.FindKernel("KMain");
m_ColorPyramidMips = colorMipIds;
m_DepthPyramidCS = depthPyramidCS;
m_GPUCopy = gpuCopy;
m_DepthPyramidMips = depthMipIds;
m_DepthPyramidKernel_8 = m_DepthPyramidCS.FindKernel("KMain_8");
m_DepthPyramidKernel_1 = m_DepthPyramidCS.FindKernel("KMain_1");
return new Vector2((float)camera.actualWidth / m_DepthPyramidBuffer.rt.width, (float)camera.actualHeight / m_DepthPyramidBuffer.rt.height);
}
public void RenderDepthPyramid(

RenderTargetIdentifier depthTexture,
RenderTargetIdentifier targetTexture)
RTHandle depthTexture)
var depthPyramidDesc = m_DepthRenderTextureDescriptor;
int lodCount = GetPyramidLodCount(hdCamera);
UpdatePyramidMips(hdCamera, m_DepthPyramidBuffer.rt.format, m_DepthPyramidMips, lodCount);
var lodCount = depthBufferMipMapCount;
if (lodCount > m_DepthPyramidMips.Length)
{
Debug.LogWarningFormat("Cannot compute all mipmaps of the depth pyramid, max texture size supported: {0}", (2 << m_DepthPyramidMips.Length).ToString());
lodCount = m_DepthPyramidMips.Length;
}
cmd.SetGlobalVector(HDShaderIDs._DepthPyramidMipSize, new Vector4(hdCamera.actualWidth, hdCamera.actualHeight, lodCount, 0.0f));
cmd.ReleaseTemporaryRT(m_DepthPyramidMips[0]);
m_GPUCopy.SampleCopyChannel_xyzw2x(cmd, depthTexture, m_DepthPyramidBuffer, new Vector2(hdCamera.actualWidth, hdCamera.actualHeight));
depthPyramidDesc.sRGB = false;
depthPyramidDesc.enableRandomWrite = true;
depthPyramidDesc.useMipMap = false;
Vector2 scale = GetPyramidToScreenScale(hdCamera);
cmd.GetTemporaryRT(m_DepthPyramidMips[0], depthPyramidDesc, FilterMode.Bilinear);
m_GPUCopy.SampleCopyChannel_xyzw2x(cmd, depthTexture, m_DepthPyramidMips[0], new Vector2(depthPyramidDesc.width, depthPyramidDesc.height));
cmd.CopyTexture(m_DepthPyramidMips[0], 0, 0, targetTexture, 0, 0);
RTHandle src = m_DepthPyramidBuffer;
var srcMipWidth = depthPyramidDesc.width;
var srcMipHeight = depthPyramidDesc.height;
depthPyramidDesc.width = srcMipWidth >> 1;
depthPyramidDesc.height = srcMipHeight >> 1;
RTHandle dest = m_DepthPyramidMips[i];
var srcMipWidth = hdCamera.actualWidth >> i;
var srcMipHeight = hdCamera.actualHeight >> i;
var dstMipWidth = srcMipWidth >> 1;
var dstMipHeight = srcMipHeight >> 1;
if (depthPyramidDesc.width < 4 * k_DepthBlockSize
|| depthPyramidDesc.height < 4 * k_DepthBlockSize)
if (dstMipWidth < 4 * k_DepthBlockSize
|| dstMipHeight < 4 * k_DepthBlockSize)
cmd.ReleaseTemporaryRT(m_DepthPyramidMips[i + 1]);
cmd.GetTemporaryRT(m_DepthPyramidMips[i + 1], depthPyramidDesc, FilterMode.Bilinear);
cmd.SetComputeTextureParam(m_DepthPyramidCS, kernel, _Source, m_DepthPyramidMips[i]);
cmd.SetComputeTextureParam(m_DepthPyramidCS, kernel, _Result, m_DepthPyramidMips[i + 1]);
cmd.SetComputeVectorParam(m_DepthPyramidCS, _SrcSize, new Vector4(srcMipWidth, srcMipHeight, 1f / srcMipWidth, 1f / srcMipHeight));
cmd.SetComputeTextureParam(m_DepthPyramidCS, kernel, _Source, src);
cmd.SetComputeTextureParam(m_DepthPyramidCS, kernel, _Result, dest);
cmd.SetComputeVectorParam(m_DepthPyramidCS, _SrcSize, new Vector4(srcMipWidth, srcMipHeight, (1.0f / srcMipWidth) * scale.x, (1.0f / srcMipHeight) * scale.y));
Mathf.CeilToInt(depthPyramidDesc.width / kernelBlockSize),
Mathf.CeilToInt(depthPyramidDesc.height / kernelBlockSize),
Mathf.CeilToInt(dstMipWidth / kernelBlockSize),
Mathf.CeilToInt(dstMipHeight / kernelBlockSize),
cmd.CopyTexture(m_DepthPyramidMips[i + 1], 0, 0, targetTexture, 0, i + 1);
// If we could bind texture mips as UAV we could avoid this copy...(which moreover copies more than the needed viewport if not fullscreen)
cmd.CopyTexture(m_DepthPyramidMips[i], 0, 0, 0, 0, dstMipWidth, dstMipHeight, m_DepthPyramidBuffer, 0, i + 1, 0, 0);
src = dest;
for (int i = 0; i < lodCount + 1; i++)
cmd.ReleaseTemporaryRT(m_DepthPyramidMips[i]);
cmd.SetGlobalTexture(HDShaderIDs._PyramidDepthTexture, m_DepthPyramidBuffer);
}
public void RenderColorPyramid(

RenderTargetIdentifier colorTexture,
RenderTargetIdentifier targetTexture)
RTHandle colorTexture)
var colorPyramidDesc = colorRenderTextureDescriptor;
int lodCount = GetPyramidLodCount(hdCamera);
UpdatePyramidMips(hdCamera, m_ColorPyramidBuffer.rt.format, m_ColorPyramidMips, lodCount);
var lodCount = colorBufferMipMapCount;
if (lodCount > m_ColorPyramidMips.Length)
{
Debug.LogWarningFormat("Cannot compute all mipmaps of the color pyramid, max texture size supported: {0}", (2 << m_ColorPyramidMips.Length).ToString());
lodCount = m_ColorPyramidMips.Length;
}
Vector2 scale = GetPyramidToScreenScale(hdCamera);
cmd.SetGlobalVector(HDShaderIDs._GaussianPyramidColorMipSize, new Vector4(scale.x, scale.y, lodCount, 0.0f));
cmd.CopyTexture(colorTexture, 0, 0, targetTexture, 0, 0);
var last = colorTexture;
// Here we blit a "camera space" texture into a square texture but we want to keep the original viewport.
// Other BlitCameraTexture version will setup the viewport based on the destination RT scale (square here) so we need override it here.
HDUtils.BlitCameraTexture(cmd, hdCamera, colorTexture, m_ColorPyramidBuffer, new Rect(0.0f, 0.0f, hdCamera.actualWidth, hdCamera.actualHeight));
colorPyramidDesc.sRGB = false;
colorPyramidDesc.enableRandomWrite = true;
colorPyramidDesc.useMipMap = false;
RTHandle src = m_ColorPyramidBuffer;
colorPyramidDesc.width = colorPyramidDesc.width >> 1;
colorPyramidDesc.height = colorPyramidDesc.height >> 1;
RTHandle dest = m_ColorPyramidMips[i];
var srcMipWidth = hdCamera.actualWidth >> i;
var srcMipHeight = hdCamera.actualHeight >> i;
var dstMipWidth = srcMipWidth >> 1;
var dstMipHeight = srcMipHeight >> 1;
cmd.ReleaseTemporaryRT(m_ColorPyramidMips[i + 1]);
cmd.GetTemporaryRT(m_ColorPyramidMips[i + 1], colorPyramidDesc, FilterMode.Bilinear);
cmd.SetComputeTextureParam(m_ColorPyramidCS, m_ColorPyramidKernel, _Source, last);
cmd.SetComputeTextureParam(m_ColorPyramidCS, m_ColorPyramidKernel, _Result, m_ColorPyramidMips[i + 1]);
cmd.SetComputeVectorParam(m_ColorPyramidCS, _Size, new Vector4(colorPyramidDesc.width, colorPyramidDesc.height, 1f / colorPyramidDesc.width, 1f / colorPyramidDesc.height));
cmd.SetComputeTextureParam(m_ColorPyramidCS, m_ColorPyramidKernel, _Source, src);
cmd.SetComputeTextureParam(m_ColorPyramidCS, m_ColorPyramidKernel, _Result, dest);
// _Size is used as a scale inside the whole render target so here we need to keep the full size (and not the scaled size depending on the current camera)
cmd.SetComputeVectorParam(m_ColorPyramidCS, _Size, new Vector4(dest.rt.width, dest.rt.height, 1f / dest.rt.width, 1f / dest.rt.height));
Mathf.CeilToInt(colorPyramidDesc.width / 8f),
Mathf.CeilToInt(colorPyramidDesc.height / 8f),
Mathf.CeilToInt(dstMipWidth / 8f),
Mathf.CeilToInt(dstMipHeight / 8f),
cmd.CopyTexture(m_ColorPyramidMips[i + 1], 0, 0, targetTexture, 0, i + 1);
// If we could bind texture mips as UAV we could avoid this copy...(which moreover copies more than the needed viewport if not fullscreen)
cmd.CopyTexture(m_ColorPyramidMips[i], 0, 0, 0, 0, dstMipWidth, dstMipHeight, m_ColorPyramidBuffer, 0, i + 1, 0, 0);
last = m_ColorPyramidMips[i + 1];
src = dest;
for (int i = 0; i < lodCount; i++)
cmd.ReleaseTemporaryRT(m_ColorPyramidMips[i + 1]);
}
public void Initialize(HDCamera hdCamera, bool enableStereo)
{
var colorDesc = CalculateRenderTextureDescriptor(hdCamera, enableStereo);
colorDesc.colorFormat = RenderTextureFormat.ARGBHalf;
m_ColorRenderTextureDescriptor = colorDesc;
var depthDesc = CalculateRenderTextureDescriptor(hdCamera, enableStereo);
depthDesc.colorFormat = RenderTextureFormat.RFloat;
m_DepthRenderTextureDescriptor = depthDesc;
}
public static RenderTextureDescriptor CalculateRenderTextureDescriptor(HDCamera hdCamera, bool enableStereo)
{
var desc = hdCamera.renderTextureDesc;
desc.depthBufferBits = 0;
desc.useMipMap = true;
desc.autoGenerateMips = false;
desc.msaaSamples = 1; // These are approximation textures, they don't need MSAA
// for stereo double-wide, each half of the texture will represent a single eye's pyramid
//var widthModifier = 1;
//if (stereoEnabled && (desc.dimension != TextureDimension.Tex2DArray))
// widthModifier = 2; // double-wide
//desc.width = pyramidSize * widthModifier;
desc.width = (int)hdCamera.screenSize.x;
desc.height = (int)hdCamera.screenSize.y;
return desc;
cmd.SetGlobalTexture(HDShaderIDs._GaussianPyramidColorTexture, m_ColorPyramidBuffer);
}
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset


combineLighting: {fileID: 4800000, guid: 2e37131331fbdca449b1a2bc47a639ca, type: 3}
cameraMotionVectors: {fileID: 4800000, guid: 035941b63024d1943af48811c1db20d9, type: 3}
copyStencilBuffer: {fileID: 4800000, guid: 3d1574f1cdfa0ce4995f9bc79ed7f8ec, type: 3}
copyDepthBuffer: {fileID: 4800000, guid: 42dfcc8fe803ece4096c58630689982f, type: 3}
blitFlipMip: {fileID: 4800000, guid: ef092fc4aaa1bb546a9ab4e457c4b07a, type: 3}
blitCubemap: {fileID: 4800000, guid: d05913e251bed7a4992c921c62e1b647, type: 3}
buildProbabilityTables: {fileID: 7200000, guid: b9f26cf340afe9145a699753531b2a4c,
type: 3}

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/RenderPipelineResources.cs


// General
public Shader cameraMotionVectors;
public Shader copyStencilBuffer;
public Shader copyDepthBuffer;
public Shader blit;
// Sky

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariables.hlsl


// w = 1 + 1.0/height
float4 _ScreenParams;
// x = camera.pixelWidth / RTHandle.maxWidth
// y = camera.pixelHeight / RTHandle.maxHeight
float4 _ScreenToTargetScale;
// Values used to linearize the Z buffer (http://www.humus.name/temp/Linearize%20depth.txt)
// x = 1-far/near
// y = far/near

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariablesFunctions.hlsl


projMatrix._13_23_33_43 = -projMatrix._13_23_33_43;
}
// This method should be used for rendering any full screen quad that uses an auto-scaling Render Targets (see RTHandle/HDCamera)
// It will account for the fact that the textures it samples are not necesarry using the full space of the render texture but only a partial viewport.
float2 GetNormalizedFullScreenTriangleTexCoord(uint vertexID)
{
return GetFullScreenTriangleTexCoord(vertexID) * _ScreenToTargetScale.xy;
}
#endif // UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISkyRenderer.cs


{
if (builtinParams.depthBuffer == BuiltinSkyParameters.nullRT)
{
CoreUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.colorBuffer);
HDUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.hdCamera, builtinParams.colorBuffer);
CoreUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.colorBuffer, builtinParams.depthBuffer);
HDUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.hdCamera, builtinParams.colorBuffer, builtinParams.depthBuffer);
}
}

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSkyRenderer.cs


{
if (builtinParams.depthBuffer == BuiltinSkyParameters.nullRT)
{
CoreUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.colorBuffer);
HDUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.hdCamera, builtinParams.colorBuffer);
CoreUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.colorBuffer, builtinParams.depthBuffer);
HDUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.hdCamera, builtinParams.colorBuffer, builtinParams.depthBuffer);
}
}

19
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyManager.cs


public class BuiltinSkyParameters
{
public Matrix4x4 pixelCoordToViewDirMatrix;
public Matrix4x4 invViewProjMatrix;
public Vector3 cameraPosWS;
public Vector4 screenSize;
public CommandBuffer commandBuffer;
public Light sunLight;
public RenderTargetIdentifier colorBuffer;
public RenderTargetIdentifier depthBuffer;
public Matrix4x4 pixelCoordToViewDirMatrix;
public Matrix4x4 invViewProjMatrix;
public Vector3 cameraPosWS;
public Vector4 screenSize;
public CommandBuffer commandBuffer;
public Light sunLight;
public RTHandle colorBuffer;
public RTHandle depthBuffer;
public HDCamera hdCamera;
public static RenderTargetIdentifier nullRT = -1;
}

}
}
public void RenderSky(HDCamera camera, Light sunLight, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, CommandBuffer cmd)
public void RenderSky(HDCamera camera, Light sunLight, RTHandle colorBuffer, RTHandle depthBuffer, CommandBuffer cmd)
{
m_SkyRenderingContext.RenderSky(m_VisualSky, camera, sunLight, colorBuffer, depthBuffer, cmd);
}

77
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyRenderingContext.cs


internal class SkyRenderingContext
{
IBLFilterGGX m_IBLFilterGGX;
RenderTexture m_SkyboxCubemapRT;
RenderTexture m_SkyboxGGXCubemapRT;
RenderTexture m_SkyboxMarginalRowCdfRT;
RenderTexture m_SkyboxConditionalCdfRT;
RTHandle m_SkyboxCubemapRT;
RTHandle m_SkyboxGGXCubemapRT;
RTHandle m_SkyboxMarginalRowCdfRT;
RTHandle m_SkyboxConditionalCdfRT;
Vector4 m_CubemapScreenSize;
Matrix4x4[] m_facePixelCoordToViewDirMatrices = new Matrix4x4[6];
Matrix4x4[] m_faceCameraInvViewProjectionMatrix = new Matrix4x4[6];

public void RebuildTextures(int resolution)
{
bool updateNeeded = m_SkyboxCubemapRT == null || (m_SkyboxCubemapRT.width != resolution);
bool updateNeeded = m_SkyboxCubemapRT == null || (m_SkyboxCubemapRT.rt.width != resolution);
CoreUtils.Destroy(m_SkyboxCubemapRT);
CoreUtils.Destroy(m_SkyboxGGXCubemapRT);
RTHandle.Release(m_SkyboxCubemapRT);
RTHandle.Release(m_SkyboxGGXCubemapRT);
m_SkyboxCubemapRT = null;
m_SkyboxGGXCubemapRT = null;

{
CoreUtils.Destroy(m_SkyboxConditionalCdfRT);
CoreUtils.Destroy(m_SkyboxMarginalRowCdfRT);
RTHandle.Release(m_SkyboxConditionalCdfRT);
RTHandle.Release(m_SkyboxMarginalRowCdfRT);
m_SkyboxConditionalCdfRT = null;
m_SkyboxMarginalRowCdfRT = null;

if (m_SkyboxCubemapRT == null)
{
m_SkyboxCubemapRT = new RenderTexture(resolution, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.DontSave,
dimension = TextureDimension.Cube,
useMipMap = true,
autoGenerateMips = false, // We will generate regular mipmap for filtered importance sampling manually
filterMode = FilterMode.Trilinear
};
m_SkyboxCubemapRT.Create();
m_SkyboxCubemapRT = RTHandle.Alloc(resolution, resolution, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, dimension: TextureDimension.Cube, useMipMap: true, autoGenerateMips: false, filterMode: FilterMode.Trilinear);
m_SkyboxGGXCubemapRT = new RenderTexture(resolution, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.DontSave,
dimension = TextureDimension.Cube,
useMipMap = true,
autoGenerateMips = false,
filterMode = FilterMode.Trilinear
};
m_SkyboxGGXCubemapRT.Create();
m_SkyboxGGXCubemapRT = RTHandle.Alloc(resolution, resolution, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, dimension: TextureDimension.Cube, useMipMap: true, autoGenerateMips: false, filterMode: FilterMode.Trilinear);
}
if (m_SupportsMIS && (m_SkyboxConditionalCdfRT == null))

int height = (int)LightSamplingParameters.TextureHeight;
// + 1 because we store the value of the integral of the cubemap at the end of the texture.
m_SkyboxMarginalRowCdfRT = new RenderTexture(height + 1, 1, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.DontSave,
useMipMap = false,
autoGenerateMips = false,
enableRandomWrite = true,
filterMode = FilterMode.Point
};
m_SkyboxMarginalRowCdfRT.Create();
m_SkyboxMarginalRowCdfRT = RTHandle.Alloc(height + 1, 1, colorFormat: RenderTextureFormat.RFloat, sRGB: false, useMipMap: false, enableRandomWrite: true, filterMode: FilterMode.Point);
m_SkyboxConditionalCdfRT = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.DontSave,
useMipMap = false,
autoGenerateMips = false,
enableRandomWrite = true,
filterMode = FilterMode.Point
};
m_SkyboxConditionalCdfRT.Create();
m_SkyboxMarginalRowCdfRT = RTHandle.Alloc(width, height, colorFormat: RenderTextureFormat.RFloat, sRGB: false, useMipMap: false, enableRandomWrite: true, filterMode: FilterMode.Point);
}
m_CubemapScreenSize = new Vector4((float)resolution, (float)resolution, 1.0f / (float)resolution, 1.0f / (float)resolution);

}
public void Cleanup()
{
CoreUtils.Destroy(m_SkyboxCubemapRT);
CoreUtils.Destroy(m_SkyboxGGXCubemapRT);
CoreUtils.Destroy(m_SkyboxMarginalRowCdfRT);
CoreUtils.Destroy(m_SkyboxConditionalCdfRT);
RTHandle.Release(m_SkyboxCubemapRT);
RTHandle.Release(m_SkyboxGGXCubemapRT);
RTHandle.Release(m_SkyboxMarginalRowCdfRT);
RTHandle.Release(m_SkyboxConditionalCdfRT);
}
void RenderSkyToCubemap(SkyUpdateContext skyContext)

m_BuiltinParameters.pixelCoordToViewDirMatrix = m_facePixelCoordToViewDirMatrices[i];
m_BuiltinParameters.invViewProjMatrix = m_faceCameraInvViewProjectionMatrix[i];
m_BuiltinParameters.colorBuffer = m_SkyboxCubemapRT;
m_BuiltinParameters.depthBuffer = BuiltinSkyParameters.nullRT;
m_BuiltinParameters.depthBuffer = null;
m_BuiltinParameters.hdCamera = null;
CoreUtils.SetRenderTarget(m_BuiltinParameters.commandBuffer, m_SkyboxCubemapRT, ClearFlag.None, 0, (CubemapFace)i);
skyContext.renderer.RenderSky(m_BuiltinParameters, true);

Debug.Assert(m_SkyboxCubemapRT.autoGenerateMips == false);
Debug.Assert(m_SkyboxCubemapRT.rt.autoGenerateMips == false);
m_BuiltinParameters.commandBuffer.GenerateMips(m_SkyboxCubemapRT);
}

m_BuiltinParameters.sunLight = sunLight;
m_BuiltinParameters.screenSize = m_CubemapScreenSize;
m_BuiltinParameters.cameraPosWS = camera.camera.transform.position;
m_BuiltinParameters.hdCamera = null;
int sunHash = 0;
if (sunLight != null)

#if UNITY_EDITOR
// In the editor when we change the sky we want to make the GI dirty so when baking again the new sky is taken into account.
// Changing the hash of the rendertarget allow to say that GI is dirty
m_SkyboxCubemapRT.imageContentsHash = new Hash128((uint)skyContext.skySettings.GetHashCode(), 0, 0, 0);
m_SkyboxCubemapRT.rt.imageContentsHash = new Hash128((uint)skyContext.skySettings.GetHashCode(), 0, 0, 0);
#endif
}
}

return result;
}
public void RenderSky(SkyUpdateContext skyContext, HDCamera camera, Light sunLight, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, CommandBuffer cmd)
public void RenderSky(SkyUpdateContext skyContext, HDCamera camera, Light sunLight, RTHandle colorBuffer, RTHandle depthBuffer, CommandBuffer cmd)
{
if (skyContext.IsValid())
{

m_BuiltinParameters.cameraPosWS = camera.camera.transform.position;
m_BuiltinParameters.colorBuffer = colorBuffer;
m_BuiltinParameters.depthBuffer = depthBuffer;
m_BuiltinParameters.hdCamera = camera;
skyContext.renderer.SetRenderTargets(m_BuiltinParameters);
skyContext.renderer.RenderSky(m_BuiltinParameters, false);

57
ScriptableRenderPipeline/HDRenderPipeline/HDRP/MRTBufferManager.cs


using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public abstract class MRTBufferManager
{
protected int m_BufferCount;
protected RenderTargetIdentifier[] m_RTIDs;
protected RTHandle[] m_RTs;
protected int[] m_TextureShaderIDs;
public int bufferCount { get { return m_BufferCount; } }
public MRTBufferManager(int maxBufferCount)
{
m_BufferCount = maxBufferCount;
m_RTIDs = new RenderTargetIdentifier[maxBufferCount];
m_RTs = new RTHandle[maxBufferCount];
m_TextureShaderIDs = new int[maxBufferCount];
}
public RenderTargetIdentifier[] GetBuffersRTI()
{
// nameID can change from one frame to another depending on the msaa flag so so we need to update this array to be sure it's up to date.
for (int i = 0; i < m_BufferCount; ++i)
{
m_RTIDs[i] = m_RTs[i].nameID;
}
return m_RTIDs;
}
public RTHandle GetBuffer(int index)
{
Debug.Assert(index < m_BufferCount);
return m_RTs[index];
}
public abstract void CreateBuffers();
public void BindBufferAsTextures(CommandBuffer cmd)
{
for (int i = 0; i < m_BufferCount; ++i)
{
cmd.SetGlobalTexture(m_TextureShaderIDs[i], m_RTs[i]);
}
}
virtual public void DestroyBuffers()
{
for (int i = 0; i < m_BufferCount; ++i)
{
RTHandle.Release(m_RTs[i]);
m_RTs[i] = null;
}
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/MRTBufferManager.cs.meta


fileFormatVersion: 2
guid: 8a1cfa206308c414989b3240a61bc7ef
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

63
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DBufferManager.cs


using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class DBufferManager : MRTBufferManager
{
public int vsibleDecalCount { get; set; }
RTHandle m_HTile;
public DBufferManager()
: base(Decal.GetMaterialDBufferCount())
{
Debug.Assert(m_BufferCount <= 4);
}
public override void CreateBuffers()
{
RenderTextureFormat[] rtFormat;
bool[] sRGBFlags;
Decal.GetMaterialDBufferDescription(out rtFormat, out sRGBFlags);
for (int dbufferIndex = 0; dbufferIndex < m_BufferCount; ++dbufferIndex)
{
m_RTs[dbufferIndex] = RTHandle.Alloc(Vector2.one, colorFormat: rtFormat[dbufferIndex], sRGB: sRGBFlags[dbufferIndex], filterMode: FilterMode.Point);
m_RTIDs[dbufferIndex] = m_RTs[dbufferIndex].nameID;
m_TextureShaderIDs[dbufferIndex] = HDShaderIDs._DBufferTexture[dbufferIndex];
}
// We use 8x8 tiles in order to match the native GCN HTile as closely as possible.
m_HTile = RTHandle.Alloc(size => new Vector2Int((size.x + 7) / 8, (size.y + 7) / 8), filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.R8, sRGB: false, enableRandomWrite: true); // Enable UAV
}
override public void DestroyBuffers()
{
base.DestroyBuffers();
RTHandle.Release(m_HTile);
}
public void ClearNormalTargetAndHTile(CommandBuffer cmd, HDCamera camera, Color clearColor)
{
// index 1 is normals
HDUtils.SetRenderTarget(cmd, camera, m_RTs[1], ClearFlag.Color, clearColor);
HDUtils.SetRenderTarget(cmd, camera, m_HTile, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}
public void SetHTile(int bindSlot, CommandBuffer cmd)
{
cmd.SetRandomWriteTarget(bindSlot, m_HTile);
}
public void UnSetHTile(CommandBuffer cmd)
{
cmd.ClearRandomWriteTargets();
}
public void PushGlobalParams(CommandBuffer cmd)
{
cmd.SetGlobalInt(HDShaderIDs._EnableDBuffer, vsibleDecalCount > 0 ? 1 : 0);
BindBufferAsTextures(cmd);
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DBufferManager.cs.meta


fileFormatVersion: 2
guid: 9335119d0dd7cc748a67cfcc6f1040ab
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

71
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GBufferManager.cs


using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class GBufferManager : MRTBufferManager
{
int m_GBufferCount = 0;
bool m_EnableShadowMask = false;
RenderPipelineMaterial m_DeferredMaterial;
protected RenderTargetIdentifier[] m_RTIDsNoShadowMask;
public GBufferManager(RenderPipelineMaterial deferredMaterial, bool enableBakeShadowMask)
: base(deferredMaterial.GetMaterialGBufferCount() + (enableBakeShadowMask ? 1 : 0))
{
Debug.Assert(m_BufferCount <= 8);
m_DeferredMaterial = deferredMaterial;
m_GBufferCount = deferredMaterial.GetMaterialGBufferCount();
m_EnableShadowMask = enableBakeShadowMask;
m_RTIDsNoShadowMask = new RenderTargetIdentifier[m_GBufferCount];
}
public override void CreateBuffers()
{
RenderTextureFormat[] rtFormat;
bool[] sRGBFlags;
m_DeferredMaterial.GetMaterialGBufferDescription(out rtFormat, out sRGBFlags);
for (int gbufferIndex = 0; gbufferIndex < m_GBufferCount; ++gbufferIndex)
{
m_RTs[gbufferIndex] = RTHandle.Alloc(Vector2.one, colorFormat: rtFormat[gbufferIndex], sRGB: sRGBFlags[gbufferIndex], filterMode: FilterMode.Point);
m_RTIDs[gbufferIndex] = m_RTs[gbufferIndex].nameID;
m_TextureShaderIDs[gbufferIndex] = HDShaderIDs._GBufferTexture[gbufferIndex];
m_RTIDsNoShadowMask[gbufferIndex] = HDShaderIDs._GBufferTexture[gbufferIndex];
}
if (m_EnableShadowMask)
{
m_RTs[m_GBufferCount] = RTHandle.Alloc(Vector2.one, colorFormat: Builtin.GetShadowMaskBufferFormat(), sRGB: Builtin.GetShadowMaskSRGBFlag(), filterMode: FilterMode.Point);
m_RTIDs[m_GBufferCount] = new RenderTargetIdentifier(m_RTs[m_GBufferCount]);
m_TextureShaderIDs[m_GBufferCount] = HDShaderIDs._ShadowMaskTexture;
}
}
public RenderTargetIdentifier[] GetBuffersRTI(bool enableShadowMask)
{
if(!enableShadowMask)
{
// nameID can change from one frame to another depending on the msaa flag so so we need to update this array to be sure it's up to date.
// Moreover, if we don't have shadow masks we only need to bind the first GBuffers
// This is important because in the shader the shadowmask buffer gets optimized out so anything bound after (like the DBuffer HTile) has a different bind point.
for (int i = 0; i < m_GBufferCount; ++i)
{
m_RTIDsNoShadowMask[i] = m_RTs[i].nameID;
}
return m_RTIDsNoShadowMask;
}
else
{
return GetBuffersRTI();
}
}
public int GetBufferCount(bool enableShadowMask)
{
return enableShadowMask ? m_BufferCount : m_GBufferCount;
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GBufferManager.cs.meta


fileFormatVersion: 2
guid: fd31fc09c5f088f43ac4c8e0065ed56c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

59
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CopyDepthBuffer.shader


Shader "Hidden/HDRenderPipeline/CopyDepthBuffer"
{
HLSLINCLUDE
ENDHLSL
SubShader
{
Pass
{
Name "Copy Depth"
Cull Off
ZTest Always
ZWrite On
Blend Off
HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
#pragma fragment Frag
#pragma vertex Vert
// #pragma enable_d3d11_debug_symbols
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "../ShaderVariables.hlsl"
TEXTURE2D(_InputDepthTexture);
struct Attributes
{
uint vertexID : SV_VertexID;
};
struct Varyings
{
float4 positionCS : SV_Position;
};
Varyings Vert(Attributes input)
{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
return output;
}
float Frag(Varyings input) : SV_Depth
{
PositionInputs posInputs = GetPositionInput(input.positionCS, _ScreenSize.zw);
return LOAD_TEXTURE2D(_InputDepthTexture, posInputs.positionSS).x;
}
ENDHLSL
}
}
Fallback Off
}

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CopyDepthBuffer.shader.meta


fileFormatVersion: 2
guid: 42dfcc8fe803ece4096c58630689982f
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存