浏览代码

Merge branch 'master' into LWRP

# Conflicts:
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images.meta
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/GettingStarted1.png.meta
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/GettingStarted2.png.meta
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader1.png.meta
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader10.png.meta
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader11.png.meta
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader12.png.meta
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader13.png.meta
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader14.png.meta
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader15.png.meta
#	ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader16.png.meta
#	ScriptableRe...
/main
Felipe Lira 7 年前
当前提交
65fc1c54
共有 161 个文件被更改,包括 1119 次插入495 次删除
  1. 9
      CHANGELOG.md
  2. 4
      ScriptableRenderPipeline/Core/CHANGELOG.md
  3. 16
      ScriptableRenderPipeline/Core/CoreRP/CoreResources/GPUCopy.compute
  4. 81
      ScriptableRenderPipeline/Core/CoreRP/CoreResources/GPUCopy.cs
  5. 109
      ScriptableRenderPipeline/Core/CoreRP/CoreResources/GPUCopyAsset.cs
  6. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images.meta
  7. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/GettingStarted1.png.meta
  8. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/GettingStarted2.png.meta
  9. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader1.png.meta
  10. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader10.png.meta
  11. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader11.png.meta
  12. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader12.png.meta
  13. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader13.png.meta
  14. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader14.png.meta
  15. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader15.png.meta
  16. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader16.png.meta
  17. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader17.png.meta
  18. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader18.png.meta
  19. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader19.png.meta
  20. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader2.png.meta
  21. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader20.png.meta
  22. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader21.png.meta
  23. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader22.png.meta
  24. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader23.png.meta
  25. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader24.png.meta
  26. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader25.png.meta
  27. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader26.png.meta
  28. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader27.png.meta
  29. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader3.png.meta
  30. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader4.png.meta
  31. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader5.png.meta
  32. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader6.png.meta
  33. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader7.png.meta
  34. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader8.png.meta
  35. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader9.png.meta
  36. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog1.png.meta
  37. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog2.png.meta
  38. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog3.png.meta
  39. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog4.png.meta
  40. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog5.png.meta
  41. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog7.png.meta
  42. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog8.png.meta
  43. 2
      ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyandFog6.png.meta
  44. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugColorPicker.shader
  45. 32
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs
  46. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.hlsl
  47. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplayLatlong.shader
  48. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugViewMaterialGBuffer.shader
  49. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/LightingDebug.cs
  50. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalProjectorComponent.cs
  51. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalSystem.cs
  52. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDAssetFactory.cs
  53. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs
  54. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Drawers.cs
  55. 17
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Handles.cs
  56. 45
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs
  57. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/GlobalLightLoopSettingsUI.cs
  58. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/HDRenderPipelineEditor.cs
  59. 169
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
  60. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.asset
  61. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs
  62. 26
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs
  63. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs
  64. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightEvaluation.hlsl
  65. 94
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  66. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs.hlsl
  67. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.hlsl
  68. 24
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopDef.hlsl
  69. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-bigtile.compute
  70. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-clustered.compute
  71. 19
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild.compute
  72. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/HomogeneousDensityVolume.cs
  73. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/HomogeneousDensityVolume.cs.meta
  74. 324
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLighting.cs
  75. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLighting.cs.hlsl
  76. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DBufferManager.cs
  77. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.hlsl
  78. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalData.hlsl
  79. 48
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalUtilities.hlsl
  80. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/DiffusionProfile/DiffusionProfileSettings.cs
  81. 79
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs
  82. 17
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitData.hlsl
  83. 22
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl
  84. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitData.hlsl
  85. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitDataIndividualLayer.hlsl
  86. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDepthPass.hlsl
  87. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitVelocityPass.hlsl
  88. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs
  89. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/ApplyDistorsion.compute
  90. 128
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/BufferPyramid.cs
  91. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CopyDepthBuffer.shader
  92. 58
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/DepthPyramid.compute
  93. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset
  94. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/RenderPipelineResources.cs
  95. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPass.cs
  96. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPass.cs.hlsl
  97. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISkyRenderer.cs
  98. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSkyRenderer.cs
  99. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyManager.cs
  100. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyRenderer.cs

9
CHANGELOG.md


The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- Planar Reflection Probe support roughness (gaussian convolution of captured probe)
### Changed
- Depth and color pyramid are properly computed and sampled when the camera renders inside a viewport of a RTHandle.
- Forced Planar Probe update modes to (Realtime, Every Update, Mirror Camera)
- Removed Planar Probe mirror plane position and normal fields in inspector, always display mirror plane and normal gizmos
## [0.1.6] - 2018-xx-yy
### Changelog starting

4
ScriptableRenderPipeline/Core/CHANGELOG.md


The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Changed
- Moved root files into folders for easier maintenance
## [0.1.6] - 2018-xx-yy
### Changelog starting

16
ScriptableRenderPipeline/Core/CoreRP/CoreResources/GPUCopy.compute


// Autogenerated file. Do not edit by hand
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
CBUFFER_START (UnityCBuffer)
uint2 _RectOffset;
CBUFFER_END
#pragma kernel KSampleCopy4_1_x
[numthreads(8, 8, 1)]
void KSampleCopy4_1_x(uint2 dispatchThreadId : SV_DispatchThreadID)
#pragma kernel KSampleCopy4_1_x_8 KERNEL_NAME=KSampleCopy4_1_x_8 KERNEL_SIZE=8
#pragma kernel KSampleCopy4_1_x_1 KERNEL_NAME=KSampleCopy4_1_x_1 KERNEL_SIZE=1
[numthreads(KERNEL_SIZE, KERNEL_SIZE, 1)]
void KERNEL_NAME(uint2 dispatchThreadId : SV_DispatchThreadID)
_Result1[dispatchThreadId] = LOAD_TEXTURE2D(_Source4, dispatchThreadId).x;
_Result1[_RectOffset + dispatchThreadId] = LOAD_TEXTURE2D(_Source4, _RectOffset + dispatchThreadId).x;
}

81
ScriptableRenderPipeline/Core/CoreRP/CoreResources/GPUCopy.cs


public class GPUCopy
{
ComputeShader m_Shader;
int k_SampleKernel_xyzw2x;
int k_SampleKernel_xyzw2x_8;
int k_SampleKernel_xyzw2x_1;
k_SampleKernel_xyzw2x = m_Shader.FindKernel("KSampleCopy4_1_x");
k_SampleKernel_xyzw2x_8 = m_Shader.FindKernel("KSampleCopy4_1_x_8");
k_SampleKernel_xyzw2x_1 = m_Shader.FindKernel("KSampleCopy4_1_x_1");
static readonly int _RectOffset = Shader.PropertyToID("_RectOffset");
public void SampleCopyChannel_xyzw2x(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, Vector2 size)
void SampleCopyChannel(
CommandBuffer cmd,
RectInt rect,
int _source,
RenderTargetIdentifier source,
int _target,
RenderTargetIdentifier target,
int kernel8,
int kernel1)
{
RectInt main, topRow, rightCol, topRight;
unsafe
cmd.SetComputeTextureParam(m_Shader, k_SampleKernel_xyzw2x, _Source4, source);
cmd.SetComputeTextureParam(m_Shader, k_SampleKernel_xyzw2x, _Result1, target);
cmd.DispatchCompute(m_Shader, k_SampleKernel_xyzw2x, (int)Mathf.Max((size.x) / 8, 1), (int)Mathf.Max((size.y) / 8, 1), 1);
RectInt* dispatch1Rects = stackalloc RectInt[3];
int dispatch1RectCount = 0;
RectInt dispatch8Rect = RectInt.zero;
if (TileLayoutUtils.TryLayoutByTiles(
rect,
8,
out main,
out topRow,
out rightCol,
out topRight))
{
if (topRow.width > 0 && topRow.height > 0)
{
dispatch1Rects[dispatch1RectCount] = topRow;
++dispatch1RectCount;
}
if (rightCol.width > 0 && rightCol.height > 0)
{
dispatch1Rects[dispatch1RectCount] = rightCol;
++dispatch1RectCount;
}
if (topRight.width > 0 && topRight.height > 0)
{
dispatch1Rects[dispatch1RectCount] = topRight;
++dispatch1RectCount;
}
dispatch8Rect = main;
}
else if (rect.width > 0 && rect.height > 0)
{
dispatch1Rects[dispatch1RectCount] = rect;
++dispatch1RectCount;
}
cmd.SetComputeTextureParam(m_Shader, kernel8, _source, source);
cmd.SetComputeTextureParam(m_Shader, kernel1, _source, source);
cmd.SetComputeTextureParam(m_Shader, kernel8, _target, target);
cmd.SetComputeTextureParam(m_Shader, kernel1, _target, target);
if (dispatch8Rect.width > 0 && dispatch8Rect.height > 0)
{
var r = dispatch8Rect;
cmd.SetComputeIntParams(m_Shader, _RectOffset, (int)r.x, (int)r.y);
cmd.DispatchCompute(m_Shader, kernel8, (int)Mathf.Max(r.width / 8, 1), (int)Mathf.Max(r.height / 8, 1), 1);
}
for (int i = 0, c = dispatch1RectCount; i < c; ++i)
{
var r = dispatch1Rects[i];
cmd.SetComputeIntParams(m_Shader, _RectOffset, (int)r.x, (int)r.y);
cmd.DispatchCompute(m_Shader, kernel1, (int)Mathf.Max(r.width, 1), (int)Mathf.Max(r.height, 1), 1);
}
}
public void SampleCopyChannel_xyzw2x(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, RectInt rect)
{
SampleCopyChannel(cmd, rect, _Source4, source, _Result1, target, k_SampleKernel_xyzw2x_8, k_SampleKernel_xyzw2x_1);
}
}
}

109
ScriptableRenderPipeline/Core/CoreRP/CoreResources/GPUCopyAsset.cs


}
ccp.AppendLine();
ccp.AppendLine("CBUFFER_START (UnityCBuffer)");
ccp.AppendLine(" uint2 _RectOffset;");
ccp.AppendLine("CBUFFER_END");
ccp.AppendLine();
csm.AppendLine(" static readonly int _RectOffset = Shader.PropertyToID(\"_RectOffset\");");
ccp.AppendLine();
ccp.AppendLine();
csm.AppendLine(@" void SampleCopyChannel(
CommandBuffer cmd,
RectInt rect,
int _source,
RenderTargetIdentifier source,
int _target,
RenderTargetIdentifier target,
int kernel8,
int kernel1)
{
RectInt main, topRow, rightCol, topRight;
unsafe
{
RectInt* dispatch1Rects = stackalloc RectInt[3];
int dispatch1RectCount = 0;
RectInt dispatch8Rect = RectInt.zero;
if (TileLayoutUtils.TryLayoutByTiles(
rect,
8,
out main,
out topRow,
out rightCol,
out topRight))
{
if (topRow.width > 0 && topRow.height > 0)
{
dispatch1Rects[dispatch1RectCount] = topRow;
++dispatch1RectCount;
}
if (rightCol.width > 0 && rightCol.height > 0)
{
dispatch1Rects[dispatch1RectCount] = rightCol;
++dispatch1RectCount;
}
if (topRight.width > 0 && topRight.height > 0)
{
dispatch1Rects[dispatch1RectCount] = topRight;
++dispatch1RectCount;
}
dispatch8Rect = main;
}
else if (rect.width > 0 && rect.height > 0)
{
dispatch1Rects[dispatch1RectCount] = rect;
++dispatch1RectCount;
}
cmd.SetComputeTextureParam(m_Shader, kernel8, _source, source);
cmd.SetComputeTextureParam(m_Shader, kernel1, _source, source);
cmd.SetComputeTextureParam(m_Shader, kernel8, _target, target);
cmd.SetComputeTextureParam(m_Shader, kernel1, _target, target);
if (dispatch8Rect.width > 0 && dispatch8Rect.height > 0)
{
var r = dispatch8Rect;
cmd.SetComputeIntParams(m_Shader, _RectOffset, (int)r.x, (int)r.y);
cmd.DispatchCompute(m_Shader, kernel8, (int)Mathf.Max(r.width / 8, 1), (int)Mathf.Max(r.height / 8, 1), 1);
}
for (int i = 0, c = dispatch1RectCount; i < c; ++i)
{
var r = dispatch1Rects[i];
cmd.SetComputeIntParams(m_Shader, _RectOffset, (int)r.x, (int)r.y);
cmd.DispatchCompute(m_Shader, kernel1, (int)Mathf.Max(r.width, 1), (int)Mathf.Max(r.height, 1), 1);
}
}
}");
csc.AppendLine(" public GPUCopy(ComputeShader shader)");
csc.AppendLine(" {");

