浏览代码

Merge branch 'master' into decals/texture_atlas

# Conflicts:
#	ScriptableRenderPipeline/Core/CoreRP/CoreResources/TexturePadding.compute
#	ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs
/main
Paul Melamed 6 年前
当前提交
5e4ad2d7
共有 144 个文件被更改,包括 6107 次插入3537 次删除
  1. 8
      CHANGELOG.md
  2. 999
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1102_Unlit_Distortion.unity.png
  3. 998
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1103_Unlit_Distortion_DepthTest.unity.png
  4. 998
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1203_Lit_Transparent.unity.png
  5. 999
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction.unity.png
  6. 999
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity.png
  7. 999
      ImageTemplates/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward.unity.png
  8. 4
      ScriptableRenderPipeline/Core/CHANGELOG.md
  9. 1
      ScriptableRenderPipeline/Core/CoreRP/CoreResources/GPUCopy.compute
  10. 1
      ScriptableRenderPipeline/Core/CoreRP/CoreResources/GPUCopyAsset.cs
  11. 5
      ScriptableRenderPipeline/Core/CoreRP/CoreResources/TexturePadding.compute
  12. 10
      ScriptableRenderPipeline/Core/CoreRP/CoreResources/TexturePadding.cs
  13. 1
      ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugUI.Panel.cs
  14. 3
      ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugUI.cs
  15. 15
      ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugWindow.cs
  16. 5
      ScriptableRenderPipeline/Core/CoreRP/Editor/ShaderGenerator/CSharpToHLSL.cs
  17. 2
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/EntityLighting.hlsl
  18. 15
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDAdditionalCameraData.cs
  19. 275
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs
  20. 121
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs.hlsl
  21. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.hlsl
  22. 84
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugFullScreen.shader
  23. 18
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/LightingDebug.cs
  24. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/LightingDebug.cs.hlsl
  25. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/SerializedHDCamera.cs
  26. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/EditorRenderPipelineResources/ReflectionProbesPreview.shader
  27. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs
  28. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Drawers.cs
  29. 17
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Handles.cs
  30. 45
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs
  31. 34
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/LitUI.cs
  32. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/HDRenderPipelineEditor.cs
  33. 133
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
  34. 22
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs
  35. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs
  36. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs
  37. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  38. 157
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.hlsl
  39. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopDef.hlsl
  40. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-bigtile.compute
  41. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-clustered.compute
  42. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild.compute
  43. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/materialflags.compute
  44. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/scrbound.compute
  45. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumeVoxelization.compute
  46. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/DiffusionProfile/DiffusionProfileSettings.cs
  47. 79
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs
  48. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLit.shader
  49. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitData.hlsl
  50. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitTessellation.shader
  51. 19
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.cs
  52. 15
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.cs.hlsl
  53. 177
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl
  54. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.shader
  55. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitTessellation.shader
  56. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDepthPass.hlsl
  57. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitVelocityPass.hlsl
  58. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs
  59. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Unlit/Unlit.shader
  60. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/ApplyDistorsion.compute
  61. 167
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/BufferPyramid.cs
  62. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CopyDepthBuffer.shader
  63. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs
  64. 4
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Materials/PreRefractionPassTester.mat
  65. 30
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Default_Sky.asset
  66. 926
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction.unity
  67. 5
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Plane_NM.mat
  68. 6
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Plane_NM_Thickness.mat
  69. 5
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Plane_Thickness.mat
  70. 5
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Sphere_NM.mat
  71. 6
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Sphere_NM_Thickness.mat
  72. 5
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Sphere_Thickness.mat
  73. 6
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Sphere_HiZ.mat
  74. 6
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Plane_HiZ.mat
  75. 16
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/ComplexMaterial_Flipped.mat
  76. 46
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat_H.png.meta
  77. 4
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat__N.png.meta
  78. 4
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/GlassLike.mat
  79. 3
      Tests/Scripts/GraphicTests/Framework/TestFrameworkTools.cs
  80. 49
      ScriptableRenderPipeline/Core/CoreRP/Debugging/MousePositionDebug.cs
  81. 8
      ScriptableRenderPipeline/Core/CoreRP/Common.meta
  82. 8
      ScriptableRenderPipeline/Core/CoreRP/Textures.meta
  83. 8
      ScriptableRenderPipeline/Core/CoreRP/Utilities.meta
  84. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDAdditionalCameraEditor.cs
  85. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDAdditionalCameraEditor.cs.meta
  86. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/AdditionalShadowDataEditor.cs
  87. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/AdditionalShadowDataEditor.cs.meta
  88. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDAdditionalLightDataEditor.cs
  89. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDAdditionalLightDataEditor.cs.meta
  90. 42
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/ScreenSpaceRefractionEditor.cs
  91. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/ScreenSpaceRefractionEditor.cs.meta
  92. 38
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ScreenSpaceRefraction.cs
  93. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ScreenSpaceRefraction.cs.meta
  94. 498
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ScreenSpaceTracing.hlsl
  95. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ScreenSpaceTracing.hlsl.meta
  96. 235
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/BufferPyramidProcessor.cs
  97. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/BufferPyramidProcessor.cs.meta

8
CHANGELOG.md


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)
- Screen Space Refraction projection model (Proxy raycasting, HiZ raymarching)
- Screen Space Refraction settings as volume component
- 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
- Screen Space Refraction proxy model uses the proxy of the first environment light (Reflection probe/Planar probe) or the sky
## [0.1.6] - 2018-xx-yy

999
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1102_Unlit_Distortion.unity.png
文件差异内容过多而无法显示
查看文件

998
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1103_Unlit_Distortion_DepthTest.unity.png
文件差异内容过多而无法显示
查看文件

998
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1203_Lit_Transparent.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward.unity.png
文件差异内容过多而无法显示
查看文件

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

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


// Autogenerated file. Do not edit by hand
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
#include "../ShaderLibrary/Common.hlsl"
CBUFFER_START (UnityCBuffer)

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


// Compute Shader
cc.AppendLine(@"// Autogenerated file. Do not edit by hand");
cc.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

5
ScriptableRenderPipeline/Core/CoreRP/CoreResources/TexturePadding.compute


// Texture buffers
// ------------------------------------------------
RW_TEXTURE2D(float4, _Source);
RW_TEXTURE2D(float4, _InOutTexture);
// ------------------------------------------------
// Constant buffers

const int2 loadId = targetId - int2(1 + dispatchThreadId.x, 0);
#endif
//_Source[targetId] = LOAD_TEXTURE2D_LOD(_Source, loadId, 0);
_Source[targetId] = _Source[loadId];
_InOutTexture[targetId] = _InOutTexture[loadId];
}

10
ScriptableRenderPipeline/Core/CoreRP/CoreResources/TexturePadding.cs


public class TexturePadding
{
static readonly int _RectOffset = Shader.PropertyToID("_RectOffset");
static readonly int _Source = Shader.PropertyToID("_Source");
static readonly int _InOutTexture = Shader.PropertyToID("_InOutTexture");
ComputeShader m_CS;
int m_KMainTopRight;

m_KMainTop = m_CS.FindKernel("KMainTop");
m_KMainRight = m_CS.FindKernel("KMainRight");
}
public void Pad(CommandBuffer cmd, RTHandle source, RectInt from, RectInt to)
public void Pad(CommandBuffer cmd, RenderTexture inOutTexture, RectInt from, RectInt to)
cmd.SetComputeTextureParam(m_CS, m_KMainRight, _Source, source);
cmd.SetComputeTextureParam(m_CS, m_KMainRight, _InOutTexture, inOutTexture);
cmd.SetComputeTextureParam(m_CS, m_KMainTop, _Source, source);
cmd.SetComputeTextureParam(m_CS, m_KMainTop, _InOutTexture, inOutTexture);
cmd.SetComputeTextureParam(m_CS, m_KMainTopRight, _Source, source);
cmd.SetComputeTextureParam(m_CS, m_KMainTopRight, _InOutTexture, inOutTexture);
cmd.DispatchCompute(m_CS, m_KMainTopRight, to.width - from.width, to.height - from.height, 1);
}
}

1
ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugUI.Panel.cs


public bool isEditorOnly { get { return (flags & Flags.EditorOnly) != 0; } }
public bool isRuntimeOnly { get { return (flags & Flags.RuntimeOnly) != 0; } }
public bool editorForceUpdate { get { return (flags & Flags.EditorForceUpdate) != 0; } }
public ObservableList<Widget> children { get; private set; }
public event Action<Panel> onSetDirty = delegate { };

3
ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugUI.cs


{
None = 0,
EditorOnly = 1 << 1,
RuntimeOnly = 1 << 2
RuntimeOnly = 1 << 2,
EditorForceUpdate = 1 << 3
}
// Base class for all debug UI widgets

15
ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugWindow.cs


// First init
m_DebugTreeState = DebugManager.instance.GetState();
UpdateWidgetStates();
EditorApplication.update -= Repaint;
var panels = DebugManager.instance.panels;
var selectedPanelIndex = m_Settings.selectedPanel;
if (selectedPanelIndex >= 0
&& selectedPanelIndex < panels.Count
&& panels[selectedPanelIndex].editorForceUpdate)
EditorApplication.update += Repaint;
}
// Note: this won't get called if the window is opened when the editor itself is closed

if (EditorGUI.EndChangeCheck())
{
Undo.RegisterCompleteObjectUndo(m_Settings, "Debug Panel Selection");
var previousPanel = m_Settings.selectedPanel >= 0 && m_Settings.selectedPanel < panels.Count
? panels[m_Settings.selectedPanel]
: null;
if (previousPanel != null && previousPanel.editorForceUpdate && !panel.editorForceUpdate)
EditorApplication.update -= Repaint;
else if ((previousPanel == null || !previousPanel.editorForceUpdate) && panel.editorForceUpdate)
EditorApplication.update += Repaint;
m_Settings.selectedPanel = i;
}
}

5
ScriptableRenderPipeline/Core/CoreRP/Editor/ShaderGenerator/CSharpToHLSL.cs


s_TypeName = new Dictionary<string, ShaderTypeGenerator>();
// Iterate over assemblyList, discover all applicable types with fully qualified names
var assemblyList = AppDomain.CurrentDomain.GetAssemblies().ToList();
var assemblyList = AppDomain.CurrentDomain.GetAssemblies()
// We need to exclude dynamic assemblies (their type can't be queried, throwing an exception below)
.Where(ass => !(ass.ManifestModule is System.Reflection.Emit.ModuleBuilder))
.ToList();
foreach (var assembly in assemblyList)
{

2
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/EntityLighting.hlsl


#ifndef UNITY_ENTITY_LIGHTING_INCLUDED
#define UNITY_ENTITY_LIGHTING_INCLUDED
#include "common.hlsl"
#include "Common.hlsl"
// TODO: Check if PI is correctly handled!

15
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDAdditionalCameraData.cs


// Tag as dirty so frameSettings are correctly initialize at next HDRenderPipeline.Render() call
m_frameSettingsIsDirty = true;
}
// This is called at the creation of the HD Additional Camera Data, to convert the legacy camera settings to HD
public static void InitDefaultHDAdditionalCameraData(HDAdditionalCameraData cameraData)
{
var camera = cameraData.gameObject.GetComponent<Camera>();
cameraData.clearDepth = camera.clearFlags != CameraClearFlags.Nothing;
if (camera.clearFlags == CameraClearFlags.Skybox)
cameraData.clearColorMode = ClearColorMode.Sky;
else if (camera.clearFlags == CameraClearFlags.SolidColor)
cameraData.clearColorMode = ClearColorMode.BackgroundColor;
else // None
cameraData.clearColorMode = ClearColorMode.None;
}
}
}

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


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine.Experimental.Rendering.HDPipeline.Attributes;

PreRefractionColorPyramid,
DepthPyramid,
FinalColorPyramid,
ScreenSpaceTracing,
MaxLightingFullScreenDebug,
// Rendering

MaxRenderingFullScreenDebug
}
[GenerateHLSL]
public struct ScreenSpaceTracingDebug
{
// Used to debug SSRay model
// 1x32 bits
public Lit.RefractionSSRayModel tracingModel;
// 6x32 bits
public uint loopStartPositionSSX; // Proxy, HiZ
public uint loopStartPositionSSY; // Proxy, HiZ
public float loopStartLinearDepth; // Proxy, HiZ
public Vector3 loopRayDirectionSS; // HiZ
public uint loopMipLevelMax; // HiZ
public uint loopIterationMax; // HiZ
// 9x32 bits
public Vector3 iterationPositionSS; // HiZ
public uint iterationMipLevel; // HiZ
public uint iteration; // HiZ
public float iterationLinearDepthBuffer; // HiZ
public Lit.HiZIntersectionKind iterationIntersectionKind; // HiZ
public uint iterationCellSizeW; // HiZ
public uint iterationCellSizeH; // HiZ
public EnvShapeType proxyShapeType; // Proxy
public float projectionDistance; // Proxy
// 4x32 bits
public bool endHitSuccess; // Proxy, HiZ
public float endLinearDepth; // Proxy, HiZ
public uint endPositionSSX; // Proxy, HiZ
public uint endPositionSSY; // Proxy, HiZ
// 0x32 bits (padding)
public Vector2 loopStartPositionSS { get { return new Vector2(loopStartPositionSSX, loopStartPositionSSY); } }
public Vector2 endPositionSS { get { return new Vector2(endPositionSSX, endPositionSSY); } }
public Vector2 iterationCellId { get { return new Vector2(((int)iterationPositionSS.x) >> (int)iterationMipLevel, ((int)iterationPositionSS.y) >> (int)iterationMipLevel); } }
public Vector2 iterationCellSize { get { return new Vector2(iterationCellSizeW, iterationCellSizeH); } }
}
public class DebugDisplaySettings
{
public static string k_PanelDisplayStats = "Display Stats";

public static string k_PanelScreenSpaceTracing = "Screen Space Tracing";
static readonly string[] k_HiZIntersectionKind = { "None", "Depth", "Cell" };
DebugUI.Widget[] m_DebugScreenSpaceTracingItems;
public bool showSSRayGrid = true;
public bool showSSRayDepthPyramid = true;
public MaterialDebugSettings materialDebugSettings = new MaterialDebugSettings();
public LightingDebugSettings lightingDebugSettings = new LightingDebugSettings();

public static int[] lightingFullScreenDebugValues = null;
public static GUIContent[] renderingFullScreenDebugStrings = null;
public static int[] renderingFullScreenDebugValues = null;
public static GUIContent[] debugScreenSpaceTracingProxyStrings = null;
public static int[] debugScreenSpaceTracingProxyValues = null;
public static GUIContent[] debugScreenSpaceTracingHiZStrings = null;
public static int[] debugScreenSpaceTracingHiZValues = null;
Lit.RefractionSSRayModel m_LastSSRayModel = Lit.RefractionSSRayModel.None;
ScreenSpaceTracingDebug m_ScreenSpaceTracingDebugData;
public ScreenSpaceTracingDebug screenSpaceTracingDebugData
{
get { return m_ScreenSpaceTracingDebugData; }
internal set
{
m_ScreenSpaceTracingDebugData = value;
if (m_LastSSRayModel != m_ScreenSpaceTracingDebugData.tracingModel)
{
m_LastSSRayModel = m_ScreenSpaceTracingDebugData.tracingModel;
RefreshScreenSpaceTracingDebug<Lit.RefractionSSRayModel>(null, m_LastSSRayModel);
}
if (m_ScreenSpaceTracingDebugData.tracingModel != Lit.RefractionSSRayModel.HiZ)
{
showSSRayDepthPyramid = false;
showSSRayGrid = false;
}
}
}
var debugScreenSpaceTracingStrings = Enum.GetNames(typeof(DebugScreenSpaceTracing))
.Select(s => new GUIContent(s))
.ToArray();
var debugScreenSpaceTracingValues = (int[])Enum.GetValues(typeof(DebugScreenSpaceTracing));
var debugScreenSpaceTracingHiZStringsList = new List<GUIContent>();
var debugScreenSpaceTracingProxyStringsList = new List<GUIContent>();
var debugScreenSpaceTracingHiZValueList = new List<int>();
var debugScreenSpaceTracingProxyValueList = new List<int>();
for (int i = 0, c = debugScreenSpaceTracingStrings.Length; i < c; ++i)
{
var g = debugScreenSpaceTracingStrings[i];
var v = debugScreenSpaceTracingValues[i];
if (!g.text.StartsWith("Proxy"))
{
debugScreenSpaceTracingHiZStringsList.Add(g);
debugScreenSpaceTracingHiZValueList.Add(v);
}
if (!g.text.StartsWith("HiZ"))
{
debugScreenSpaceTracingProxyStringsList.Add(g);
debugScreenSpaceTracingProxyValueList.Add(v);
}
}
debugScreenSpaceTracingHiZStrings = debugScreenSpaceTracingHiZStringsList.ToArray();
debugScreenSpaceTracingHiZValues = debugScreenSpaceTracingHiZValueList.ToArray();
debugScreenSpaceTracingProxyStrings = debugScreenSpaceTracingProxyStringsList.ToArray();
debugScreenSpaceTracingProxyValues = debugScreenSpaceTracingProxyValueList.ToArray();
}
public int GetDebugMaterialIndex()

public DebugLightingMode GetDebugLightingMode()
{
return lightingDebugSettings.debugLightingMode;
}
public int GetDebugLightingSubMode()
{
switch (lightingDebugSettings.debugLightingMode)
{
case DebugLightingMode.ScreenSpaceTracingRefraction:
case DebugLightingMode.ScreenSpaceTracingReflection:
return (int)lightingDebugSettings.debugScreenSpaceTracingMode;
default:
return 0;
}
}
public DebugMipMapMode GetDebugMipMapMode()

mipMapDebugSettings.debugMipMapMode = value;
}
bool IsScreenSpaceTracingRefractionDebugEnabled()
{
return fullScreenDebugMode == FullScreenDebugMode.ScreenSpaceTracing
&& lightingDebugSettings.debugLightingMode == DebugLightingMode.ScreenSpaceTracingRefraction;
}
void SetScreenSpaceTracingRefractionDebugEnabled(bool value)
{
if (value)
{
lightingDebugSettings.debugLightingMode = DebugLightingMode.ScreenSpaceTracingRefraction;
fullScreenDebugMode = FullScreenDebugMode.ScreenSpaceTracing;
}
else
{
lightingDebugSettings.debugLightingMode = DebugLightingMode.None;
fullScreenDebugMode = FullScreenDebugMode.None;
}
}
void SetScreenSpaceTracingRefractionDebugMode(int value)
{
var val = (DebugScreenSpaceTracing)value;
if (val != DebugScreenSpaceTracing.None)
{
lightingDebugSettings.debugLightingMode = DebugLightingMode.ScreenSpaceTracingRefraction;
lightingDebugSettings.debugScreenSpaceTracingMode = (DebugScreenSpaceTracing)value;
}
else
{
lightingDebugSettings.debugLightingMode = DebugLightingMode.None;
lightingDebugSettings.debugScreenSpaceTracingMode = DebugScreenSpaceTracing.None;
}
}
public void UpdateMaterials()
{
//if (mipMapDebugSettings.debugMipMapMode != 0)

panel.children.Add(m_DebugDisplayStatsItems);
}
void RegisterScreenSpaceTracingDebug()
{
var list = new List<DebugUI.Container>();
var refractionContainer = new DebugUI.Container
{
displayName = "Refraction",
children =
{
new DebugUI.BoolField { displayName = "Debug Enabled", getter = IsScreenSpaceTracingRefractionDebugEnabled, setter = SetScreenSpaceTracingRefractionDebugEnabled, onValueChanged = RefreshScreenSpaceTracingDebug },
}
};
list.Add(refractionContainer);
if (IsScreenSpaceTracingRefractionDebugEnabled())
{
var debugSettingsContainer = new DebugUI.Container
{
displayName = "Debug Settings",
children =
{
new DebugUI.Value { displayName = string.Empty, getter = () => "Click in the scene view, or press 'End' key to select the pixel under the mouse in the scene view to debug." },
new DebugUI.Value { displayName = "SSRay Model", getter = () => screenSpaceTracingDebugData.tracingModel }
}
};
refractionContainer.children.Add(debugSettingsContainer);
switch (screenSpaceTracingDebugData.tracingModel)
{
case Lit.RefractionSSRayModel.Proxy:
{
debugSettingsContainer.children.Add(
new DebugUI.EnumField { displayName = "Debug Mode", getter = GetDebugLightingSubMode, setter = SetScreenSpaceTracingRefractionDebugMode, enumNames = debugScreenSpaceTracingProxyStrings, enumValues = debugScreenSpaceTracingProxyValues, onValueChanged = RefreshScreenSpaceTracingDebug }
);
refractionContainer.children.Add(
new DebugUI.Container
{
displayName = "Debug Values",
children =
{
new DebugUI.Value { displayName = "Hit Success", getter = () => screenSpaceTracingDebugData.endHitSuccess },
new DebugUI.Value { displayName = "Proxy Shape", getter = () => screenSpaceTracingDebugData.proxyShapeType },
new DebugUI.Value { displayName = "Projection Distance", getter = () => screenSpaceTracingDebugData.projectionDistance },
new DebugUI.Value { displayName = "Start Position", getter = () => screenSpaceTracingDebugData.loopStartPositionSS },
new DebugUI.Value { displayName = "Start Linear Depth", getter = () => screenSpaceTracingDebugData.loopStartLinearDepth },
new DebugUI.Value { displayName = "End Linear Depth", getter = () => screenSpaceTracingDebugData.endLinearDepth },
new DebugUI.Value { displayName = "End Position", getter = () => screenSpaceTracingDebugData.endPositionSS },
}
}
);
break;
}
case Lit.RefractionSSRayModel.HiZ:
{
debugSettingsContainer.children.Insert(1, new DebugUI.Value { displayName = string.Empty, getter = () => "Press PageUp/PageDown to Increase/Decrease the HiZ step." });
debugSettingsContainer.children.Add(
new DebugUI.EnumField { displayName = "Debug Mode", getter = GetDebugLightingSubMode, setter = SetScreenSpaceTracingRefractionDebugMode, enumNames = debugScreenSpaceTracingHiZStrings, enumValues = debugScreenSpaceTracingHiZValues, onValueChanged = RefreshScreenSpaceTracingDebug },
new DebugUI.BoolField { displayName = "Display Grid", getter = () => showSSRayGrid, setter = v => showSSRayGrid = v },
new DebugUI.BoolField { displayName = "Display Depth", getter = () => showSSRayDepthPyramid, setter = v => showSSRayDepthPyramid = v }
);
refractionContainer.children.Add(
new DebugUI.Container
{
displayName = "Debug Values (loop)",
children =
{
new DebugUI.Value { displayName = "Hit Success", getter = () => screenSpaceTracingDebugData.endHitSuccess },
new DebugUI.Value { displayName = "Start Position", getter = () => screenSpaceTracingDebugData.loopStartPositionSS },
new DebugUI.Value { displayName = "Start Linear Depth", getter = () => screenSpaceTracingDebugData.loopStartLinearDepth },
new DebugUI.Value { displayName = "Ray Direction SS", getter = () => new Vector2(screenSpaceTracingDebugData.loopRayDirectionSS.x, screenSpaceTracingDebugData.loopRayDirectionSS.y) },
new DebugUI.Value { displayName = "Ray Depth", getter = () => 1f / screenSpaceTracingDebugData.loopRayDirectionSS.z },
new DebugUI.Value { displayName = "End Position", getter = () => screenSpaceTracingDebugData.endPositionSS },
new DebugUI.Value { displayName = "End Linear Depth", getter = () => screenSpaceTracingDebugData.endLinearDepth },
}
},
new DebugUI.Container
{
displayName = "Debug Values (iteration)",
children =
{
new DebugUI.Value { displayName = "Iteration", getter = () => string.Format("{0}/{1}", screenSpaceTracingDebugData.iteration, screenSpaceTracingDebugData.loopIterationMax) },
new DebugUI.Value { displayName = "Position SS", getter = () => new Vector2(screenSpaceTracingDebugData.iterationPositionSS.x, screenSpaceTracingDebugData.iterationPositionSS.y) },
new DebugUI.Value { displayName = "Depth", getter = () => 1f / screenSpaceTracingDebugData.iterationPositionSS.z },
new DebugUI.Value { displayName = "Depth Buffer", getter = () => screenSpaceTracingDebugData.iterationLinearDepthBuffer },
new DebugUI.Value { displayName = "Mip Level", getter = () => string.Format("{0}/{1}", screenSpaceTracingDebugData.iterationMipLevel, screenSpaceTracingDebugData.loopMipLevelMax) },
new DebugUI.Value { displayName = "Intersection kind", getter = () => screenSpaceTracingDebugData.iterationIntersectionKind },
new DebugUI.Value { displayName = "Cell Id", getter = () => screenSpaceTracingDebugData.iterationCellId },
new DebugUI.Value { displayName = "Cell Size", getter = () => screenSpaceTracingDebugData.iterationCellSize },
}
}
);
break;
}
}
}
m_DebugScreenSpaceTracingItems = list.ToArray();
var panel = DebugManager.instance.GetPanel(k_PanelScreenSpaceTracing, true);
panel.flags |= DebugUI.Flags.EditorForceUpdate;
panel.children.Add(m_DebugScreenSpaceTracingItems);
}
public void RegisterMaterialDebug()
{
m_DebugMaterialItems = new DebugUI.Widget[]

RegisterLightingDebug();
}
void RefreshScreenSpaceTracingDebug<T>(DebugUI.Field<T> field, T value)
{
UnregisterDebugItems(k_PanelScreenSpaceTracing, m_DebugScreenSpaceTracingItems);
RegisterScreenSpaceTracingDebug();
}
public void RegisterLightingDebug()
{
var list = new List<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);

RegisterMaterialDebug();
RegisterLightingDebug();
RegisterRenderingDebug();
RegisterScreenSpaceTracingDebug();
}
public void UnregisterDebug()

UnregisterDebugItems(k_PanelLighting, m_DebugLightingItems);
UnregisterDebugItems(k_PanelRendering, m_DebugRenderingItems);
UnregisterDebugItems(k_PanelScreenSpaceTracing, m_DebugScreenSpaceTracingItems);
}
void UnregisterDebugItems(string panelName, DebugUI.Widget[] items)

121
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs.hlsl


#define FULLSCREENDEBUGMODE_PRE_REFRACTION_COLOR_PYRAMID (4)
#define FULLSCREENDEBUGMODE_DEPTH_PYRAMID (5)
#define FULLSCREENDEBUGMODE_FINAL_COLOR_PYRAMID (6)
#define FULLSCREENDEBUGMODE_MAX_LIGHTING_FULL_SCREEN_DEBUG (7)
#define FULLSCREENDEBUGMODE_MIN_RENDERING_FULL_SCREEN_DEBUG (8)
#define FULLSCREENDEBUGMODE_MOTION_VECTORS (9)
#define FULLSCREENDEBUGMODE_NAN_TRACKER (10)
#define FULLSCREENDEBUGMODE_MAX_RENDERING_FULL_SCREEN_DEBUG (11)
#define FULLSCREENDEBUGMODE_SCREEN_SPACE_TRACING (7)
#define FULLSCREENDEBUGMODE_MAX_LIGHTING_FULL_SCREEN_DEBUG (8)
#define FULLSCREENDEBUGMODE_MIN_RENDERING_FULL_SCREEN_DEBUG (9)
#define FULLSCREENDEBUGMODE_MOTION_VECTORS (10)
#define FULLSCREENDEBUGMODE_NAN_TRACKER (11)
#define FULLSCREENDEBUGMODE_MAX_RENDERING_FULL_SCREEN_DEBUG (12)
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.ScreenSpaceTracingDebug
// PackingRules = Exact
struct ScreenSpaceTracingDebug
{
int tracingModel;
uint loopStartPositionSSX;
uint loopStartPositionSSY;
float loopStartLinearDepth;
float3 loopRayDirectionSS;
uint loopMipLevelMax;
uint loopIterationMax;
float3 iterationPositionSS;
uint iterationMipLevel;
uint iteration;
float iterationLinearDepthBuffer;
int iterationIntersectionKind;
uint iterationCellSizeW;
uint iterationCellSizeH;
int proxyShapeType;
float projectionDistance;
bool endHitSuccess;
float endLinearDepth;
uint endPositionSSX;
uint endPositionSSY;
};
//
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.ScreenSpaceTracingDebug
//
int GetTracingModel(ScreenSpaceTracingDebug value)
{
return value.tracingModel;
}
uint GetLoopStartPositionSSX(ScreenSpaceTracingDebug value)
{
return value.loopStartPositionSSX;
}
uint GetLoopStartPositionSSY(ScreenSpaceTracingDebug value)
{
return value.loopStartPositionSSY;
}
float GetLoopStartLinearDepth(ScreenSpaceTracingDebug value)
{
return value.loopStartLinearDepth;
}
float3 GetLoopRayDirectionSS(ScreenSpaceTracingDebug value)
{
return value.loopRayDirectionSS;
}
uint GetLoopMipLevelMax(ScreenSpaceTracingDebug value)
{
return value.loopMipLevelMax;
}
uint GetLoopIterationMax(ScreenSpaceTracingDebug value)
{
return value.loopIterationMax;
}
float3 GetIterationPositionSS(ScreenSpaceTracingDebug value)
{
return value.iterationPositionSS;
}
uint GetIterationMipLevel(ScreenSpaceTracingDebug value)
{
return value.iterationMipLevel;
}
uint GetIteration(ScreenSpaceTracingDebug value)
{
return value.iteration;
}
float GetIterationLinearDepthBuffer(ScreenSpaceTracingDebug value)
{
return value.iterationLinearDepthBuffer;
}
int GetIterationIntersectionKind(ScreenSpaceTracingDebug value)
{
return value.iterationIntersectionKind;
}
uint GetIterationCellSizeW(ScreenSpaceTracingDebug value)
{
return value.iterationCellSizeW;
}
uint GetIterationCellSizeH(ScreenSpaceTracingDebug value)
{
return value.iterationCellSizeH;
}
int GetProxyShapeType(ScreenSpaceTracingDebug value)
{
return value.proxyShapeType;
}
float GetProjectionDistance(ScreenSpaceTracingDebug value)
{
return value.projectionDistance;
}
bool GetEndHitSuccess(ScreenSpaceTracingDebug value)
{
return value.endHitSuccess;
}
float GetEndLinearDepth(ScreenSpaceTracingDebug value)
{
return value.endLinearDepth;
}
uint GetEndPositionSSX(ScreenSpaceTracingDebug value)
{
return value.endPositionSSX;
}
uint GetEndPositionSSY(ScreenSpaceTracingDebug value)
{
return value.endPositionSSY;
}
#endif

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