var o = operations[i];
// Compute kernel
var kernelName = string.Format("KSampleCopy{0}_{1}_{2}", o.sourceChannel.ToString(), o.targetChannel.ToString(), o.subscript);
cck.AppendLine(string.Format("#pragma kernel {0}", kernelName));
cck.AppendLine(string.Format(@"[numthreads({0}, {0}, 1)]",
k_KernelSize.ToString(), k_KernelSize.ToString()));
cck.AppendLine(string.Format(@"void {0}(uint2 dispatchThreadId : SV_DispatchThreadID)", kernelName));
var kernelName8 = string.Format("KSampleCopy{0}_{1}_{2}_8", o.sourceChannel.ToString(), o.targetChannel.ToString(), o.subscript);
var kernelName1 = string.Format("KSampleCopy{0}_{1}_{2}_1", o.sourceChannel.ToString(), o.targetChannel.ToString(), o.subscript);
cck.AppendLine(string.Format("#pragma kernel {0} KERNEL_NAME={0} KERNEL_SIZE=8", kernelName8));
cck.AppendLine(string.Format("#pragma kernel {0} KERNEL_NAME={0} KERNEL_SIZE=1", kernelName1));
cck.AppendLine(@"[numthreads(KERNEL_SIZE, KERNEL_SIZE, 1)]");
cck.AppendLine(@"void KERNEL_NAME(uint2 dispatchThreadId : SV_DispatchThreadID)");
cck.AppendLine(string.Format(" _Result{0}[dispatchThreadId] = LOAD_TEXTURE2D(_Source{1}, dispatchThreadId).{2};",
cck.AppendLine(string.Format(" _Result{0}[_RectOffset + dispatchThreadId] = LOAD_TEXTURE2D(_Source{1}, _RectOffset + dispatchThreadId).{2};",
o.targetChannel.ToString(), o.sourceChannel.ToString(), o.subscript));
cck.AppendLine("}");
cck.AppendLine();

var kernelIndexName = string.Format("k_SampleKernel_{0}2{1}", channelName, o.subscript);
csp.AppendLine(string.Format(" int {0};", kernelIndexName));
var kernelIndexName8 = string.Format("k_SampleKernel_{0}2{1}_8", channelName, o.subscript);
var kernelIndexName1 = string.Format("k_SampleKernel_{0}2{1}_1", channelName, o.subscript);
csp.AppendLine(string.Format(" int {0};", kernelIndexName8));
csp.AppendLine(string.Format(" int {0};", kernelIndexName1));
csc.AppendLine(string.Format(" {0} = m_Shader.FindKernel(\"{1}\");", kernelIndexName, kernelName));
csc.AppendLine(string.Format(" {0} = m_Shader.FindKernel(\"{1}\");", kernelIndexName8, kernelName8));
csc.AppendLine(string.Format(" {0} = m_Shader.FindKernel(\"{1}\");", kernelIndexName1, kernelName1));
csm.AppendLine(string.Format(@" public void SampleCopyChannel_{0}2{1}(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, Vector2 size)", channelName, o.subscript));
csm.AppendLine(" {");
csm.AppendLine(string.Format(" cmd.SetComputeTextureParam(m_Shader, {0}, _Source{1}, source);", kernelIndexName, o.sourceChannel.ToString()));
csm.AppendLine(string.Format(" cmd.SetComputeTextureParam(m_Shader, {0}, _Result{1}, target);", kernelIndexName, o.targetChannel.ToString()));
csm.AppendLine(string.Format(" cmd.DispatchCompute(m_Shader, {0}, (int)Mathf.Max((size.x) / {1}, 1), (int)Mathf.Max((size.y) / {1}, 1), 1);", kernelIndexName, k_KernelSize.ToString()));
csm.AppendLine(" }");
csm.AppendLine(string.Format(@" public void SampleCopyChannel_{0}2{1}(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, RectInt rect)", channelName, o.subscript));
csm.AppendLine (" {");
csm.AppendLine(string.Format(" SampleCopyChannel(cmd, rect, _Source{0}, source, _Result{1}, target, {2}, {3});", o.sourceChannel.ToString(), o.targetChannel.ToString(), kernelIndexName8, kernelIndexName1));
csm.AppendLine (" }");
}
csc.AppendLine(" }");

cc.AppendLine("#pragma only_renderers d3d11 ps4 xboxone vulkan metal");
cc.AppendLine(@"#include ""../ShaderLibrary/Common.hlsl""");
cc.AppendLine(ccp.ToString()); // Properties
cc.AppendLine(cck.ToString()); // Kernels

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images.meta


fileFormatVersion: 2
guid: 7cb552a4872af4e66afe37ce1270e4b1
guid: 6cd0b4ce44113ec4aad28d5eaecc5b84
folderAsset: yes
DefaultImporter:
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/GettingStarted1.png.meta


fileFormatVersion: 2
guid: 9ee982c2703c947418ba6e8e1c6caace
guid: ba8953ced78ea88408ecb61d6af22076
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/GettingStarted2.png.meta


fileFormatVersion: 2
guid: 27748cf39dacc434e8629923ecae768f
guid: 9db6836f814f6b24387d769d3b1d1cd1
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader1.png.meta


fileFormatVersion: 2
guid: 7bf846dfce0904c2fbae62c1ea6487da
guid: 1ee26fd1cbb5c2544850ece6d12c1198
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader10.png.meta


fileFormatVersion: 2
guid: c4f4ea34bfbae4333b4d9b5429585774
guid: 70e752fa1a7b0fa4cb2c858051cbc440
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader11.png.meta


fileFormatVersion: 2
guid: 249eebc72b7f04c2394ed1f71932ba79
guid: 662b2f538cff6be41b851d2356022750
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader12.png.meta


fileFormatVersion: 2
guid: 8c4a66236b97c4b45a431e3cc4b82edd
guid: 1af0a84166662744d860125fe1b17e60
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader13.png.meta


fileFormatVersion: 2
guid: ead83b83582034676b7952451468625b
guid: 864d5eff3136f3f4380a91e8f6f8b226
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader14.png.meta


fileFormatVersion: 2
guid: 22351c6fbd0804178801512ce250ad3e
guid: 1a84befbf2fd07c4e9e810b300038130
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader15.png.meta


fileFormatVersion: 2
guid: 24f7c5a5b54fb48f896d87f97ed57e3f
guid: 638879a9006811c4fb9f91db1c6fed5f
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader16.png.meta


fileFormatVersion: 2
guid: 125d632f384254a73af886f72180f4d3
guid: c2ad2158a102d2b43a5ccb35618192ca
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader17.png.meta


fileFormatVersion: 2
guid: d190f2828523942ee8e5b5d420d0738a
guid: 4dcf49e9d4338c8478ae4317da05bf49
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader18.png.meta


fileFormatVersion: 2
guid: 033e10b26eb8b41a5a50e7345cc0a311
guid: 35dc684f56a805646b4f3fab51fa145b
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader19.png.meta


fileFormatVersion: 2
guid: 695cf09ddf5ef4e39a703680fa89d055
guid: 791de754d75c216459157dfc2e8864f8
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader2.png.meta


fileFormatVersion: 2
guid: 29a68d02912ac428f872f984819a838d
guid: 6c429b89a78ce204d9305da6a45e46dd
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader20.png.meta


fileFormatVersion: 2
guid: 3a387904cabc54e2ea48fc60ee7e6606
guid: 96fe5aa80960ee245a2bd24c53138b52
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader21.png.meta


fileFormatVersion: 2
guid: b28f0ba6256774dfa9c104780e169eec
guid: cb800812366024a488f97b9e60815d7e
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader22.png.meta


fileFormatVersion: 2
guid: 13e5e4695e0d24747b958f7285fac27d
guid: 950eb73387de6f246bca03f73ea8f670
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader23.png.meta


fileFormatVersion: 2
guid: e5ac2ab1ac9e74c9fba0af842ba29771
guid: 14d462ea7048ffa4f81add8f4a7b6e39
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader24.png.meta


fileFormatVersion: 2
guid: 1c368fc06d04b4f729a8983d89753e70
guid: 90d2454a88afb994da4790a77bfcf786
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader25.png.meta


fileFormatVersion: 2
guid: 3c7bd8e83ccdb4db7ab78791aa618db1
guid: d5118aaeb60496047ac874e421a59617
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader26.png.meta


fileFormatVersion: 2
guid: 225733197344f4f2fa9aff01085aea88
guid: ddd31f9c54d4cfb4fa21d5cda651f8f0
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader27.png.meta


fileFormatVersion: 2
guid: a84de95a1864641889a576434646136a
guid: 99468103b5c3bc5448d40a420e9c6955
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader3.png.meta


fileFormatVersion: 2
guid: e28a1904fc6da49c0ad7de6026db7a6d
guid: 1db4a2f29a95c004bae32a9e9964f698
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader4.png.meta


fileFormatVersion: 2
guid: 08387424bc772473a9d9e62d01db3d8b
guid: 90bc1c159124817439f33867eda0a849
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader5.png.meta


fileFormatVersion: 2
guid: a3bacf6a139244d44b78d8141ac72b42
guid: 7e8aba01470ab6543a0b5e7cf33ad275
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader6.png.meta


fileFormatVersion: 2
guid: 1a1112a146ef046e18e062da35146193
guid: 6be725d9f4edb624b9a5019e70ae368c
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader7.png.meta


fileFormatVersion: 2
guid: 451687993ffd148579efca7fc9e10dda
guid: 93630eabfd3efb74f966ad1a89e0e546
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader8.png.meta


fileFormatVersion: 2
guid: 2d0fe97117e6d4ff08c7619ea8b416ef
guid: f3ac1f8fca4d46a43810a0aaa7ef755d
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/LitShader9.png.meta


fileFormatVersion: 2
guid: f006ed1792f6c4cd89524cbef6079da2
guid: c310a737b32a33c409fecf09b45689c0
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog1.png.meta


fileFormatVersion: 2
guid: 5232f4fba96944e6490ffae9763a99f2
guid: 0745a22fb0d2b0f46b608d64bda30de7
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog2.png.meta


fileFormatVersion: 2
guid: 050c3e5c52d784a8cb70a355c1ed1bc6
guid: 30bd8cfc8c1002942bde8a6710950d9a
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog3.png.meta


fileFormatVersion: 2
guid: 327d9a1e581094e628cd5d74ab9c9b1a
guid: 63fcd7b71364e1d45a60bca81549e0ec
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog4.png.meta


fileFormatVersion: 2
guid: 2aa3bd16121834293ac415df3fcd9e34
guid: ecb95dcd618ddc64297d82f20e539e3a
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog5.png.meta


fileFormatVersion: 2
guid: 4c99d63158b044afaad82558992e98df
guid: 10c9f3e027eaca0408c61dba877e2bcd
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog7.png.meta


fileFormatVersion: 2
guid: a262ebea9f80b4ed69e668bf142e67e0
guid: 3a44ef404734a024d96eacae04710493
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyAndFog8.png.meta


fileFormatVersion: 2
guid: a50fd1183967641a2921a86a941c420b
guid: f0d4f6a2f40fa0b428d0f29f297250fe
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

2
ScriptableRenderPipeline/HDRenderPipeline/Documentation/Images/SkyandFog6.png.meta


fileFormatVersion: 2
guid: 6d0e82dd59e504af68f1e1dc85e91dae
guid: b217921bf86644342b2b36a699e29adf
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

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


}
float4 mouseResult = SAMPLE_TEXTURE2D(_DebugColorPickerTexture, sampler_DebugColorPickerTexture, mousePixelCoord.zw);
// Reverse debug exposure in order to display the real values.
// _DebugExposure will be set to zero if the debug view does not need it so we don't need to make a special case here. It's handled in only one place in C#
mouseResult = mouseResult / exp2(_DebugExposure);
float4 finalResult = DisplayPixelInformationAtMousePosition(input, result, mouseResult, mousePixelCoord);
return finalResult;

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


public bool IsDebugDisplayEnabled()
{
return materialDebugSettings.IsDebugDisplayEnabled() || lightingDebugSettings.IsDebugDisplayEnabled() || mipMapDebugSettings.IsDebugDisplayEnabled();
return materialDebugSettings.IsDebugDisplayEnabled() || lightingDebugSettings.IsDebugDisplayEnabled() || mipMapDebugSettings.IsDebugDisplayEnabled() || IsDebugFullScreenEnabled();
}
public bool IsDebugMaterialDisplayEnabled()

public bool IsDebugFullScreenEnabled()
{
return fullScreenDebugMode != FullScreenDebugMode.None;
}
public bool IsDebugMipMapDisplayEnabled()
{
return mipMapDebugSettings.IsDebugDisplayEnabled();

// Texture.SetStreamingTextureMaterialDebugProperties();
}
public bool DebugNeedsExposure()
{
DebugLightingMode debugLighting = lightingDebugSettings.debugLightingMode;
DebugViewGbuffer debugGBuffer = (DebugViewGbuffer)materialDebugSettings.debugViewGBuffer;
return (debugLighting == DebugLightingMode.DiffuseLighting || debugLighting == DebugLightingMode.SpecularLighting) ||
(debugGBuffer == DebugViewGbuffer.BakeDiffuseLightingWithAlbedoPlusEmissive) ||
(fullScreenDebugMode == FullScreenDebugMode.PreRefractionColorPyramid || fullScreenDebugMode == FullScreenDebugMode.FinalColorPyramid);
}
void RegisterDisplayStatsDebug()
{
m_DebugDisplayStatsItems = new DebugUI.Widget[]

{
case FullScreenDebugMode.FinalColorPyramid:
case FullScreenDebugMode.PreRefractionColorPyramid:
id = HDShaderIDs._GaussianPyramidColorMipSize;
id = HDShaderIDs._ColorPyramidScale;
id = HDShaderIDs._DepthPyramidMipSize;
id = HDShaderIDs._DepthPyramidScale;
break;
}
var size = Shader.GetGlobalVector(id);

{
case FullScreenDebugMode.FinalColorPyramid:
case FullScreenDebugMode.PreRefractionColorPyramid:
id = HDShaderIDs._GaussianPyramidColorMipSize;
id = HDShaderIDs._ColorPyramidScale;
id = HDShaderIDs._DepthPyramidMipSize;
id = HDShaderIDs._DepthPyramidScale;
break;
}
var size = Shader.GetGlobalVector(id);

{
case FullScreenDebugMode.FinalColorPyramid:
case FullScreenDebugMode.PreRefractionColorPyramid:
id = HDShaderIDs._GaussianPyramidColorMipSize;
id = HDShaderIDs._ColorPyramidScale;
id = HDShaderIDs._DepthPyramidMipSize;
id = HDShaderIDs._DepthPyramidScale;
break;
}
var size = Shader.GetGlobalVector(id);

}
});
}
if (DebugNeedsExposure())
list.Add(new DebugUI.FloatField { displayName = "Debug Exposure", getter = () => lightingDebugSettings.debugExposure, setter = value => lightingDebugSettings.debugExposure = value });
m_DebugLightingItems = list.ToArray();
var panel = DebugManager.instance.GetPanel(k_PanelLighting, true);

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.hlsl


float4 _DebugLightingSpecularColor; // x == bool override, yzw = specular color
float4 _MousePixelCoord; // xy unorm, zw norm
float _DebugEnvironmentProxyDepthScale;
float _DebugExposure;
CBUFFER_END
TEXTURE2D(_DebugFont); // Debug font to write string in shader

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplayLatlong.shader


SAMPLER(sampler_InputCubemap);
float _Mipmap;
float _RequireToFlipInputTexture;
float _DebugExposure;
struct Attributes
{

width = height = depth = mipCount = 0;
_InputCubemap.GetDimensions(width, height, depth, mipCount);
mipCount = clamp(mipCount, 0, UNITY_SPECCUBE_LOD_STEPS);
return SAMPLE_TEXTURECUBE_LOD(_InputCubemap, sampler_InputCubemap, LatlongToDirectionCoordinate(input.texcoord.xy), _Mipmap * mipCount);
return SAMPLE_TEXTURECUBE_LOD(_InputCubemap, sampler_InputCubemap, LatlongToDirectionCoordinate(input.texcoord.xy), _Mipmap * mipCount) * exp2(_DebugExposure);
}
ENDHLSL

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugViewMaterialGBuffer.shader


// Caution: This value is not the same than the builtin data bakeDiffuseLighting. It also include emissive and multiply by the albedo
else if (_DebugViewMaterial == DEBUGVIEWGBUFFER_BAKE_DIFFUSE_LIGHTING_WITH_ALBEDO_PLUS_EMISSIVE)
{
// TODO: require a remap
// TODO: we should not gamma correct, but easier to debug for now without correct high range value
result = bakeLightingData.bakeDiffuseLighting; needLinearToSRGB = true;
result = bakeLightingData.bakeDiffuseLighting;;
result *= exp2(_DebugExposure);
needLinearToSRGB = true;
}
#ifdef SHADOWS_SHADOWMASK
else if (_DebugViewMaterial == DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK0)

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


public float environmentProxyDepthScale = 20;
public float debugExposure = 0.0f;
public LightLoop.TileClusterDebug tileClusterDebug = LightLoop.TileClusterDebug.None;
public LightLoop.TileClusterCategoryDebug tileClusterDebugByCategory = LightLoop.TileClusterCategoryDebug.Punctual;
}

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalProjectorComponent.cs


}
}
public void Update()
{
if (m_Handle != null)
{
if (transform.hasChanged == true)
{
DecalSystem.instance.UpdateCachedData(transform, m_DrawDistance, m_FadeScale, m_Handle);
transform.hasChanged = false;
}
}
}
private void DrawGizmo(bool selected)
{
var col = new Color(0.0f, 0.7f, 1f, 1.0f);

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalSystem.cs


{
public class DecalSystem
{
public const int kInvalidIndex = -1;
public const int kInvalidIndex = -1;
public const int kDecalAtlasSize = 128;
public class DecalHandle
{

if (m_DecalAtlas == null)
{
m_DecalAtlas = new TextureCache2D("DecalAtlas");
m_DecalAtlas.AllocTextureArray(2048, 128, 128, TextureFormat.RGBA32, true);
m_DecalAtlas.AllocTextureArray(2048, kDecalAtlasSize, kDecalAtlasSize, TextureFormat.ARGB32, true);
}
return m_DecalAtlas;
}

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


newAsset.colorPyramidCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/ColorPyramid.compute");
newAsset.depthPyramidCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/DepthPyramid.compute");
newAsset.copyChannelCS = Load<ComputeShader>(CorePath + "CoreResources/GPUCopy.compute");
newAsset.texturePaddingCS = Load<ComputeShader>(CorePath + "CoreResources/TexturePadding.compute");
newAsset.applyDistortionCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/ApplyDistorsion.compute");
newAsset.clearDispatchIndirectShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/LightLoop/cleardispatchindirect.compute");

newAsset.deferredComputeShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/LightLoop/Deferred.compute");
newAsset.deferredDirectionalShadowComputeShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/DeferredDirectionalShadow.compute");
newAsset.volumetricLightingCS = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/Volumetrics/Resources/VolumetricLighting.compute");
newAsset.volumeVoxelizationCS = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/Volumetrics/VolumeVoxelization.compute");
newAsset.volumetricLightingCS = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/Volumetrics/VolumetricLighting.compute");
newAsset.subsurfaceScatteringCS = Load<ComputeShader>(HDRenderPipelinePath + "Material/SubsurfaceScattering/SubsurfaceScattering.compute");
newAsset.subsurfaceScattering = Load<Shader>(HDRenderPipelinePath + "Material/SubsurfaceScattering/SubsurfaceScattering.shader");

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs


// Caution: this function must match the one in HDAdditionalLightData.ConvertPhysicalLightIntensityToLightIntensity - any change need to be replicated
void UpdateLightIntensity()
{
// Clamp negative values.
m_AdditionalLightData.directionalIntensity.floatValue = Mathf.Max(0, m_AdditionalLightData.directionalIntensity.floatValue);
m_AdditionalLightData.punctualIntensity.floatValue = Mathf.Max(0, m_AdditionalLightData.punctualIntensity.floatValue);
m_AdditionalLightData.areaIntensity.floatValue = Mathf.Max(0, m_AdditionalLightData.areaIntensity.floatValue);
switch (m_LightShape)
{
case LightShape.Directional:

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Drawers.cs


static void Drawer_SectionCaptureMirror(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)
{
EditorGUILayout.PropertyField(d.captureMirrorPlaneLocalPosition, _.GetContent("Plane Position"));
EditorGUILayout.PropertyField(d.captureMirrorPlaneLocalNormal, _.GetContent("Plane Normal"));
// EditorGUILayout.PropertyField(d.captureMirrorPlaneLocalPosition, _.GetContent("Plane Position"));
// EditorGUILayout.PropertyField(d.captureMirrorPlaneLocalNormal, _.GetContent("Plane Normal"));
}
static void Drawer_SectionCaptureSettings(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)

static void Drawer_SectionProbeModeRealtimeSettings(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)
{
GUI.enabled = false;
d.refreshMode.enumValueIndex = (int)ReflectionProbeRefreshMode.EveryFrame;
d.capturePositionMode.enumValueIndex = (int)PlanarReflectionProbe.CapturePositionMode.MirrorCamera;
GUI.enabled = true;
}
static void Drawer_SectionInfluenceSettings(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)

static void Drawer_FieldCaptureType(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)
{
GUI.enabled = false;
d.mode.enumValueIndex = (int)ReflectionProbeMode.Realtime;
GUI.enabled = true;
}
static void Drawer_FieldProxyVolumeReference(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)

17
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Handles.cs


}
}
if (d.useMirrorPlane)
{
var m = Handles.matrix;
Handles.matrix = mat;
Handles.color = k_GizmoMirrorPlaneCamera;
Handles.ArrowHandleCap(
0,
d.captureMirrorPlaneLocalPosition,
Quaternion.LookRotation(d.captureMirrorPlaneLocalNormal),
HandleUtility.GetHandleSize(d.captureMirrorPlaneLocalPosition),
Event.current.type
);
Handles.matrix = m;
}
if (d.proxyVolumeReference != null)
ReflectionProxyVolumeComponentUI.DrawHandles_EditNone(s.reflectionProxyVolume, d.proxyVolumeReference);
}

var showFrustrum = s.showCaptureHandles
|| EditMode.editMode == EditCenter;
var showCaptureMirror = (s.showCaptureHandles && d.useMirrorPlane)
var showCaptureMirror = d.useMirrorPlane
|| EditMode.editMode == EditMirrorPosition
|| EditMode.editMode == EditMirrorRotation;

45
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs


bool mainLayerInfluenceEnable = useMainLayerInfluence.floatValue > 0.0f;
if(mainLayerInfluenceEnable) // This is the only case where we need this sub category.
// Main layer does not have any options but height base blend.
if (layerIndex > 0)
// Main layer does not have any options but height base blend.
if (layerIndex > 0)
{
int paramIndex = layerIndex - 1;
int paramIndex = layerIndex - 1;
m_MaterialEditor.ShaderProperty(opacityAsDensity[layerIndex], styles.opacityAsDensityText);
m_MaterialEditor.ShaderProperty(opacityAsDensity[layerIndex], styles.opacityAsDensityText);
if (mainLayerInfluenceEnable)
{
m_MaterialEditor.ShaderProperty(inheritBaseColor[paramIndex], styles.inheritBaseColorText);
m_MaterialEditor.ShaderProperty(inheritBaseNormal[paramIndex], styles.inheritBaseNormalText);
// Main height influence is only available if the shader use the heightmap for displacement (per vertex or per level)
// We always display it as it can be tricky to know when per pixel displacement is enabled or not
m_MaterialEditor.ShaderProperty(inheritBaseHeight[paramIndex], styles.inheritBaseHeightText);
}
}
else
if (mainLayerInfluenceEnable)
if (!useMainLayerInfluence.hasMixedValue && useMainLayerInfluence.floatValue != 0.0f)
{
m_MaterialEditor.TexturePropertySingleLine(styles.layerInfluenceMapMaskText, layerInfluenceMaskMap);
}
m_MaterialEditor.ShaderProperty(inheritBaseColor[paramIndex], styles.inheritBaseColorText);
m_MaterialEditor.ShaderProperty(inheritBaseNormal[paramIndex], styles.inheritBaseNormalText);
// Main height influence is only available if the shader use the heightmap for displacement (per vertex or per level)
// We always display it as it can be tricky to know when per pixel displacement is enabled or not
m_MaterialEditor.ShaderProperty(inheritBaseHeight[paramIndex], styles.inheritBaseHeightText);
EditorGUILayout.Space();
else
{
if (!useMainLayerInfluence.hasMixedValue && useMainLayerInfluence.floatValue != 0.0f)
{
EditorGUILayout.LabelField(styles.layeringOptionText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.TexturePropertySingleLine(styles.layerInfluenceMapMaskText, layerInfluenceMaskMap);
EditorGUI.indentLevel--;
}
}
EditorGUILayout.Space();
DoLayerGUI(material, layerIndex, true, m_UseHeightBasedBlend);

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/GlobalLightLoopSettingsUI.cs


++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(d.skyReflectionSize, _.GetContent("Sky Reflection Size"));
EditorGUILayout.PropertyField(d.skyLightingOverrideLayerMask, _.GetContent("Sky Lighting Override Mask|This layer mask will define in which layers the sky system will look for sky settings volumes for lighting override"));
if(d.skyLightingOverrideLayerMask.intValue == -1)
{
EditorGUILayout.HelpBox("Be careful, Sky Lighting Override Mask is set to Everything. This is most likely a mistake as it serves no purpose.", MessageType.Warning);
}
--EditorGUI.indentLevel;
}
}

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/HDRenderPipelineEditor.cs


public override void OnInspectorGUI()
{
var hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (hdPipeline == null)
return;
var s = m_HDRenderPipelineUI;
var d = m_SerializedHDRenderPipeline;
var o = this;

169
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs


readonly SkyManager m_SkyManager = new SkyManager();
readonly LightLoop m_LightLoop = new LightLoop();
readonly ShadowSettings m_ShadowSettings = new ShadowSettings();
readonly VolumetricLightingModule m_VolumetricLightingModule = new VolumetricLightingModule();
readonly VolumetricLightingSystem m_VolumetricLightingSystem = new VolumetricLightingSystem();
// Debugging
MaterialPropertyBlock m_SharedPropertyBlock = new MaterialPropertyBlock();

RTHandle m_DebugColorPickerBuffer;
RTHandle m_DebugFullScreenTempBuffer;
bool m_FullScreenDebugPushed;
bool m_ValidAPI; // False by default mean we render normally, true mean we don't render anything
public Material GetBlitMaterial() { return m_Blit; }

{
SetRenderingFeatures();
m_ValidAPI = true;
if (!SetRenderingFeatures())
{
m_ValidAPI = false;
return ;
}
m_BufferPyramid = new BufferPyramid(
var bufferPyramidProcessor = new BufferPyramidProcessor(
m_GPUCopy);
m_GPUCopy,
new TexturePadding(asset.renderPipelineResources.texturePaddingCS)
);
m_BufferPyramid = new BufferPyramid(bufferPyramidProcessor);
EncodeBC6H.DefaultInstance = EncodeBC6H.DefaultInstance ?? new EncodeBC6H(asset.renderPipelineResources.encodeBC6HCS);

m_MaterialList.ForEach(material => material.Build(asset));
m_IBLFilterGGX = new IBLFilterGGX(asset.renderPipelineResources);
m_IBLFilterGGX = new IBLFilterGGX(asset.renderPipelineResources, bufferPyramidProcessor);
m_VolumetricLightingModule.Build(asset);
m_VolumetricLightingSystem.Build(asset);
m_DebugDisplaySettings.RegisterDebug();
#if UNITY_EDITOR

}
void SetRenderingFeatures()
bool SetRenderingFeatures()
{
// Set subshader pipeline tag
Shader.globalRenderPipeline = "HDRenderPipeline";

Debug.LogError("High Definition Render Pipeline doesn't support Gamma mode, change to Linear mode");
}
#endif
if (!IsSupportedPlatform())
{
Debug.LogError("Platform " + SystemInfo.operatingSystem + " with device " + SystemInfo.graphicsDeviceType.ToString() + " is not supported, no rendering will occur");
#if UNITY_EDITOR
foreach (UnityEditor.SceneView sv in Resources.FindObjectsOfTypeAll(typeof(UnityEditor.SceneView)))
sv.ShowNotification(new GUIContent("Platform " + SystemInfo.operatingSystem + " with device " + SystemInfo.graphicsDeviceType.ToString() + " is not supported, no rendering will occur"));
#endif
return false;
}
return true;
}
bool IsSupportedPlatform()
{
if (!SystemInfo.supportsComputeShaders)
return false;
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11 ||
SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12 ||
SystemInfo.graphicsDeviceType == GraphicsDeviceType.PlayStation4 ||
SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne ||
SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12 ||
SystemInfo.graphicsDeviceType == GraphicsDeviceType.Vulkan)
{
return true;
}
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal)
{
string os = SystemInfo.operatingSystem;
// Metal support depends on OS version:
// macOS 10.11.x doesn't have tessellation / earlydepthstencil support, early driver versions were buggy in general
// macOS 10.12.x should usually work with AMD, but issues with Intel/Nvidia GPUs. Regardless of the GPU, there are issues with MTLCompilerService crashing with some shaders
// macOS 10.13.x is expected to work, and if it's a driver/shader compiler issue, there's still hope on getting it fixed to next shipping OS patch release
//
// Has worked experimentally with iOS in the past, but it's not currently supported
//
if (os.StartsWith("Mac"))
{
// TODO: Expose in C# version number, for now assume "Mac OS X 10.10.4" format with version 10 at least
int startIndex = os.LastIndexOf(" ");
var parts = os.Substring(startIndex + 1).Split('.');
int a = Convert.ToInt32(parts[0]);
int b = Convert.ToInt32(parts[1]);
// In case in the future there's a need to disable specific patch releases
// int c = Convert.ToInt32(parts[2]);
if (a >= 10 && b >= 13)
return true;
}
}
return false;
}
void UnsetRenderingFeatures()

public override void Dispose()
{
UnsetRenderingFeatures();
if (!m_ValidAPI)
return ;
base.Dispose();
m_DebugDisplaySettings.UnregisterDebug();

m_SSSBufferManager.Cleanup();
m_SkyManager.Cleanup();
m_VolumetricLightingModule.Cleanup();
m_VolumetricLightingSystem.Cleanup();
UnsetRenderingFeatures();
#if UNITY_EDITOR
SceneViewDrawMode.ResetDrawMode();
FrameSettings.UnRegisterDebug("Scene View");

}
// Warning: (resolutionChanged == false) if you open a new Editor tab of the same size!
m_VolumetricLightingModule.ResizeVBuffer(hdCamera, hdCamera.actualWidth, hdCamera.actualHeight);
m_VolumetricLightingSystem.ResizeVBuffer(hdCamera, hdCamera.actualWidth, hdCamera.actualHeight);
// update recorded window resolution
m_CurrentWidth = hdCamera.actualWidth;

m_DbufferManager.PushGlobalParams(cmd, m_FrameSettings);
m_VolumetricLightingModule.PushGlobalParams(hdCamera, cmd);
m_VolumetricLightingSystem.PushGlobalParams(hdCamera, cmd);
}
}

ReflectionProbeCullResults m_ReflectionProbeCullResults;
public override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
{
if (!m_ValidAPI)
return;
base.Render(renderContext, cameras);
RenderPipeline.BeginFrameRendering(cameras);

}
else
{
// Temporary hack. For scene view, by default, we don't want to have the lighting override layers in the current sky.
// Temporary hack:
// For scene view, by default, we use the "main" camera volume layer mask if it exists
// Otherwise we just remove the lighting override layers in the current sky to avoid conflicts
layerMask = (-1 & ~m_Asset.renderPipelineSettings.lightLoopSettings.skyLightingOverrideLayerMask);
var mainCamera = Camera.main;
bool needFallback = true;
if (mainCamera != null)
{
var mainCamAdditionalData = mainCamera.GetComponent<HDAdditionalCameraData>();
if (mainCamAdditionalData != null)
{
layerMask = mainCamAdditionalData.volumeLayerMask;
needFallback = false;
}
}
if (needFallback)
{
// If the override layer is "Everything", we fall-back to "Everything" for the current layer mask to avoid issues by having no current layer
// In practice we should never have "Everything" as an override mask as it does not make sense (a warning is issued in the UI)
if (m_Asset.renderPipelineSettings.lightLoopSettings.skyLightingOverrideLayerMask == -1)
layerMask = -1;
else
layerMask = (-1 & ~m_Asset.renderPipelineSettings.lightLoopSettings.skyLightingOverrideLayerMask);
}
}
}
VolumeManager.instance.Update(camera.transform, layerMask);

var postProcessLayer = camera.GetComponent<PostProcessLayer>();
// Disable post process if we enable debug mode or if the post process layer is disabled
if (m_CurrentDebugDisplaySettings.fullScreenDebugMode != FullScreenDebugMode.None || m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() || !CoreUtils.IsPostProcessingActive(postProcessLayer))
if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() || !CoreUtils.IsPostProcessingActive(postProcessLayer))
{
m_FrameSettings.enablePostprocess = false;
}

continue;
}
// Frustum cull density volumes on the CPU. Can be performed as soon as the camera is set up.
DensityVolumeList densityVolumes = m_VolumetricLightingSystem.PrepareVisibleDensityVolumeList(hdCamera, cmd);
// Note: Legacy Unity behave like this for ShadowMask
// When you select ShadowMask in Lighting panel it recompile shaders on the fly with the SHADOW_MASK keyword.
// However there is no C# function that we can query to know what mode have been select in Lighting Panel and it will be wrong anyway. Lighting Panel setup what will be the next bake mode. But until light is bake, it is wrong.

bool enableBakeShadowMask;
using (new ProfilingSample(cmd, "TP_PrepareLightsForGPU", CustomSamplerId.TPPrepareLightsForGPU.GetSampler()))
{
enableBakeShadowMask = m_LightLoop.PrepareLightsForGPU(cmd, m_ShadowSettings, m_CullResults, m_ReflectionProbeCullResults, camera) && m_FrameSettings.enableShadowMask;
enableBakeShadowMask = m_LightLoop.PrepareLightsForGPU(cmd, camera, m_ShadowSettings, m_CullResults, m_ReflectionProbeCullResults, densityVolumes) && m_FrameSettings.enableShadowMask;
}
ConfigureForShadowMask(enableBakeShadowMask, cmd);

renderContext.ExecuteCommandBuffer(cmd);
cmd.Clear();
buildGPULightListsCompleteFence = m_LightLoop.BuildGPULightListsAsyncBegin(hdCamera, renderContext, m_CameraDepthStencilBuffer, m_CameraStencilBufferCopy, startFence, m_SkyManager.IsSkyValid());
buildGPULightListsCompleteFence = m_LightLoop.BuildGPULightListsAsyncBegin(hdCamera, renderContext, m_CameraDepthStencilBuffer, m_CameraStencilBufferCopy, startFence, m_SkyManager.IsLightingSkyValid());
}
using (new ProfilingSample(cmd, "Render shadows", CustomSamplerId.RenderShadows.GetSampler()))

{
using (new ProfilingSample(cmd, "Build Light list", CustomSamplerId.BuildLightList.GetSampler()))
{
m_LightLoop.BuildGPULightLists(hdCamera, cmd, m_CameraDepthStencilBuffer, m_CameraStencilBufferCopy, m_SkyManager.IsSkyValid());
m_LightLoop.BuildGPULightLists(hdCamera, cmd, m_CameraDepthStencilBuffer, m_CameraStencilBufferCopy, m_SkyManager.IsLightingSkyValid());
// The pass only requires the volume properties, and can run async.
m_VolumetricLightingModule.VoxelizeDensityVolumes(hdCamera, cmd);
// Perform the voxelization step which fills the density 3D texture.
// Requires the clustered lighting data structure to be built, and can run async.
m_VolumetricLightingSystem.VolumeVoxelizationPass(densityVolumes, hdCamera, cmd, m_FrameSettings);
m_VolumetricLightingModule.VolumetricLightingPass(hdCamera, cmd, m_FrameSettings);
m_VolumetricLightingSystem.VolumetricLightingPass(hdCamera, cmd, m_FrameSettings);
RenderDeferredLighting(hdCamera, cmd);

uint x, y, z;
m_applyDistortionCS.GetKernelThreadGroupSizes(m_applyDistortionKernel, out x, out y, out z);
cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._DistortionTexture, m_DistortionBuffer);
cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._GaussianPyramidColorTexture, m_BufferPyramid.colorPyramid);
cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._ColorPyramidTexture, m_BufferPyramid.colorPyramid);
cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._CameraColorTexture, m_CameraColorBuffer);
cmd.SetComputeVectorParam(m_applyDistortionCS, HDShaderIDs._Size, size);
cmd.SetComputeVectorParam(m_applyDistortionCS, HDShaderIDs._ZBufferParams, Shader.GetGlobalVector(HDShaderIDs._ZBufferParams));