CBUFFER_START(UnityDebugDisplay)
// Set of parameters available when switching to debug shader mode
int _DebugLightingMode; // Match enum DebugLightingMode
int _DebugLightingSubMode;
int _DebugStep;
float4 _MouseClickPixelCoord; // xy unorm, zw norm
RWStructuredBuffer<ScreenSpaceTracingDebug> _DebugScreenSpaceTracingData;
void GetPropertiesDataDebug(uint paramId, inout float3 result, inout bool needLinearToSRGB)
{

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


#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/Color.hlsl"
#include "CoreRP/ShaderLibrary/Debug.hlsl"
#include "HDRP/Material/Lit/Lit.cs.hlsl"
TEXTURE2D(_DebugFullScreenTexture);
CBUFFER_START (UnityDebug)
float _ShowGrid;
float _ShowDepthPyramidDebug;
CBUFFER_END
TEXTURE2D(_DebugFullScreenTexture);
TEXTURE2D(_DepthPyramidTexture);
StructuredBuffer<ScreenSpaceTracingDebug> _DebugScreenSpaceTracingData;
struct Attributes
{

PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_VP);
float linearDepth = frac(posInput.linearDepth * 0.1);
return float4(linearDepth.xxx, 1.0);
}
if (_FullScreenDebugMode == FULLSCREENDEBUGMODE_SCREEN_SPACE_TRACING)
{
const float circleRadius = 3.5;
const float ringSize = 1.5;
float4 color = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, s_point_clamp_sampler, input.texcoord);
ScreenSpaceTracingDebug debug = _DebugScreenSpaceTracingData[0];
// Fetch Depth Buffer and Position Inputs
const float deviceDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, int2(input.positionCS.xy) >> debug.iterationMipLevel, debug.iterationMipLevel).r;
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, deviceDepth, UNITY_MATRIX_I_VP, UNITY_MATRIX_VP);
float4 col = float4(0, 0, 0, 1);
// Common Pre Specific
// Fetch debug data
const uint2 loopStartPositionSS = uint2(debug.loopStartPositionSSX, debug.loopStartPositionSSY);
const uint2 endPositionSS = uint2(debug.endPositionSSX, debug.endPositionSSY);
float distanceToPosition = FLT_MAX;
float positionSDF = 0;
// Start position dot rendering
const float distanceToStartPosition = length(int2(posInput.positionSS) - int2(loopStartPositionSS));
const float startPositionSDF = clamp(circleRadius - distanceToStartPosition, 0, 1);
// Line rendering
const float distanceToRaySegment = DistanceToSegment(posInput.positionSS, loopStartPositionSS, endPositionSS);
const float raySegmentSDF = clamp(1 - distanceToRaySegment, 0, 1);
float cellSDF = 0;
float debugLinearDepth = 0;
if (debug.tracingModel == REFRACTIONSSRAYMODEL_HI_Z)
{
const uint2 iterationCellSize = uint2(debug.iterationCellSizeW, debug.iterationCellSizeH);
const float hasData = iterationCellSize.x != 0 || iterationCellSize.y != 0;
// Position dot rendering
distanceToPosition = length(int2(posInput.positionSS) - int2(debug.iterationPositionSS.xy));
positionSDF = clamp(circleRadius - distanceToPosition, 0, 1);
// Grid rendering
float2 distanceToCell = float2(posInput.positionSS % iterationCellSize);
distanceToCell = min(distanceToCell, float2(iterationCellSize) - distanceToCell);
distanceToCell = clamp(1 - distanceToCell, 0, 1);
cellSDF = max(distanceToCell.x, distanceToCell.y) * _ShowGrid;
debugLinearDepth = posInput.linearDepth;
}
col = float4(
( GetIndexColor(1) * startPositionSDF
+ GetIndexColor(3) * positionSDF
+ GetIndexColor(5) * cellSDF
+ GetIndexColor(7) * raySegmentSDF
),
col.a
);
// Common Post Specific
// Calculate SDF to draw a ring on both dots
const float startPositionRingDistance = abs(distanceToStartPosition - circleRadius);
const float startPositionRingSDF = clamp(ringSize - startPositionRingDistance, 0, 1);
const float positionRingDistance = abs(distanceToPosition - circleRadius);
const float positionRingSDF = clamp(ringSize - positionRingDistance, 0, 1);
const float w = clamp(1 - startPositionRingSDF - positionRingSDF, 0, 1);
col.rgb = col.rgb * w + float3(1, 1, 1) * (1 - w);
if (_ShowDepthPyramidDebug == 1)
color.rgb = frac(float3(debugLinearDepth, debugLinearDepth, debugLinearDepth) * 0.1);
col = float4(col.rgb * col.a + color.rgb, 1);
return col;
}
return float4(0.0, 0.0, 0.0, 0.0);

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


IndirectSpecularGtaoFromSsao,
EnvironmentProxyVolume,
EnvironmentSampleCoordinates,
ScreenSpaceTracingRefraction,
ScreenSpaceTracingReflection
}
[GenerateHLSL]
public enum DebugScreenSpaceTracing
{
None,
Color,
RayDirWS,
HitDepth,
HitSuccess,
HiZPositionNDC,
HiZRayDirNDC,
HiZIterationCount,
HiZMaxUsedMipLevel,
HiZIntersectionKind
}
public enum ShadowMapDebugMode

}
public DebugLightingMode debugLightingMode = DebugLightingMode.None;
public DebugScreenSpaceTracing debugScreenSpaceTracingMode = DebugScreenSpaceTracing.None;
public ShadowMapDebugMode shadowDebugMode = ShadowMapDebugMode.None;
public bool shadowDebugUseSelection = false;
public uint shadowMapIndex = 0;

16
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/LightingDebug.cs.hlsl


#define DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_GTAO_FROM_SSAO (8)
#define DEBUGLIGHTINGMODE_ENVIRONMENT_PROXY_VOLUME (9)
#define DEBUGLIGHTINGMODE_ENVIRONMENT_SAMPLE_COORDINATES (10)
#define DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFRACTION (11)
#define DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFLECTION (12)
//
// UnityEngine.Experimental.Rendering.HDPipeline.DebugScreenSpaceTracing: static fields
//
#define DEBUGSCREENSPACETRACING_NONE (0)
#define DEBUGSCREENSPACETRACING_COLOR (1)
#define DEBUGSCREENSPACETRACING_RAY_DIR_WS (2)
#define DEBUGSCREENSPACETRACING_HIT_DEPTH (3)
#define DEBUGSCREENSPACETRACING_HIT_SUCCESS (4)
#define DEBUGSCREENSPACETRACING_HI_ZPOSITION_NDC (5)
#define DEBUGSCREENSPACETRACING_HI_ZRAY_DIR_NDC (6)
#define DEBUGSCREENSPACETRACING_HI_ZITERATION_COUNT (7)
#define DEBUGSCREENSPACETRACING_HI_ZMAX_USED_MIP_LEVEL (8)
#define DEBUGSCREENSPACETRACING_HI_ZINTERSECTION_KIND (9)
#endif

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/SerializedHDCamera.cs


public SerializedHDCamera(SerializedObject serializedObject)
{
this.serializedObject = serializedObject;
var additionals = CoreEditorUtils.GetAdditionalData<HDAdditionalCameraData>(serializedObject.targetObjects);
var additionals = CoreEditorUtils.GetAdditionalData<HDAdditionalCameraData>(serializedObject.targetObjects, HDAdditionalCameraData.InitDefaultHDAdditionalCameraData);
hideFlags.intValue = (int)HideFlags.HideInInspector;
// We don't hide additional camera data anymore on UX team request. To be compatible with already author scene we force to be visible
//hideFlags.intValue = (int)HideFlags.HideInInspector;
hideFlags.intValue = (int)HideFlags.None;
serializedAdditionalDataObject.ApplyModifiedProperties();
//backgroundColor = serializedObject.FindProperty("m_BackGroundColor");

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/EditorRenderPipelineResources/ReflectionProbesPreview.shader


#pragma vertex vert
#pragma fragment frag
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "HDRP/ShaderVariables.hlsl"
struct appdata

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


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:

// Internal utilities
void ApplyAdditionalComponentsVisibility(bool hide)
{
var flags = hide ? HideFlags.HideInInspector : HideFlags.None;
// UX team decided thta we should always show component in inspector.
// However already authored scene save this settings, so force the component to be visible
// var flags = hide ? HideFlags.HideInInspector : HideFlags.None;
var flags = HideFlags.None;
foreach (var t in m_SerializedAdditionalLightData.targetObjects)
((HDAdditionalLightData)t).hideFlags = flags;

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);

34
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/LitUI.cs


public static GUIContent normalMapSpaceWarning = new GUIContent("Object space normal can't be use with triplanar mapping.");
// Transparency
public static string refractionModeText = "Refraction Mode";
public static string refractionModelText = "Refraction Model";
public static GUIContent refractionSSRayModelText = new GUIContent("SSRay Model", "Screen Space Ray Model");
public static GUIContent refractionIorText = new GUIContent("Index of refraction", "Index of refraction");
public static GUIContent refractionThicknessText = new GUIContent("Refraction Thickness", "Thickness for rough refraction");
public static GUIContent refractionThicknessMultiplierText = new GUIContent("Refraction Thickness multiplier (m)", "Thickness multiplier");

protected const string kATDistance = "_ATDistance";
protected MaterialProperty thicknessMultiplier = null;
protected const string kThicknessMultiplier = "_ThicknessMultiplier";
protected MaterialProperty refractionMode = null;
protected const string kRefractionMode = "_RefractionMode";
protected MaterialProperty refractionModel = null;
protected const string kRefractionModel = "_RefractionModel";
protected MaterialProperty refractionSSRayModel = null;
protected const string kRefractionSSRayModel = "_RefractionSSRayModel";
get { return refractionMode == null || refractionMode.floatValue == 0f; }
get { return refractionModel == null || refractionModel.floatValue == 0f; }
}
protected void FindMaterialLayerProperties(MaterialProperty[] props)

coatMaskMap = FindProperty(kCoatMaskMap, props);
// Transparency
refractionMode = FindProperty(kRefractionMode, props, false);
refractionModel = FindProperty(kRefractionModel, props, false);
refractionSSRayModel = FindProperty(kRefractionSSRayModel, props, false);
transmittanceColor = FindProperty(kTransmittanceColor, props, false);
transmittanceColorMap = FindProperty(kTransmittanceColorMap, props, false);
atDistance = FindProperty(kATDistance, props, false);

var surfaceTypeValue = (SurfaceType)surfaceType.floatValue;
if (surfaceTypeValue == SurfaceType.Transparent
&& refractionMode != null)
&& refractionModel != null)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(StylesBaseUnlit.TransparencyInputsText, EditorStyles.boldLabel);

if (refractionMode != null
if (refractionModel != null
m_MaterialEditor.ShaderProperty(refractionMode, Styles.refractionModeText);
var mode = (Lit.RefractionMode)refractionMode.floatValue;
if (mode != Lit.RefractionMode.None)
m_MaterialEditor.ShaderProperty(refractionModel, Styles.refractionModelText);
var mode = (Lit.RefractionModel)refractionModel.floatValue;
if (mode != Lit.RefractionModel.None)
m_MaterialEditor.ShaderProperty(refractionSSRayModel, Styles.refractionSSRayModelText);
m_MaterialEditor.ShaderProperty(ior, Styles.refractionIorText);
blendMode.floatValue = (float)BlendMode.Alpha;

CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_IRIDESCENCE", materialId == BaseLitGUI.MaterialId.LitIridescence);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SPECULAR_COLOR", materialId == BaseLitGUI.MaterialId.LitSpecular);
var refractionModeValue = (Lit.RefractionMode)material.GetFloat(kRefractionMode);
var refractionModelValue = (Lit.RefractionModel)material.GetFloat(kRefractionModel);
var refractionSSRayModelValue = (Lit.RefractionSSRayModel)material.GetFloat(kRefractionSSRayModel);
CoreUtils.SetKeyword(material, "_REFRACTION_PLANE", (refractionModeValue == Lit.RefractionMode.Plane) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SPHERE", (refractionModeValue == Lit.RefractionMode.Sphere) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_PLANE", (refractionModelValue == Lit.RefractionModel.Plane) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SPHERE", (refractionModelValue == Lit.RefractionModel.Sphere) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SSRAY_PROXY", (refractionSSRayModelValue == Lit.RefractionSSRayModel.Proxy) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SSRAY_HIZ", (refractionSSRayModelValue == Lit.RefractionSSRayModel.HiZ) && canHaveRefraction);
}
}
} // namespace UnityEditor

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;

133
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs


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
ComputeBuffer m_DebugScreenSpaceTracingData = null;
ScreenSpaceTracingDebug[] m_DebugScreenSpaceTracingDataArray = new ScreenSpaceTracingDebug[1];
SetRenderingFeatures();
m_ValidAPI = true;
if (!SetRenderingFeatures())
{
m_ValidAPI = false;
return ;
}
m_BufferPyramid = new BufferPyramid(
var bufferPyramidProcessor = new BufferPyramidProcessor(
);
);
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_LightLoop.Build(asset, m_ShadowSettings, m_IBLFilterGGX);

// We don't need the debug of Scene View at runtime (each camera have its own debug settings)
FrameSettings.RegisterDebug("Scene View", m_Asset.GetFrameSettings());
#endif
m_DebugScreenSpaceTracingData = new ComputeBuffer(1, System.Runtime.InteropServices.Marshal.SizeOf(typeof(ScreenSpaceTracingDebug)));
InitializeRenderTextures();

RTHandle.Release(m_DebugColorPickerBuffer);
RTHandle.Release(m_DebugFullScreenTempBuffer);
m_DebugScreenSpaceTracingData.Release();
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_IBLFilterGGX.Cleanup();
DestroyRenderTextures();
UnsetRenderingFeatures();
#if UNITY_EDITOR
SceneViewDrawMode.ResetDrawMode();