var visualEnv = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();
visualEnv.PushFogShaderParameters(cmd, m_FrameSettings);
m_SkyManager.RenderSky(hdCamera, m_LightLoop.GetCurrentSunLight(), m_CameraColorBuffer, m_CameraDepthStencilBuffer, cmd);
m_SkyManager.RenderSky(hdCamera, m_LightLoop.GetCurrentSunLight(), m_CameraColorBuffer, m_CameraDepthStencilBuffer, m_CurrentDebugDisplaySettings, cmd);
if (visualEnv.fogType != FogType.None || m_VolumetricLightingModule.preset != VolumetricLightingModule.VolumetricLightingPreset.Off)
if (visualEnv.fogType != FogType.None || m_VolumetricLightingSystem.preset != VolumetricLightingSystem.VolumetricLightingPreset.Off)
m_SkyManager.RenderOpaqueAtmosphericScattering(cmd);
}

context.command = cmd;
context.camera = hdcamera.camera;
context.sourceFormat = RenderTextureFormat.ARGBHalf;
context.flip = true;
context.flip = hdcamera.camera.targetTexture == null;
layer.Render(context);
}

{
if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() ||
m_CurrentDebugDisplaySettings.fullScreenDebugMode != FullScreenDebugMode.None ||
m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
{
// enable globally the keyword DEBUG_DISPLAY on shader that support it with multicompile

cmd.SetGlobalVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(hdCamera));
cmd.SetGlobalTexture(HDShaderIDs._DebugFont, m_Asset.renderPipelineResources.debugFontTexture);
// The DebugNeedsExposure test allows us to set a neutral value if exposure is not needed. This way we don't need to make various tests inside shaders but only in this function.
cmd.SetGlobalFloat(HDShaderIDs._DebugExposure, m_CurrentDebugDisplaySettings.DebugNeedsExposure() ? lightingDebugSettings.debugExposure : 0.0f);
}
else
{

{
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
{
HDUtils.BlitCameraTexture(cmd, hdCamera, textureID, m_DebugColorPickerBuffer);
using (new ProfilingSample(cmd, "Push To Color Picker"))
{
HDUtils.BlitCameraTexture(cmd, hdCamera, textureID, m_DebugColorPickerBuffer);
}
}
}

if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
{
HDUtils.BlitCameraTexture(cmd, hdCamera, textureID, m_DebugColorPickerBuffer);
using (new ProfilingSample(cmd, "Push To Color Picker"))
{
HDUtils.BlitCameraTexture(cmd, hdCamera, textureID, m_DebugColorPickerBuffer);
}
}
}

m_SharedPropertyBlock.SetTexture(HDShaderIDs._InputCubemap, skyReflection);
m_SharedPropertyBlock.SetFloat(HDShaderIDs._Mipmap, lightingDebug.skyReflectionMipmap);
m_SharedPropertyBlock.SetFloat(HDShaderIDs._RequireToFlipInputTexture, hdCamera.camera.cameraType != CameraType.SceneView ? 1.0f : 0.0f);
m_SharedPropertyBlock.SetFloat(HDShaderIDs._DebugExposure, lightingDebug.debugExposure);
cmd.SetViewport(new Rect(x, y, overlaySize, overlaySize));
cmd.DrawProcedural(Matrix4x4.identity, m_DebugDisplayLatlong, 0, MeshTopology.Triangles, 3, 1, m_SharedPropertyBlock);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.actualWidth);

{
if (hdCamera.clearColorMode == HDAdditionalCameraData.ClearColorMode.BackgroundColor ||
// If we want the sky but the sky don't exist, still clear with background color
(hdCamera.clearColorMode == HDAdditionalCameraData.ClearColorMode.Sky && !m_SkyManager.IsSkyValid()) ||
(hdCamera.clearColorMode == HDAdditionalCameraData.ClearColorMode.Sky && !m_SkyManager.IsVisualSkyValid()) ||
// Special handling for Preview we force to clear with background color (i.e black)
// Note that the sky use in this case is the last one setup. If there is no scene or game, there is no sky use as reflection in the preview
hdCamera.camera.cameraType == CameraType.Preview

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.asset


pointCookieSize: 512
cubeCookieTexArraySize: 16
reflectionProbeCacheSize: 128
planarReflectionProbeCacheSize: 128
planarReflectionProbeCacheSize: 4
planarReflectionTextureSize: 128
planarReflectionTextureSize: 1024
reflectionCacheCompressed: 0
planarReflectionCacheCompressed: 0
maxPlanarReflectionProbes: 128

16
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs


public static readonly int g_LayeredSingleIdxBuffer = Shader.PropertyToID("g_LayeredSingleIdxBuffer");
public static readonly int _EnvLightIndexShift = Shader.PropertyToID("_EnvLightIndexShift");
public static readonly int _DensityVolumeIndexShift = Shader.PropertyToID("_DensityVolumeIndexShift");
public static readonly int g_isOrthographic = Shader.PropertyToID("g_isOrthographic");
public static readonly int g_iNrVisibLights = Shader.PropertyToID("g_iNrVisibLights");

public static readonly int _ViewTilesFlags = Shader.PropertyToID("_ViewTilesFlags");
public static readonly int _MousePixelCoord = Shader.PropertyToID("_MousePixelCoord");
public static readonly int _DebugFont = Shader.PropertyToID("_DebugFont");
public static readonly int _DebugExposure = Shader.PropertyToID("_DebugExposure");
public static readonly int _DebugEnvironmentProxyDepthScale = Shader.PropertyToID("_DebugEnvironmentProxyDepthScale");
public static readonly int _DebugViewMaterial = Shader.PropertyToID("_DebugViewMaterial");

public static readonly int _IrradianceSource = Shader.PropertyToID("_IrradianceSource");
public static readonly int _EnableDBuffer = Shader.PropertyToID("_EnableDBuffer");
public static readonly int _DecalAtlasResolution = Shader.PropertyToID("_DecalAtlasResolution");
public static readonly int[] _GBufferTexture =
{

public static readonly int _VelocityTexture = Shader.PropertyToID("_VelocityTexture");
public static readonly int _ShadowMaskTexture = Shader.PropertyToID("_ShadowMaskTexture");
public static readonly int _DistortionTexture = Shader.PropertyToID("_DistortionTexture");
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 _DepthPyramidMipSize = Shader.PropertyToID("_PyramidDepthMipSize");
public static readonly int _ColorPyramidTexture = Shader.PropertyToID("_ColorPyramidTexture");
public static readonly int _DepthPyramidTexture = Shader.PropertyToID("_DepthPyramidTexture");
public static readonly int _ColorPyramidSize = Shader.PropertyToID("_ColorPyramidSize");
public static readonly int _ColorPyramidScale = Shader.PropertyToID("_ColorPyramidScale");
public static readonly int _DepthPyramidSize = Shader.PropertyToID("_DepthPyramidSize");
public static readonly int _DepthPyramidScale = Shader.PropertyToID("_DepthPyramidScale");
public static readonly int _DebugColorPickerTexture = Shader.PropertyToID("_DebugColorPickerTexture");
public static readonly int _ColorPickerParam = Shader.PropertyToID("_ColorPickerParam");

public static readonly int _VBufferLightingHistory = Shader.PropertyToID("_VBufferLightingHistory");
public static readonly int _VBufferLightingFeedback = Shader.PropertyToID("_VBufferLightingFeedback");
public static readonly int _VBufferSampleOffset = Shader.PropertyToID("_VBufferSampleOffset");
public static readonly int _VolumeBounds = Shader.PropertyToID("_VolumeBounds");
public static readonly int _VolumeProperties = Shader.PropertyToID("_VolumeProperties");
public static readonly int _NumVisibleDensityVolumes = Shader.PropertyToID("_NumVisibleDensityVolumes");
}
}

26
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs


return Matrix4x4.Transpose(worldToViewMatrix.transpose * viewSpaceRasterTransform);
}
private static void SetViewportAndClear(CommandBuffer cmd, HDCamera camera, RTHandle buffer, ClearFlag clearFlag, Color clearColor)
{
// Clearing a partial viewport currently does not go through the hardware clear.
// Instead it goes through a quad rendered with a specific shader.
// When enabling wireframe mode in the scene view, unfortunately it overrides this shader thus breaking every clears.
// That's why in the editor we don't set the viewport before clearing (it's set to full screen by the previous SetRenderTarget) but AFTER so that we benefit from un-bugged hardware clear.
// We consider that the small loss in performance is acceptable in the editor.
// A refactor of wireframe is needed before we can fix this properly (with not doing anything!)
#if !UNITY_EDITOR
SetViewport(cmd, camera, buffer);
#endif
CoreUtils.ClearRenderTarget(cmd, clearFlag, clearColor);
#if UNITY_EDITOR
SetViewport(cmd, camera, buffer);
#endif
}
SetViewport(cmd, camera, buffer);
CoreUtils.ClearRenderTarget(cmd, clearFlag, clearColor);
SetViewportAndClear(cmd, camera, buffer, 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)

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);
SetViewportAndClear(cmd, camera, colorBuffer, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier[] colorBuffers, RTHandle 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);
SetViewportAndClear(cmd, camera, depthBuffer, clearFlag, CoreUtils.clearColorAllBlack);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier[] colorBuffers, RTHandle depthBuffer, ClearFlag clearFlag, Color clearColor)

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs


// As we have our own default value, we need to initialize the light intensity correctly
public static void InitDefaultHDAdditionalLightData(HDAdditionalLightData lightData)
{
// At first init we need to initialize correctly the default value
lightData.ConvertPhysicalLightIntensityToLightIntensity();
// Special treatment for Unity builtin area light. Change it to our rectangle light
// Special treatment for Unity built-in area light. Change it to our rectangle light
var light = lightData.gameObject.GetComponent<Light>();
// Sanity check: lightData.lightTypeExtent is init to LightTypeExtent.Punctual (in case for unknow reasons we recreate additional data on an existing line)

light.type = LightType.Point; // Same as in HDLightEditor
#if UNITY_EDITOR
light.lightmapBakeType = LightmapBakeType.Realtime;
#endif
// At first init we need to initialize correctly the default value
lightData.ConvertPhysicalLightIntensityToLightIntensity();
}
}

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightEvaluation.hlsl


lightData.angleScale, lightData.angleOffset);
#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET != 0)
// TODO: sample the extinction from the density V-buffer.
float distVol = (lightData.lightType == GPULIGHTTYPE_PROJECTOR_BOX) ? distances.w : distances.x;
attenuation *= TransmittanceHomogeneousMedium(_GlobalExtinction, distVol);
#endif

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


Area,
Env,
Decal,
DensityVolume,
Count
}

EnvironmentAndPunctual = 5,
EnvironmentAndArea = 6,
EnvironmentAndAreaAndPunctual = 7,
Decal = 8
Decal = 8,
DensityVolumes = 16
};
public const int k_MaxDirectionalLightsOnScreen = 4;

int m_punctualLightCount = 0;
int m_areaLightCount = 0;
int m_lightCount = 0;
int m_densityVolumeCount = 0;
bool m_enableBakeShadowMask = false; // Track if any light require shadow mask. In this case we will need to enable the keyword shadow mask
float m_maxShadowDistance = 0.0f; // Save value from shadow settings

}
}
public void AddBoxVolumeDataAndBound(OrientedBBox obb, LightCategory category, LightFeatureFlags featureFlags, Matrix4x4 worldToView)
{
var bound = new SFiniteLightBound();
var volumeData = new LightVolumeData();
// transform to camera space (becomes a left hand coordinate frame in Unity since Determinant(worldToView)<0)
var positionVS = worldToView.MultiplyPoint(obb.center);
var rightVS = worldToView.MultiplyVector(obb.right);
var upVS = worldToView.MultiplyVector(obb.up);
var forwardVS = Vector3.Cross(upVS, rightVS);
var extents = new Vector3(obb.extentX, obb.extentY, obb.extentZ);
volumeData.lightVolume = (uint)LightVolumeType.Box;
volumeData.lightCategory = (uint)category;
volumeData.featureFlags = (uint)featureFlags;
bound.center = positionVS;
bound.boxAxisX = obb.extentX * rightVS;
bound.boxAxisY = obb.extentY * upVS;
bound.boxAxisZ = obb.extentZ * forwardVS;
bound.radius = extents.magnitude;
bound.scaleXY.Set(1.0f, 1.0f);
// The culling system culls pixels that are further
// than a threshold to the box influence extents.
// So we use an arbitrary threshold here (k_BoxCullingExtentOffset)
volumeData.lightPos = positionVS;
volumeData.lightAxisX = rightVS;
volumeData.lightAxisY = upVS;
volumeData.lightAxisZ = forwardVS;
volumeData.boxInnerDist = extents - k_BoxCullingExtentThreshold; // We have no blend range, but the culling code needs a small EPS value for some reason???
volumeData.boxInvRange.Set(1.0f / k_BoxCullingExtentThreshold.x, 1.0f / k_BoxCullingExtentThreshold.y, 1.0f / k_BoxCullingExtentThreshold.z);
m_lightList.bounds.Add(bound);
m_lightList.lightVolumes.Add(volumeData);
}
public int GetCurrentShadowCount()
{
return m_ShadowRequests.Count;

}
// Return true if BakedShadowMask are enabled
public bool PrepareLightsForGPU(CommandBuffer cmd, ShadowSettings shadowSettings, CullResults cullResults, ReflectionProbeCullResults reflectionProbeCullResults, Camera camera)
public bool PrepareLightsForGPU(CommandBuffer cmd, Camera camera, ShadowSettings shadowSettings, CullResults cullResults,
ReflectionProbeCullResults reflectionProbeCullResults, DensityVolumeList densityVolumes)
{
using (new ProfilingSample(cmd, "Prepare Lights For GPU"))
{

if (ShaderConfig.s_CameraRelativeRendering != 0)
{
// Caution: 'DirectionalLightData.positionWS' is camera-relative after this point.
int n = m_lightList.directionalLights.Count;
DirectionalLightData lightData = m_lightList.directionalLights[n - 1];
int last = m_lightList.directionalLights.Count - 1;
DirectionalLightData lightData = m_lightList.directionalLights[last];
m_lightList.directionalLights[n - 1] = lightData;
m_lightList.directionalLights[last] = lightData;
}
}
continue;

if (ShaderConfig.s_CameraRelativeRendering != 0)
{
// Caution: 'LightData.positionWS' is camera-relative after this point.
int n = m_lightList.lights.Count;
LightData lightData = m_lightList.lights[n - 1];
int last = m_lightList.lights.Count - 1;
LightData lightData = m_lightList.lights[last];
m_lightList.lights[n - 1] = lightData;
m_lightList.lights[last] = lightData;
}
}
}

if (ShaderConfig.s_CameraRelativeRendering != 0)
{
// Caution: 'EnvLightData.positionWS' is camera-relative after this point.
int n = m_lightList.envLights.Count;
EnvLightData envLightData = m_lightList.envLights[n - 1];
int last = m_lightList.envLights.Count - 1;
EnvLightData envLightData = m_lightList.envLights[last];
m_lightList.envLights[n - 1] = envLightData;
m_lightList.envLights[last] = envLightData;
// Inject density volumes into the clustered data structure for efficient look up.
m_densityVolumeCount = densityVolumes.bounds != null ? densityVolumes.bounds.Count : 0;
Matrix4x4 worldToViewCR = worldToView;
if (ShaderConfig.s_CameraRelativeRendering != 0)
{
// The OBBs are camera-relative, the matrix is not. Fix it.
worldToViewCR.SetColumn(3, new Vector4(0, 0, 0, 1));
}
for (int i = 0, n = m_densityVolumeCount; i < n; i++)
{
// Density volumes are not lights and therefore should not affect light classification.
LightFeatureFlags featureFlags = 0;
AddBoxVolumeDataAndBound(densityVolumes.bounds[i], LightCategory.DensityVolume, featureFlags, worldToViewCR);
}
m_lightCount = m_lightList.lights.Count + m_lightList.envLights.Count;
Debug.Assert(m_lightList.bounds.Count == m_lightCount);
Debug.Assert(m_lightList.lightVolumes.Count == m_lightCount);
m_lightCount = m_lightList.lights.Count + m_lightList.envLights.Count + m_densityVolumeCount;
Debug.Assert(m_lightCount == m_lightList.bounds.Count);
Debug.Assert(m_lightCount == m_lightList.lightVolumes.Count);
int decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, k_MaxDecalsOnScreen);
if (decalDatasCount > 0)