m_DbufferManager.PushGlobalParams(cmd, m_FrameSettings);
m_VolumetricLightingSystem.PushGlobalParams(hdCamera, cmd);
var ssrefraction = VolumeManager.instance.stack.GetComponent<ScreenSpaceRefraction>()
?? ScreenSpaceRefraction.@default;
ssrefraction.PushShaderParameters(cmd);
}
}

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

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

}
}
#endif
PushFullScreenDebugTexture(cmd, m_CameraColorBuffer, hdCamera, FullScreenDebugMode.ScreenSpaceTracing);
// Caution: RenderDebug need to take into account that we have flip the screen (so anything capture before the flip will be flipped)
RenderDebug(hdCamera, cmd);

CommandBufferPool.Release(cmd);
renderContext.Submit();
if (m_CurrentDebugDisplaySettings.fullScreenDebugMode == FullScreenDebugMode.ScreenSpaceTracing)
{
m_DebugScreenSpaceTracingData.GetData(m_DebugScreenSpaceTracingDataArray);
var data = m_DebugScreenSpaceTracingDataArray[0];
m_CurrentDebugDisplaySettings.screenSpaceTracingDebugData = data;
}
} // For each camera
}

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));

}
else
{
// Assign debug data
if (m_CurrentDebugDisplaySettings.fullScreenDebugMode == FullScreenDebugMode.ScreenSpaceTracing
&& pass == ForwardPass.Transparent)
{
cmd.SetGlobalBuffer(HDShaderIDs._DebugScreenSpaceTracingData, m_DebugScreenSpaceTracingData);
cmd.SetRandomWriteTarget(1, m_DebugScreenSpaceTracingData);
}
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer);
if ((m_FrameSettings.enableDBuffer) && (DecalSystem.m_DecalsVisibleThisFrame > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
{

if (m_CurrentDebugDisplaySettings.fullScreenDebugMode == FullScreenDebugMode.ScreenSpaceTracing
&& pass == ForwardPass.Transparent)
{
cmd.ClearRandomWriteTargets();
}
}
}
}

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

cmd.SetGlobalInt(HDShaderIDs._DebugViewMaterial, (int)m_CurrentDebugDisplaySettings.GetDebugMaterialIndex());
cmd.SetGlobalInt(HDShaderIDs._DebugLightingMode, (int)m_CurrentDebugDisplaySettings.GetDebugLightingMode());
cmd.SetGlobalInt(HDShaderIDs._DebugLightingSubMode, (int)m_CurrentDebugDisplaySettings.GetDebugLightingSubMode());
cmd.SetGlobalInt(HDShaderIDs._DebugMipMapMode, (int)m_CurrentDebugDisplaySettings.GetDebugMipMapMode());
cmd.SetGlobalVector(HDShaderIDs._DebugLightingAlbedo, debugAlbedo);

cmd.SetGlobalVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(hdCamera));
cmd.SetGlobalVector(HDShaderIDs._MouseClickPixelCoord, HDUtils.GetMouseClickCoordinates(hdCamera));
cmd.SetGlobalInt(HDShaderIDs._DebugStep, HDUtils.debugStep);
cmd.SetGlobalInt(HDShaderIDs._ShowGrid, m_CurrentDebugDisplaySettings.showSSRayGrid ? 1 : 0);
cmd.SetGlobalInt(HDShaderIDs._ShowDepthPyramidDebug, m_CurrentDebugDisplaySettings.showSSRayDepthPyramid ? 1 : 0);
// 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);

// Everything we have capture is flipped (as it happen before FinalPass/postprocess/Blit. So if we are not in SceneView
// (i.e. we have perform a flip, we need to flip the input texture)
m_DebugFullScreen.SetFloat(HDShaderIDs._RequireToFlipInputTexture, hdCamera.camera.cameraType != CameraType.SceneView ? 1.0f : 0.0f);
m_DebugFullScreen.SetBuffer(HDShaderIDs._DebugScreenSpaceTracingData, m_DebugScreenSpaceTracingData);
m_DebugFullScreen.SetTexture(HDShaderIDs._DepthPyramidTexture, m_BufferPyramid.depthPyramid);
HDUtils.DrawFullScreen(cmd, hdCamera, m_DebugFullScreen, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget);
PushColorPickerDebugTexture(cmd, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget, hdCamera);

22
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs


public static readonly int _ViewTilesFlags = Shader.PropertyToID("_ViewTilesFlags");
public static readonly int _MousePixelCoord = Shader.PropertyToID("_MousePixelCoord");
public static readonly int _MouseClickPixelCoord = Shader.PropertyToID("_MouseClickPixelCoord");
public static readonly int _DebugStep = Shader.PropertyToID("_DebugStep");
public static readonly int _DebugScreenSpaceTracingData = Shader.PropertyToID("_DebugScreenSpaceTracingData");
public static readonly int _ShowGrid = Shader.PropertyToID("_ShowGrid");
public static readonly int _ShowDepthPyramidDebug = Shader.PropertyToID("_ShowDepthPyramidDebug");
public static readonly int _DebugLightingSubMode = Shader.PropertyToID("_DebugLightingSubMode");
public static readonly int _DebugLightingAlbedo = Shader.PropertyToID("_DebugLightingAlbedo");
public static readonly int _DebugLightingSmoothness = Shader.PropertyToID("_DebugLightingSmoothness");
public static readonly int _DebugLightingNormal = Shader.PropertyToID("_DebugLightingNormal");

Shader.PropertyToID("_SSSBufferTexture3"),
};
public static readonly int _SSRefractionRayMinLevel = Shader.PropertyToID("_SSRefractionRayMinLevel");
public static readonly int _SSRefractionRayMaxLevel = Shader.PropertyToID("_SSRefractionRayMaxLevel");
public static readonly int _SSRefractionRayMaxIterations = Shader.PropertyToID("_SSRefractionRayMaxIterations");
public static readonly int _SSRefractionRayDepthSuccessBias = Shader.PropertyToID("_SSRefractionRayDepthSuccessBias");
public static readonly int _SSRefractionInvScreenWeightDistance = Shader.PropertyToID("_SSRefractionInvScreenWeightDistance");
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");

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs


return null;
}
}
public static int debugStep { get { return MousePositionDebug.instance.debugStep; } }
static MaterialPropertyBlock s_PropertyBlock = new MaterialPropertyBlock();

public static Vector4 GetMouseCoordinates(HDCamera camera)
{
Vector2 mousePixelCoord = MousePositionDebug.instance.GetMousePosition(camera.screenSize.y);
return new Vector4(mousePixelCoord.x, mousePixelCoord.y, camera.scaleBias.x * mousePixelCoord.x / camera.screenSize.x, camera.scaleBias.y * mousePixelCoord.y / camera.screenSize.y);
}
// Returns mouse click coordinates: (x,y) in pixels and (z,w) normalized inside the render target (not the viewport)
public static Vector4 GetMouseClickCoordinates(HDCamera camera)
{
Vector2 mousePixelCoord = MousePositionDebug.instance.GetMouseClickPosition(camera.screenSize.y);
return new Vector4(mousePixelCoord.x, mousePixelCoord.y, camera.scaleBias.x * mousePixelCoord.x / camera.screenSize.x, camera.scaleBias.y * mousePixelCoord.y / camera.screenSize.y);
}
}

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


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

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


public void RenderDeferredDirectionalShadow(HDCamera hdCamera, RTHandle deferredShadowRT, RenderTargetIdentifier depthTexture, CommandBuffer cmd)
{
if (m_CurrentSunLight == null || m_CurrentSunLight.GetComponent<AdditionalShadowData>() == null)
if (m_CurrentSunLight == null || m_CurrentSunLight.GetComponent<AdditionalShadowData>() == null || m_CurrentSunLightShadowIndex < 0)
{
cmd.SetGlobalTexture(HDShaderIDs._DeferredShadowTexture, RuntimeUtilities.blackTexture);
return;

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

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

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


#include "CoreRP/ShaderLibrary/Macros.hlsl"
//-----------------------------------------------------------------------------
// LightLoop
// ----------------------------------------------------------------------------

float reflectionHierarchyWeight = 0.0; // Max: 1.0
float refractionHierarchyWeight = 0.0; // Max: 1.0
if (featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION)
// First loop iteration is:
// 1. Screen Space Refraction / Reflection
// 2. Environment Reflection / Refraction
// 3. Sky Reflection / Refraction
//
// Following loop iterations are:
// 1. Environment Reflection / Refraction
// 2. Sky Reflection / Refraction
// Common variable for all iterations
// Define macro for a better understanding of the loop
#ifdef LIGHTLOOP_TILE_PASS
uint envLightStart;
# define FETCHINDEX(index) FetchIndex(envLightStart, index);
#else
# define FETCHINDEX(index) index
#endif
uint envLightCount;
#define EVALUATE_BSDF_ENV(envLightData, TYPE, type) {\
IndirectLighting lighting = EvaluateBSDF_Env( context, V, posInput, preLightData, envLightData, bsdfData, \
envLightData.influenceShapeType, \
MERGE_NAME (GPUIMAGEBASEDLIGHTINGTYPE_, TYPE), MERGE_NAME (type, HierarchyWeight)); \
AccumulateIndirectLighting(lighting, aggregateLighting);\
}
// First loop iteration
if (featureFlags & (
LIGHTFEATUREFLAGS_ENV
| LIGHTFEATUREFLAGS_SKY
| LIGHTFEATUREFLAGS_SSREFRACTION
| LIGHTFEATUREFLAGS_SSREFLECTION
)
)
IndirectLighting lighting = EvaluateBSDF_SSLighting(
context,
V,
posInput,
preLightData,
bsdfData,
GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION,
refractionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
}
// Fetch first env light to provide the scene proxy for screen space computation
EnvLightData envLightData;
ZERO_INITIALIZE(EnvLightData, envLightData);
{
#ifdef LIGHTLOOP_TILE_PASS
GetCountAndStart(posInput, LIGHTCATEGORY_ENV, envLightStart, envLightCount);
#else
envLightCount = _EnvLightCount;
#endif
if (envLightCount > 0)
{
uint envLightIndex = FETCHINDEX(0);
envLightData = _EnvLightDatas[envLightIndex];
}
else
envLightData = InitSkyEnvLightData(0);
}
if (featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION)
{
IndirectLighting lighting = EvaluateBSDF_SSLighting( context, V, posInput, preLightData, bsdfData, envLightData,
GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION, refractionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
}
if (featureFlags & LIGHTFEATUREFLAGS_SSREFLECTION)
{
IndirectLighting lighting = EvaluateBSDF_SSLighting( context, V, posInput, preLightData, bsdfData, envLightData,
GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION, reflectionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
}
if ((featureFlags & LIGHTFEATUREFLAGS_ENV) && envLightCount > 0)
{
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES;
EVALUATE_BSDF_ENV(envLightData, REFLECTION, reflection);
if (featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION)
EVALUATE_BSDF_ENV(envLightData, REFRACTION, refraction);
}
// Only apply the sky IBL if the sky texture is available
if ((featureFlags & LIGHTFEATUREFLAGS_SKY) && _EnvLightSkyEnabled)
{
// The sky is a single cubemap texture separate from the reflection probe texture array (different resolution and compression)
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_SKY;
if (featureFlags & LIGHTFEATUREFLAGS_SSREFLECTION)
{
IndirectLighting lighting = EvaluateBSDF_SSLighting(
context,
V,
posInput,
preLightData,
bsdfData,
GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION,
reflectionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
// The sky data are generated on the fly so the compiler can optimize the code
EnvLightData envLightSky = InitSkyEnvLightData(0);
EVALUATE_BSDF_ENV(envLightSky, REFLECTION, reflection);
if (featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION)
EVALUATE_BSDF_ENV(envLightSky, REFRACTION, refraction);
}
// Following loop iterations
if (featureFlags & LIGHTFEATUREFLAGS_ENV || featureFlags & LIGHTFEATUREFLAGS_SKY)
{
// Reflection probes are sorted by volume (in the increasing order).

#ifdef LIGHTLOOP_TILE_PASS
uint envLightStart;
uint envLightCount;
GetCountAndStart(posInput, LIGHTCATEGORY_ENV, envLightStart, envLightCount);
#else
uint envLightCount = _EnvLightCount;
#endif
#ifdef LIGHTLOOP_TILE_PASS
uint envLightIndex = FetchIndex(envLightStart, i);
#else
uint envLightIndex = i;
#endif
IndirectLighting lighting = EvaluateBSDF_Env( context, V, posInput, preLightData, _EnvLightDatas[envLightIndex], bsdfData,
_EnvLightDatas[envLightIndex].influenceShapeType,
GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION, reflectionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
uint envLightIndex = FETCHINDEX(i);
EVALUATE_BSDF_ENV(_EnvLightDatas[envLightIndex], REFLECTION, reflection);
}
// Refraction probe and reflection probe will process exactly the same weight. It will be good for performance to be able to share this computation

{
for (i = 0; i < envLightCount && refractionHierarchyWeight < 1.0; ++i)
{
#ifdef LIGHTLOOP_TILE_PASS
uint envLightIndex = FetchIndex(envLightStart, i);
#else
uint envLightIndex = i;
#endif
IndirectLighting lighting = EvaluateBSDF_Env( context, V, posInput, preLightData, _EnvLightDatas[envLightIndex], bsdfData,
_EnvLightDatas[envLightIndex].influenceShapeType,
GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION, refractionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
uint envLightIndex = FETCHINDEX(i);
EVALUATE_BSDF_ENV(_EnvLightDatas[envLightIndex], REFRACTION, refraction);
}
}
}

// The sky data are generated on the fly so the compiler can optimize the code
EnvLightData envLightSky = InitSkyEnvLightData(0);
IndirectLighting lighting = EvaluateBSDF_Env( context, V, posInput, preLightData, envLightSky, bsdfData,
ENVSHAPETYPE_SKY,
GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION, reflectionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
EVALUATE_BSDF_ENV(envLightSky, REFLECTION, reflection);
}
if (featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION)

// The sky data are generated on the fly so the compiler can optimize the code
EnvLightData envLightSky = InitSkyEnvLightData(0);
IndirectLighting lighting = EvaluateBSDF_Env( context, V, posInput, preLightData, envLightSky, bsdfData,
ENVSHAPETYPE_SKY,
GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION, refractionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
EVALUATE_BSDF_ENV(envLightSky, REFRACTION, refraction);
#undef EVALUATE_BSDF_ENV
#undef FETCHINDEX
// Also Apply indiret diffuse (GI)
// PostEvaluateBSDF will perform any operation wanted by the material and sum everything into diffuseLighting and specularLighting

2
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

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


#pragma kernel BigTileLightListGen
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "LightLoop.cs.hlsl"
#include "LightingConvexHullUtils.hlsl"
#include "SortingComputeUtils.hlsl"

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


#pragma kernel TileLightListGen_DepthRT_MSAA_SrcBigTile LIGHTLISTGEN=TileLightListGen_DepthRT_MSAA_SrcBigTile ENABLE_DEPTH_TEXTURE_BACKPLANE MSAA_ENABLED USE_TWO_PASS_TILED_LIGHTING
#pragma kernel ClearAtomic
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "ShaderBase.hlsl"
#include "LightLoop.cs.hlsl"
#include "LightingConvexHullUtils.hlsl"

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


//#pragma #pragma enable_d3d11_debug_symbols
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "ShaderBase.hlsl"
#include "LightLoop.cs.hlsl"
#include "LightingConvexHullUtils.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/materialflags.compute


// #pragma enable_d3d11_debug_symbols
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "ShaderBase.hlsl"
#include "LightLoop.cs.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/scrbound.compute


#pragma kernel ScreenBoundsAABB
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "LightLoop.cs.hlsl"
#include "LightCullUtils.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumeVoxelization.compute


//--------------------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/GeometryUtils.cs.hlsl"
#include "CoreRP/Utilities/GeometryUtils.cs.hlsl"
#include "../../ShaderVariables.hlsl"
#include "VolumetricLighting.cs.hlsl"

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();
}
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLit.shader


// Include
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/Wind.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.hlsl"

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


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)

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitTessellation.shader


// Include
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/tessellation.hlsl"
#include "CoreRP/ShaderLibrary/Tessellation.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.hlsl"

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


LitClearCoat = 1 << 6
};
[GenerateHLSL(PackingRules.Exact)]
public enum RefractionMode
public enum RefractionModel
[GenerateHLSL]
public enum RefractionSSRayModel
{
None = 0,
Proxy = 1,
HiZ = 2
};
[GenerateHLSL]
public enum HiZIntersectionKind
{
None,
Cell,
Depth
}
//-----------------------------------------------------------------------------
// SurfaceData

15
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.cs.hlsl


#define MATERIALFEATUREFLAGS_LIT_CLEAR_COAT (64)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+RefractionMode: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+RefractionSSRayModel: static fields
//
#define REFRACTIONSSRAYMODEL_NONE (0)
#define REFRACTIONSSRAYMODEL_PROXY (1)
#define REFRACTIONSSRAYMODEL_HI_Z (2)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+HiZIntersectionKind: static fields
#define REFRACTIONMODE_NONE (0)
#define REFRACTIONMODE_PLANE (1)
#define REFRACTIONMODE_SPHERE (2)
#define HIZINTERSECTIONKIND_NONE (0)
#define HIZINTERSECTIONKIND_CELL (1)
#define HIZINTERSECTIONKIND_DEPTH (2)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+SurfaceData: static fields

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


// Rough refraction texture
// Color pyramid (width, height, lodcount, Unused)
TEXTURE2D(_GaussianPyramidColorTexture);
TEXTURE2D(_ColorPyramidTexture);
TEXTURE2D(_PyramidDepthTexture);
TEXTURE2D(_DepthPyramidTexture);
CBUFFER_START(UnityLightingParameters)
// Buffer pyramid
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
// Screen space lighting
float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback
CBUFFER_START(UnityGaussianPyramidParameters)
float4 _GaussianPyramidColorMipSize; // (x,y) = PyramidToScreenScale, z = lodCount
float4 _PyramidDepthMipSize;
// Ambiant occlusion
float4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght
CBUFFER_START(UnityAmbientOcclusionParameters)
float4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght
CBUFFER_END
// Area light textures
// TODO: This one should be set into a constant Buffer at pass frequency (with _Screensize)

#define GBufferType2 float4
#define GBufferType3 float4
#define HAS_REFRACTION (defined(_REFRACTION_PLANE) || defined(_REFRACTION_SPHERE))
#define HAS_REFRACTION (defined(_REFRACTION_PLANE) || defined(_REFRACTION_SPHERE)) && (defined(_REFRACTION_SSRAY_PROXY) || defined(_REFRACTION_SSRAY_HIZ))
#define DEFAULT_SPECULAR_VALUE 0.04

#if HAS_REFRACTION
# include "CoreRP/ShaderLibrary/Refraction.hlsl"
# include "HDRP/Lighting/Reflection/VolumeProjection.hlsl"
# include "HDRP/Lighting/LightDefinition.cs.hlsl"
# define SSRTID Refraction
# include "HDRP/Lighting/Reflection/ScreenSpaceTracing.hlsl"
# undef SSRTID
# if defined(_REFRACTION_PLANE)
# define REFRACTION_MODEL(V, posInputs, bsdfData) RefractionModelPlane(V, posInputs.positionWS, bsdfData.normalWS, bsdfData.ior, bsdfData.thickness)

#endif
float3 EstimateRaycast(float3 V, PositionInputs posInputs, float3 positionWS, float3 rayWS)
{
// For all refraction approximation, to calculate the refracted point in world space,
// 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);
// Get the depth of the approximated back plane
float pyramidDepth = LOAD_TEXTURE2D_LOD(_PyramidDepthTexture, posInputs.positionNDC * (depthSize >> 2), 2).r;
float depth = LinearEyeDepth(pyramidDepth, _ZBufferParams);
// Distance from point to the back plane
float depthFromPositionInput = depth - posInputs.linearDepth;
float offset = dot(-V, positionWS - posInputs.positionWS);
float depthFromPosition = depthFromPositionInput - offset;
float hitDistanceFromPosition = depthFromPosition / dot(-V, rayWS);
return positionWS + rayWS * hitDistanceFromPosition;
}
# if defined(_REFRACTION_SSRAY_PROXY)
# define REFRACTION_SSRAY_IN ScreenSpaceProxyRaycastInput
# define REFRACTION_SSRAY_QUERY(input, hit) ScreenSpaceProxyRaycastRefraction(input, hit)
# elif defined(_REFRACTION_SSRAY_HIZ)
# define REFRACTION_SSRAY_IN ScreenSpaceHiZRaymarchInput
# define REFRACTION_SSRAY_QUERY(input, hit) ScreenSpaceHiZRaymarchRefraction(input, hit)
# endif
#endif
// This method allows us to know at compile time what material features should be removed from the code by Tile (Indepenently of the value of material feature flag per pixel).
// This is only useful for classification during lighting, so it's not needed in EncodeIntoGBuffer and ConvertSurfaceDataToBSDFData (where we always know exactly what the material feature is)

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;

IndirectLighting EvaluateBSDF_SSLighting(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, BSDFData bsdfData,
EnvLightData envLightData,
int GPUImageBasedLightingType,
inout float hierarchyWeight)
{

case GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION:
{
#if HAS_REFRACTION
// Refraction process:
// 1. Depending on the shape model, we calculate the refracted point in world space and the optical depth
// 2. We calculate the screen space position of the refracted point

float3 refractedBackPointWS = EstimateRaycast(V, posInput, preLightData.transparentPositionWS, preLightData.transparentRefractV);
float3 rayOriginWS = preLightData.transparentPositionWS;
float3 rayDirWS = preLightData.transparentRefractV;
#if DEBUG_DISPLAY
int debugMode = DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFRACTION;
bool debug = _DebugLightingMode == debugMode
&& !any(int2(_MouseClickPixelCoord.xy) - int2(posInput.positionSS));
#endif
// Initialize screen space tracing
REFRACTION_SSRAY_IN ssRayInput;
ZERO_INITIALIZE(REFRACTION_SSRAY_IN, ssRayInput);
// Common initialization
ssRayInput.rayOriginWS = rayOriginWS;
ssRayInput.rayDirWS = rayDirWS;
#if DEBUG_DISPLAY
ssRayInput.debug = debug;
#endif
// Algorithm specific initialization
#ifdef _REFRACTION_SSRAY_HIZ
ssRayInput.maxIterations = uint(-1);
#elif _REFRACTION_SSRAY_PROXY
ssRayInput.proxyData = envLightData;
#endif
// 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);
// Perform ray query
ScreenSpaceRayHit hit;
ZERO_INITIALIZE(ScreenSpaceRayHit, hit);
bool hitSuccessful = REFRACTION_SSRAY_QUERY(ssRayInput, hit);
// Debug screen space tracing
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == debugMode
&& _DebugLightingSubMode != DEBUGSCREENSPACETRACING_COLOR)
{
float weight = 1.0;
UpdateLightingHierarchyWeights(hierarchyWeight, weight);
lighting.specularTransmitted = hit.debugOutput;
return lighting;
}
#endif
if (!hitSuccessful)
return lighting;
float2 weightNDC = clamp(min(hit.positionNDC, 1 - hit.positionNDC) * _SSRefractionInvScreenWeightDistance, 0, 1);
weightNDC = weightNDC * weightNDC * (3 - 2 * weightNDC);
float weight = weightNDC.x * weightNDC.y;
float hitDeviceDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, hit.positionSS, 0).r;
float hitLinearDepth = LinearEyeDepth(hitDeviceDepth, _ZBufferParams);
if (refractedBackPointDepth < posInput.linearDepth
|| any(refractedBackPointNDC < 0.0)
|| any(refractedBackPointNDC > 1.0))
if (hitLinearDepth < posInput.linearDepth
|| weight == 0)
// 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;
UpdateLightingHierarchyWeights(hierarchyWeight, weight); // Shouldn't be needed, but safer in case we decide to change hierarchy priority
// Beer-Lamber law for absorption
lighting.specularTransmitted *= preLightData.transparentTransmittance;
float3 preLD = SAMPLE_TEXTURE2D_LOD(
_ColorPyramidTexture,
s_trilinear_clamp_sampler,
hit.positionNDC * _ColorPyramidScale.xy,
preLightData.transparentSSMipLevel
).rgb;
float weight = 1.0;
UpdateLightingHierarchyWeights(hierarchyWeight, weight); // Shouldn't be needed, but safer in case we decide to change hierarchy priority
lighting.specularTransmitted *= (1.0 - preLightData.specularFGD) * weight;
float3 F = preLightData.specularFGD;
lighting.specularTransmitted = (1.0 - F) * preLD.rgb * preLightData.transparentTransmittance * weight;
#else
// No refraction, no need to go further
hierarchyWeight = 1.0;

#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)
switch(_DebugLightingMode)
case DEBUGLIGHTINGMODE_LUX_METER:
}
else if (_DebugLightingMode == DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_OCCLUSION_FROM_SSAO)
{
break;
case DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_OCCLUSION_FROM_SSAO:
}
else if (_DebugLightingMode == DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_OCCLUSION_FROM_SSAO)
{
break;
case DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_OCCLUSION_FROM_SSAO:
}
break;
else if (_DebugLightingMode == DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_GTAO_FROM_SSAO)
{
case DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_GTAO_FROM_SSAO:
}
else if (_DebugLightingMode == DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_GTAO_FROM_SSAO)
{
break;
case DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_GTAO_FROM_SSAO:
}
break;
else if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)
case DEBUGMIPMAPMODE_NONE:
diffuseLighting = bsdfData.diffuseColor;
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
break;
case DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFRACTION:
if (_DebugLightingSubMode != DEBUGSCREENSPACETRACING_COLOR)
diffuseLighting = bsdfData.diffuseColor;
diffuseLighting = lighting.indirect.specularTransmitted;
}
break;
}
#endif
}

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


_TransparentSortPriority("_TransparentSortPriority", Float) = 0
// Transparency
[Enum(None, 0, Plane, 1, Sphere, 2)]_RefractionMode("Refraction Mode", Int) = 0
[Enum(None, 0, Plane, 1, Sphere, 2)]_RefractionModel("Refraction Model", Int) = 0
[Enum(Proxy, 1, HiZ, 2)]_RefractionSSRayModel("Refraction SSRay Model", Int) = 0
_Ior("Index Of Refraction", Range(1.0, 2.5)) = 1.0
_ThicknessMultiplier("Thickness Multiplier", Float) = 1.0
_TransmittanceColor("Transmittance Color", Color) = (1.0, 1.0, 1.0)

#pragma shader_feature _PIXEL_DISPLACEMENT_LOCK_OBJECT_SCALE
#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _ _REFRACTION_PLANE _REFRACTION_SPHERE
#pragma shader_feature _ _REFRACTION_SSRAY_PROXY _REFRACTION_SSRAY_HIZ
#pragma shader_feature _ _EMISSIVE_MAPPING_PLANAR _EMISSIVE_MAPPING_TRIPLANAR
#pragma shader_feature _ _MAPPING_PLANAR _MAPPING_TRIPLANAR

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitTessellation.shader


_TransparentSortPriority("_TransparentSortPriority", Float) = 0
// Transparency
[Enum(None, 0, Plane, 1, Sphere, 2)]_RefractionMode("Refraction Mode", Int) = 0
[Enum(None, 0, Plane, 1, Sphere, 2)]_RefractionModel("Refraction Model", Int) = 0
[Enum(Proxy, 1, HiZ, 2)]_RefractionSSRayModel("Refraction SSRay Model", Int) = 0
_Ior("Index Of Refraction", Range(1.0, 2.5)) = 1.0
_ThicknessMultiplier("Thickness Multiplier", Float) = 1.0
_TransmittanceColor("Transmittance Color", Color) = (1.0, 1.0, 1.0)

#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _ _TESSELLATION_PHONG
#pragma shader_feature _ _REFRACTION_PLANE _REFRACTION_SPHERE
#pragma shader_feature _ _REFRACTION_SSRAY_PROXY _REFRACTION_SSRAY_HIZ
#pragma shader_feature _ _EMISSIVE_MAPPING_PLANAR _EMISSIVE_MAPPING_TRIPLANAR
#pragma shader_feature _ _MAPPING_PLANAR _MAPPING_TRIPLANAR

// Include
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/tessellation.hlsl"
#include "CoreRP/ShaderLibrary/Tessellation.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.hlsl"

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();
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Unlit/Unlit.shader


// Include
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "../../ShaderVariables.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.hlsl"

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;
}