cmd.SetComputeBufferParam(buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, s_GlobalLightListAtomic);
cmd.DispatchCompute(buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, 1, 1, 1);
int decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, k_MaxDecalsOnScreen);
cmd.SetComputeIntParam(buildPerVoxelLightListShader, HDShaderIDs._DensityVolumeIndexShift, m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount);
cmd.SetComputeIntParam(buildPerVoxelLightListShader, HDShaderIDs.g_iNrVisibLights, m_lightCount);
cmd.SetComputeMatrixArrayParam(buildPerVoxelLightListShader, HDShaderIDs.g_mScrProjectionArr, projscrArr);
cmd.SetComputeMatrixArrayParam(buildPerVoxelLightListShader, HDShaderIDs.g_mInvScrProjectionArr, invProjscrArr);

else // Pixel shader evaluation
{
int index = GetDeferredLightingMaterialIndex( options.outputSplitLighting ? 1 : 0,
m_FrameSettings.lightLoopSettings.enableTileAndCluster ? 1 : 0,
m_enableBakeShadowMask ? 1 : 0,
m_FrameSettings.lightLoopSettings.enableTileAndCluster ? 1 : 0,
m_enableBakeShadowMask ? 1 : 0,
debugDisplaySettings.IsDebugDisplayEnabled() ? 1 : 0);
Material currentLightingMaterial = m_deferredLightingMaterial[index];

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs.hlsl


#define LIGHTCATEGORY_AREA (1)
#define LIGHTCATEGORY_ENV (2)
#define LIGHTCATEGORY_DECAL (3)
#define LIGHTCATEGORY_COUNT (4)
#define LIGHTCATEGORY_DENSITY_VOLUME (4)
#define LIGHTCATEGORY_COUNT (5)
//
// UnityEngine.Experimental.Rendering.HDPipeline.LightFeatureFlags: static fields

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.hlsl


}
}
// We always apply exposure when in debug mode. The exposure value will be at a neutral 0.0 when not needed.
diffuseLighting *= exp2(_DebugExposure);
specularLighting *= exp2(_DebugExposure);
#endif
}

24
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopDef.hlsl


//_Env2DCaptureVP is in capture space
float3 ndc = ComputeNormalizedDeviceCoordinatesWithZ(texCoord, _Env2DCaptureVP[index]);
color.rgb = SAMPLE_TEXTURE2D_ARRAY_LOD(_Env2DTextures, s_trilinear_clamp_sampler, ndc.xy, index, 0).rgb;
color.rgb = SAMPLE_TEXTURE2D_ARRAY_LOD(_Env2DTextures, s_trilinear_clamp_sampler, ndc.xy, index, lod).rgb;
color.a = any(ndc.xyz < 0) || any(ndc.xyz > 1) ? 0.0 : 1.0;
#ifdef DEBUG_DISPLAY

return 1;
}
uint FetchIndex(uint globalOffset, uint lightIndex)
{
return globalOffset + lightIndex;
}
uint FetchIndexWithBoundsCheck(uint start, uint count, uint i)
{
if (i < count)
{
return FetchIndex(start, i);
}
else
{
return UINT_MAX;
}
}
#ifdef LIGHTLOOP_TILE_PASS
#else
int j = start + i;
#endif
return _LightDatas[j];
}

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-bigtile.compute


uniform float g_fNearPlane;
uniform float g_fFarPlane;
uniform uint g_isOrthographic;
// TODO: These aren't used, we should remove them
uniform int _EnvLightIndexShift;
uniform int _DecalIndexShift;
StructuredBuffer<float3> g_vBoundsBuffer : register( t1 );
StructuredBuffer<LightVolumeData> _LightVolumeData : register(t2);

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


uint g_isOrthographic;
int _EnvLightIndexShift;
int _DecalIndexShift;
int _DensityVolumeIndexShift;
float g_fClustScale;
float g_fClustBase;

int shiftIndex[LIGHTCATEGORY_COUNT];
ZERO_INITIALIZE_ARRAY(int, shiftIndex, LIGHTCATEGORY_COUNT);
// NOTE: Why is this indexed like this?
shiftIndex[LIGHTCATEGORY_COUNT - 2] = _EnvLightIndexShift;
shiftIndex[LIGHTCATEGORY_COUNT - 1] = _DecalIndexShift;
shiftIndex[LIGHTCATEGORY_COUNT - 3] = _EnvLightIndexShift;
shiftIndex[LIGHTCATEGORY_COUNT - 2] = _DecalIndexShift;
shiftIndex[LIGHTCATEGORY_COUNT - 1] = _DensityVolumeIndexShift;
int categoryListCount[LIGHTCATEGORY_COUNT]; // direct light count and reflection lights
int categoryListCount[LIGHTCATEGORY_COUNT]; // number of direct lights, reflection probes, decals and density volumes
ZERO_INITIALIZE_ARRAY(int, categoryListCount, LIGHTCATEGORY_COUNT);
uint offs = start;

const int lightVolIndex = GenerateLightCullDataIndex(coarseList[l], g_iNrVisibLights, eyeIndex);
uint lightCategory = _LightVolumeData[lightVolIndex].lightCategory;
++categoryListCount[lightCategory];
g_vLayeredLightList[offs++] = coarseList[l] - shiftIndex[lightCategory]; // reflection lights will be last since we sorted
}
g_vLayeredLightList[offs++] = coarseList[l] - shiftIndex[lightCategory];
}
}
#if !defined(SHADER_API_XBOXONE) && !defined(SHADER_API_PSSL)

19
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild.compute


#define MAX_NR_COARSE_ENTRIES 64
#define MAX_NR_PRUNED_ENTRIES 24
#define CATEGORY_LIST_SIZE (LIGHTCATEGORY_COUNT - 1) // Skip density volumes
groupshared unsigned int coarseList[MAX_NR_COARSE_ENTRIES];
groupshared unsigned int prunedList[MAX_NR_COARSE_ENTRIES]; // temporarily support room for all 64 while in LDS

#endif
groupshared int ldsNrLightsFinal;
groupshared int ldsCategoryListCount[LIGHTCATEGORY_COUNT];
groupshared int ldsCategoryListCount[CATEGORY_LIST_SIZE];
#ifdef PERFORM_SPHERICAL_INTERSECTION_TESTS
groupshared uint lightOffsSph;

for(int l=(int) t; l<(int) g_iNrVisibLights; l += NR_THREADS)
{
#endif
// Skip density volumes (lights are sorted by category). TODO: improve data locality
if (_LightVolumeData[l].lightCategory == LIGHTCATEGORY_DENSITY_VOLUME) { break; }
const float3 vMi = g_vBoundsBuffer[l];
const float3 vMa = g_vBoundsBuffer[l+g_iNrVisibLights];

}
#endif
//
if(t<LIGHTCATEGORY_COUNT) ldsCategoryListCount[t]=0;
if(t<CATEGORY_LIST_SIZE) ldsCategoryListCount[t]=0;
#ifdef USE_FEATURE_FLAGS
if(t==0) ldsFeatureFlags=0;
#endif

// All our cull data are in the same list, but at render time envLights are separated so we need to shift the index
// to make it work correctly
int shiftIndex[LIGHTCATEGORY_COUNT];
ZERO_INITIALIZE_ARRAY(int, shiftIndex, LIGHTCATEGORY_COUNT);
shiftIndex[LIGHTCATEGORY_COUNT - 2] = _EnvLightIndexShift;
shiftIndex[LIGHTCATEGORY_COUNT - 1] = _DecalIndexShift;
int shiftIndex[CATEGORY_LIST_SIZE];
ZERO_INITIALIZE_ARRAY(int, shiftIndex, CATEGORY_LIST_SIZE);
shiftIndex[CATEGORY_LIST_SIZE - 2] = _EnvLightIndexShift;
shiftIndex[CATEGORY_LIST_SIZE - 1] = _DecalIndexShift;
for(int category=0; category<LIGHTCATEGORY_COUNT; category++)
for(int category=0; category<CATEGORY_LIST_SIZE; category++)
{
int nrLightsFinal = ldsCategoryListCount[category];
int nrLightsFinalClamped = nrLightsFinal<MAX_NR_PRUNED_ENTRIES ? nrLightsFinal : MAX_NR_PRUNED_ENTRIES;

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/HomogeneousDensityVolume.cs


[AddComponentMenu("Rendering/Homogeneous Density Volume", 1100)]
public class HomogeneousDensityVolume : MonoBehaviour
{
public VolumeParameters volumeParameters = new VolumeParameters();
public DensityVolumeParameters parameters = new DensityVolumeParameters();
private void Awake()
{

private void OnValidate()
{
volumeParameters.Constrain();
parameters.Constrain();
if (volumeParameters.IsLocalVolume())
if (parameters.IsLocalVolume())
Gizmos.color = volumeParameters.albedo;
Gizmos.color = parameters.albedo;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawWireCube(Vector3.zero, Vector3.one);
}

foreach (HomogeneousDensityVolume volume in volumes)
{
if (volume.enabled && !volume.volumeParameters.IsLocalVolume())
if (volume.enabled && !volume.parameters.IsLocalVolume())
{
globalVolume = volume;
break;

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/HomogeneousDensityVolume.cs.meta


fileFormatVersion: 2
guid: 1c273c50d71d46a4f98a1d23256a8c63
guid: e1fbb15bf92b84f40a1eb030765b5afe
MonoImporter:
externalObjects: {}
serializedVersion: 2

324
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLighting.cs


namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[GenerateHLSL]
public struct VolumeProperties
public struct DensityVolumeProperties
public static VolumeProperties GetNeutralVolumeProperties()
public static DensityVolumeProperties GetNeutralProperties()
VolumeProperties properties = new VolumeProperties();
DensityVolumeProperties properties = new DensityVolumeProperties();
properties.scattering = Vector3.zero;
properties.extinction = 0;

} // struct VolumeProperties
[Serializable]
public class VolumeParameters
public class DensityVolumeParameters
public bool isLocal; // Enables voxelization
public Color albedo; // Single scattering albedo [0, 1]
public float meanFreePath; // In meters [1, inf]. Should be chromatic - this is an optimization!
public float asymmetry; // Single global parameter for all volumes. TODO: UX
public bool isLocal; // Enables voxelization
public Color albedo; // Single scattering albedo [0, 1]
public float meanFreePath; // In meters [1, inf]. Should be chromatic - this is an optimization!
public float asymmetry; // Only used if (isLocal == false)
public VolumeParameters()
public DensityVolumeParameters()
{
isLocal = true;
albedo = new Color(0.5f, 0.5f, 0.5f);

asymmetry = Mathf.Clamp(asymmetry, -1.0f, 1.0f);
}
public VolumeProperties GetProperties()
public DensityVolumeProperties GetProperties()
VolumeProperties properties = new VolumeProperties();
DensityVolumeProperties properties = new DensityVolumeProperties();
properties.scattering = GetScatteringCoefficient();
properties.extinction = GetExtinctionCoefficient();

} // class VolumeParameters
public class VolumetricLightingModule
public struct DensityVolumeList
{
public List<OrientedBBox> bounds;
public List<DensityVolumeProperties> properties;
}
public class VolumetricLightingSystem
{
public enum VolumetricLightingPreset
{

}
class VBuffer
{
public long viewID = -1; // -1 is invalid; positive for Game Views, 0 otherwise
public RenderTexture[] lightingRTEX = null;
public RenderTargetIdentifier[] lightingRTID = null;
public RenderTexture densityRTEX = null;
public RenderTargetIdentifier densityRTID = -1; // RenderTargetIdentifier cannot be NULL
const int k_IndexDensity = 0;
const int k_IndexIntegral = 1;
const int k_IndexHistory = 2; // Depends on frame ID
const int k_IndexFeedback = 3; // Depends on frame ID
long m_ViewID = -1; // -1 is invalid; positive for Game Views, 0 otherwise
RenderTexture[] m_Textures = null;
RenderTargetIdentifier[] m_Identifiers = null;
public RenderTargetIdentifier GetDensityBuffer()
{
Debug.Assert(m_ViewID >= 0);
return m_Identifiers[k_IndexDensity];
}
Debug.Assert(viewID >= 0);
return lightingRTID[0];
Debug.Assert(m_ViewID >= 0);
return m_Identifiers[k_IndexIntegral];
Debug.Assert(viewID > 0); // Game View only
return lightingRTID[1 + ((Time.renderedFrameCount + 0) & 1)];
Debug.Assert(m_ViewID > 0); // Game View only
return m_Identifiers[k_IndexHistory + (Time.renderedFrameCount & 1)];
Debug.Assert(viewID > 0); // Game View only
return lightingRTID[1 + ((Time.renderedFrameCount + 1) & 1)];
}
public RenderTargetIdentifier GetDensityBuffer()
{
Debug.Assert(viewID >= 0);
return densityRTID;
Debug.Assert(m_ViewID > 0); // Game View only
return m_Identifiers[k_IndexFeedback - (Time.renderedFrameCount & 1)];
}
public void Create(long viewID, int w, int h, int d)

// Clean up first.
Destroy();
// The required number of buffers depends on the view type.
// Only Game Views need history and feedback buffers.
int n = isGameView ? 3 : 1;
int n = isGameView ? 4 : 2;
this.viewID = viewID;
this.lightingRTEX = new RenderTexture[n];
this.lightingRTID = new RenderTargetIdentifier[n];
m_ViewID = viewID;
m_Textures = new RenderTexture[n];
m_Identifiers = new RenderTargetIdentifier[n];
this.lightingRTEX[i] = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
this.lightingRTEX[i].hideFlags = HideFlags.HideAndDontSave;
this.lightingRTEX[i].filterMode = FilterMode.Trilinear; // Custom
this.lightingRTEX[i].dimension = TextureDimension.Tex3D; // TODO: request the thick 3D tiling layout
this.lightingRTEX[i].volumeDepth = d;
this.lightingRTEX[i].enableRandomWrite = true;
this.lightingRTEX[i].name = CoreUtils.GetRenderTargetAutoName(w, h, RenderTextureFormat.ARGBHalf, String.Format("Volumetric{0}", i));
this.lightingRTEX[i].Create();
this.lightingRTID[i] = new RenderTargetIdentifier(this.lightingRTEX[i]);
m_Textures[i] = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
m_Textures[i].hideFlags = HideFlags.HideAndDontSave;
m_Textures[i].filterMode = FilterMode.Trilinear; // Custom
m_Textures[i].dimension = TextureDimension.Tex3D; // TODO: request the thick 3D tiling layout
m_Textures[i].volumeDepth = d;
m_Textures[i].enableRandomWrite = true;
m_Textures[i].name = CoreUtils.GetRenderTargetAutoName(w, h, RenderTextureFormat.ARGBHalf, String.Format("VBuffer{0}", i));
m_Textures[i].Create();
// TODO: clear the texture. Clearing 3D textures does not appear to work right now.
m_Identifiers[i] = new RenderTargetIdentifier(m_Textures[i]);
if (this.lightingRTEX != null)
if (m_Textures != null)
for (int i = 0, n = this.lightingRTEX.Length; i < n; i++)
for (int i = 0, n = m_Textures.Length; i < n; i++)
if (this.lightingRTEX[i] != null)
if (m_Textures[i] != null)
this.lightingRTEX[i].Release();
m_Textures[i].Release();
this.viewID = -1;
this.lightingRTEX = null;
this.lightingRTID = null;
m_ViewID = -1;
m_Textures = null;
m_Identifiers = null;
}
public void GetResolution(ref int w, ref int h, ref int d)
{
Debug.Assert(m_Textures != null);
Debug.Assert(m_Textures[0] != null);
Debug.Assert(m_Identifiers != null);
w = m_Textures[0].width;
h = m_Textures[0].height;
d = m_Textures[0].volumeDepth;
}
public long GetViewID()
{
return m_ViewID;
}
public bool IsValid()
{
return m_ViewID >= 0 && m_Textures != null && m_Textures[0] != null;
ComputeShader m_VolumeVoxelizationCS = null;
List<VBuffer> m_VBuffers = null;
List<OrientedBBox> m_VisibleVolumes = null;
List<VolumeProperties> m_VisibleVolumeProperties = null;
public const int k_MaxVisibleVolumeCount = 512;
List<VBuffer> m_VBuffers = null;
List<OrientedBBox> m_VisibleVolumeBounds = null;
List<DensityVolumeProperties> m_VisibleVolumeProperties = null;
public const int k_MaxVisibleVolumeCount = 512;
static ComputeBuffer s_VisibleVolumesBuffer = null;
static ComputeBuffer s_VisibleVolumeBoundsBuffer = null;
const float k_LogScale = 0.5f;
const float k_LogScale = 0.5f; // Tweak constant, controls the logarithmic depth distribution
m_VolumeVoxelizationCS = asset.renderPipelineResources.volumeVoxelizationCS;
m_VisibleVolumes = new List<OrientedBBox>();
m_VisibleVolumeProperties = new List<VolumeProperties>();
s_VisibleVolumesBuffer = new ComputeBuffer(k_MaxVisibleVolumeCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(OrientedBBox)));
s_VisibleVolumePropertiesBuffer = new ComputeBuffer(k_MaxVisibleVolumeCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(VolumeProperties)));
m_VisibleVolumeBounds = new List<OrientedBBox>();
m_VisibleVolumeProperties = new List<DensityVolumeProperties>();
s_VisibleVolumeBoundsBuffer = new ComputeBuffer(k_MaxVisibleVolumeCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(OrientedBBox)));
s_VisibleVolumePropertiesBuffer = new ComputeBuffer(k_MaxVisibleVolumeCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DensityVolumeProperties)));
}
public void Cleanup()