167
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;
TexturePadding m_TexturePadding;
ComputeShader m_ColorPyramidCS;
int m_ColorPyramidKernel;
ComputeShader m_DepthPyramidCS;
int[] m_DepthKernels = null;
int depthKernel8 { get { return m_DepthKernels[0]; } }
int depthKernel1 { get { return m_DepthKernels[1]; } }
public BufferPyramid(
ComputeShader colorPyramidCS,
ComputeShader depthPyramidCS,
GPUCopy gpuCopy,
TexturePadding texturePadding
)
{
m_ColorPyramidCS = colorPyramidCS;
m_ColorPyramidKernel = m_ColorPyramidCS.FindKernel("KMain");
BufferPyramidProcessor m_Processor;
m_DepthPyramidCS = depthPyramidCS;
m_GPUCopy = gpuCopy;
m_DepthKernels = new int[]
public BufferPyramid(BufferPyramidProcessor processor)
m_DepthPyramidCS.FindKernel("KDepthDownSample8"),
m_DepthPyramidCS.FindKernel("KDepthDownSample1")
};
m_TexturePadding = texturePadding;
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_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.
}

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 RectInt(0, 0, hdCamera.actualWidth, hdCamera.actualHeight));
RTHandle src = m_DepthPyramidBuffer;
for (var i = 0; i < lodCount; i++)
{
RTHandle dest = m_DepthPyramidMips[i];
var srcMip = new RectInt(0, 0, hdCamera.actualWidth >> i, hdCamera.actualHeight >> i);
var dstMip = new RectInt(0, 0, srcMip.width >> 1, srcMip.height >> 1);
var kernel = depthKernel1;
var kernelSize = 1;
var srcWorkMip = srcMip;
var dstWorkMip = dstMip;
if (dstWorkMip.width >= 8 && dstWorkMip.height >= 8)
{
srcWorkMip.width = Mathf.CeilToInt(srcWorkMip.width / 16.0f) * 16;
srcWorkMip.height = Mathf.CeilToInt(srcWorkMip.height / 16.0f) * 16;
dstWorkMip.width = srcWorkMip.width >> 1;
dstWorkMip.height = srcWorkMip.height >> 1;
m_TexturePadding.Pad(cmd, src, srcMip, srcWorkMip);
kernel = depthKernel8;
kernelSize = 8;
}
else
{
m_TexturePadding.Pad(cmd, src, srcMip, new RectInt(0, 0, src.rt.width, src.rt.height));
}
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));
cmd.SetComputeTextureParam(m_DepthPyramidCS, kernel, _Source, src);
cmd.SetComputeTextureParam(m_DepthPyramidCS, kernel, _Result, dest);
cmd.SetComputeVectorParam(m_DepthPyramidCS, _SrcSize, new Vector4(
srcWorkMip.width, srcWorkMip.height,
(1.0f / srcWorkMip.width) * scale.x, (1.0f / srcWorkMip.height) * scale.y)
m_Processor.RenderDepthPyramid(
hdCamera.actualWidth, hdCamera.actualHeight,
cmd,
depthTexture,
m_DepthPyramidBuffer,
m_DepthPyramidMips,
lodCount,
scale
cmd.DispatchCompute(
m_DepthPyramidCS,
kernel,
Mathf.CeilToInt(dstWorkMip.width / (float)kernelSize),
Mathf.CeilToInt(dstWorkMip.height / (float)kernelSize),
1
);
var dstMipWidthToCopy = Mathf.Min(dest.rt.width, dstWorkMip.width);
var dstMipHeightToCopy = Mathf.Min(dest.rt.height, dstWorkMip.height);
// 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, dstMipWidthToCopy, dstMipHeightToCopy, m_DepthPyramidBuffer, 0, i + 1, 0, 0);
src = dest;
}
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));
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));
RTHandle src = m_ColorPyramidBuffer;
for (var i = 0; i < lodCount; i++)
{
RTHandle dest = m_ColorPyramidMips[i];
var srcMip = new RectInt(0, 0, hdCamera.actualWidth >> i, hdCamera.actualHeight >> i);
var dstMip = new RectInt(0, 0, srcMip.width >> 1, srcMip.height >> 1);
var srcWorkMip = new RectInt(
0,
0,
Mathf.CeilToInt(srcMip.width / 16.0f) * 16,
Mathf.CeilToInt(srcMip.height / 16.0f) * 16
m_Processor.RenderColorPyramid(
hdCamera,
cmd,
colorTexture,
m_ColorPyramidBuffer,
m_ColorPyramidMips,
lodCount,
scale
var dstWorkMip = new RectInt(0, 0, srcWorkMip.width >> 1, srcWorkMip.height >> 1);
m_TexturePadding.Pad(cmd, src, srcMip, srcWorkMip);
// 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,
dstWorkMip.width / 8,
dstWorkMip.height / 8,
1
);
var dstMipWidthToCopy = Mathf.Min(dest.rt.width, dstWorkMip.width);
var dstMipHeightToCopy = Mathf.Min(dest.rt.height, dstWorkMip.height);
// 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,
dstMipWidthToCopy, dstMipHeightToCopy, m_ColorPyramidBuffer, 0, i + 1, 0, 0
);
src = dest;
}
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

2
ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs


m_PostProcessRenderContext.sourceFormat = m_ColorFormat;
m_PostProcessRenderContext.destination = dest;
m_PostProcessRenderContext.command = cmd;
m_PostProcessRenderContext.flip = true;
m_PostProcessRenderContext.flip = m_CurrCamera.targetTexture == null;
if (opaqueOnly)
{

4
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Materials/PreRefractionPassTester.mat


m_Name: PreRefractionPassTester
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _BLENDMODE_ALPHA _ENABLE_FOG_ON_TRANSPARENT _NORMALMAP_TANGENT_SPACE
_REFRACTION_PLANE _SURFACE_TYPE_TRANSPARENT
_REFRACTION_PLANE _REFRACTION_SSRAY_PROXY _SURFACE_TYPE_TRANSPARENT
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 1
- _RefractionModel: 1
- _RefractionSSRayModel: 1
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

30
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/SkySettings/HDRP_Default_Sky.asset


components:
- {fileID: 114827887035766406}
- {fileID: 114408460862325740}
- {fileID: 114596847542454078}
--- !u!114 &114408460862325740
MonoBehaviour:
m_ObjectHideFlags: 3

hdriSky:
m_OverrideState: 1
m_Value: {fileID: 8900000, guid: fb0bf2eac2381484187ba8a68cdca165, type: 3}
--- !u!114 &114596847542454078
MonoBehaviour:
m_ObjectHideFlags: 3
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5e17fad69ea181b4483974138b566975, type: 3}
m_Name: ScreenSpaceRefraction
m_EditorClassIdentifier:
active: 1
rayMinLevel:
m_OverrideState: 0
m_Value: 2
rayMaxLevel:
m_OverrideState: 0
m_Value: 6
rayMaxIterations:
m_OverrideState: 0
m_Value: 32
rayDepthSuccessBias:
m_OverrideState: 0
m_Value: 0.2
screenWeightDistance:
m_OverrideState: 1
m_Value: 0.05
min: 0
max: 1
--- !u!114 &114827887035766406
MonoBehaviour:
m_ObjectHideFlags: 3

926
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction.unity
文件差异内容过多而无法显示
查看文件

5
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Plane_NM.mat


m_Name: Lit_Refraction_Plane_NM
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _BLENDMODE_ALPHA _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _ENABLE_FOG_ON_TRANSPARENT
_NORMALMAP _NORMALMAP_TANGENT_SPACE _REFRACTION_PLANE _SURFACE_TYPE_TRANSPARENT
_NORMALMAP _NORMALMAP_TANGENT_SPACE _REFRACTION_PLANE _REFRACTION_SSRAY_PROXY
_SURFACE_TYPE_TRANSPARENT
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 1
- _RefractionModel: 1
- _RefractionSSRayModel: 1
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

6
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Plane_NM_Thickness.mat


m_Name: Lit_Refraction_Plane_NM_Thickness
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _BLENDMODE_ALPHA _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _ENABLE_FOG_ON_TRANSPARENT
_NORMALMAP _NORMALMAP_TANGENT_SPACE _REFRACTION_PLANE _SURFACE_TYPE_TRANSPARENT
_THICKNESSMAP
_NORMALMAP _NORMALMAP_TANGENT_SPACE _REFRACTION_PLANE _REFRACTION_SSRAY_PROXY
_SURFACE_TYPE_TRANSPARENT _THICKNESSMAP
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 1
- _RefractionModel: 1
- _RefractionSSRayModel: 1
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

5
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Plane_Thickness.mat


m_Name: Lit_Refraction_Plane_Thickness
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _BLENDMODE_ALPHA _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _ENABLE_FOG_ON_TRANSPARENT
_NORMALMAP_TANGENT_SPACE _REFRACTION_PLANE _SURFACE_TYPE_TRANSPARENT _THICKNESSMAP
_NORMALMAP_TANGENT_SPACE _REFRACTION_PLANE _REFRACTION_SSRAY_PROXY _SURFACE_TYPE_TRANSPARENT
_THICKNESSMAP
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 1
- _RefractionModel: 1
- _RefractionSSRayModel: 1
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

5
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Sphere_NM.mat


m_Name: Lit_Refraction_Sphere_NM
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _BLENDMODE_ALPHA _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _ENABLE_FOG_ON_TRANSPARENT
_NORMALMAP _NORMALMAP_TANGENT_SPACE _REFRACTION_SPHERE _SURFACE_TYPE_TRANSPARENT
_NORMALMAP _NORMALMAP_TANGENT_SPACE _REFRACTION_SPHERE _REFRACTION_SSRAY_PROXY
_SURFACE_TYPE_TRANSPARENT
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 2
- _RefractionModel: 2
- _RefractionSSRayModel: 1
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

6
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Sphere_NM_Thickness.mat


m_Name: Lit_Refraction_Sphere_NM_Thickness
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _BLENDMODE_ALPHA _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _ENABLE_FOG_ON_TRANSPARENT
_NORMALMAP _NORMALMAP_TANGENT_SPACE _REFRACTION_SPHERE _SURFACE_TYPE_TRANSPARENT
_THICKNESSMAP
_NORMALMAP _NORMALMAP_TANGENT_SPACE _REFRACTION_SPHERE _REFRACTION_SSRAY_PROXY
_SURFACE_TYPE_TRANSPARENT _THICKNESSMAP
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 2
- _RefractionModel: 2
- _RefractionSSRayModel: 1
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

5
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Sphere_Thickness.mat


m_Name: Lit_Refraction_Sphere_Thickness
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _BLENDMODE_ALPHA _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _ENABLE_FOG_ON_TRANSPARENT
_NORMALMAP_TANGENT_SPACE _REFRACTION_SPHERE _SURFACE_TYPE_TRANSPARENT _THICKNESSMAP
_NORMALMAP_TANGENT_SPACE _REFRACTION_SPHERE _REFRACTION_SSRAY_PROXY _SURFACE_TYPE_TRANSPARENT
_THICKNESSMAP
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 2
- _RefractionModel: 2
- _RefractionSSRayModel: 1
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

6
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Sphere_HiZ.mat


m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lit_Refraction_Sphere
m_Name: Lit_Refraction_Sphere_HiZ
_NORMALMAP_TANGENT_SPACE _REFRACTION_SPHERE _SURFACE_TYPE_TRANSPARENT
_NORMALMAP_TANGENT_SPACE _REFRACTION_SPHERE _REFRACTION_SSRAY_HIZ _SURFACE_TYPE_TRANSPARENT
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 2
- _RefractionModel: 2
- _RefractionSSRayModel: 2
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

6
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1205_Lit_Transparent_Refraction/Lit_Refraction_Plane_HiZ.mat


m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lit_Refraction_Plane
m_Name: Lit_Refraction_Plane_HiZ
_NORMALMAP_TANGENT_SPACE _REFRACTION_PLANE _SURFACE_TYPE_TRANSPARENT
_NORMALMAP_TANGENT_SPACE _REFRACTION_PLANE _REFRACTION_SSRAY_HIZ _SURFACE_TYPE_TRANSPARENT
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 1
- _RefractionModel: 1
- _RefractionSSRayModel: 2
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

16
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/ComplexMaterial_Flipped.mat


m_PrefabInternal: {fileID: 0}
m_Name: ComplexMaterial_Flipped
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _DEPTHOFFSET_ON _DISPLACEMENT_LOCK_TILING_SCALE _NORMALMAP_TANGENT_SPACE
_PIXEL_DISPLACEMENT _PIXEL_DISPLACEMENT_LOCK_OBJECT_SCALE
m_ShaderKeywords: _DEPTHOFFSET_ON _DISPLACEMENT_LOCK_TILING_SCALE _HEIGHTMAP _MASKMAP
_NORMALMAP _NORMALMAP_TANGENT_SPACE _PIXEL_DISPLACEMENT _PIXEL_DISPLACEMENT_LOCK_OBJECT_SCALE
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BaseColorMap:
m_Texture: {fileID: 2800000, guid: b6df07666246e084ca55b5b8350198d5, type: 3}
m_Texture: {fileID: 2800000, guid: 2634cf73e49fcb441be8dd497e2c6e8e, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BentNormalMap:

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _HeightMap:
m_Texture: {fileID: 2800000, guid: c3ec713a6f2b97f4ea724a902595594b, type: 3}
m_Texture: {fileID: 2800000, guid: 918d9a75a9ac1754db592f3548a52f7c, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _IridescenceMaskMap:

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Texture: {fileID: 2800000, guid: 2634cf73e49fcb441be8dd497e2c6e8e, type: 3}
m_Texture: {fileID: 2800000, guid: e20e6361c7446a1479f49d10c5d054c3, type: 3}
m_Texture: {fileID: 2800000, guid: 9fb31f0c9b4bb5045985f56fac81d86e, type: 3}
m_Texture: {fileID: 2800000, guid: 260e01b71437c7649a10c1dad5b7ca70, type: 3}
m_Texture: {fileID: 2800000, guid: 754c4d2de266018488c6400f53842b7b, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _NormalMapOS:

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 0
- _RefractionModel: 0
- _RefractionSSRayModel: 0
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

46
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat_H.png.meta


mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0

platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: PS4
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Windows Store Apps
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1

4
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat__N.png.meta


mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0

alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureType: 1
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0

4
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/GlassLike.mat


m_Name: GlassLike
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _BLENDMODE_ALPHA _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _ENABLE_FOG_ON_TRANSPARENT
_NORMALMAP_TANGENT_SPACE _REFRACTION_SPHERE _SURFACE_TYPE_TRANSPARENT
_NORMALMAP_TANGENT_SPACE _REFRACTION_SPHERE _REFRACTION_SSRAY_PROXY _SURFACE_TYPE_TRANSPARENT
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 2
- _RefractionModel: 2
- _RefractionSSRayModel: 1
- _SSSAndTransmissionType: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2

3
Tests/Scripts/GraphicTests/Framework/TestFrameworkTools.cs


#if UNITY_EDITOR
string absoluteScenesPath = s_Path.Aggregate(s_RootPath, Path.Combine);
string assetScenesPath = absoluteScenesPath.Replace(Application.dataPath, "");
assetScenesPath = Path.Combine("Assets", assetScenesPath.Remove(0, 1));
string assetScenesPath = absoluteScenesPath.Substring(absoluteScenesPath.IndexOf("Assets"));
string filesPath = Path.Combine(assetScenesPath, _pipelinePath);

49
ScriptableRenderPipeline/Core/CoreRP/Debugging/MousePositionDebug.cs


}
}
public int debugStep
{
get
{
#if UNITY_EDITOR
return m_DebugStep;
#else
return 0;
#endif
}
}
Vector2 m_MouseClickPosition = Vector2.zero;
int m_DebugStep = 0;
switch (Event.current.type)
{
case EventType.MouseDown:
m_MouseClickPosition = m_mousePosition;
break;
case EventType.KeyDown:
switch (Event.current.keyCode)
{
case KeyCode.PageUp:
++m_DebugStep;
sceneview.Repaint();
break;
case KeyCode.PageDown:
m_DebugStep = Mathf.Max(0, m_DebugStep - 1);
sceneview.Repaint();
break;
case KeyCode.End:
// Usefull we you don't want to change the scene viewport but still update the mouse click position
m_MouseClickPosition = m_mousePosition;
sceneview.Repaint();
break;
}
break;
}
}
#endif

}
#endif
return mousePixelCoord;
}
public Vector2 GetMouseClickPosition(float ScreenHeight)
{
#if UNITY_EDITOR
Vector2 mousePixelCoord = m_MouseClickPosition;
mousePixelCoord.y = (ScreenHeight - 1.0f) - mousePixelCoord.y;
return mousePixelCoord;
#else
return Vector2.zero;
#endif
}
}
}