m_VolumeVoxelizationCS = null;
m_VolumetricLightingCS = null;
for (int i = 0, n = m_VBuffers.Count; i < n; i++)

m_VBuffers = null;
m_VisibleVolumes = null;
m_VisibleVolumeBounds = null;
CoreUtils.SafeRelease(s_VisibleVolumesBuffer);
CoreUtils.SafeRelease(s_VisibleVolumeBoundsBuffer);
CoreUtils.SafeRelease(s_VisibleVolumePropertiesBuffer);
}

if (vBuffer != null)
{
Debug.Assert(vBuffer.lightingRTEX != null);
Debug.Assert(vBuffer.lightingRTEX[0] != null);
Debug.Assert(vBuffer.lightingRTID != null);
int width = 0, height = 0, depth = 0;
vBuffer.GetResolution(ref width, ref height, ref depth);
if (w == vBuffer.lightingRTEX[0].width &&
h == vBuffer.lightingRTEX[0].height &&
d == vBuffer.lightingRTEX[0].volumeDepth)
if (w == width && h == height && d == depth)
{
// Everything matches, nothing to do here.
return;

for (int i = 0; i < n; i++)
{
// Check whether domain reload killed it...
if (viewID == m_VBuffers[i].viewID && m_VBuffers[i].lightingRTEX != null && m_VBuffers[i].lightingRTEX[0] != null)
if (viewID == m_VBuffers[i].GetViewID() && m_VBuffers[i].IsValid())
{
vBuffer = m_VBuffers[i];
}

HomogeneousDensityVolume globalVolume = HomogeneousDensityVolume.GetGlobalHomogeneousDensityVolume();
// TODO: may want to cache these results somewhere.
VolumeProperties globalVolumeProperties = (globalVolume != null) ? globalVolume.volumeParameters.GetProperties()
: VolumeProperties.GetNeutralVolumeProperties();
DensityVolumeProperties globalVolumeProperties = (globalVolume != null) ? globalVolume.parameters.GetProperties()
: DensityVolumeProperties.GetNeutralProperties();
float asymmetry = globalVolume != null ? globalVolume.volumeParameters.asymmetry : 0;
float asymmetry = globalVolume != null ? globalVolume.parameters.asymmetry : 0;
int w = 0, h = 0, d = 0;
ComputeVBufferResolutionAndScale(preset, (int)camera.screenSize.x, (int)camera.screenSize.y, ref w, ref h, ref d);
int w = 0, h = 0, d = 0;
vBuffer.GetResolution(ref w, ref h, ref d);
SetPreconvolvedAmbientLightProbe(cmd, asymmetry);
cmd.SetGlobalVector( HDShaderIDs._VBufferResolution, new Vector4(w, h, 1.0f / w, 1.0f / h));
cmd.SetGlobalVector( HDShaderIDs._VBufferSliceCount, new Vector4(d, 1.0f / d));

}
public void VoxelizeDensityVolumes(HDCamera camera, CommandBuffer cmd)
public DensityVolumeList PrepareVisibleDensityVolumeList(HDCamera camera, CommandBuffer cmd)
if (preset == VolumetricLightingPreset.Off) return;
DensityVolumeList densityVolumes = new DensityVolumeList();
Vector3 camPosition = camera.camera.transform.position;
Vector3 camOffset = Vector3.zero; // World-origin-relative
if (preset == VolumetricLightingPreset.Off) return densityVolumes;
if (ShaderConfig.s_CameraRelativeRendering != 0)
using (new ProfilingSample(cmd, "Prepare Visible Density Volume List"))
camOffset = -camPosition; // Camera-relative
}
Vector3 camPosition = camera.camera.transform.position;
Vector3 camOffset = Vector3.zero; // World-origin-relative
m_VisibleVolumes.Clear();
m_VisibleVolumeProperties.Clear();
if (ShaderConfig.s_CameraRelativeRendering != 0)
{
camOffset = camPosition; // Camera-relative
}
// Collect all the visible volume data, and upload it to the GPU.
HomogeneousDensityVolume[] volumes = Object.FindObjectsOfType(typeof(HomogeneousDensityVolume)) as HomogeneousDensityVolume[];
m_VisibleVolumeBounds.Clear();
m_VisibleVolumeProperties.Clear();
foreach (HomogeneousDensityVolume volume in volumes)
{
// Only test active finite volumes.
if (volume.enabled && volume.volumeParameters.IsLocalVolume())
// Collect all visible finite volume data, and upload it to the GPU.
HomogeneousDensityVolume[] volumes = Object.FindObjectsOfType(typeof(HomogeneousDensityVolume)) as HomogeneousDensityVolume[];
for (int i = 0; i < Math.Min(volumes.Length, k_MaxVisibleVolumeCount); i++)
// TODO: cache these?
var obb = OrientedBBox.Create(volume.transform);
HomogeneousDensityVolume volume = volumes[i];
// Frustum cull on the CPU for now. TODO: do it on the GPU.
if (GeometryUtils.Overlap(obb, camOffset, camera.frustum, 6, 8))
// Only test active finite volumes.
if (volume.enabled && volume.parameters.IsLocalVolume())
var properties = volume.volumeParameters.GetProperties();
var obb = OrientedBBox.Create(volume.transform);
m_VisibleVolumes.Add(obb);
m_VisibleVolumeProperties.Add(properties);
// Handle camera-relative rendering.
obb.center -= camOffset;
// Frustum cull on the CPU for now. TODO: do it on the GPU.
if (GeometryUtils.Overlap(obb, camera.frustum, 6, 8))
{
// TODO: cache these?
var properties = volume.parameters.GetProperties();
m_VisibleVolumeBounds.Add(obb);
m_VisibleVolumeProperties.Add(properties);
}
s_VisibleVolumeBoundsBuffer.SetData(m_VisibleVolumeBounds);
s_VisibleVolumePropertiesBuffer.SetData(m_VisibleVolumeProperties);
// Fill the struct with pointers in order to share the data with the light loop.
densityVolumes.bounds = m_VisibleVolumeBounds;
densityVolumes.properties = m_VisibleVolumeProperties;
return densityVolumes;
}
s_VisibleVolumesBuffer.SetData(m_VisibleVolumes);
s_VisibleVolumePropertiesBuffer.SetData(m_VisibleVolumeProperties);
public void VolumeVoxelizationPass(DensityVolumeList densityVolumes, HDCamera camera, CommandBuffer cmd, FrameSettings settings)
{
if (preset == VolumetricLightingPreset.Off) return;
using (new ProfilingSample(cmd, "Volume Voxelization"))
{
int numVisibleVolumes = m_VisibleVolumeBounds.Count;
if (numVisibleVolumes == 0)
{
// Clear the render target instead of running the shader.
// CoreUtils.SetRenderTarget(cmd, vBuffer.GetDensityBuffer(), ClearFlag.Color, CoreUtils.clearColorAllBlack);
// return;
// Clearing 3D textures does not seem to work!
// Use the workaround by running the full shader with 0 density.
}
VBuffer vBuffer = FindVBuffer(camera.GetViewID());
Debug.Assert(vBuffer != null);
int w = 0, h = 0, d = 0;
vBuffer.GetResolution(ref w, ref h, ref d);
bool enableClustered = settings.lightLoopSettings.enableTileAndCluster;
int kernel = m_VolumeVoxelizationCS.FindKernel(enableClustered ? "VolumeVoxelizationClustered"
: "VolumeVoxelizationBruteforce");
float vFoV = camera.camera.fieldOfView * Mathf.Deg2Rad;
Vector4 resolution = new Vector4(w, h, 1.0f / w, 1.0f / h);
Matrix4x4 transform = HDUtils.ComputePixelCoordToWorldSpaceViewDirectionMatrix(vFoV, resolution, camera.viewMatrix, false);
camera.SetupComputeShader( m_VolumeVoxelizationCS, cmd);
cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VBufferDensity, vBuffer.GetDensityBuffer());
cmd.SetComputeBufferParam( m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeBounds, s_VisibleVolumeBoundsBuffer);
cmd.SetComputeBufferParam( m_VolumeVoxelizationCS, kernel, HDShaderIDs._VolumeProperties, s_VisibleVolumePropertiesBuffer);
// TODO: set the constant buffer data only once.
cmd.SetComputeMatrixParam( m_VolumeVoxelizationCS, HDShaderIDs._VBufferCoordToViewDirWS, transform);
cmd.SetComputeIntParam( m_VolumeVoxelizationCS, HDShaderIDs._NumVisibleDensityVolumes, numVisibleVolumes);
// The shader defines GROUP_SIZE_1D = 8.
cmd.DispatchCompute(m_VolumeVoxelizationCS, kernel, (w + 7) / 8, (h + 7) / 8, 1);
}
}
// Ref: https://en.wikipedia.org/wiki/Close-packing_of_equal_spheres

return coords;
}
public void VolumetricLightingPass(HDCamera camera, CommandBuffer cmd, FrameSettings frameSettings)
public void VolumetricLightingPass(HDCamera camera, CommandBuffer cmd, FrameSettings settings)
{
if (preset == VolumetricLightingPreset.Off) return;

Debug.Assert(vBuffer != null);
HomogeneousDensityVolume globalVolume = HomogeneousDensityVolume.GetGlobalHomogeneousDensityVolume();
float asymmetry = globalVolume != null ? globalVolume.volumeParameters.asymmetry : 0;
float asymmetry = globalVolume != null ? globalVolume.parameters.asymmetry : 0;
// CoreUtils.SetRenderTarget(cmd, GetVBufferLightingIntegral(viewOffset), ClearFlag.Color, CoreUtils.clearColorAllBlack);
// CoreUtils.SetRenderTarget(cmd, vBuffer.GetLightingIntegralBuffer(), ClearFlag.Color, CoreUtils.clearColorAllBlack);
// CoreUtils.SetRenderTarget(cmd, vBuffer.GetLightingFeedbackBuffer(), ClearFlag.Color, CoreUtils.clearColorAllBlack);
// Use the workaround by running the full shader with no volume.
// Use the workaround by running the full shader with 0 density.
bool enableClustered = frameSettings.lightLoopSettings.enableTileAndCluster;
// Only available in the Play Mode because all the frame counters in the Edit Mode are broken.
bool enableClustered = settings.lightLoopSettings.enableTileAndCluster;
bool enableReprojection = Application.isPlaying && camera.camera.cameraType == CameraType.Game;
int kernel;

// Only available in the Play Mode because all the frame counters in the Edit Mode are broken.
: "VolumetricLightingAllLightsReproj");
: "VolumetricLightingBruteforceReproj");
: "VolumetricLightingAllLights");
: "VolumetricLightingBruteforce");
ComputeVBufferResolutionAndScale(preset, (int)camera.screenSize.x, (int)camera.screenSize.y, ref w, ref h, ref d);
vBuffer.GetResolution(ref w, ref h, ref d);
// Compose the matrix which allows us to compute the world space view direction.
float vFoV = camera.camera.fieldOfView * Mathf.Deg2Rad;

Vector4 offset = new Vector4(xySeq[sampleIndex].x, xySeq[sampleIndex].y, zSeq[sampleIndex], rfc);
// TODO: set 'm_VolumetricLightingPreset'.
cmd.SetComputeFloatParam( m_VolumetricLightingCS, HDShaderIDs._CornetteShanksConstant, CornetteShanksPhasePartConstant(asymmetry));
cmd.SetComputeVectorParam( m_VolumetricLightingCS, HDShaderIDs._VBufferSampleOffset, offset);
// TODO: set the constant buffer data only once.
cmd.SetComputeVectorParam( m_VolumetricLightingCS, HDShaderIDs._VBufferSampleOffset, offset);
cmd.SetComputeFloatParam( m_VolumetricLightingCS, HDShaderIDs._CornetteShanksConstant, CornetteShanksPhasePartConstant(asymmetry));
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferDensity, vBuffer.GetDensityBuffer()); // Read
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingIntegral, vBuffer.GetLightingIntegralBuffer()); // Write
if (enableReprojection)
{

// The shader defines GROUP_SIZE_1D = 16.
cmd.DispatchCompute(m_VolumetricLightingCS, kernel, (w + 15) / 16, (h + 15) / 16, 1);
// The shader defines GROUP_SIZE_1D = 8.
cmd.DispatchCompute(m_VolumetricLightingCS, kernel, (w + 7) / 8, (h + 7) / 8, 1);
}
}
} // class VolumetricLightingModule

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLighting.cs.hlsl


#ifndef VOLUMETRICLIGHTING_CS_HLSL
#define VOLUMETRICLIGHTING_CS_HLSL
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.VolumeProperties
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.DensityVolumeProperties
struct VolumeProperties
struct DensityVolumeProperties
{
float3 scattering;
float extinction;

// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.VolumeProperties
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.DensityVolumeProperties
float3 GetScattering(VolumeProperties value)
float3 GetScattering(DensityVolumeProperties value)
float GetExtinction(VolumeProperties value)
float GetExtinction(DensityVolumeProperties value)
{
return value.extinction;
}

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


if (frameSettings.enableDBuffer)
{
cmd.SetGlobalInt(HDShaderIDs._EnableDBuffer, vsibleDecalCount > 0 ? 1 : 0);
cmd.SetGlobalVector(HDShaderIDs._DecalAtlasResolution, new Vector2(DecalSystem.kDecalAtlasSize, DecalSystem.kDecalAtlasSize));
BindBufferAsTextures(cmd);
}
else

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.hlsl


CBUFFER_START(UnityDecalParameters)
uint _EnableDBuffer;
float2 _DecalAtlasResolution;
CBUFFER_END
UNITY_INSTANCING_BUFFER_START(Decal)

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalData.hlsl


#if _COLORMAP
surfaceData.baseColor = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, texCoordDS.xy);
surfaceData.baseColor.w *= totalBlend;
totalBlend = surfaceData.baseColor.w; // base alpha affects aall other channels;
surfaceData.HTileMask |= DBUFFERHTILEBIT_DIFFUSE;
#endif
#if _NORMALMAP

48
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalUtilities.hlsl


// Caution: We can't compute LOD inside a dynamic loop. The gradient are not accessible.
// we need to find a way to calculate mips. For now just fetch first mip of the decals
void ApplyBlendNormal(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float3x3 decalToWorld, float blend)
void ApplyBlendNormal(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float3x3 decalToWorld, float blend, float lod)
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, 0 /* ComputeTextureLOD(texCoords) */))) * 0.5f + 0.5f;
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, lod))) * 0.5f + 0.5f;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);

void ApplyBlendDiffuse(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float blend)
void ApplyBlendDiffuse(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, inout float blend, float lod)
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, 0 /* ComputeTextureLOD(texCoords) */);
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, lod);
blend = src.w; // diffuse texture alpha affects all other channels
void ApplyBlendMask(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float blend)
void ApplyBlendMask(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float blend, float lod)
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, 0 /* ComputeTextureLOD(texCoords) */);
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, lod);
src.z = src.w;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);