8
ScriptableRenderPipeline/Core/CoreRP/Common.meta


fileFormatVersion: 2
guid: e58bd4f13d26cde488393d3a2e9bf9cd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
ScriptableRenderPipeline/Core/CoreRP/Textures.meta


fileFormatVersion: 2
guid: 89be4d313c8b0fa4c8d2449dbbbf13f0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
ScriptableRenderPipeline/Core/CoreRP/Utilities.meta


fileFormatVersion: 2
guid: f57623255fe8c064bb8297404521464a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDAdditionalCameraEditor.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering
{
[CanEditMultipleObjects]
[CustomEditor(typeof(HDAdditionalCameraData))]
class HDAdditionalCameraDataEditor : Editor
{
public override void OnInspectorGUI()
{
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDAdditionalCameraEditor.cs.meta


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

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/AdditionalShadowDataEditor.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
[CanEditMultipleObjects]
[CustomEditor(typeof(AdditionalShadowData))]
class AdditionalShadowDataEditor : Editor
{
public override void OnInspectorGUI()
{
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/AdditionalShadowDataEditor.cs.meta


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

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDAdditionalLightDataEditor.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
[CanEditMultipleObjects]
[CustomEditor(typeof(HDAdditionalLightData))]
class HDAdditionalLightDataEditor : Editor
{
public override void OnInspectorGUI()
{
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDAdditionalLightDataEditor.cs.meta


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

42
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/ScreenSpaceRefractionEditor.cs


using System.Collections;
using UnityEngine;
using UnityEditor;
using UnityEditor.Experimental.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[CanEditMultipleObjects]
[VolumeComponentEditor(typeof(ScreenSpaceRefraction))]
public class ScreenSpaceRefractionEditor : VolumeComponentEditor
{
SerializedDataParameter m_RayMinLevel;
SerializedDataParameter m_RayMaxLevel;
SerializedDataParameter m_RayMaxIterations;
SerializedDataParameter m_RayDepthSuccessBias;
SerializedDataParameter m_ScreenWeightDistance;
public override void OnEnable()
{
var o = new PropertyFetcher<ScreenSpaceRefraction>(serializedObject);
m_RayMinLevel = Unpack(o.Find(x => x.rayMinLevel));
m_RayMaxLevel = Unpack(o.Find(x => x.rayMaxLevel));
m_RayMaxIterations = Unpack(o.Find(x => x.rayMaxIterations));
m_RayDepthSuccessBias = Unpack(o.Find(x => x.rayDepthSuccessBias));
m_ScreenWeightDistance = Unpack(o.Find(x => x.screenWeightDistance));
}
public override void OnInspectorGUI()
{
EditorGUILayout.LabelField(CoreEditorUtils.GetContent("HiZ Settings"));
PropertyField(m_RayMinLevel, CoreEditorUtils.GetContent("Ray Min Level"));
PropertyField(m_RayMaxLevel, CoreEditorUtils.GetContent("Ray Max Level"));
PropertyField(m_RayMaxIterations, CoreEditorUtils.GetContent("Ray Max Iterations"));
PropertyField(m_RayDepthSuccessBias, CoreEditorUtils.GetContent("Ray Depth Success Bias"));
EditorGUILayout.Separator();
EditorGUILayout.LabelField(CoreEditorUtils.GetContent("Common Settings"));
PropertyField(m_ScreenWeightDistance, CoreEditorUtils.GetContent("Screen Weight Distance"));
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/ScreenSpaceRefractionEditor.cs.meta


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

38
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ScreenSpaceRefraction.cs


using System;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[Serializable]
public class ScreenSpaceRefraction : VolumeComponent
{
static ScreenSpaceRefraction s_Default = null;
public static ScreenSpaceRefraction @default
{
get
{
if (s_Default == null)
{
s_Default = ScriptableObject.CreateInstance<ScreenSpaceRefraction>();
s_Default.hideFlags = HideFlags.HideAndDontSave;
}
return s_Default;
}
}
public IntParameter rayMinLevel = new IntParameter(2);
public IntParameter rayMaxLevel = new IntParameter(6);
public IntParameter rayMaxIterations = new IntParameter(32);
public FloatParameter rayDepthSuccessBias = new FloatParameter(0.1f);
public ClampedFloatParameter screenWeightDistance = new ClampedFloatParameter(0.1f, 0, 1);
public void PushShaderParameters(CommandBuffer cmd)
{
cmd.SetGlobalInt(HDShaderIDs._SSRefractionRayMinLevel, rayMinLevel.value);
cmd.SetGlobalInt(HDShaderIDs._SSRefractionRayMaxLevel, rayMaxLevel.value);
cmd.SetGlobalInt(HDShaderIDs._SSRefractionRayMaxIterations, rayMaxIterations.value);
cmd.SetGlobalFloat(HDShaderIDs._SSRefractionRayDepthSuccessBias, rayDepthSuccessBias.value);
cmd.SetGlobalFloat(HDShaderIDs._SSRefractionInvScreenWeightDistance, 1f / screenWeightDistance.value);
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ScreenSpaceRefraction.cs.meta


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

498
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ScreenSpaceTracing.hlsl


#ifndef UNITY_SCREEN_SPACE_TRACING_INCLUDED
#define UNITY_SCREEN_SPACE_TRACING_INCLUDED
// -------------------------------------------------
// Algorithm uniform parameters
// -------------------------------------------------
const float DepthPlaneBias = 1E-5;
// -------------------------------------------------
// Output
// -------------------------------------------------
struct ScreenSpaceRayHit
{
uint2 positionSS; // Position of the hit point (SS)
float2 positionNDC; // Position of the hit point (NDC)
float linearDepth; // Linear depth of the hit point
#ifdef DEBUG_DISPLAY
float3 debugOutput;
#endif
};
struct ScreenSpaceHiZRaymarchInput
{
float3 rayOriginWS; // Ray origin (WS)
float3 rayDirWS; // Ray direction (WS)
uint maxIterations; // Number of iterations before failing
#ifdef DEBUG_DISPLAY
bool debug;
#endif
};
struct ScreenSpaceProxyRaycastInput
{
float3 rayOriginWS; // Ray origin (WS)
float3 rayDirWS; // Ray direction (WS)
EnvLightData proxyData;
#ifdef DEBUG_DISPLAY
bool debug;
#endif
};
// -------------------------------------------------
// Utilities
// -------------------------------------------------
// Calculate the ray origin and direction in SS
// out positionSS : (x, y, 1/depth)
// out raySS : (x, y, 1/depth)
void CalculateRaySS(
float3 rayOriginWS,
float3 rayDirWS,
uint2 bufferSize,
out float3 positionSS,
out float3 raySS
)
{
float3 positionWS = rayOriginWS;
float3 rayEndWS = rayOriginWS + rayDirWS * 10;
float4 positionCS = ComputeClipSpacePosition(positionWS, GetWorldToHClipMatrix());
float4 rayEndCS = ComputeClipSpacePosition(rayEndWS, GetWorldToHClipMatrix());
float2 positionNDC = ComputeNormalizedDeviceCoordinates(positionWS, GetWorldToHClipMatrix());
float2 rayEndNDC = ComputeNormalizedDeviceCoordinates(rayEndWS, GetWorldToHClipMatrix());
float3 rayStartSS = float3(
positionNDC.xy * bufferSize,
1.0 / positionCS.w); // Screen space depth interpolate properly in 1/z
float3 rayEndSS = float3(
rayEndNDC.xy * bufferSize,
1.0 / rayEndCS.w); // Screen space depth interpolate properly in 1/z
positionSS = rayStartSS;
raySS = rayEndSS - rayStartSS;
}
// Check whether the depth of the ray is above the sampled depth
// Arguments are inversed linear depth
bool IsPositionAboveDepth(float rayDepth, float invLinearDepth)
{
// as depth is inverted, we must invert the check as well
// rayZ > HiZ <=> 1/rayZ < 1/HiZ
return rayDepth > invLinearDepth;
}
// Sample the Depth buffer at a specific mip and linear depth
float LoadDepth(float2 positionSS, int level)
{
float pyramidDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, int2(positionSS.xy) >> level, level).r;
float linearDepth = LinearEyeDepth(pyramidDepth, _ZBufferParams);
return linearDepth;
}
// Sample the Depth buffer at a specific mip and return 1/linear depth
float LoadInvDepth(float2 positionSS, int level)
{
float linearDepth = LoadDepth(positionSS, level);
float invLinearDepth = 1 / linearDepth;
return invLinearDepth;
}
bool CellAreEquals(int2 cellA, int2 cellB)
{
return cellA.x == cellB.x && cellA.y == cellB.y;
}
// Calculate intersection between the ray and the depth plane
// positionSS.z is 1/depth
// raySS.z is 1/depth
float3 IntersectDepthPlane(float3 positionSS, float3 raySS, float invDepth)
{
// The depth of the intersection with the depth plane is: positionSS.z + raySS.z * t = invDepth
float t = (invDepth - positionSS.z) / raySS.z;
// (t<0) When the ray is going away from the depth plane,
// put the intersection away.
// Instead the intersection with the next tile will be used.
// (t>=0) Add a small distance to go through the depth plane.
t = t >= 0.0f ? (t + DepthPlaneBias) : 1E5;
// Return the point on the ray
return positionSS + raySS * t;
}
// Calculate intersection between a ray and a cell
float3 IntersectCellPlanes(
float3 positionSS,
float3 raySS,
float2 invRaySS,
int2 cellId,
uint2 cellSize,
int2 cellPlanes,
float2 crossOffset
)
{
const float SQRT_2 = sqrt(2);
const float CellPlaneBias = 1E-2;
// Planes to check
int2 planes = (cellId + cellPlanes) * cellSize;
// Hit distance to each planes
float2 distanceToCellAxes = float2(planes - positionSS.xy) * invRaySS; // (distance to x axis, distance to y axis)
float t = min(distanceToCellAxes.x, distanceToCellAxes.y)
// Offset by 1E-3 to ensure cell boundary crossing
// This assume that length(raySS.xy) == 1;
+ CellPlaneBias;
// Interpolate screen space to get next test point
float3 testHitPositionSS = positionSS + raySS * t;
return testHitPositionSS;
}
#ifdef DEBUG_DISPLAY
// -------------------------------------------------
// Debug Utilities
// -------------------------------------------------
void DebugComputeCommonOutput(
float3 rayDirWS,
bool hitSuccessful,
inout ScreenSpaceRayHit hit
)
{
switch (_DebugLightingSubMode)
{
case DEBUGSCREENSPACETRACING_RAY_DIR_WS:
hit.debugOutput = rayDirWS * 0.5 + 0.5;
break;
case DEBUGSCREENSPACETRACING_HIT_DEPTH:
hit.debugOutput = frac(hit.linearDepth * 0.1);
break;
case DEBUGSCREENSPACETRACING_HIT_SUCCESS:
hit.debugOutput = hitSuccessful;
break;
}
}
void DebugComputeHiZOutput(
int iteration,
float3 startPositionSS,
float3 rayDirSS,
int maxIterations,
int maxUsedLevel,
int maxMipLevel,
int intersectionKind,
inout ScreenSpaceRayHit hit
)
{
switch (_DebugLightingSubMode)
{
case DEBUGSCREENSPACETRACING_HI_ZPOSITION_NDC:
hit.debugOutput = float3(float2(startPositionSS.xy) * _ScreenSize.zw, 0);
break;
case DEBUGSCREENSPACETRACING_HI_ZITERATION_COUNT:
hit.debugOutput = float(iteration) / float(maxIterations);
break;
case DEBUGSCREENSPACETRACING_HI_ZRAY_DIR_NDC:
hit.debugOutput = float3(rayDirSS.xy * 0.5 + 0.5, frac(0.1 / rayDirSS.z));
break;
case DEBUGSCREENSPACETRACING_HI_ZMAX_USED_MIP_LEVEL:
hit.debugOutput = float(maxUsedLevel) / float(maxMipLevel);
break;
case DEBUGSCREENSPACETRACING_HI_ZINTERSECTION_KIND:
hit.debugOutput = GetIndexColor(intersectionKind);
break;
}
}
#endif
#endif
// -------------------------------------------------
// Algorithm: Proxy raycast
// -------------------------------------------------
#ifdef SSRTID
#define SSRT_SETTING(name, SSRTID) _SS ## SSRTID ## name
#define SSRT_FUNC(name, SSRTID) name ## SSRTID
CBUFFER_START(SSRT_FUNC(UnityScreenSpaceRaymarching, SSRTID))
int SSRT_SETTING(RayMinLevel, SSRTID);
int SSRT_SETTING(RayMaxLevel, SSRTID);
int SSRT_SETTING(RayMaxIterations, SSRTID);
float SSRT_SETTING(RayDepthSuccessBias, SSRTID);
CBUFFER_END
bool SSRT_FUNC(ScreenSpaceProxyRaycast, SSRTID)(
ScreenSpaceProxyRaycastInput input,
out ScreenSpaceRayHit hit
)
{
ZERO_INITIALIZE(ScreenSpaceRayHit, hit);
float3x3 worldToPS = WorldToProxySpace(input.proxyData);
float3 rayOriginPS = WorldToProxyPosition(input.proxyData, worldToPS, input.rayOriginWS);
float3 rayDirPS = mul(input.rayDirWS, worldToPS);
float projectionDistance = 0.0;
switch(input.proxyData.influenceShapeType)
{
case ENVSHAPETYPE_SPHERE:
case ENVSHAPETYPE_SKY:
{
projectionDistance = IntersectSphereProxy(input.proxyData, rayDirPS, rayOriginPS);
break;
}
case ENVSHAPETYPE_BOX:
projectionDistance = IntersectBoxProxy(input.proxyData, rayDirPS, rayOriginPS);
break;
}
float3 hitPositionWS = input.rayOriginWS + input.rayDirWS * projectionDistance;
float4 hitPositionCS = ComputeClipSpacePosition(hitPositionWS, GetWorldToHClipMatrix());
float4 rayOriginCS = ComputeClipSpacePosition(input.rayOriginWS, GetWorldToHClipMatrix());
float2 hitPositionNDC = ComputeNormalizedDeviceCoordinates(hitPositionWS, GetWorldToHClipMatrix());
uint2 hitPositionSS = uint2(hitPositionNDC *_ScreenSize.xy);
float hitLinearDepth = hitPositionCS.w;
hit.positionNDC = hitPositionNDC;
hit.positionSS = hitPositionSS;
hit.linearDepth = hitLinearDepth;
bool hitSuccessful = true;
#ifdef DEBUG_DISPLAY
DebugComputeCommonOutput(input.rayDirWS, hitSuccessful, hit);
if (input.debug)
{
ScreenSpaceTracingDebug debug;
ZERO_INITIALIZE(ScreenSpaceTracingDebug, debug);
float2 rayOriginNDC = ComputeNormalizedDeviceCoordinates(input.rayOriginWS, GetWorldToHClipMatrix());
uint2 rayOriginSS = uint2(rayOriginNDC * _ScreenSize.xy);
debug.tracingModel = REFRACTIONSSRAYMODEL_PROXY;
debug.loopStartPositionSSX = rayOriginSS.x;
debug.loopStartPositionSSY = rayOriginSS.y;
debug.loopStartLinearDepth = rayOriginCS.w;
debug.endHitSuccess = hitSuccessful;
debug.endLinearDepth = hitLinearDepth;
debug.endPositionSSX = hitPositionSS.x;
debug.endPositionSSY = hitPositionSS.y;
debug.proxyShapeType = input.proxyData.influenceShapeType;
debug.projectionDistance = projectionDistance;
_DebugScreenSpaceTracingData[0] = debug;
}
#endif
return hitSuccessful;
}
// -------------------------------------------------
// Algorithm: HiZ raymarching
// -------------------------------------------------
// Based on Yasin Uludag, 2014. "Hi-Z Screen-Space Cone-Traced Reflections", GPU Pro5: Advanced Rendering Techniques
bool SSRT_FUNC(ScreenSpaceHiZRaymarch, SSRTID)(
ScreenSpaceHiZRaymarchInput input,
out ScreenSpaceRayHit hit
)
{
const float2 CROSS_OFFSET = float2(1, 1);
// Initialize loop
ZERO_INITIALIZE(ScreenSpaceRayHit, hit);
bool hitSuccessful = true;
uint iteration = 0u;
int minMipLevel = max(SSRT_SETTING(RayMinLevel, SSRTID), 0);
int maxMipLevel = min(SSRT_SETTING(RayMaxLevel, SSRTID), int(_DepthPyramidScale.z));
uint2 bufferSize = uint2(_DepthPyramidSize.xy);
uint maxIterations = min(input.maxIterations, SSRT_SETTING(RayMaxIterations, SSRTID));
float3 startPositionSS;
float3 raySS;
CalculateRaySS(
input.rayOriginWS,
input.rayDirWS,
bufferSize,
startPositionSS,
raySS
);
#ifdef DEBUG_DISPLAY
// Initialize debug variables
int debugLoopMipMaxUsedLevel = minMipLevel;
int debugIterationMipLevel = minMipLevel;
uint2 debugIterationCellSize = uint2(0u, 0u);
float3 debugIterationPositionSS = float3(0, 0, 0);
uint debugIteration = 0u;
uint debugIterationIntersectionKind = 0u;
float debugIterationLinearDepthBuffer = 0;
#endif
int intersectionKind = 0;
float raySSLength = length(raySS.xy);
raySS /= raySSLength;
// Initialize raymarching
float2 invRaySS = float2(1, 1) / raySS.xy;
// Calculate planes to intersect for each cell
int2 cellPlanes = sign(raySS.xy);
float2 crossOffset = CROSS_OFFSET * cellPlanes;
cellPlanes = clamp(cellPlanes, 0, 1);
int currentLevel = minMipLevel;
uint2 cellCount = bufferSize >> currentLevel;
uint2 cellSize = uint2(1, 1) << currentLevel;
float3 positionSS = startPositionSS;
float invHiZDepth = 0;
while (currentLevel >= minMipLevel)
{
if (iteration >= maxIterations)
{
hitSuccessful = false;
break;
}
cellCount = bufferSize >> currentLevel;
cellSize = uint2(1, 1) << currentLevel;
#ifdef DEBUG_DISPLAY
// Fetch pre iteration debug values
if (input.debug && _DebugStep >= iteration)
debugIterationMipLevel = currentLevel;
#endif
// Go down in HiZ levels by default
int mipLevelDelta = -1;
// Sampled as 1/Z so it interpolate properly in screen space.
invHiZDepth = LoadInvDepth(positionSS.xy, currentLevel);
intersectionKind = HIZINTERSECTIONKIND_NONE;
if (IsPositionAboveDepth(positionSS.z, invHiZDepth))
{
float3 candidatePositionSS = IntersectDepthPlane(positionSS, raySS, invHiZDepth);
intersectionKind = HIZINTERSECTIONKIND_DEPTH;
const int2 cellId = int2(positionSS.xy) / cellSize;
const int2 candidateCellId = int2(candidatePositionSS.xy) / cellSize;
// If we crossed the current cell
if (!CellAreEquals(cellId, candidateCellId))
{
candidatePositionSS = IntersectCellPlanes(
positionSS,
raySS,
invRaySS,
cellId,
cellSize,
cellPlanes,
crossOffset);
intersectionKind = HIZINTERSECTIONKIND_CELL;
// Go up a level to go faster
mipLevelDelta = 1;
}
positionSS = candidatePositionSS;
}
currentLevel = min(currentLevel + mipLevelDelta, maxMipLevel);
#ifdef DEBUG_DISPLAY
// Fetch post iteration debug values
if (input.debug && _DebugStep >= iteration)
{
debugLoopMipMaxUsedLevel = max(debugLoopMipMaxUsedLevel, currentLevel);
debugIterationPositionSS = positionSS;
debugIterationLinearDepthBuffer = 1 / invHiZDepth;
debugIteration = iteration;
debugIterationIntersectionKind = intersectionKind;
debugIterationCellSize = cellSize;
}
#endif
// Check if we are out of the buffer
if (any(int2(positionSS.xy) > int2(bufferSize))
|| any(positionSS.xy < 0)
)
{
hitSuccessful = false;
break;
}
++iteration;
}
hit.linearDepth = 1 / positionSS.z;
hit.positionNDC = float2(positionSS.xy) / float2(bufferSize);
hit.positionSS = uint2(positionSS.xy);
if (hit.linearDepth > (1 / invHiZDepth) + SSRT_SETTING(RayDepthSuccessBias, SSRTID))
hitSuccessful = false;
#ifdef DEBUG_DISPLAY
DebugComputeCommonOutput(input.rayDirWS, hitSuccessful, hit);
DebugComputeHiZOutput(
iteration,
startPositionSS,
raySS,
SSRT_SETTING(RayMaxIterations, SSRTID),
debugLoopMipMaxUsedLevel,
maxMipLevel,
intersectionKind,
hit
);
if (input.debug)
{
// Build debug structure
ScreenSpaceTracingDebug debug;
ZERO_INITIALIZE(ScreenSpaceTracingDebug, debug);
debug.tracingModel = REFRACTIONSSRAYMODEL_HI_Z;
debug.loopStartPositionSSX = uint(startPositionSS.x);
debug.loopStartPositionSSY = uint(startPositionSS.y);
debug.loopStartLinearDepth = 1 / startPositionSS.z;
debug.loopRayDirectionSS = raySS;
debug.loopMipLevelMax = debugLoopMipMaxUsedLevel;
debug.loopIterationMax = iteration;
debug.iterationPositionSS = debugIterationPositionSS;
debug.iterationMipLevel = debugIterationMipLevel;
debug.iteration = debugIteration;
debug.iterationLinearDepthBuffer = debugIterationLinearDepthBuffer;
debug.iterationIntersectionKind = debugIterationIntersectionKind;
debug.iterationCellSizeW = debugIterationCellSize.x;
debug.iterationCellSizeH = debugIterationCellSize.y;
debug.endHitSuccess = hitSuccessful;
debug.endLinearDepth = hit.linearDepth;
debug.endPositionSSX = hit.positionSS.x;
debug.endPositionSSY = hit.positionSS.y;
_DebugScreenSpaceTracingData[0] = debug;
}
#endif
return hitSuccessful;
}
#undef SSRT_SETTING
#undef SSRT_FUNC
#endif

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ScreenSpaceTracing.hlsl.meta


fileFormatVersion: 2
guid: aee64cd8304a9fa46a29f5533aa77b29
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

235
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/BufferPyramidProcessor.cs


using System.Collections.Generic;
using UnityEngine.Assertions;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class BufferPyramidProcessor
{
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;
TexturePadding m_TexturePadding;
ComputeShader m_ColorPyramidCS;
int m_ColorPyramidKernel;
ComputeShader m_DepthPyramidCS;
int[] m_DepthKernels = null;
int depthKernel8 { get { return m_DepthKernels[0]; } }
int depthKernel1 { get { return m_DepthKernels[1]; } }
List<RenderTexture> m_RenderColorPyramid_CastTmp = new List<RenderTexture>();
public BufferPyramidProcessor(
ComputeShader colorPyramidCS,
ComputeShader depthPyramidCS,
GPUCopy gpuCopy,
TexturePadding texturePadding
)
{
m_ColorPyramidCS = colorPyramidCS;
m_ColorPyramidKernel = m_ColorPyramidCS.FindKernel("KMain");
m_DepthPyramidCS = depthPyramidCS;
m_GPUCopy = gpuCopy;
m_DepthKernels = new int[]
{
m_DepthPyramidCS.FindKernel("KDepthDownSample8"),
m_DepthPyramidCS.FindKernel("KDepthDownSample1")
};
m_TexturePadding = texturePadding;
}
public void RenderDepthPyramid(
int width, int height,
CommandBuffer cmd,
RTHandle sourceTexture,
RTHandle targetTexture,
List<RTHandle> mips,
int lodCount,
Vector2 scale
)
{
m_GPUCopy.SampleCopyChannel_xyzw2x(cmd, sourceTexture, targetTexture, new RectInt(0, 0, width, height));
RTHandle src = targetTexture;
for (var i = 0; i < lodCount; i++)
{
RTHandle dest = mips[i];
var srcMip = new RectInt(0, 0, width >> i, height >> i);
var dstMip = new RectInt(0, 0, srcMip.width >> 1, srcMip.height >> 1);
var kernel = depthKernel1;
var kernelSize = 1;
var srcWorkMip = srcMip;
var dstWorkMip = dstMip;
if (dstWorkMip.width >= 8 && dstWorkMip.height >= 8)
{
srcWorkMip.width = Mathf.CeilToInt(srcWorkMip.width / 16.0f) * 16;
srcWorkMip.height = Mathf.CeilToInt(srcWorkMip.height / 16.0f) * 16;
dstWorkMip.width = srcWorkMip.width >> 1;
dstWorkMip.height = srcWorkMip.height >> 1;
m_TexturePadding.Pad(cmd, src, srcMip, srcWorkMip);
kernel = depthKernel8;
kernelSize = 8;
}
else
{
m_TexturePadding.Pad(cmd, src, srcMip, new RectInt(0, 0, src.rt.width, src.rt.height));
}
cmd.SetComputeTextureParam(m_DepthPyramidCS, kernel, _Source, src);
cmd.SetComputeTextureParam(m_DepthPyramidCS, kernel, _Result, dest);
cmd.SetComputeVectorParam(m_DepthPyramidCS, _SrcSize, new Vector4(
srcWorkMip.width, srcWorkMip.height,
(1.0f / srcWorkMip.width) * scale.x, (1.0f / srcWorkMip.height) * scale.y)
);
cmd.DispatchCompute(
m_DepthPyramidCS,
kernel,
Mathf.CeilToInt(dstWorkMip.width / (float)kernelSize),
Mathf.CeilToInt(dstWorkMip.height / (float)kernelSize),
1
);
var dstMipWidthToCopy = Mathf.Min(dest.rt.width, dstWorkMip.width);
var dstMipHeightToCopy = Mathf.Min(dest.rt.height, dstWorkMip.height);
// 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(mips[i], 0, 0, 0, 0, dstMipWidthToCopy, dstMipHeightToCopy, targetTexture, 0, i + 1, 0, 0);
src = dest;
}
}
public void RenderColorPyramid(
HDCamera hdCamera,
CommandBuffer cmd,
RTHandle sourceTexture,
RTHandle targetTexture,
List<RTHandle> mips,
int lodCount,
Vector2 scale
)
{
// 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, sourceTexture, targetTexture, new Rect(0.0f, 0.0f, hdCamera.actualWidth, hdCamera.actualHeight));
m_RenderColorPyramid_CastTmp.Clear();
for (var i = 0 ; i < mips.Count; ++i)
m_RenderColorPyramid_CastTmp.Add(mips[i]);
RenderColorPyramidMips(
new RectInt(0, 0, hdCamera.actualWidth, hdCamera.actualHeight),
cmd,
targetTexture,
m_RenderColorPyramid_CastTmp,
lodCount,
scale
);
}
public void RenderColorPyramid(
RectInt srcRect,
CommandBuffer cmd,
Texture sourceTexture,
RenderTexture targetTexture,
List<RenderTexture> mips,
int lodCount
)
{
Assert.AreEqual(0, srcRect.x, "Offset are not supported");
Assert.AreEqual(0, srcRect.y, "Offset are not supported");
Assert.IsTrue(srcRect.width > 0);
Assert.IsTrue(srcRect.height > 0);
var scale = new Vector2(
sourceTexture.width / (float)srcRect.width,
sourceTexture.height / (float)srcRect.height
);
cmd.Blit(sourceTexture, targetTexture, scale, Vector2.zero);
RenderColorPyramidMips(
srcRect,
cmd,
targetTexture,
mips,
lodCount,
scale
);
}
void RenderColorPyramidMips(
RectInt srcRect,
CommandBuffer cmd,
RenderTexture targetTexture,
List<RenderTexture> mips,
int lodCount,
Vector2 scale
)
{
Assert.AreEqual(0, srcRect.x, "Offset are not supported");
Assert.AreEqual(0, srcRect.y, "Offset are not supported");
Assert.IsTrue(srcRect.width > 0);
Assert.IsTrue(srcRect.height > 0);
var src = targetTexture;
for (var i = 0; i < lodCount; i++)
{
var dest = mips[i];
var srcMip = new RectInt(0, 0, srcRect.width >> i, srcRect.height >> i);
//var dstMip = new RectInt(0, 0, srcMip.width >> 1, srcMip.height >> 1);
var srcWorkMip = new RectInt(
0,
0,
Mathf.CeilToInt(srcMip.width / 16.0f) * 16,
Mathf.CeilToInt(srcMip.height / 16.0f) * 16
);
var dstWorkMip = new RectInt(0, 0, srcWorkMip.width >> 1, srcWorkMip.height >> 1);
m_TexturePadding.Pad(cmd, src, srcMip, srcWorkMip);
// 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.width, dest.height, 1f / dest.width, 1f / dest.height)
);
cmd.DispatchCompute(
m_ColorPyramidCS,
m_ColorPyramidKernel,
dstWorkMip.width / 8,
dstWorkMip.height / 8,
1
);
var dstMipWidthToCopy = Mathf.Min(dest.width, dstWorkMip.width);
var dstMipHeightToCopy = Mathf.Min(dest.height, dstWorkMip.height);
// 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(
mips[i],
0, 0, 0, 0,
dstMipWidthToCopy, dstMipHeightToCopy, targetTexture, 0, i + 1, 0, 0
);
src = dest;
}
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/BufferPyramidProcessor.cs.meta


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

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

正在加载...
取消
保存