void AddDecalContribution(PositionInputs posInput, inout SurfaceData surfaceData)
void AddDecalContribution(PositionInputs posInput, inout SurfaceData surfaceData, inout float alpha)
{
if(_EnableDBuffer)
{

#endif
float3 positionWS = GetAbsolutePositionWS(posInput.positionWS);
uint i = 0;
UNITY_LOOP
for (i = 0; i < decalCount; i++)
{
DecalData decalData = FetchDecal(decalStart, i);

int diffuseIndex = decalData.normalToWorld[1][3];
int normalIndex = decalData.normalToWorld[2][3];
int maskIndex = decalData.normalToWorld[3][3];
if((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f))) // clip to decal space
float lod = ComputeTextureLOD(positionDS.xz, _DecalAtlasResolution);
decalBlend = ((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f))) ? decalBlend : 0; // use blend of 0 instead of an 'if' because compiler moves the lod calculation inside the 'if' which causes incorrect values
// if any of the pixels in the 2x2 quad gets rejected
// Verified that lod calculation works with a test texture, looking at the shader code in Razor the lod calculation is outside the dynamic branches where the texture fetch happens,
// however compiler was placing it inside the branch that was rejecting the pixel, which was causing incorrect lod to be calculated for any 2x2 quad where any of the pixels were rejected,
// so had to use alpha blend of 0 instead of branching to solve that issue."
if(diffuseIndex != -1)
if(diffuseIndex != -1)
{
ApplyBlendDiffuse(DBuffer0, mask, positionDS.xz, diffuseIndex, DBUFFERHTILEBIT_DIFFUSE, decalBlend);
}
ApplyBlendDiffuse(DBuffer0, mask, positionDS.xz, diffuseIndex, DBUFFERHTILEBIT_DIFFUSE, decalBlend, lod);
alpha = alpha < decalBlend ? decalBlend : alpha; // use decal alpha if it higher than transparent alpha
}
if(normalIndex != -1)
{
ApplyBlendNormal(DBuffer1, mask, positionDS.xz, normalIndex, DBUFFERHTILEBIT_NORMAL, (float3x3)decalData.normalToWorld, decalBlend);
}
if(normalIndex != -1)
{
ApplyBlendNormal(DBuffer1, mask, positionDS.xz, normalIndex, DBUFFERHTILEBIT_NORMAL, (float3x3)decalData.normalToWorld, decalBlend, lod);
}
if(maskIndex != -1)
{
ApplyBlendMask(DBuffer2, mask, positionDS.xz, maskIndex, DBUFFERHTILEBIT_MASK, decalBlend);
}
if(maskIndex != -1)
{
ApplyBlendMask(DBuffer2, mask, positionDS.xz, maskIndex, DBUFFERHTILEBIT_MASK, decalBlend, lod);
}
}
#else

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/DiffusionProfile/DiffusionProfileSettings.cs


ValidateArray(ref halfRcpVariancesAndWeights, DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 2);
ValidateArray(ref filterKernelsBasic, DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * DiffusionProfileConstants.SSS_BASIC_N_SAMPLES);
Debug.Assert(DiffusionProfileConstants.DIFFUSION_PROFILE_NEUTRAL_ID <= 32, "Transmission and Texture flags (32-bit integer) cannot support more than 32 profiles.");
Debug.Assert(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT <= 32, "Transmission and Texture flags (32-bit integer) cannot support more than 32 profiles.");
UpdateCache();
}

worldScales[neutralId] = Vector4.one;
shapeParams[neutralId] = Vector4.zero;
transmissionTintsAndFresnel0[neutralId].w = 0.04f; // Match DEFAULT_SPECULAR_VALUE defined in Lit.hlsl
for (int j = 0, n = DiffusionProfileConstants.SSS_N_SAMPLES_NEAR_FIELD; j < n; j++)
{

79
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs


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

RenderPipelineResources m_RenderPipelineResources;
BufferPyramidProcessor m_BufferPyramidProcessor;
List<RenderTexture> m_PlanarColorMips = new List<RenderTexture>();
public IBLFilterGGX(RenderPipelineResources renderPipelineResources)
public IBLFilterGGX(RenderPipelineResources renderPipelineResources, BufferPyramidProcessor processor)
m_BufferPyramidProcessor = processor;
}
public bool IsInitialized()

{
CoreUtils.Destroy(m_GgxConvolveMaterial);
CoreUtils.Destroy(m_GgxIblSampleData);
for (var i = 0; i < m_PlanarColorMips.Count; ++i)
m_PlanarColorMips[i].Release();
m_PlanarColorMips.Clear();
}
void FilterCubemapCommon( CommandBuffer cmd,

public void FilterPlanarTexture(CommandBuffer cmd, Texture source, RenderTexture target)
{
// TODO: planar convolution
cmd.CopyTexture(source, 0, 0, target, 0, 0);
var lodCount = Mathf.Max(Mathf.FloorToInt(Mathf.Log(Mathf.Min(source.width, source.height), 2f)), 0);
for (var i = 0 ; i < lodCount - 0; ++i)
{
var width = target.width >> (i + 1);
var height = target.height >> (i + 1);
var rtHash = HashRenderTextureProperties(
width,
height,
target.depth,
target.format,
target.sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear
);
var lodIsMissing = i >= m_PlanarColorMips.Count;
RenderTexture rt = null;
var createRT = lodIsMissing
|| (rt = m_PlanarColorMips[i]) == null
|| rtHash != HashRenderTextureProperties(
rt.width, rt.height, rt.depth, rt.format, rt.sRGB
? RenderTextureReadWrite.sRGB
: RenderTextureReadWrite.Linear
);
if (createRT && rt)
rt.Release();
if (createRT)
{
rt = new RenderTexture(
width,
height,
target.depth,
target.format,
target.sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear
);
rt.enableRandomWrite = true;
rt.name = "Planar Convolution Tmp RT";
rt.hideFlags = HideFlags.HideAndDontSave;
rt.Create();
}
if (lodIsMissing)
m_PlanarColorMips.Add(rt);
else if (createRT)
m_PlanarColorMips[i] = rt;
}
m_BufferPyramidProcessor.RenderColorPyramid(
new RectInt(0, 0, source.width, source.height),
cmd,
source,
target,
m_PlanarColorMips,
lodCount
);
}
// Filters MIP map levels (other than 0) with GGX using multiple importance sampling.

m_GgxConvolveMaterial.SetTexture("_MarginalRowDensities", marginalRowCdf);
FilterCubemapCommon(cmd, source, target, m_faceWorldToViewMatrixMatrices);
}
int HashRenderTextureProperties(
int width,
int height,
int depth,
RenderTextureFormat format,
RenderTextureReadWrite sRGB)
{
return width.GetHashCode()
^ height.GetHashCode()
^ depth.GetHashCode()
^ format.GetHashCode()
^ sRGB.GetHashCode();
}
}
}

17
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitData.hlsl


#endif
#if defined(_SUBSURFACE_MASK_MAP0)
#define _SUBSURFACE_MASK_MAP_IDX sampler_SubsurfaceMaskMap0
#define SAMPLER_SUBSURFACE_MASK_MAP_IDX sampler_SubsurfaceMaskMap0
#define _SUBSURFACE_MASK_MAP_IDX sampler_SubsurfaceMaskMap1
#define SAMPLER_SUBSURFACE_MASK_MAP_IDX sampler_SubsurfaceMaskMap1
#define _SUBSURFACE_MASK_MAP_IDX sampler_SubsurfaceMaskMap2
#define SAMPLER_SUBSURFACE_MASK_MAP_IDX sampler_SubsurfaceMaskMap2
#define _SUBSURFACE_MASK_MAP_IDX sampler_SubsurfaceMaskMap3
#define SAMPLER_SUBSURFACE_MASK_MAP_IDX sampler_SubsurfaceMaskMap3
#endif
#if defined(_THICKNESSMAP0)

void ComputeMaskWeights(float4 inputMasks, out float outWeights[_MAX_LAYER])
{
ZERO_INITIALIZE_ARRAY(float, outWeights, _MAX_LAYER);
float masks[_MAX_LAYER];
masks[0] = inputMasks.a;

// This function handle triplanar
void ComputeLayerWeights(FragInputs input, LayerTexCoord layerTexCoord, float4 inputAlphaMask, float4 blendMasks, out float outWeights[_MAX_LAYER])
{
for (int i = 0; i < _MAX_LAYER; ++i)
{
outWeights[i] = 0.0f;
}
#if defined(_DENSITY_MODE)
// Note: blendMasks.argb because a is main layer
float4 opacityAsDensity = saturate((inputAlphaMask - (float4(1.0, 1.0, 1.0, 1.0) - blendMasks.argb)) * 20.0); // 20.0 is the number of steps in inputAlphaMask (Density mask. We decided 20 empirically)

#endif
#ifndef _DISABLE_DBUFFER
AddDecalContribution(posInput, surfaceData);
AddDecalContribution(posInput, surfaceData, alpha);
#endif
#if defined(DEBUG_DISPLAY)

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


// Rough refraction texture
// Color pyramid (width, height, lodcount, Unused)
TEXTURE2D(_GaussianPyramidColorTexture);
TEXTURE2D(_ColorPyramidTexture);
TEXTURE2D(_PyramidDepthTexture);
TEXTURE2D(_DepthPyramidTexture);
float4 _GaussianPyramidColorMipSize; // (x,y) = PyramidToScreenScale, z = lodCount
float4 _PyramidDepthMipSize;
float4 _ColorPyramidSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size
float4 _DepthPyramidSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size
float4 _ColorPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused
float4 _DepthPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused
CBUFFER_END
// Ambient occlusion texture

// we approximate the scene as a plane (back plane) with normal -V at the depth hit point.
// (We avoid to raymarch the depth texture to get the refracted point.)
uint2 depthSize = uint2(_PyramidDepthMipSize.xy);
uint2 depthSize = uint2(_DepthPyramidSize.xy);
float pyramidDepth = LOAD_TEXTURE2D_LOD(_PyramidDepthTexture, posInputs.positionNDC * (depthSize >> 2), 2).r;
float pyramidDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, posInputs.positionNDC * (depthSize >> 2), 2).r;
float depth = LinearEyeDepth(pyramidDepth, _ZBufferParams);
// Distance from point to the back plane

preLightData.transparentTransmittance = exp(-bsdfData.absorptionCoefficient * refraction.dist);
// Empirical remap to try to match a bit the refraction probe blurring for the fallback
// Use IblPerceptualRoughness so we can handle approx of clear coat.
preLightData.transparentSSMipLevel = sqrt(preLightData.iblPerceptualRoughness) * uint(_GaussianPyramidColorMipSize.z);
preLightData.transparentSSMipLevel = sqrt(preLightData.iblPerceptualRoughness) * uint(_ColorPyramidScale.z);
#endif
return preLightData;

// Calculate screen space coordinates of refracted point in back plane
float2 refractedBackPointNDC = ComputeNormalizedDeviceCoordinates(refractedBackPointWS, UNITY_MATRIX_VP);
uint2 depthSize = uint2(_PyramidDepthMipSize.xy);
float refractedBackPointDepth = LinearEyeDepth(LOAD_TEXTURE2D_LOD(_PyramidDepthTexture, refractedBackPointNDC * depthSize, 0).r, _ZBufferParams);
uint2 depthSize = uint2(_DepthPyramidSize.xy);
float refractedBackPointDepth = LinearEyeDepth(LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, refractedBackPointNDC * depthSize, 0).r, _ZBufferParams);
// Exit if texel is out of color buffer
// Or if the texel is from an object in front of the object

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

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


#define SAMPLER_MASKMAP_IDX sampler_MaskMap
#define SAMPLER_HEIGHTMAP_IDX sampler_HeightMap
#define SAMPLER_SUBSURFACE_MASKMAP_IDX sampler_SubsurfaceMaskMap
#define SAMPLER_SUBSURFACE_MASK_MAP_IDX sampler_SubsurfaceMaskMap
#define SAMPLER_THICKNESSMAP_IDX sampler_ThicknessMap
// include LitDataIndividualLayer to define GetSurfaceData

surfaceData.tangentWS = Orthonormalize(surfaceData.tangentWS, surfaceData.normalWS);
#ifndef _DISABLE_DBUFFER
AddDecalContribution(posInput, surfaceData);
AddDecalContribution(posInput, surfaceData, alpha);
#endif
#if defined(DEBUG_DISPLAY)

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitDataIndividualLayer.hlsl


surfaceData.subsurfaceMask = ADD_IDX(_SubsurfaceMask);
#ifdef _SUBSURFACE_MASK_MAP_IDX
surfaceData.subsurfaceMask *= SAMPLE_UVMAPPING_TEXTURE2D(ADD_IDX(_SubsurfaceMaskMap), SAMPLER_SUBSURFACE_MASKMAP_IDX, ADD_IDX(layerTexCoord.base)).r;
surfaceData.subsurfaceMask *= SAMPLE_UVMAPPING_TEXTURE2D(ADD_IDX(_SubsurfaceMaskMap), SAMPLER_SUBSURFACE_MASK_MAP_IDX, ADD_IDX(layerTexCoord.base)).r;
#endif
#ifdef _THICKNESSMAP_IDX

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDepthPass.hlsl


// Attributes
#define REQUIRE_TANGENT_TO_WORLD defined(_PIXEL_DISPLACEMENT)
#define REQUIRE_NORMAL defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD || defined(_VERTEX_WIND) || defined(_VERTEX_DISPLACEMENT)
#define REQUIRE_VERTEX_COLOR ((defined(_VERTEX_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT)) && defined(LAYERED_LIT_SHADER) && (defined(_LAYER_MASK_VERTEX_COLOR_MUL) || defined(_LAYER_MASK_VERTEX_COLOR_ADD))) || defined(_VERTEX_WIND)
#define REQUIRE_VERTEX_COLOR (defined(_VERTEX_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT) || (defined(LAYERED_LIT_SHADER) && (defined(_LAYER_MASK_VERTEX_COLOR_MUL) || defined(_LAYER_MASK_VERTEX_COLOR_ADD))) || defined(_VERTEX_WIND))
// This first set of define allow to say which attributes will be use by the mesh in the vertex and domain shader (for tesselation)

#define VARYINGS_NEED_TEXCOORD3
#endif
#endif
#endif
#if REQUIRE_VERTEX_COLOR
#define VARYINGS_NEED_COLOR
#endif
// This include will define the various Attributes/Varyings structure

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitVelocityPass.hlsl


// Attributes
#define REQUIRE_TANGENT_TO_WORLD defined(_PIXEL_DISPLACEMENT)
#define REQUIRE_NORMAL defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD || defined(_VERTEX_WIND) || defined(_VERTEX_DISPLACEMENT)
#define REQUIRE_VERTEX_COLOR ((defined(_VERTEX_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT)) && defined(LAYERED_LIT_SHADER) && (defined(_LAYER_MASK_VERTEX_COLOR_MUL) || defined(_LAYER_MASK_VERTEX_COLOR_ADD))) || defined(_VERTEX_WIND)
#define REQUIRE_VERTEX_COLOR (defined(_VERTEX_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT) || (defined(LAYERED_LIT_SHADER) && (defined(_LAYER_MASK_VERTEX_COLOR_MUL) || defined(_LAYER_MASK_VERTEX_COLOR_ADD))) || defined(_VERTEX_WIND))
// This first set of define allow to say which attributes will be use by the mesh in the vertex and domain shader (for tesselation)

#define VARYINGS_NEED_TEXCOORD3
#endif
#endif
#endif
#if REQUIRE_VERTEX_COLOR
#define VARYINGS_NEED_COLOR
#endif
// This include will define the various Attributes/Varyings structure

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


{
// 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.
// Clear the HTile texture. TODO: move this to ClearBuffers(). Clear operations must be batched!
HDUtils.SetRenderTarget(cmd, hdCamera, 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();
}

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/ApplyDistorsion.compute


#pragma only_renderers d3d11 ps4 xboxone vulkan metal
TEXTURE2D(_DistortionTexture);
TEXTURE2D(_GaussianPyramidColorTexture);
TEXTURE2D(_ColorPyramidTexture);
SamplerState sampler_GaussianPyramidColorTexture;
SamplerState sampler_ColorPyramidTexture;
float4 _GaussianPyramidColorMipSize;
float4 _ColorPyramidScale;
CBUFFER_END
#pragma kernel KMain

// Get source pixel for distortion
float2 distordedUV = float2(dispatchThreadId + int2(distortion * _FetchBias)) * _Size.zw;
float mip = (_GaussianPyramidColorMipSize.z - 1) * clamp(distortionBlur, 0.0, 1.0);
float4 sampled = SAMPLE_TEXTURE2D_LOD(_GaussianPyramidColorTexture, sampler_GaussianPyramidColorTexture, distordedUV, mip);
float mip = (_ColorPyramidScale.z - 1) * clamp(distortionBlur, 0.0, 1.0);
float4 sampled = SAMPLE_TEXTURE2D_LOD(_ColorPyramidTexture, sampler_ColorPyramidTexture, distordedUV, mip);
_CameraColorTexture[dispatchThreadId] = sampled;
}

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


{
class BufferPyramid
{
static readonly int _Size = Shader.PropertyToID("_Size");
static readonly int _Source = Shader.PropertyToID("_Source");
static readonly int _Result = Shader.PropertyToID("_Result");
static readonly int _SrcSize = Shader.PropertyToID("_SrcSize");
const int k_DepthBlockSize = 4;
GPUCopy m_GPUCopy;
ComputeShader m_ColorPyramidCS;
int m_ColorPyramidKernel;
ComputeShader m_DepthPyramidCS;
int m_DepthPyramidKernel_8;
int m_DepthPyramidKernel_1;
public BufferPyramid(
ComputeShader colorPyramidCS,
ComputeShader depthPyramidCS, GPUCopy gpuCopy)
{
m_ColorPyramidCS = colorPyramidCS;
m_ColorPyramidKernel = m_ColorPyramidCS.FindKernel("KMain");
BufferPyramidProcessor m_Processor;
m_DepthPyramidCS = depthPyramidCS;
m_GPUCopy = gpuCopy;
m_DepthPyramidKernel_8 = m_DepthPyramidCS.FindKernel("KMain_8");
m_DepthPyramidKernel_1 = m_DepthPyramidCS.FindKernel("KMain_1");
public BufferPyramid(BufferPyramidProcessor processor)
{
m_Processor = processor;
}
float GetXRscale()

public void CreateBuffers()
{
m_ColorPyramidBuffer = RTHandle.Alloc(size => CalculatePyramidSize(size), filterMode: FilterMode.Trilinear, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, useMipMap: true, autoGenerateMips: false, name: "ColorPymarid");
m_DepthPyramidBuffer = RTHandle.Alloc(size => CalculatePyramidSize(size), filterMode: FilterMode.Trilinear, colorFormat: RenderTextureFormat.RFloat, sRGB: false, useMipMap: true, autoGenerateMips: false, enableRandomWrite: true, name: "DepthPyramid"); // Need randomReadWrite because we downsample the first mip with a compute shader.
m_ColorPyramidBuffer = RTHandle.Alloc(size => CalculatePyramidSize(size), filterMode: FilterMode.Trilinear, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, useMipMap: true, autoGenerateMips: false, enableRandomWrite: true, name: "ColorPyramid");
m_DepthPyramidBuffer = RTHandle.Alloc(size => CalculatePyramidSize(size), filterMode: FilterMode.Trilinear, colorFormat: RenderTextureFormat.RGFloat, sRGB: false, useMipMap: true, autoGenerateMips: false, enableRandomWrite: true, name: "DepthPyramid"); // Need randomReadWrite because we downsample the first mip with a compute shader.
}
public void DestroyBuffers()

int lodCount = GetPyramidLodCount(hdCamera);
UpdatePyramidMips(hdCamera, m_DepthPyramidBuffer.rt.format, m_DepthPyramidMips, lodCount);
cmd.SetGlobalVector(HDShaderIDs._DepthPyramidMipSize, new Vector4(hdCamera.actualWidth, hdCamera.actualHeight, lodCount, 0.0f));
m_GPUCopy.SampleCopyChannel_xyzw2x(cmd, depthTexture, m_DepthPyramidBuffer, new Vector2(hdCamera.actualWidth, hdCamera.actualHeight));
RTHandle src = m_DepthPyramidBuffer;
for (var i = 0; i < lodCount; i++)
{
RTHandle dest = m_DepthPyramidMips[i];
var srcMipWidth = hdCamera.actualWidth >> i;
var srcMipHeight = hdCamera.actualHeight >> i;
var dstMipWidth = srcMipWidth >> 1;
var dstMipHeight = srcMipHeight >> 1;
var kernel = m_DepthPyramidKernel_8;
var kernelBlockSize = 8f;
if (dstMipWidth < 4 * k_DepthBlockSize
|| dstMipHeight < 4 * k_DepthBlockSize)
{
kernel = m_DepthPyramidKernel_1;
kernelBlockSize = 1;
}
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));
cmd.DispatchCompute(
m_DepthPyramidCS,
kernel,
Mathf.CeilToInt(dstMipWidth / kernelBlockSize),
Mathf.CeilToInt(dstMipHeight / kernelBlockSize),
1);
cmd.SetGlobalVector(HDShaderIDs._DepthPyramidSize, new Vector4(hdCamera.actualWidth, hdCamera.actualHeight, 1f / hdCamera.actualWidth, 1f / hdCamera.actualHeight));
cmd.SetGlobalVector(HDShaderIDs._DepthPyramidScale, new Vector4(scale.x, scale.y, lodCount, 0.0f));
// 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;
}
m_Processor.RenderDepthPyramid(
hdCamera.actualWidth, hdCamera.actualHeight,
cmd,
depthTexture,
m_DepthPyramidBuffer,
m_DepthPyramidMips,
lodCount,
scale
);
cmd.SetGlobalTexture(HDShaderIDs._PyramidDepthTexture, m_DepthPyramidBuffer);
cmd.SetGlobalTexture(HDShaderIDs._DepthPyramidTexture, m_DepthPyramidBuffer);
}
public void RenderColorPyramid(

UpdatePyramidMips(hdCamera, m_ColorPyramidBuffer.rt.format, m_ColorPyramidMips, lodCount);
Vector2 scale = GetPyramidToScreenScale(hdCamera);
cmd.SetGlobalVector(HDShaderIDs._GaussianPyramidColorMipSize, new Vector4(scale.x, scale.y, lodCount, 0.0f));
// Copy mip 0
// 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));
RTHandle src = m_ColorPyramidBuffer;
for (var i = 0; i < lodCount; i++)
{
RTHandle dest = m_ColorPyramidMips[i];
var srcMipWidth = hdCamera.actualWidth >> i;
var srcMipHeight = hdCamera.actualHeight >> i;
var dstMipWidth = srcMipWidth >> 1;
var dstMipHeight = srcMipHeight >> 1;
// TODO: Add proper stereo support to the compute job
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));
cmd.DispatchCompute(
m_ColorPyramidCS,
m_ColorPyramidKernel,
Mathf.CeilToInt(dstMipWidth / 8f),
Mathf.CeilToInt(dstMipHeight / 8f),
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);
cmd.SetGlobalVector(HDShaderIDs._ColorPyramidSize, new Vector4(hdCamera.actualWidth, hdCamera.actualHeight, 1f / hdCamera.actualWidth, 1f / hdCamera.actualHeight));
cmd.SetGlobalVector(HDShaderIDs._ColorPyramidScale, new Vector4(scale.x, scale.y, lodCount, 0.0f));
src = dest;
}
m_Processor.RenderColorPyramid(
hdCamera,
cmd,
colorTexture,
m_ColorPyramidBuffer,
m_ColorPyramidMips,
lodCount,
scale
);
cmd.SetGlobalTexture(HDShaderIDs._GaussianPyramidColorTexture, m_ColorPyramidBuffer);
cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, m_ColorPyramidBuffer);
}
}
}

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


ZTest Always
ZWrite On
Blend Off
ColorMask 0
HLSLPROGRAM
#pragma target 4.5

58
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/DepthPyramid.compute


#include "CoreRP/ShaderLibrary/Common.hlsl"
#pragma kernel KMain_8 KERNEL_SIZE=8 KERNEL_NAME=KMain_8
#pragma kernel KMain_1 KERNEL_SIZE=1 KERNEL_NAME=KMain_1
// ------------------------------------------------
// Algorithm
// ------------------------------------------------
// Downsample a depth texture by taking min value of sampled pixels
// ------------------------------------------------
// Variants
// ------------------------------------------------
#pragma kernel KDepthDownSample8 KERNEL_SIZE=8 KERNEL_NAME=KDepthDownSample8
#pragma kernel KDepthDownSample1 KERNEL_SIZE=1 KERNEL_NAME=KDepthDownSample1
Texture2D<float> _Source;
RWTexture2D<float> _Result;
// ------------------------------------------------
// Texture buffers
// ------------------------------------------------
Texture2D<float2> _Source;
RW_TEXTURE2D(float2, _Result);
// ------------------------------------------------
// Constant buffers
// ------------------------------------------------
int2 _RectOffset; // Offset in source texture
// ------------------------------------------------
// Kernel
// ------------------------------------------------
#if UNITY_REVERSED_Z
# define MIN_DEPTH(l, r) max(l, r)
# define MAX_DEPTH(l, r) min(l, r)
#else
# define MIN_DEPTH(l, r) min(l, r)
# define MAX_DEPTH(l, r) max(l, r)
#endif
int2 threadUL = dispatchThreadId;
uint2 srcPixelUL = _RectOffset + (dispatchThreadId << 1);
// Offset by 0.5 so sampling get the proper pixels
float2 offset = float2(srcPixelUL) + 0.5;
// Downsample the block
float2 offset = float2(threadUL) * 2.0f + 1.0f;
float4 depths = GATHER_RED_TEXTURE2D(_Source, sampler_PointClamp, offset * _SrcSize.zw, 0.0);
float4 depths = GATHER_RED_TEXTURE2D(_Source, sampler_PointClamp, offset * _SrcSize.zw, 0.0).wzxy;
// Downsample the block
float p00 = SAMPLE_TEXTURE2D_LOD(_Source, sampler_PointClamp, (offset) * _SrcSize.zw, 0.0).x;
float p10 = SAMPLE_TEXTURE2D_LOD(_Source, sampler_PointClamp, (offset + float2(1.0, 0.0)) * _SrcSize.zw, 0.0).x;
float p01 = SAMPLE_TEXTURE2D_LOD(_Source, sampler_PointClamp, (offset + float2(0.0, 1.0)) * _SrcSize.zw, 0.0).x;

// Select the nearest sample
#if UNITY_REVERSED_Z
float minDepth = max(max(depths.x, depths.y), max(depths.z, depths.w));
#else
float minDepth = min(min(depths.x, depths.y), min(depths.z, depths.w));
#endif
float minDepth = MIN_DEPTH(MIN_DEPTH(depths.x, depths.y), MIN_DEPTH(depths.z, depths.w));
float maxDepth = MAX_DEPTH(MAX_DEPTH(depths.x, depths.y), MAX_DEPTH(depths.z, depths.w));
_Result[dispatchThreadId] = minDepth;
uint2 dstPixel = (_RectOffset >> 1) + dispatchThreadId;
_Result[dstPixel] = float2(minDepth, maxDepth);
#undef MIN_DEPTH
#undef MAX_DEPTH

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


colorPyramidCS: {fileID: 7200000, guid: 4e3267a1135742441a14298d8dcac04a, type: 3}
depthPyramidCS: {fileID: 7200000, guid: 64a553bb564274041906f78ffba955e4, type: 3}
copyChannelCS: {fileID: 7200000, guid: a4d45eda75e8e474dbe24a31f741f3b4, type: 3}
texturePaddingCS: {fileID: 7200000, guid: 6736f53014c69f84aa2130aeae99730b, type: 3}
applyDistortionCS: {fileID: 7200000, guid: 2fa6c0e3fe6dc3145a4156f21913fe5c, type: 3}
clearDispatchIndirectShader: {fileID: 7200000, guid: fc1f553acb80a6446a32d33e403d0656,
type: 3}

type: 3}
deferredDirectionalShadowComputeShader: {fileID: 7200000, guid: fbde6fae193b2a94e9fd97c163c204f4,
type: 3}
volumetricLightingCS: {fileID: 7200000, guid: 799166e2ee6a4b041bba9e74f6942097,
volumeVoxelizationCS: {fileID: 7200000, guid: c20b371db720da244b73830ec74a343a,
type: 3}
volumetricLightingCS: {fileID: 7200000, guid: b4901a10df2d1e24282725e9fbc77c97,
type: 3}
subsurfaceScatteringCS: {fileID: 7200000, guid: b06a7993621def248addd55d0fe931b1,
type: 3}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/RenderPipelineResources.cs


public ComputeShader colorPyramidCS;
public ComputeShader depthPyramidCS;
public ComputeShader copyChannelCS;
public ComputeShader texturePaddingCS;
public ComputeShader applyDistortionCS;
// Lighting tile pass resources

public ComputeShader buildMaterialFlagsShader;
public ComputeShader deferredComputeShader;
public ComputeShader deferredDirectionalShadowComputeShader;
public ComputeShader volumeVoxelizationCS;
public ComputeShader volumetricLightingCS;
public ComputeShader subsurfaceScatteringCS; // Disney SSS

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPass.cs


LightTransport,
Shadows,
SubsurfaceScattering,
VolumeVoxelization,
VolumetricLighting,
DBuffer
}

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPass.cs.hlsl


#define SHADERPASS_LIGHT_TRANSPORT (7)
#define SHADERPASS_SHADOWS (8)
#define SHADERPASS_SUBSURFACE_SCATTERING (9)
#define SHADERPASS_VOLUMETRIC_LIGHTING (10)
#define SHADERPASS_DBUFFER (11)
#define SHADERPASS_VOLUME_VOXELIZATION (10)
#define SHADERPASS_VOLUMETRIC_LIGHTING (11)
#define SHADERPASS_DBUFFER (12)
#endif

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


public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap)
{
m_SkyHDRIMaterial.SetTexture(HDShaderIDs._Cubemap, m_HdriSkyParams.hdriSky);
m_SkyHDRIMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_HdriSkyParams.exposure, m_HdriSkyParams.multiplier, -m_HdriSkyParams.rotation, 0.0f)); // -rotation to match Legacy...
m_SkyHDRIMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(GetExposure(m_HdriSkyParams, builtinParams.debugSettings), m_HdriSkyParams.multiplier, -m_HdriSkyParams.rotation, 0.0f)); // -rotation to match Legacy...
// This matrix needs to be updated at the draw call frequency.
m_PropertyBlock.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);

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


sunDirection = -builtinParams.sunLight.transform.forward;
}
m_ProceduralSkyMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_ProceduralSkyParams.exposure, m_ProceduralSkyParams.multiplier, 0.0f, 0.0f));
m_ProceduralSkyMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(GetExposure(m_ProceduralSkyParams, builtinParams.debugSettings), m_ProceduralSkyParams.multiplier, 0.0f, 0.0f));
m_ProceduralSkyMaterial.SetFloat(_SunSizeParam, m_ProceduralSkyParams.sunSize);
m_ProceduralSkyMaterial.SetFloat(_SunSizeConvergenceParam, m_ProceduralSkyParams.sunSizeConvergence);
m_ProceduralSkyMaterial.SetFloat(_AtmoshpereThicknessParam, m_ProceduralSkyParams.atmosphereThickness);

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


public RTHandle depthBuffer;
public HDCamera hdCamera;
public DebugDisplaySettings debugSettings;
public static RenderTargetIdentifier nullRT = -1;
}

m_SkyRenderingContext.Cleanup();
}
public bool IsSkyValid()
public bool IsLightingSkyValid()
public bool IsVisualSkyValid()
{
return m_VisualSky.IsValid();
}
void BlitCubemap(CommandBuffer cmd, Cubemap source, RenderTexture dest)
{

m_UpdateRequired = false;
SetGlobalSkyTexture(cmd);
if (IsSkyValid())
if (IsLightingSkyValid())
{
cmd.SetGlobalInt(HDShaderIDs._EnvLightSkyEnabled, 1);
}

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

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyRenderer.cs


// renderForCubemap: When rendering into a cube map, no depth buffer is available so user has to make sure not to use depth testing or the depth texture.
public abstract void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap);
public abstract bool IsValid();
protected float GetExposure(SkySettings skySettings, DebugDisplaySettings debugSettings)
{
float debugExposure = 0.0f;
if(debugSettings != null && debugSettings.DebugNeedsExposure())
{
debugExposure = debugSettings.lightingDebugSettings.debugExposure;
}
return skySettings.exposure + debugExposure;
}
}
}

部分文件因为文件数量过多而无法显示

正在加载...
取消
保存