浏览代码

Merge remote-tracking branch 'origin/master' into HDRP-GraphicTests

/asmdef
Remy 7 年前
当前提交
5d52724a
共有 68 个文件被更改,包括 1795 次插入1014 次删除
  1. 6
      ImageTemplates/LightweightPipeline/Scenes/007_LitShaderMaps.unity.png.meta
  2. 14
      SampleScenes/HDTest/BasicProfiling/Lit_SSS.mat
  3. 6
      ScriptableRenderPipeline/Core/Resources/BlitCubeTextureFace.shader
  4. 8
      ScriptableRenderPipeline/Core/Resources/EncodeBC6H.compute
  5. 2
      ScriptableRenderPipeline/Core/Resources/GPUCopy.compute
  6. 6
      ScriptableRenderPipeline/Core/ShaderLibrary/CommonLighting.hlsl
  7. 68
      ScriptableRenderPipeline/Core/ShaderLibrary/CommonMaterial.hlsl
  8. 2
      ScriptableRenderPipeline/Core/ShaderLibrary/Packing.hlsl
  9. 2
      ScriptableRenderPipeline/Core/Volume/Editor/VolumeEditor.cs
  10. 2
      ScriptableRenderPipeline/Core/Volume/Volume.cs
  11. 223
      ScriptableRenderPipeline/Core/Volume/VolumeManager.cs
  12. 473
      ScriptableRenderPipeline/Core/Volume/VolumeParameter.cs
  13. 14
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineInspector.cs
  14. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDCustomSamplerId.cs
  15. 524
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  16. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset
  17. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.cs
  18. 13
      ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs
  19. 6
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs
  20. 12
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs.hlsl
  21. 27
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightLoop/LightLoop.cs
  22. 4
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightLoop/materialflags.compute
  23. 19
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader
  24. 19
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader
  25. 222
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  26. 19
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader
  27. 19
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader
  28. 120
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CopyStencilBuffer.shader
  29. 27
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.compute
  30. 21
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.shader
  31. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader
  32. 1
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader
  33. 29
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassForward.hlsl
  34. 3
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SSSProfile.meta
  35. 4
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SSSProfile/SSS Settings.asset.meta
  36. 82
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SSSProfile/SSS Settings.asset
  37. 144
      ScriptableRenderPipeline/Core/Volume/Editor/Drawers/FloatParameterDrawer.cs
  38. 107
      ScriptableRenderPipeline/Core/Volume/Editor/Drawers/IntParameterDrawer.cs
  39. 8
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering.meta
  40. 61
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/CommonSubsurfaceScattering.hlsl
  41. 9
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/CommonSubsurfaceScattering.hlsl.meta
  42. 8
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/Editor.meta
  43. 11
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/Editor/SubsurfaceScatteringSettingsEditor.Styles.cs.meta
  44. 11
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/Editor/SubsurfaceScatteringSettingsEditor.cs.meta
  45. 99
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl
  46. 9
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl.meta
  47. 47
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs
  48. 11
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs.meta
  49. 9
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringSettings.cs.hlsl.meta
  50. 11
      ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringSettings.cs.meta
  51. 77
      ScriptableRenderPipeline/Core/Volume/Editor/Drawers/ClampedFloatParameterDrawer.cs
  52. 77
      ScriptableRenderPipeline/Core/Volume/Editor/Drawers/ClampedIntParameterDrawer.cs
  53. 42
      ScriptableRenderPipeline/Core/Volume/Editor/Drawers/RangeParameterDrawer.cs
  54. 11
      ScriptableRenderPipeline/Core/Volume/Editor/Drawers/RangeParameterDrawer.cs.meta
  55. 13
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/SubsurfaceScatteringSettingsEditor.Styles.cs.meta
  56. 13
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/SubsurfaceScatteringSettingsEditor.cs.meta
  57. 13
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs.meta
  58. 10
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs.hlsl.meta
  59. 0
      /ScriptableRenderPipeline/Core/Volume/Editor/Drawers/IntParameterDrawer.cs.meta
  60. 0
      /ScriptableRenderPipeline/Core/Volume/Editor/Drawers/FloatParameterDrawer.cs.meta
  61. 0
      /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/Editor/SubsurfaceScatteringSettingsEditor.cs
  62. 0
      /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/Editor/SubsurfaceScatteringSettingsEditor.Styles.cs
  63. 0
      /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SSSProfile.meta
  64. 0
      /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SSSProfile
  65. 0
      /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringSettings.cs.hlsl
  66. 0
      /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringSettings.cs

6
ImageTemplates/LightweightPipeline/Scenes/007_LitShaderMaps.unity.png.meta


sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
userData:
assetBundleName:

14
SampleScenes/HDTest/BasicProfiling/Lit_SSS.mat


stringTagMap: {}
disabledShaderPasses:
- DistortionVectors
- TransparentBackface
- TransparentBackfaceDebugDisplay
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:

m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TransmittanceColorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _AORemapMax: 1
- _AORemapMin: 0
- _ATDistance: 1
- _AlbedoAffectEmissive: 0
- _AlphaCutoff: 0.5

- _DistortionOnly: 0
- _DistortionScale: 1
- _DistortionSrcBlend: 1
- _DistortionVectorBias: -1
- _DistortionVectorScale: 2
- _DoubleSidedEnable: 0
- _DoubleSidedNormalMode: 1
- _Drag: 1

- _SrcBlend: 1
- _StencilRef: 1
- _Stiffness: 1
- _SubsurfaceProfile: 3
- _SubsurfaceProfile: 1
- _TransparentBackfaceEnable: 0
- _UVBase: 0
- _UVDetail: 0
- _UVSec: 0

- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _InvPrimScale: {r: 1, g: 1, b: 0, a: 0}
- _SpecularColor: {r: 1, g: 1, b: 1, a: 1}
- _ThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
- _TransmittanceColor: {r: 1, g: 1, b: 1, a: 1}
- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}

6
ScriptableRenderPipeline/Core/Resources/BlitCubeTextureFace.shader


Shader "Hidden/SRP/BlitCubeTextureFace"
{
SubShader
SubShader
Pass
Pass
{
ZTest Always

HLSLPROGRAM
#include "../ShaderLibrary/Common.hlsl"
#include "ShaderLibrary/Common.hlsl"
#pragma vertex vert
#pragma fragment frag

8
ScriptableRenderPipeline/Core/Resources/EncodeBC6H.compute


#include "../ShaderLibrary/Common.hlsl"
#include "../ShaderLibrary/BC6H.hlsl"
#include "../ShaderLibrary/Sampling.hlsl"
#include "ShaderLibrary/Common.hlsl"
#include "ShaderLibrary/BC6H.hlsl"
#include "ShaderLibrary/Sampling.hlsl"
TextureCube<float4> _Source;
RWTexture2DArray<uint4> _Target;

EncodeMode11(block, blockMSLE, texels);
_Target[dispatchThreadId] = block;
}
}

2
ScriptableRenderPipeline/Core/Resources/GPUCopy.compute


// Autogenerated file. Do not edit by hand
#include "../ShaderLibrary/Common.hlsl"
#include "ShaderLibrary/Common.hlsl"
SamplerState sampler_LinearClamp;

6
ScriptableRenderPipeline/Core/ShaderLibrary/CommonLighting.hlsl


return area;
}
// Ref: Steve McAuley - Energy-Conserving Wrapped Diffuse
float ComputeWrappedDiffuseLighting(float NdotL, float w)
{
return saturate((NdotL + w) / ((1 + w) * (1 + w)));
}
//-----------------------------------------------------------------------------
// Helper functions
//-----------------------------------------------------------------------------

68
ScriptableRenderPipeline/Core/ShaderLibrary/CommonMaterial.hlsl


return float3(oneMinusT, oneMinusT, oneMinusT) + b * t;
}
// ----------------------------------------------------------------------------
// SSS/Transmittance
// ----------------------------------------------------------------------------
// Computes the fraction of light passing through the object.
// Evaluate Int{0, inf}{2 * Pi * r * R(sqrt(r^2 + d^2))}, where R is the diffusion profile.
// Note: 'volumeAlbedo' should be premultiplied by 0.25.
// Ref: Approximate Reflectance Profiles for Efficient Subsurface Scattering by Pixar (BSSRDF only).
float3 ComputeTransmittanceDisney(float3 S, float3 volumeAlbedo, float thickness, float radiusScale)
{
// Thickness and SSS radius are decoupled for artists.
// In theory, we should modify the thickness by the inverse of the radius scale of the profile.
// thickness /= radiusScale;
#if 0
float3 expOneThird = exp(((-1.0 / 3.0) * thickness) * S);
#else
// Help the compiler.
float k = (-1.0 / 3.0) * LOG2_E;
float3 p = (k * thickness) * S;
float3 expOneThird = exp2(p);
#endif
// Premultiply & optimize: T = (1/4 * A) * (e^(-t * S) + 3 * e^(-1/3 * t * S))
return volumeAlbedo * (expOneThird * expOneThird * expOneThird + 3 * expOneThird);
}
// Evaluates transmittance for a linear combination of two normalized 2D Gaussians.
// Ref: Real-Time Realistic Skin Translucency (2010), equation 9 (modified).
// Note: 'volumeAlbedo' should be premultiplied by 0.25, correspondingly 'lerpWeight' by 4,
// and 'halfRcpVariance1' should be prescaled by (0.1 * SssConstants.SSS_BASIC_DISTANCE_SCALE)^2.
float3 ComputeTransmittanceJimenez(float3 halfRcpVariance1, float lerpWeight1,
float3 halfRcpVariance2, float lerpWeight2,
float3 volumeAlbedo, float thickness, float radiusScale)
{
// Thickness and SSS radius are decoupled for artists.
// In theory, we should modify the thickness by the inverse of the radius scale of the profile.
// thickness /= radiusScale;
float t2 = thickness * thickness;
// T = A * lerp(exp(-t2 * halfRcpVariance1), exp(-t2 * halfRcpVariance2), lerpWeight2)
return volumeAlbedo * (exp(-t2 * halfRcpVariance1) * lerpWeight1 + exp(-t2 * halfRcpVariance2) * lerpWeight2);
}
// Ref: Steve McAuley - Energy-Conserving Wrapped Diffuse
float ComputeWrappedDiffuseLighting(float NdotL, float w)
{
return saturate((NdotL + w) / ((1 + w) * (1 + w)));
}
// In order to support subsurface scattering, we need to know which pixels have an SSS material.
// It can be accomplished by reading the stencil buffer.
// A faster solution (which avoids an extra texture fetch) is to simply make sure that
// all pixels which belong to an SSS material are not black (those that don't always are).
// We choose the blue color channel since it's perceptually the least noticeable.
float3 TagLightingForSSS(float3 subsurfaceLighting)
{
subsurfaceLighting.b = max(subsurfaceLighting.b, HALF_MIN);
return subsurfaceLighting;
}
// See TagLightingForSSS() for details.
bool TestLightingForSSS(float3 subsurfaceLighting)
{
return subsurfaceLighting.b > 0;
}
#endif // UNITY_COMMON_MATERIAL_INCLUDED

2
ScriptableRenderPipeline/Core/ShaderLibrary/Packing.hlsl


#ifndef UNITY_PACKING_INCLUDED
#define UNITY_PACKING_INCLUDED
#include "Common.hlsl"
//-----------------------------------------------------------------------------
// Normal packing
//-----------------------------------------------------------------------------

2
ScriptableRenderPipeline/Core/Volume/Editor/VolumeEditor.cs


var script = (MonoScript)o;
var scriptType = script.GetClass();
if (!scriptType.IsSubclassOf(typeof(VolumeComponent)))
if (!scriptType.IsSubclassOf(typeof(VolumeComponent)) || scriptType.IsAbstract)
return false;
if (actualTarget.components.Exists(t => t.GetType() == scriptType))

2
ScriptableRenderPipeline/Core/Volume/Volume.cs


[Tooltip("Volume priority in the stack. Higher number means higher priority. Negative values are supported.")]
public float priority = 0f;
[Tooltip("Outer distance to start blending from. A value of 0 means no blending and the volume overrides will be applied immediatly upon entry.")]
[Tooltip("Outer distance to start blending from. A value of 0 means no blending and the volume overrides will be applied immediately upon entry.")]
public float blendDistance = 0f;
[Range(0f, 1f), Tooltip("Total weight of this volume in the scene. 0 means it won't do anything, 1 means full effect.")]

223
ScriptableRenderPipeline/Core/Volume/VolumeManager.cs


using System;
using System.Collections.Generic;
using System.Diagnostics;
using UnityObject = UnityEngine.Object;
static object s_LockObj = new Object();
static object s_LockObj = new UnityObject();
public static VolumeManager instance
{

// Max amount of layers available in Unity
const int k_MaxLayerCount = 32;
// List of all volumes (sorted by priority) per layer
readonly List<Volume>[] m_Volumes;
// Cached lists of all volumes (sorted by priority) by layer mask
readonly Dictionary<LayerMask, List<Volume>> m_SortedVolumes;
// Keep track of sorting states for all layers
readonly bool[] m_SortNeeded;
// Holds all the registered volumes
readonly List<Volume> m_Volumes;
// Keep track of sorting states for layer masks
readonly Dictionary<LayerMask, bool> m_SortNeeded;
// Internal state of all component types
readonly Dictionary<Type, VolumeComponent> m_Components;

VolumeManager()
{
m_Volumes = new List<Volume>[k_MaxLayerCount];
m_SortNeeded = new bool[k_MaxLayerCount];
m_SortedVolumes = new Dictionary<LayerMask, List<Volume>>();
m_Volumes = new List<Volume>();
m_SortNeeded = new Dictionary<LayerMask, bool>();
m_TempColliders = new List<Collider>(8);
m_Components = new Dictionary<Type, VolumeComponent>();
m_ComponentsDefaultState = new List<VolumeComponent>();

.SelectMany(
a => a.GetTypes()
.Where(
t => t.IsSubclassOf(typeof(VolumeComponent))
t => t.IsSubclassOf(typeof(VolumeComponent)) && !t.IsAbstract
)
);

m_Components.Add(type, inst);
inst = (VolumeComponent)ScriptableObject.CreateInstance(type);
inst.SetAllOverridesTo(true);
m_ComponentsDefaultState.Add(inst);
}

{
VolumeComponent comp;
m_Components.TryGetValue(type, out comp);
Assert.IsNotNull(comp, "Component map is corrupted, \"" + type + "\" not found");
var volumes = m_Volumes[layer];
m_Volumes.Add(volume);
if (volumes == null)
// Look for existing cached layer masks and add it there if needed
foreach (var kvp in m_SortedVolumes)
volumes = new List<Volume>();
m_Volumes[layer] = volumes;
var mask = kvp.Key;
if ((mask & (1 << layer)) != 0)
kvp.Value.Add(volume);
Assert.IsFalse(volumes.Contains(volume), "Volume has already been registered");
volumes.Add(volume);
var volumes = m_Volumes[layer];
m_Volumes.Remove(volume);
if (volumes == null)
return;
foreach (var kvp in m_SortedVolumes)
{
var mask = kvp.Key;
volumes.Remove(volume);
// Skip layer masks this volume doesn't belong to
if ((mask & (1 << layer)) == 0)
continue;
kvp.Value.Remove(volume);
}
m_SortNeeded[layer] = true;
foreach (var kvp in m_SortedVolumes)
{
var mask = kvp.Key;
if ((mask & (1 << layer)) != 0)
m_SortNeeded[mask] = true;
}
}
internal void UpdateVolumeLayer(Volume volume, int prevLayer, int newLayer)

for (int i = 0; i < count; i++)
{
var fromParam = target.parameters[i];
// Keep track of the override state for debugging purpose
fromParam.overrideState = toParam.overrideState;
{
var fromParam = target.parameters[i];
}
}
}
}

}
}
// Update the global state - should be called once per frame in the update loop before
// anything else
public void Update(Transform trigger, LayerMask layerMask)
[Conditional("UNITY_EDITOR")]
public void CheckBaseTypes()
#if UNITY_EDITOR
// play mode -> re-create the world when bad things happen
if (m_ComponentsDefaultState == null
|| (m_ComponentsDefaultState.Count > 0 && m_ComponentsDefaultState[0] == null))
{
if (m_ComponentsDefaultState == null || (m_ComponentsDefaultState.Count > 0 && m_ComponentsDefaultState[0] == null))
}
else
#endif
{
// Start by resetting the global state to default values
ReplaceData(m_ComponentsDefaultState);
}
}
// Do magic
// Update the global state - should be called once per frame per transform/layer mask combo
// in the update loop before rendering
public void Update(Transform trigger, LayerMask layerMask)
{
CheckBaseTypes();
// Start by resetting the global state to default values
ReplaceData(m_ComponentsDefaultState);
int mask = layerMask.value;
for (int i = 0; i < k_MaxLayerCount; i++)
// Sort the cached volume list(s) for the given layer mask if needed and return it
var volumes = GrabVolumes(layerMask);
// Traverse all volumes
foreach (var volume in volumes)
// Skip layers not in the mask
if ((mask & (1 << i)) == 0)
// Skip disabled volumes and volumes without any data or weight
if (!volume.enabled || volume.weight <= 0f)
continue;
// Global volumes always have influence
if (volume.isGlobal)
{
OverrideData(volume.components, Mathf.Clamp01(volume.weight));
}
// Skip empty layers
var volumes = m_Volumes[i];
if (onlyGlobal)
continue;
if (volumes == null)
// If volume isn't global and has no collider, skip it as it's useless
var colliders = m_TempColliders;
volume.GetComponents(colliders);
if (colliders.Count == 0)
// Sort the volume list if needed
if (m_SortNeeded[i])
{
SortByPriority(volumes);
m_SortNeeded[i] = false;
}
// Find closest distance to volume, 0 means it's inside it
float closestDistanceSqr = float.PositiveInfinity;
// Traverse all volumes
foreach (var volume in volumes)
foreach (var collider in colliders)
// Skip disabled volumes and volumes without any data or weight
if (!volume.enabled || volume.weight <= 0f)
if (!collider.enabled)
var components = volume.components;
var closestPoint = collider.ClosestPoint(triggerPos);
var d = (closestPoint - triggerPos).sqrMagnitude;
// Global volumes always have influence
if (volume.isGlobal)
{
OverrideData(components, Mathf.Clamp01(volume.weight));
continue;
}
if (d < closestDistanceSqr)
closestDistanceSqr = d;
}
if (onlyGlobal)
continue;
colliders.Clear();
float blendDistSqr = volume.blendDistance * volume.blendDistance;
// If volume isn't global and has no collider, skip it as it's useless
var colliders = m_TempColliders;
volume.GetComponents(colliders);
if (colliders.Count == 0)
continue;
// Volume has no influence, ignore it
// Note: Volume doesn't do anything when `closestDistanceSqr = blendDistSqr` but
// we can't use a >= comparison as blendDistSqr could be set to 0 in which
// case volume would have total influence
if (closestDistanceSqr > blendDistSqr)
continue;
// Find closest distance to volume, 0 means it's inside it
float closestDistanceSqr = float.PositiveInfinity;
// Volume has influence
float interpFactor = 1f;
foreach (var collider in colliders)
{
if (!collider.enabled)
continue;
if (blendDistSqr > 0f)
interpFactor = 1f - (closestDistanceSqr / blendDistSqr);
var closestPoint = collider.ClosestPoint(triggerPos);
var d = (closestPoint - triggerPos).sqrMagnitude;
// No need to clamp01 the interpolation factor as it'll always be in [0;1[ range
OverrideData(volume.components, interpFactor * Mathf.Clamp01(volume.weight));
}
}
if (d < closestDistanceSqr)
closestDistanceSqr = d;
}
List<Volume> GrabVolumes(LayerMask mask)
{
List<Volume> list;
colliders.Clear();
float blendDistSqr = volume.blendDistance * volume.blendDistance;
if (!m_SortedVolumes.TryGetValue(mask, out list))
{
// New layer mask detected, create a new list and cache all the volumes that belong
// to this mask in it
list = new List<Volume>();
// Volume has no influence, ignore it
// Note: Volume doesn't do anything when `closestDistanceSqr = blendDistSqr` but
// we can't use a >= comparison as blendDistSqr could be set to 0 in which
// case volume would have total influence
if (closestDistanceSqr > blendDistSqr)
foreach (var volume in m_Volumes)
{
if ((mask & (1 << volume.gameObject.layer)) == 0)
// Volume has influence
float interpFactor = 1f;
list.Add(volume);
m_SortNeeded[mask] = true;
}
if (blendDistSqr > 0f)
interpFactor = 1f - (closestDistanceSqr / blendDistSqr);
m_SortedVolumes.Add(mask, list);
}
// No need to clamp01 the interpolation factor as it'll always be in [0;1[ range
OverrideData(components, interpFactor * Mathf.Clamp01(volume.weight));
}
// Check sorting state
bool sortNeeded;
if (m_SortNeeded.TryGetValue(mask, out sortNeeded) && sortNeeded)
{
m_SortNeeded[mask] = false;
SortByPriority(list);
return list;
}
// Stable insertion sort. Faster than List<T>.Sort() for our needs.

473
ScriptableRenderPipeline/Core/Volume/VolumeParameter.cs


using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;

// of the following is a bit hacky...
public abstract class VolumeParameter
{
public const string k_DebuggerDisplay = "{m_Value} ({m_OverrideState})";
[SerializeField]
protected bool m_OverrideState;

}
}
[Serializable]
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public class VolumeParameter<T> : VolumeParameter
{
[SerializeField]

get { return m_Value; }
set { m_Value = value; }
}
protected const float k_DefaultInterpSwap = 0f;
public VolumeParameter()
: this(default(T), false)

public virtual void Interp(T from, T to, float t)
{
// Returns `b` if `dt > 0` by default so we don't have to write overrides for bools and
// enumerations.
m_Value = t > 0f ? to : from;
// Default interpolation is naive
m_Value = t > k_DefaultInterpSwap ? to : from;
}
public void Override(T x)

}
}
public override string ToString()
{
return string.Format("{0} ({1})", value, overrideState);
}
//
// Implicit conversion; assuming the following:
//

}
}
public enum ParameterClampMode
{
Min,
Max,
MinMax
}
//
// The serialization system in Unity can't serialize generic types, the workaround is to extend
// and flatten pre-defined generic types.

// public enum MyEnum { One, Two }
//
[Serializable]
public sealed class BoolParameter : VolumeParameter<bool> { }
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class BoolParameter : VolumeParameter<bool>
{
public BoolParameter(bool value, bool overrideState = false)
: base(value, overrideState) { }
}
[Serializable]
public sealed class IntParameter : VolumeParameter<int>
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public class IntParameter : VolumeParameter<int>
public override void Interp(int from, int to, float t)
public IntParameter(int value, bool overrideState = false)
: base(value, overrideState) { }
public sealed override void Interp(int from, int to, float t)
{
// Int snapping interpolation. Don't use this for enums as they don't necessarily have
// contiguous values. Use the default interpolator instead (same as bool).

[Serializable]
public sealed class InstantIntParameter : VolumeParameter<int> { }
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpIntParameter : VolumeParameter<int>
{
public NoInterpIntParameter(int value, bool overrideState = false)
: base(value, overrideState) { }
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class MinIntParameter : IntParameter
{
public int min;
public override int value
{
get { return m_Value; }
set { m_Value = Mathf.Max(value, min); }
}
public MinIntParameter(int value, int min, bool overrideState = false)
: base(value, overrideState)
{
this.min = min;
}
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpMinIntParameter : VolumeParameter<int>
{
public int min;
public override int value
{
get { return m_Value; }
set { m_Value = Mathf.Max(value, min); }
}
public NoInterpMinIntParameter(int value, int min, bool overrideState = false)
: base(value, overrideState)
{
this.min = min;
}
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class MaxIntParameter : IntParameter
{
public int max;
public override int value
{
get { return m_Value; }
set { m_Value = Mathf.Min(value, max); }
}
public MaxIntParameter(int value, int max, bool overrideState = false)
: base(value, overrideState)
{
this.max = max;
}
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpMaxIntParameter : VolumeParameter<int>
{
public int max;
public override int value
{
get { return m_Value; }
set { m_Value = Mathf.Min(value, max); }
}
public NoInterpMaxIntParameter(int value, int max, bool overrideState = false)
: base(value, overrideState)
{
this.max = max;
}
}
[Serializable]
public sealed class ClampedIntParameter : VolumeParameter<int>
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class ClampedIntParameter : IntParameter
public ParameterClampMode clampMode = ParameterClampMode.MinMax;
public int min = 0;
public int max = 10;
public int min;
public int max;
set
{
switch (clampMode)
{
case ParameterClampMode.Min: m_Value = Mathf.Max(min, value); break;
case ParameterClampMode.Max: m_Value = Mathf.Min(max, value); break;
case ParameterClampMode.MinMax: m_Value = Mathf.Clamp(value, min, max); break;
}
}
set { m_Value = Mathf.Clamp(value, min, max); }
public override void Interp(int from, int to, float t)
public ClampedIntParameter(int value, int min, int max, bool overrideState = false)
: base(value, overrideState)
m_Value = (int)(from + (to - from) * t);
this.min = min;
this.max = max;
[Serializable]
public sealed class InstantClampedIntParameter : VolumeParameter<int>
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpClampedIntParameter : VolumeParameter<int>
public ParameterClampMode clampMode = ParameterClampMode.MinMax;
public int min = 0;
public int max = 10;
public int min;
public int max;
set
{
switch (clampMode)
{
case ParameterClampMode.Min: m_Value = Mathf.Max(min, value); break;
case ParameterClampMode.Max: m_Value = Mathf.Min(max, value); break;
case ParameterClampMode.MinMax: m_Value = Mathf.Clamp(value, min, max); break;
}
}
set { m_Value = Mathf.Clamp(value, min, max); }
}
public NoInterpClampedIntParameter(int value, int min, int max, bool overrideState = false)
: base(value, overrideState)
{
this.min = min;
this.max = max;
[Serializable]
public sealed class FloatParameter : VolumeParameter<float>
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public class FloatParameter : VolumeParameter<float>
public override void Interp(float from, float to, float t)
public FloatParameter(float value, bool overrideState = false)
: base(value, overrideState) { }
public sealed override void Interp(float from, float to, float t)
[Serializable]
public sealed class InstantFloatParameter : VolumeParameter<float> { }
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpFloatParameter : VolumeParameter<float>
{
public NoInterpFloatParameter(float value, bool overrideState = false)
: base(value, overrideState) { }
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class MinFloatParameter : FloatParameter
{
public float min;
public override float value
{
get { return m_Value; }
set { m_Value = Mathf.Max(value, min); }
}
public MinFloatParameter(float value, float min, bool overrideState = false)
: base(value, overrideState)
{
this.min = min;
}
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpMinFloatParameter : VolumeParameter<float>
{
public float min;
public override float value
{
get { return m_Value; }
set { m_Value = Mathf.Max(value, min); }
}
public NoInterpMinFloatParameter(float value, float min, bool overrideState = false)
: base(value, overrideState)
{
this.min = min;
}
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class MaxFloatParameter : FloatParameter
{
public float max;
public override float value
{
get { return m_Value; }
set { m_Value = Mathf.Min(value, max); }
}
public MaxFloatParameter(float value, float max, bool overrideState = false)
: base(value, overrideState)
{
this.max = max;
}
}
[Serializable]
public sealed class ClampedFloatParameter : VolumeParameter<float>
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpMaxFloatParameter : VolumeParameter<float>
public ParameterClampMode clampMode = ParameterClampMode.MinMax;
public float min = 0f;
public float max = 1f;
public float max;
set
{
switch (clampMode)
{
case ParameterClampMode.Min: m_Value = Mathf.Max(min, value); break;
case ParameterClampMode.Max: m_Value = Mathf.Min(max, value); break;
case ParameterClampMode.MinMax: m_Value = Mathf.Clamp(value, min, max); break;
}
}
set { m_Value = Mathf.Min(value, max); }
// We could override FloatParameter here but that would require making it not-sealed which
// will stop the compiler from doing specific optimizations on virtual methods - considering
// how often float is used, duplicating the code in this case is a definite win
public override void Interp(float from, float to, float t)
public NoInterpMaxFloatParameter(float value, float max, bool overrideState = false)
: base(value, overrideState)
m_Value = from + (to - from) * t;
this.max = max;
[Serializable]
public sealed class InstantClampedFloatParameter : VolumeParameter<float>
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class ClampedFloatParameter : FloatParameter
public ParameterClampMode clampMode = ParameterClampMode.MinMax;
public float min = 0f;
public float max = 1f;
public float min;
public float max;
set
{
switch (clampMode)
{
case ParameterClampMode.Min: m_Value = Mathf.Max(min, value); break;
case ParameterClampMode.Max: m_Value = Mathf.Min(max, value); break;
case ParameterClampMode.MinMax: m_Value = Mathf.Clamp(value, min, max); break;
}
}
set { m_Value = Mathf.Clamp(value, min, max); }
}
public ClampedFloatParameter(float value, float min, float max, bool overrideState = false)
: base(value, overrideState)
{
this.min = min;
this.max = max;
}
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpClampedFloatParameter : VolumeParameter<float>
{
public float min;
public float max;
public override float value
{
get { return m_Value; }
set { m_Value = Mathf.Clamp(value, min, max); }
}
public NoInterpClampedFloatParameter(float value, float min, float max, bool overrideState = false)
: base(value, overrideState)
{
this.min = min;
this.max = max;
[Serializable]
public sealed class RangeParameter : VolumeParameter<Vector2>
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class FloatRangeParameter : VolumeParameter<Vector2>
public float min = 0;
public float max = 1;
public float min;
public float max;
public override Vector2 value
{

}
}
public FloatRangeParameter(Vector2 value, float min, float max, bool overrideState = false)
: base(value, overrideState)
{
this.min = min;
this.max = max;
}
public override void Interp(Vector2 from, Vector2 to, float t)
{
m_Value.x = from.x + (to.x - from.x) * t;

[Serializable]
public sealed class InstantRangeParameter : VolumeParameter<Vector2>
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpFloatRangeParameter : VolumeParameter<Vector2>
public float min = 0;
public float max = 1;
public float min;
public float max;
public override Vector2 value
{

m_Value.y = Mathf.Min(value.y, max);
}
}
public NoInterpFloatRangeParameter(Vector2 value, float min, float max, bool overrideState = false)
: base(value, overrideState)
{
this.min = min;
this.max = max;
}
[Serializable]
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class ColorParameter : VolumeParameter<Color>
{
public bool hdr = false;

public ColorParameter(Color value, bool overrideState = false)
: base(value, overrideState) { }
public ColorParameter(Color value, bool hdr, bool showAlpha, bool showEyeDropper, bool overrideState = false)
: base(value, overrideState)
{
this.hdr = hdr;
this.showAlpha = showAlpha;
this.overrideState = overrideState;
}
public override void Interp(Color from, Color to, float t)
{
// Lerping color values is a sensitive subject... We looked into lerping colors using

}
}
[Serializable]
public sealed class InstantColorParameter : VolumeParameter<Color> { }
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpColorParameter : VolumeParameter<Color>
{
public bool hdr = false;
public bool showAlpha = true;
public bool showEyeDropper = true;
[Serializable]
public NoInterpColorParameter(Color value, bool overrideState = false)
: base(value, overrideState) { }
public NoInterpColorParameter(Color value, bool hdr, bool showAlpha, bool showEyeDropper, bool overrideState = false)
: base(value, overrideState)
{
this.hdr = hdr;
this.showAlpha = showAlpha;
this.overrideState = overrideState;
}
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public Vector2Parameter(Vector2 value, bool overrideState = false)
: base(value, overrideState) { }
public override void Interp(Vector2 from, Vector2 to, float t)
{
m_Value.x = from.x + (to.x - from.x) * t;

[Serializable]
public sealed class InstantVector2Parameter : VolumeParameter<Vector2> { }
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpVector2Parameter : VolumeParameter<Vector2>
{
public NoInterpVector2Parameter(Vector2 value, bool overrideState = false)
: base(value, overrideState) { }
}
[Serializable]
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public Vector3Parameter(Vector3 value, bool overrideState = false)
: base(value, overrideState) { }
public override void Interp(Vector3 from, Vector3 to, float t)
{
m_Value.x = from.x + (to.x - from.x) * t;

}
[Serializable]
public sealed class InstantVector3Parameter : VolumeParameter<Vector3> { }
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpVector3Parameter : VolumeParameter<Vector3>
{
public NoInterpVector3Parameter(Vector3 value, bool overrideState = false)
: base(value, overrideState) { }
}
[Serializable]
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public Vector4Parameter(Vector4 value, bool overrideState = false)
: base(value, overrideState) { }
public override void Interp(Vector4 from, Vector4 to, float t)
{
m_Value.x = from.x + (to.x - from.x) * t;

}
}
[Serializable]
public sealed class InstantVector4Parameter : VolumeParameter<Vector4> { }
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpVector4Parameter : VolumeParameter<Vector4>
{
public NoInterpVector4Parameter(Vector4 value, bool overrideState = false)
: base(value, overrideState) { }
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class TextureParameter : VolumeParameter<Texture>
{
public TextureParameter(Texture value, bool overrideState = false)
: base(value, overrideState) { }
// TODO: Texture interpolation
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpTextureParameter : VolumeParameter<Texture>
{
public NoInterpTextureParameter(Texture value, bool overrideState = false)
: base(value, overrideState) { }
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class RenderTextureParameter : VolumeParameter<RenderTexture>
{
public RenderTextureParameter(RenderTexture value, bool overrideState = false)
: base(value, overrideState) { }
// TODO: RenderTexture interpolation
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpRenderTextureParameter : VolumeParameter<RenderTexture>
{
public NoInterpRenderTextureParameter(RenderTexture value, bool overrideState = false)
: base(value, overrideState) { }
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class CubemapParameter : VolumeParameter<Cubemap>
{
public CubemapParameter(Cubemap value, bool overrideState = false)
: base(value, overrideState) { }
// TODO: Cubemap interpolation
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class NoInterpCubemapParameter : VolumeParameter<Cubemap>
{
public NoInterpCubemapParameter(Cubemap value, bool overrideState = false)
: base(value, overrideState) { }
}
[Serializable]
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public class ObjectParameter<T> : VolumeParameter<T>
{
internal ReadOnlyCollection<VolumeParameter> parameters { get; private set; }

.ToList()
.AsReadOnly();
}
}
public ObjectParameter(T value)
{
m_OverrideState = true;
this.value = value;
}
internal override void Interp(VolumeParameter from, VolumeParameter to, float t)

14
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineInspector.cs


m_DefaultShader = properties.Find("m_DefaultShader");
// Tile settings
m_enableTileAndCluster = properties.Find(x => x.tileSettings.enableTileAndCluster);
m_enableComputeLightEvaluation = properties.Find(x => x.tileSettings.enableComputeLightEvaluation);
m_enableComputeLightVariants = properties.Find(x => x.tileSettings.enableComputeLightVariants);
m_enableComputeMaterialVariants = properties.Find(x => x.tileSettings.enableComputeMaterialVariants);
m_enableFptlForForwardOpaque = properties.Find(x => x.tileSettings.enableFptlForForwardOpaque);
m_enableBigTilePrepass = properties.Find(x => x.tileSettings.enableBigTilePrepass);
m_enableAsyncCompute = properties.Find(x => x.tileSettings.enableAsyncCompute);
m_enableTileAndCluster = properties.Find(x => x.lightLoopSettings.enableTileAndCluster);
m_enableComputeLightEvaluation = properties.Find(x => x.lightLoopSettings.enableComputeLightEvaluation);
m_enableComputeLightVariants = properties.Find(x => x.lightLoopSettings.enableComputeLightVariants);
m_enableComputeMaterialVariants = properties.Find(x => x.lightLoopSettings.enableComputeMaterialVariants);
m_enableFptlForForwardOpaque = properties.Find(x => x.lightLoopSettings.enableFptlForForwardOpaque);
m_enableBigTilePrepass = properties.Find(x => x.lightLoopSettings.enableBigTilePrepass);
m_enableAsyncCompute = properties.Find(x => x.lightLoopSettings.enableAsyncCompute);
// Shadow settings
m_ShadowAtlasWidth = properties.Find(x => x.shadowInitParams.shadowAtlasWidth);

4
ScriptableRenderPipeline/HDRenderPipeline/HDCustomSamplerId.cs


PushGlobalParameters,
CopySetDepthBuffer,
CopyDepthStencilbuffer,
CopyStencilBuffer,
HTileForSSS,
Forward,
RenderSSAO,
RenderShadows,

InitGBuffersAndClearDepthStencil,
ClearSSSDiffuseTarget,
ClearSSSFilteringTarget,
ClearStencilTexture,
ClearAndCopyStencilTexture,
ClearHTile,
ClearHDRTarget,
ClearGBuffer,

524
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs


using System.Collections.Generic;
using System.Collections.Generic;
using UnityEngine.Rendering;
using System;
using System.Diagnostics;

readonly List<RenderPipelineMaterial> m_MaterialList = new List<RenderPipelineMaterial>();
readonly GBufferManager m_GbufferManager = new GBufferManager();
readonly SubsurfaceScatteringManager m_SSSBufferManager = new SubsurfaceScatteringManager();
Material m_CopyStencilForRegularLighting;
Material m_CopyStencilForNoLighting;
GPUCopy m_GPUCopy;
IBLFilterGGX m_IBLFilterGGX = null;

m_applyDistortionKernel = m_applyDistortionCS.FindKernel("KMain");
m_CopyStencilForSplitLighting = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/CopyStencilBuffer");
m_CopyStencilForSplitLighting.EnableKeyword("EXPORT_HTILE");
m_CopyStencilForRegularLighting = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/CopyStencilBuffer");
m_CopyStencilForRegularLighting.DisableKeyword("EXPORT_HTILE");
m_CopyStencilForRegularLighting.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.RegularLighting);
m_CopyStencilForNoLighting = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/CopyStencilBuffer");
m_CopyStencilForNoLighting.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.NoLighting);
m_CameraMotionVectorsMaterial = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/CameraMotionVectors");
InitializeDebugMaterials();

m_IBLFilterGGX = new IBLFilterGGX(asset.renderPipelineResources);
m_LightLoop.Build(asset.renderPipelineResources, asset.tileSettings, asset.globalTextureSettings, asset.shadowInitParams, m_ShadowSettings, m_IBLFilterGGX);
m_LightLoop.Build(asset.renderPipelineResources, asset.lightLoopSettings, asset.globalTextureSettings, asset.shadowInitParams, m_ShadowSettings, m_IBLFilterGGX);
m_SkyManager.Build(asset.renderPipelineResources, m_IBLFilterGGX);
m_SkyManager.skySettings = skySettingsToUse;

DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Deferred Depth Prepass", () => m_Asset.globalRenderingSettings.useDepthPrepassWithDeferredRendering, (value) => m_Asset.globalRenderingSettings.useDepthPrepassWithDeferredRendering = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Deferred Depth Prepass ATest Only", () => m_Asset.globalRenderingSettings.renderAlphaTestOnlyInDeferredPrepass, (value) => m_Asset.globalRenderingSettings.renderAlphaTestOnlyInDeferredPrepass = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Tile/Cluster", () => m_Asset.tileSettings.enableTileAndCluster, (value) => m_Asset.tileSettings.enableTileAndCluster = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Big Tile", () => m_Asset.tileSettings.enableBigTilePrepass, (value) => m_Asset.tileSettings.enableBigTilePrepass = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Compute Lighting", () => m_Asset.tileSettings.enableComputeLightEvaluation, (value) => m_Asset.tileSettings.enableComputeLightEvaluation = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Light Classification", () => m_Asset.tileSettings.enableComputeLightVariants, (value) => m_Asset.tileSettings.enableComputeLightVariants = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Material Classification", () => m_Asset.tileSettings.enableComputeMaterialVariants, (value) => m_Asset.tileSettings.enableComputeMaterialVariants = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Async Compute", () => m_Asset.tileSettings.enableAsyncCompute, (value) => m_Asset.tileSettings.enableAsyncCompute = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Tile/Cluster", () => m_Asset.lightLoopSettings.enableTileAndCluster, (value) => m_Asset.lightLoopSettings.enableTileAndCluster = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Big Tile", () => m_Asset.lightLoopSettings.enableBigTilePrepass, (value) => m_Asset.lightLoopSettings.enableBigTilePrepass = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Compute Lighting", () => m_Asset.lightLoopSettings.enableComputeLightEvaluation, (value) => m_Asset.lightLoopSettings.enableComputeLightEvaluation = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Light Classification", () => m_Asset.lightLoopSettings.enableComputeLightVariants, (value) => m_Asset.lightLoopSettings.enableComputeLightVariants = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Material Classification", () => m_Asset.lightLoopSettings.enableComputeMaterialVariants, (value) => m_Asset.lightLoopSettings.enableComputeMaterialVariants = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Async Compute", () => m_Asset.lightLoopSettings.enableAsyncCompute, (value) => m_Asset.lightLoopSettings.enableAsyncCompute = (bool)value, DebugItemFlag.RuntimeOnly);
}
void InitializeDebugMaterials()

return NeedDepthBufferCopy() ? m_CameraDepthBufferCopy : m_CameraDepthStencilBuffer;
}
RenderTargetIdentifier GetStencilTexture()
{
return NeedStencilBufferCopy() ? m_CameraStencilBufferCopyRT : m_CameraDepthStencilBufferRT;
}
RenderTargetIdentifier GetHTile()
{
// Currently, Unity does not offer a way to access the GCN HTile.

}
}
void PrepareAndBindStencilTexture(CommandBuffer cmd)
{
if (NeedStencilBufferCopy())
{
using (new ProfilingSample(cmd, "Copy StencilBuffer", GetSampler(CustomSamplerId.CopyStencilBuffer)))
{
cmd.SetRandomWriteTarget(1, GetHTile());
// Our method of exporting the stencil requires one pass per unique stencil value.
CoreUtils.DrawFullScreen(cmd, m_CopyStencilForSplitLighting, m_CameraStencilBufferCopyRT, m_CameraDepthStencilBufferRT);
CoreUtils.DrawFullScreen(cmd, m_CopyStencilForRegularLighting, m_CameraStencilBufferCopyRT, m_CameraDepthStencilBufferRT);
cmd.ClearRandomWriteTargets();
}
}
cmd.SetGlobalTexture(HDShaderIDs._HTile, GetHTile());
cmd.SetGlobalTexture(HDShaderIDs._StencilTexture, GetStencilTexture());
}
public void UpdateCommonSettings()
{
var commonSettings = commonSettingsToUse;

foreach (var camera in cameras)
{
// This is the main command buffer used for the frame.
var cmd = CommandBufferPool.Get("");
// This is the main command buffer used for the frame.
var cmd = CommandBufferPool.Get("");
using (new ProfilingSample(cmd, "HDRenderPipeline::Render", GetSampler(CustomSamplerId.HDRenderPipelineRender)))
{
using (new ProfilingSample(cmd, "HDRenderPipeline::Render", GetSampler(CustomSamplerId.HDRenderPipelineRender)))
{
foreach (var material in m_MaterialList)
material.RenderInit(cmd);
foreach (var material in m_MaterialList)
material.RenderInit(cmd);
// Do anything we need to do upon a new frame.
m_LightLoop.NewFrame();
if (camera == null)
{
renderContext.Submit();
continue;
}
// Do anything we need to do upon a new frame.
m_LightLoop.NewFrame();
// If we render a reflection view or a preview we should not display any debug information
// This need to be call before ApplyDebugDisplaySettings()
if (camera.cameraType == CameraType.Reflection || camera.cameraType == CameraType.Preview)
{
// Neutral allow to disable all debug settings
m_CurrentDebugDisplaySettings = s_NeutralDebugDisplaySettings;
}
else
{
m_CurrentDebugDisplaySettings = m_DebugDisplaySettings;
if (camera == null)
{
renderContext.Submit();
continue;
}
using (new ProfilingSample(cmd, "Volume Update", GetSampler(CustomSamplerId.VolumeUpdate)))
{
// TODO: Transform & layer should be configurable per camera
VolumeManager.instance.Update(camera.transform, -1);
}
}
// If we render a reflection view or a preview we should not display any debug information
// This need to be call before ApplyDebugDisplaySettings()
if (camera.cameraType == CameraType.Reflection || camera.cameraType == CameraType.Preview)
{
// Neutral allow to disable all debug settings
m_CurrentDebugDisplaySettings = s_NeutralDebugDisplaySettings;
}
else
{
m_CurrentDebugDisplaySettings = m_DebugDisplaySettings;
ApplyDebugDisplaySettings(cmd);
UpdateCommonSettings();
using (new ProfilingSample(cmd, "Volume Update", GetSampler(CustomSamplerId.VolumeUpdate)))
{
// TODO: Transform & layer should be configurable per camera
VolumeManager.instance.Update(camera.transform, -1);
}
}
ApplyDebugDisplaySettings(cmd);
UpdateCommonSettings();
if (!m_IBLFilterGGX.IsInitialized())
m_IBLFilterGGX.Initialize(cmd);
if (!m_IBLFilterGGX.IsInitialized())
m_IBLFilterGGX.Initialize(cmd);
ScriptableCullingParameters cullingParams;
if (!CullResults.GetCullingParameters(camera, out cullingParams))
{
renderContext.Submit();
continue;
}
ScriptableCullingParameters cullingParams;
if (!CullResults.GetCullingParameters(camera, out cullingParams))
{
renderContext.Submit();
continue;
}
m_LightLoop.UpdateCullingParameters( ref cullingParams );
m_LightLoop.UpdateCullingParameters( ref cullingParams );
// emit scene view UI
if (camera.cameraType == CameraType.SceneView)
{
ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
}
// emit scene view UI
if (camera.cameraType == CameraType.SceneView)
{
ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
}
using (new ProfilingSample(cmd, "CullResults.Cull", GetSampler(CustomSamplerId.CullResultsCull)))
{
CullResults.Cull(ref cullingParams, renderContext,ref m_CullResults);
}
using (new ProfilingSample(cmd, "CullResults.Cull", GetSampler(CustomSamplerId.CullResultsCull)))
{
CullResults.Cull(ref cullingParams, renderContext,ref m_CullResults);
}
var postProcessLayer = camera.GetComponent<PostProcessLayer>();
var hdCamera = HDCamera.Get(camera, postProcessLayer, m_Asset.globalRenderingSettings, stereoActive);
m_LightLoop.UpdateRenderingPathState(hdCamera.useForwardOnly);
var postProcessLayer = camera.GetComponent<PostProcessLayer>();
var hdCamera = HDCamera.Get(camera, postProcessLayer, m_Asset.globalRenderingSettings, stereoActive);
m_LightLoop.UpdateRenderingPathState(hdCamera.useForwardOnly);
Resize(camera);
Resize(camera);
renderContext.SetupCameraProperties(camera);
renderContext.SetupCameraProperties(camera);
PushGlobalParams(hdCamera, cmd, sssSettings);
PushGlobalParams(hdCamera, cmd, sssSettings);
// TODO: Find a correct place to bind these material textures
// We have to bind the material specific global parameters in this mode
m_MaterialList.ForEach(material => material.Bind());
// TODO: Find a correct place to bind these material textures
// We have to bind the material specific global parameters in this mode
m_MaterialList.ForEach(material => material.Bind());
var additionalCameraData = camera.GetComponent<HDAdditionalCameraData>();
if (additionalCameraData && additionalCameraData.renderingPath == RenderingPathHDRP.Unlit)
{
// TODO: Add another path dedicated to planar reflection / real time cubemap that implement simpler lighting
// It is up to the users to only send unlit object for this camera path
var additionalCameraData = camera.GetComponent<HDAdditionalCameraData>();
if (additionalCameraData && additionalCameraData.renderingPath == RenderingPathHDRP.Unlit)
{
// TODO: Add another path dedicated to planar reflection / real time cubemap that implement simpler lighting
// It is up to the users to only send unlit object for this camera path
using (new ProfilingSample(cmd, "Forward", GetSampler(CustomSamplerId.Forward)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Color | ClearFlag.Depth);
RenderOpaqueRenderList(m_CullResults, camera, renderContext, cmd, HDShaderPassNames.s_ForwardName);
RenderTransparentRenderList(m_CullResults, camera, renderContext, cmd, HDShaderPassNames.s_ForwardName, false);
}
using (new ProfilingSample(cmd, "Forward", GetSampler(CustomSamplerId.Forward)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Color | ClearFlag.Depth);
RenderOpaqueRenderList(m_CullResults, camera, renderContext, cmd, HDShaderPassNames.s_ForwardName);
RenderTransparentRenderList(m_CullResults, camera, renderContext, cmd, HDShaderPassNames.s_ForwardName, false);
}
renderContext.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
renderContext.Submit();
continue;
}
renderContext.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
renderContext.Submit();
continue;
}
// Note: Legacy Unity behave like this for ShadowMask
// When you select ShadowMask in Lighting panel it recompile shaders on the fly with the SHADOW_MASK keyword.
// However there is no C# function that we can query to know what mode have been select in Lighting Panel and it will be wrong anyway. Lighting Panel setup what will be the next bake mode. But until light is bake, it is wrong.
// Currently to know if you need shadow mask you need to go through all visible lights (of CullResult), check the LightBakingOutput struct and look at lightmapBakeType/mixedLightingMode. If one light have shadow mask bake mode, then you need shadow mask features (i.e extra Gbuffer).
// It mean that when we build a standalone player, if we detect a light with bake shadow mask, we generate all shader variant (with and without shadow mask) and at runtime, when a bake shadow mask light is visible, we dynamically allocate an extra GBuffer and switch the shader.
// So the first thing to do is to go through all the light: PrepareLightsForGPU
bool enableBakeShadowMask;
using (new ProfilingSample(cmd, "TP_PrepareLightsForGPU", GetSampler(CustomSamplerId.TPPrepareLightsForGPU)))
{
enableBakeShadowMask = m_LightLoop.PrepareLightsForGPU(cmd, m_ShadowSettings, m_CullResults, camera);
}
ConfigureForShadowMask(enableBakeShadowMask, cmd);
// Note: Legacy Unity behave like this for ShadowMask
// When you select ShadowMask in Lighting panel it recompile shaders on the fly with the SHADOW_MASK keyword.
// However there is no C# function that we can query to know what mode have been select in Lighting Panel and it will be wrong anyway. Lighting Panel setup what will be the next bake mode. But until light is bake, it is wrong.
// Currently to know if you need shadow mask you need to go through all visible lights (of CullResult), check the LightBakingOutput struct and look at lightmapBakeType/mixedLightingMode. If one light have shadow mask bake mode, then you need shadow mask features (i.e extra Gbuffer).
// It mean that when we build a standalone player, if we detect a light with bake shadow mask, we generate all shader variant (with and without shadow mask) and at runtime, when a bake shadow mask light is visible, we dynamically allocate an extra GBuffer and switch the shader.
// So the first thing to do is to go through all the light: PrepareLightsForGPU
bool enableBakeShadowMask;
using (new ProfilingSample(cmd, "TP_PrepareLightsForGPU", GetSampler(CustomSamplerId.TPPrepareLightsForGPU)))
{
enableBakeShadowMask = m_LightLoop.PrepareLightsForGPU(cmd, m_ShadowSettings, m_CullResults, camera);
}
ConfigureForShadowMask(enableBakeShadowMask, cmd);
InitAndClearBuffer(hdCamera, enableBakeShadowMask, cmd);
InitAndClearBuffer(hdCamera, enableBakeShadowMask, cmd);
RenderDepthPrepass(m_CullResults, hdCamera, renderContext, cmd);
RenderDepthPrepass(m_CullResults, hdCamera, renderContext, cmd);
RenderGBuffer(m_CullResults, hdCamera, renderContext, cmd);
RenderGBuffer(m_CullResults, hdCamera, renderContext, cmd);
// In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing.
CopyDepthBufferIfNeeded(cmd);
// In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing.
CopyDepthBufferIfNeeded(cmd);
RenderPyramidDepth(camera, cmd, renderContext, FullScreenDebugMode.DepthPyramid);
RenderPyramidDepth(camera, cmd, renderContext, FullScreenDebugMode.DepthPyramid);
// Required for the SSS and the shader feature classification pass.
PrepareAndBindStencilTexture(cmd);
if (m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled())
{
RenderDebugViewMaterial(m_CullResults, hdCamera, renderContext, cmd);
}
else
{
using (new ProfilingSample(cmd, "Render SSAO", GetSampler(CustomSamplerId.RenderSSAO)))
{
// TODO: Everything here (SSAO, Shadow, Build light list, deferred shadow, material and light classification can be parallelize with Async compute)
RenderSSAO(cmd, camera, renderContext, postProcessLayer);
}
if (m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled())
{
RenderDebugViewMaterial(m_CullResults, hdCamera, renderContext, cmd);
}
else
{
using (new ProfilingSample(cmd, "Render SSAO", GetSampler(CustomSamplerId.RenderSSAO)))
{
// TODO: Everything here (SSAO, Shadow, Build light list, deferred shadow, material and light classification can be parallelize with Async compute)
RenderSSAO(cmd, camera, renderContext, postProcessLayer);
}
bool enableAsyncCompute = m_LightLoop.IsAsyncEnabled();
GPUFence buildGPULightListsCompleteFence = new GPUFence();
if (enableAsyncCompute)
{
GPUFence startFence = cmd.CreateGPUFence();
renderContext.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
cmd = CommandBufferPool.Get("");
bool enableAsyncCompute = m_LightLoop.IsAsyncEnabled();
GPUFence buildGPULightListsCompleteFence = new GPUFence();
if (enableAsyncCompute)
{
GPUFence startFence = cmd.CreateGPUFence();
renderContext.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
cmd = CommandBufferPool.Get("");
buildGPULightListsCompleteFence = m_LightLoop.BuildGPULightListsAsyncBegin(camera, renderContext, m_CameraDepthStencilBufferRT, m_CameraStencilBufferCopyRT, startFence);
}
buildGPULightListsCompleteFence = m_LightLoop.BuildGPULightListsAsyncBegin(camera, renderContext, m_CameraDepthStencilBufferRT, GetStencilTexture(), startFence);
}
using (new ProfilingSample(cmd, "Render shadows", GetSampler(CustomSamplerId.RenderShadows)))
{
m_LightLoop.RenderShadows(renderContext, cmd, m_CullResults);
// TODO: check if statement below still apply
renderContext.SetupCameraProperties(camera); // Need to recall SetupCameraProperties after RenderShadows as it modify our view/proj matrix
}
using (new ProfilingSample(cmd, "Render shadows", GetSampler(CustomSamplerId.RenderShadows)))
{
m_LightLoop.RenderShadows(renderContext, cmd, m_CullResults);
// TODO: check if statement below still apply
renderContext.SetupCameraProperties(camera); // Need to recall SetupCameraProperties after RenderShadows as it modify our view/proj matrix
}
using (new ProfilingSample(cmd, "Deferred directional shadows", GetSampler(CustomSamplerId.RenderDeferredDirectionalShadow)))
{
cmd.ReleaseTemporaryRT(m_DeferredShadowBuffer);
cmd.GetTemporaryRT(m_DeferredShadowBuffer, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear, 1 , true);
m_LightLoop.RenderDeferredDirectionalShadow(hdCamera, m_DeferredShadowBufferRT, GetDepthTexture(), cmd);
PushFullScreenDebugTexture(cmd, m_DeferredShadowBuffer, hdCamera.camera, renderContext, FullScreenDebugMode.DeferredShadows);
}
using (new ProfilingSample(cmd, "Deferred directional shadows", GetSampler(CustomSamplerId.RenderDeferredDirectionalShadow)))
{
cmd.ReleaseTemporaryRT(m_DeferredShadowBuffer);
cmd.GetTemporaryRT(m_DeferredShadowBuffer, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear, 1 , true);
m_LightLoop.RenderDeferredDirectionalShadow(hdCamera, m_DeferredShadowBufferRT, GetDepthTexture(), cmd);
PushFullScreenDebugTexture(cmd, m_DeferredShadowBuffer, hdCamera.camera, renderContext, FullScreenDebugMode.DeferredShadows);
}
// TODO: Move this code inside LightLoop
if (m_LightLoop.GetFeatureVariantsEnabled())
{
// For material classification we use compute shader and so can't read into the stencil, so prepare it.
using (new ProfilingSample(cmd, "Clear and copy stencil texture", GetSampler(CustomSamplerId.ClearAndCopyStencilTexture)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraStencilBufferCopyRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
if (enableAsyncCompute)
{
m_LightLoop.BuildGPULightListAsyncEnd(camera, cmd, buildGPULightListsCompleteFence);
}
else
{
using (new ProfilingSample(cmd, "Build Light list", GetSampler(CustomSamplerId.BuildLightList)))
{
m_LightLoop.BuildGPULightLists(camera, cmd, m_CameraDepthStencilBufferRT, GetStencilTexture());
}
}
cmd.SetRandomWriteTarget(1, GetHTile());
// In the material classification shader we will simply test is we are no lighting
// Use ShaderPassID 1 => "Pass 1 - Write 1 if value different from stencilRef to output"
CoreUtils.DrawFullScreen(cmd, m_CopyStencilForNoLighting, m_CameraStencilBufferCopyRT, m_CameraDepthStencilBufferRT, null, 1);
cmd.ClearRandomWriteTargets();
}
}
// Caution: We require sun light here as some sky use the sun light to render, mean UpdateSkyEnvironment
// must be call after BuildGPULightLists.
// TODO: Try to arrange code so we can trigger this call earlier and use async compute here to run sky convolution during other passes (once we move convolution shader to compute).
UpdateSkyEnvironment(hdCamera, cmd);
if (enableAsyncCompute)
{
m_LightLoop.BuildGPULightListAsyncEnd(camera, cmd, buildGPULightListsCompleteFence);
}
else
{
using (new ProfilingSample(cmd, "Build Light list", GetSampler(CustomSamplerId.BuildLightList)))
{
m_LightLoop.BuildGPULightLists(camera, cmd, m_CameraDepthStencilBufferRT, m_CameraStencilBufferCopyRT);
}
}
RenderDeferredLighting(hdCamera, cmd);
// Caution: We require sun light here as some sky use the sun light to render, mean UpdateSkyEnvironment
// must be call after BuildGPULightLists.
// TODO: Try to arrange code so we can trigger this call earlier and use async compute here to run sky convolution during other passes (once we move convolution shader to compute).
UpdateSkyEnvironment(hdCamera, cmd);
// We compute subsurface scattering here. Therefore, no objects rendered afterwards will exhibit SSS.
// Currently, there is no efficient way to switch between SRT and MRT for the forward pass;
// therefore, forward-rendered objects do not output split lighting required for the SSS pass.
SubsurfaceScatteringPass(hdCamera, cmd, sssSettings);
RenderDeferredLighting(hdCamera, cmd);
RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.Opaque);
RenderForwardError(m_CullResults, camera, renderContext, cmd, ForwardPass.Opaque);
RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.Opaque);
RenderForwardError(m_CullResults, camera, renderContext, cmd, ForwardPass.Opaque);
RenderSky(hdCamera, cmd);
// SSS pass here handle both SSS material from deferred and forward
SubsurfaceScatteringPass(hdCamera, cmd, sssSettings);
// Render pre refraction objects
RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.PreRefraction);
RenderForwardError(m_CullResults, camera, renderContext, cmd, ForwardPass.PreRefraction);
RenderSky(hdCamera, cmd);
RenderGaussianPyramidColor(camera, cmd, renderContext, FullScreenDebugMode.PreRefractionColorPyramid);
// Render pre refraction objects
RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.PreRefraction);
RenderForwardError(m_CullResults, camera, renderContext, cmd, ForwardPass.PreRefraction);
// Render all type of transparent forward (unlit, lit, complex (hair...)) to keep the sorting between transparent objects.
RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.Transparent);
RenderForwardError(m_CullResults, camera, renderContext, cmd, ForwardPass.Transparent);
RenderGaussianPyramidColor(camera, cmd, renderContext, FullScreenDebugMode.PreRefractionColorPyramid);
PushFullScreenDebugTexture(cmd, m_CameraColorBuffer, camera, renderContext, FullScreenDebugMode.NanTracker);
// Render all type of transparent forward (unlit, lit, complex (hair...)) to keep the sorting between transparent objects.
RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.Transparent);
RenderForwardError(m_CullResults, camera, renderContext, cmd, ForwardPass.Transparent);
// Planar and real time cubemap doesn't need post process and render in FP16
if (camera.cameraType == CameraType.Reflection)
{
using (new ProfilingSample(cmd, "Blit to final RT", GetSampler(CustomSamplerId.BlitToFinalRT)))
{
// Simple blit
cmd.Blit(m_CameraColorBufferRT, BuiltinRenderTextureType.CameraTarget);
}
}
else
{
RenderVelocity(m_CullResults, hdCamera, renderContext, cmd); // Note we may have to render velocity earlier if we do temporalAO, temporal volumetric etc... Mean we will not take into account forward opaque in case of deferred rendering ?
PushFullScreenDebugTexture(cmd, m_CameraColorBuffer, camera, renderContext, FullScreenDebugMode.NanTracker);
RenderGaussianPyramidColor(camera, cmd, renderContext, FullScreenDebugMode.FinalColorPyramid);
// Planar and real time cubemap doesn't need post process and render in FP16
if (camera.cameraType == CameraType.Reflection)
{
using (new ProfilingSample(cmd, "Blit to final RT", GetSampler(CustomSamplerId.BlitToFinalRT)))
{
// Simple blit
cmd.Blit(m_CameraColorBufferRT, BuiltinRenderTextureType.CameraTarget);
}
}
else
{
RenderVelocity(m_CullResults, hdCamera, renderContext, cmd); // Note we may have to render velocity earlier if we do temporalAO, temporal volumetric etc... Mean we will not take into account forward opaque in case of deferred rendering ?
// TODO: Check with VFX team.
// Rendering distortion here have off course lot of artifact.
// But resolving at each objects that write in distortion is not possible (need to sort transparent, render those that do not distort, then resolve, then etc...)
// Instead we chose to apply distortion at the end after we cumulate distortion vector and desired blurriness.
AccumulateDistortion(m_CullResults, camera, renderContext, cmd);
RenderDistortion(cmd, m_Asset.renderPipelineResources);
RenderGaussianPyramidColor(camera, cmd, renderContext, FullScreenDebugMode.FinalColorPyramid);
// TODO: Check with VFX team.
// Rendering distortion here have off course lot of artifact.
// But resolving at each objects that write in distortion is not possible (need to sort transparent, render those that do not distort, then resolve, then etc...)
// Instead we chose to apply distortion at the end after we cumulate distortion vector and desired blurriness.
AccumulateDistortion(m_CullResults, camera, renderContext, cmd);
RenderDistortion(cmd, m_Asset.renderPipelineResources);
RenderPostProcesses(hdCamera, cmd, postProcessLayer);
}
}
RenderPostProcesses(hdCamera, cmd, postProcessLayer);
}
}
RenderDebug(hdCamera, cmd);
RenderDebug(hdCamera, cmd);
// Make sure to unbind every render texture here because in the next iteration of the loop we might have to reallocate render texture (if the camera size is different)
cmd.SetRenderTarget(new RenderTargetIdentifier(-1), new RenderTargetIdentifier(-1));
// Make sure to unbind every render texture here because in the next iteration of the loop we might have to reallocate render texture (if the camera size is different)
cmd.SetRenderTarget(new RenderTargetIdentifier(-1), new RenderTargetIdentifier(-1));
// We still need to bind correctly default camera target with our depth buffer in case we are currently rendering scene view. It should be the last camera here
// We still need to bind correctly default camera target with our depth buffer in case we are currently rendering scene view. It should be the last camera here
// bind depth surface for editor grid/gizmo/selection rendering
if (camera.cameraType == CameraType.SceneView)
cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget, m_CameraDepthStencilBufferRT);
// bind depth surface for editor grid/gizmo/selection rendering
if (camera.cameraType == CameraType.SceneView)
cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget, m_CameraDepthStencilBufferRT);
}
renderContext.ExecuteCommandBuffer(cmd);
}
// Caution: ExecuteCommandBuffer must be outside of the profiling bracket
renderContext.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
renderContext.Submit();
CommandBufferPool.Release(cmd);
renderContext.Submit();
} // For each camera
}

// Combines specular lighting and diffuse lighting with subsurface scattering.
void SubsurfaceScatteringPass(HDCamera hdCamera, CommandBuffer cmd, SubsurfaceScatteringSettings sssParameters)
{
// Currently, forward-rendered objects do not output split lighting required for the SSS pass.
if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission || hdCamera.useForwardOnly)
if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)
return;
using (new ProfilingSample(cmd, "Subsurface Scattering", GetSampler(CustomSamplerId.SubsurfaceScattering)))

using (new ProfilingSample(cmd, "HTile for SSS", GetSampler(CustomSamplerId.HTileForSSS)))
{
CoreUtils.SetRenderTarget(cmd, m_HTileRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
cmd.SetRandomWriteTarget(1, GetHTile());
// Generate HTile for the split lighting stencil usage. Don't write into stencil texture (shaderPassId = 2)
// Use ShaderPassID 1 => "Pass 2 - Export HTILE for stencilRef to output"
CoreUtils.DrawFullScreen(cmd, m_CopyStencilForSplitLighting, m_CameraStencilBufferCopyRT, m_CameraDepthStencilBufferRT, null, 2);
cmd.ClearRandomWriteTargets();
}
// TODO: Remove this once fix, see comment inside the function
hdCamera.SetupComputeShader(m_SubsurfaceScatteringCS, cmd);

cmd.SetComputeFloatParam(m_SubsurfaceScatteringCS, HDShaderIDs._TexturingModeFlags, *(float*)&texturingModeFlags);
}
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._FilterKernels, sssParameters.filterKernels);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._WorldScales, sssParameters.worldScales);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._FilterKernels, sssParameters.filterKernels);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._ShapeParams, sssParameters.shapeParams);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture0, m_GbufferManager.GetGBuffers()[0]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture1, m_GbufferManager.GetGBuffers()[1]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture2, m_GbufferManager.GetGBuffers()[2]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture3, m_GbufferManager.GetGBuffers()[3]);
for (int i = 0; i < m_SSSBufferManager.sssBufferCount; ++i)
{
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._SSSBufferTexture[i], m_SSSBufferManager.GetSSSBuffers(i));
}
if (NeedTemporarySubsurfaceBuffer())
{
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._CameraFilteringBuffer, m_CameraFilteringBufferRT);

}
else
{
for (int i = 0; i < m_SSSBufferManager.sssBufferCount; ++i)
{
cmd.SetGlobalTexture(HDShaderIDs._SSSBufferTexture[i], m_SSSBufferManager.GetSSSBuffers(i));
}
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraSssDiffuseLightingBufferRT); // Cannot set a RT on a material
m_SssVerticalFilterPass.SetVectorArray(HDShaderIDs._FilterKernelsBasic, sssParameters.filterKernelsBasic);
m_SssVerticalFilterPass.SetVectorArray(HDShaderIDs._HalfRcpWeightedVariances, sssParameters.halfRcpWeightedVariances);

using (new ProfilingSample(cmd, profileName, GetSampler(CustomSamplerId.ForwardPassName)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
var camera = hdCamera.camera;
m_LightLoop.RenderForward(camera, cmd, pass == ForwardPass.Opaque);

// In case of forward SSS we will bind all the required target. It is up to the shader to write into it or not.
if (m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)
{
RenderTargetIdentifier[] m_MRTWithSSS = new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];
m_MRTWithSSS[0] = m_CameraColorBufferRT; // Store the specular color
m_MRTWithSSS[1] = m_CameraSssDiffuseLightingBufferRT;
for (int i = 0; i < m_SSSBufferManager.sssBufferCount; ++i)
{
m_MRTWithSSS[i + 2] = m_SSSBufferManager.GetSSSBuffers(i);
}
CoreUtils.SetRenderTarget(cmd, m_MRTWithSSS, m_CameraDepthStencilBufferRT);
}
else
{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
}
if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())
{
m_ForwardAndForwardOnlyPassNames[0] = m_ForwardOnlyPassNames[0] = HDShaderPassNames.s_ForwardOnlyDebugDisplayName;

}
else
{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
var passNames = m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() ? m_AllTransparentDebugDisplayPassNames : m_AllTransparentPassNames;
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, passNames, pass == ForwardPass.PreRefraction, m_currentRendererConfigurationBakedLighting);
}

// End
if (!camera.useForwardOnly)
{
m_SSSBufferManager.InitGBuffers(w, h, m_GbufferManager, cmd);
}
else
{
// We need to allocate target for SSS
m_SSSBufferManager.InitGBuffers(w, h, cmd);
}
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Depth);
}

}
}
// <<< Old SSS Model
if (NeedStencilBufferCopy())
{
using (new ProfilingSample(cmd, "Clear stencil texture", GetSampler(CustomSamplerId.ClearStencilTexture)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraStencilBufferCopyRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}
}
if (NeedHTileCopy())
{
using (new ProfilingSample(cmd, "Clear HTile", GetSampler(CustomSamplerId.ClearHTile)))
{
CoreUtils.SetRenderTarget(cmd, m_HTileRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}
}
// TODO: As we are in development and have not all the setup pass we still clear the color in emissive buffer and gbuffer, but this will be removed later.

3
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset


pointCookieSize: 512
reflectionCubemapSize: 128
reflectionCacheCompressed: 0
sssSettings: {fileID: 11400000, guid: 873499ce7a6f749408981f512a9683f7, type: 2}
sssSettings: {fileID: 11400000, guid: c4d57f106d34d0046a33b3e66da29a72, type: 2}
tileSettings:
enableTileAndCluster: 1
enableComputeLightEvaluation: 1

enableBigTilePrepass: 1
enableAsyncCompute: 0
shadowInitParams:
shadowAtlasWidth: 4096
shadowAtlasHeight: 4096

2
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.cs


public GlobalRenderingSettings globalRenderingSettings = new GlobalRenderingSettings();
public GlobalTextureSettings globalTextureSettings = new GlobalTextureSettings();
public SubsurfaceScatteringSettings sssSettings;
public LightLoopSettings tileSettings = new LightLoopSettings();
public LightLoopSettings lightLoopSettings = new LightLoopSettings();
// Shadow Settings
public ShadowInitParameters shadowInitParams = new ShadowInitParameters();

13
ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs


public static readonly int g_BaseFeatureFlags = Shader.PropertyToID("g_BaseFeatureFlags");
public static readonly int g_TileFeatureFlags = Shader.PropertyToID("g_TileFeatureFlags");
public static readonly int _GBufferTexture0 = Shader.PropertyToID("_GBufferTexture0");
public static readonly int _GBufferTexture1 = Shader.PropertyToID("_GBufferTexture1");
public static readonly int _GBufferTexture2 = Shader.PropertyToID("_GBufferTexture2");
public static readonly int _GBufferTexture3 = Shader.PropertyToID("_GBufferTexture3");
public static readonly int g_DispatchIndirectBuffer = Shader.PropertyToID("g_DispatchIndirectBuffer");
public static readonly int g_TileList = Shader.PropertyToID("g_TileList");
public static readonly int g_NumTiles = Shader.PropertyToID("g_NumTiles");

Shader.PropertyToID("_GBufferTexture5"),
Shader.PropertyToID("_GBufferTexture6"),
Shader.PropertyToID("_GBufferTexture7")
};
public static readonly int[] _SSSBufferTexture =
{
Shader.PropertyToID("_SSSBufferTexture0"),
Shader.PropertyToID("_SSSBufferTexture1"),
Shader.PropertyToID("_SSSBufferTexture2"),
Shader.PropertyToID("_SSSBufferTexture3"),
};
public static readonly int _VelocityTexture = Shader.PropertyToID("_VelocityTexture");

6
ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs


public struct DirectionalLightData
{
public Vector3 positionWS;
public bool tileCookie;
public int tileCookie; // TODO: make it a bool
public Vector3 color;
public int shadowIndex; // -1 if unused

public Vector2 fadeDistanceScaleAndBias; // Use with ShadowMask feature
public float unused0;
public bool dynamicShadowCasterOnly; // Use with ShadowMask feature
public int dynamicShadowCasterOnly; // Use with ShadowMask feature // TODO: make it a bool
public Vector4 shadowMaskSelector; // Use with ShadowMask feature
};

public float angleScale; // Spot light
public float angleOffset; // Spot light
public float shadowDimmer;
public bool dynamicShadowCasterOnly; // Use with ShadowMask feature
public int dynamicShadowCasterOnly; // Use with ShadowMask feature // TODO: make it a bool
public Vector4 shadowMaskSelector; // Use with ShadowMask feature

12
ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs.hlsl


struct DirectionalLightData
{
float3 positionWS;
bool tileCookie;
int tileCookie;
float3 color;
int shadowIndex;
float3 forward;

float diffuseScale;
float2 fadeDistanceScaleAndBias;
float unused0;
bool dynamicShadowCasterOnly;
int dynamicShadowCasterOnly;
float4 shadowMaskSelector;
};

float angleScale;
float angleOffset;
float shadowDimmer;
bool dynamicShadowCasterOnly;
int dynamicShadowCasterOnly;
float4 shadowMaskSelector;
float2 size;
int lightType;

{
return value.positionWS;
}
bool GetTileCookie(DirectionalLightData value)
int GetTileCookie(DirectionalLightData value)
{
return value.tileCookie;
}

{
return value.unused0;
}
bool GetDynamicShadowCasterOnly(DirectionalLightData value)
int GetDynamicShadowCasterOnly(DirectionalLightData value)
{
return value.dynamicShadowCasterOnly;
}

{
return value.shadowDimmer;
}
bool GetDynamicShadowCasterOnly(LightData value)
int GetDynamicShadowCasterOnly(LightData value)
{
return value.dynamicShadowCasterOnly;
}

27
ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightLoop/LightLoop.cs


using UnityEngine.Rendering;
using UnityEngine.Rendering;
using System.Collections.Generic;
using System;

static ComputeBuffer s_GlobalLightListAtomic = null;
// clustered light list specific buffers and data end
bool m_isForwardRenderingOnly;
bool m_isFptlEnabled;
bool m_isFptlEnabledForForwardOpaque;

public bool GetFeatureVariantsEnabled()
{
return m_isFptlEnabled && m_LightLoopSettings.enableComputeLightEvaluation && (m_LightLoopSettings.enableComputeLightVariants || m_LightLoopSettings.enableComputeMaterialVariants);
return !m_isForwardRenderingOnly && m_isFptlEnabled && m_LightLoopSettings.enableComputeLightEvaluation &&
(m_LightLoopSettings.enableComputeLightVariants || m_LightLoopSettings.enableComputeMaterialVariants);
}
LightLoopSettings m_LightLoopSettings = null;

}
public void Build( RenderPipelineResources renderPipelineResources,
LightLoopSettings tileSettings,
LightLoopSettings lightLoopSettings,
m_LightLoopSettings = tileSettings;
m_LightLoopSettings = lightLoopSettings;
m_lightList = new LightList();
m_lightList.Allocate();

if (light.light.cookie != null)
{
directionalLightData.tileCookie = light.light.cookie.wrapMode == TextureWrapMode.Repeat;
directionalLightData.tileCookie = light.light.cookie.wrapMode == TextureWrapMode.Repeat ? 1 : 0;
directionalLightData.cookieIndex = m_CookieTexArray.FetchSlice(cmd, light.light.cookie);
}
// fix up shadow information

{
directionalLightData.shadowMaskSelector[light.light.bakingOutput.occlusionMaskChannel] = 1.0f;
// TODO: make this option per light, not global
directionalLightData.dynamicShadowCasterOnly = QualitySettings.shadowmaskMode == ShadowmaskMode.Shadowmask;
directionalLightData.dynamicShadowCasterOnly = QualitySettings.shadowmaskMode == ShadowmaskMode.Shadowmask ? 1 : 0;
directionalLightData.dynamicShadowCasterOnly = false;
directionalLightData.dynamicShadowCasterOnly = 0;
}
m_CurrentSunLight = m_CurrentSunLight == null ? light.light : m_CurrentSunLight;

{
lightData.shadowMaskSelector[light.light.bakingOutput.occlusionMaskChannel] = 1.0f;
// TODO: make this option per light, not global
lightData.dynamicShadowCasterOnly = QualitySettings.shadowmaskMode == ShadowmaskMode.Shadowmask;
lightData.dynamicShadowCasterOnly = QualitySettings.shadowmaskMode == ShadowmaskMode.Shadowmask ? 1 : 0;
lightData.dynamicShadowCasterOnly = false;
lightData.dynamicShadowCasterOnly = 0;
}
m_lightList.lights.Add(lightData);

// In HD, MSAA is only supported for forward only rendering, no MSAA in deferred mode (for code complexity reasons)
// If Deferred, enable Fptl. If we are forward renderer only and not using Fptl for forward opaque, disable Fptl
m_isFptlEnabled = !useForwardRenderingOnly || m_LightLoopSettings.enableFptlForForwardOpaque; // TODO: Disable if MSAA
m_isForwardRenderingOnly = useForwardRenderingOnly;
m_isFptlEnabled = !m_isForwardRenderingOnly || m_LightLoopSettings.enableFptlForForwardOpaque; // TODO: Disable if MSAA
m_isFptlEnabledForForwardOpaque = m_LightLoopSettings.enableFptlForForwardOpaque; // TODO: Disable if MSAA
if (GetFeatureVariantsEnabled())

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

}
}
}
using (new ProfilingSample(cmd, "Display Shadows", HDRenderPipeline.GetSampler(CustomSamplerId.TPDisplayShadows)))
{
if (lightingDebug.shadowDebugMode == ShadowMapDebugMode.VisualizeShadowMap)

4
ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightLoop/materialflags.compute


int idx = i * NR_THREADS + threadID;
uint2 uCrd = min( uint2(viTilLL.x + (idx & 0xf), viTilLL.y + (idx >> 4)), uint2(iWidth - 1, iHeight - 1));
if (UnpackByte(LOAD_TEXTURE2D(_StencilTexture, uCrd).r) != STENCILLIGHTINGUSAGE_NO_LIGHTING) // This test is we are the sky/background or not
// StencilTexture here contain the result of testing if we are not equal to stencil usage NoLighting. i.e (stencil value != NoLighting). The 1.0 mean true.
// This test if we are the sky/background or a forward opaque (which tag the stencil as NoLighting)
if (LOAD_TEXTURE2D(_StencilTexture, uCrd).r == 1.0)
{
PositionInputs posInput = GetPositionInput(uCrd, invScreenSize);
materialFeatureFlags |= MATERIAL_FEATURE_FLAGS_FROM_GBUFFER(posInput.positionSS);

19
ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader


// This shader support vertex modification
#define HAVE_VERTEX_MODIFICATION
// If we use subsurface scattering, enable output split lighting (for forward pass)
#if defined(_MATID_SSS) && !defined(_SURFACE_TYPE_TRANSPARENT)
#define OUTPUT_SPLIT_LIGHTING
#endif
//-------------------------------------------------------------------------------------
// Include
//-------------------------------------------------------------------------------------

Name "Forward" // Name is not used
Tags{ "LightMode" = "Forward" } // This will be only for transparent object based on the RenderQueue index
Stencil
{
Ref[_StencilRef]
Comp Always
Pass Replace
}
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]
Cull[_CullMode]

{
Name "ForwardDebugDisplay" // Name is not used
Tags{ "LightMode" = "ForwardDebugDisplay" } // This will be only for transparent object based on the RenderQueue index
Stencil
{
Ref[_StencilRef]
Comp Always
Pass Replace
}
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]

19
ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader


#define HAVE_VERTEX_MODIFICATION
#define HAVE_TESSELLATION_MODIFICATION
// If we use subsurface scattering, enable output split lighting (for forward pass)
#if defined(_MATID_SSS) && !defined(_SURFACE_TYPE_TRANSPARENT)
#define OUTPUT_SPLIT_LIGHTING
#endif
//-------------------------------------------------------------------------------------
// Include
//-------------------------------------------------------------------------------------

Name "Forward" // Name is not used
Tags{ "LightMode" = "Forward" } // This will be only for transparent object based on the RenderQueue index
Stencil
{
Ref[_StencilRef]
Comp Always
Pass Replace
}
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]
Cull[_CullMode]

{
Name "ForwardDebugDisplay" // Name is not used
Tags{ "LightMode" = "ForwardDebugDisplay" } // This will be only for transparent object based on the RenderQueue index
Stencil
{
Ref[_StencilRef]
Comp Always
Pass Replace
}
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]

222
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl


// SurfaceData is define in Lit.cs which generate Lit.cs.hlsl
#include "Lit.cs.hlsl"
#include "SubsurfaceScatteringSettings.cs.hlsl"
#include "../SubsurfaceScattering/SubsurfaceScattering.hlsl"
// Define refraction keyword helpers
#define HAS_REFRACTION (defined(_REFRACTION_PLANE) || defined(_REFRACTION_SPHERE))

#define LTC_LUT_SIZE 64
#define LTC_LUT_SCALE ((LTC_LUT_SIZE - 1) * rcp(LTC_LUT_SIZE))
#define LTC_LUT_OFFSET (0.5 * rcp(LTC_LUT_SIZE))
// Subsurface scattering constant
#define SSS_WRAP_ANGLE (PI/12) // 15 degrees
#define SSS_WRAP_LIGHT cos(PI/2 - SSS_WRAP_ANGLE)
CBUFFER_START(UnitySSSParameters)
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.
// Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader.
uint _EnableSSSAndTransmission; // Globally toggles subsurface and transmission scattering on/off
float _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
float _TransmissionFlags; // 2 bit/profile; 0 = inf. thick, 1 = thin, 2 = regular
// Old SSS Model >>>
uint _UseDisneySSS;
float4 _HalfRcpVariancesAndWeights[SSS_N_PROFILES][2]; // 2x Gaussians in RGB, A is interpolation weights
// <<< Old SSS Model
// Use float4 to avoid any packing issue between compute and pixel shaders
float4 _ThicknessRemaps[SSS_N_PROFILES]; // R: start, G = end - start, BA unused
float4 _ShapeParams[SSS_N_PROFILES]; // RGB = S = 1 / D, A = filter radius
float4 _TransmissionTints[SSS_N_PROFILES]; // RGB = 1/4 * color, A = unused
float4 _WorldScales[SSS_N_PROFILES]; // X = meters per world unit; Y = world units per meter
CBUFFER_END
//-----------------------------------------------------------------------------
// Helper for cheap screen space raycasting

return int(round(f * 3.0));
}
void FillMaterialIdStandardData(float3 baseColor, float metallic, inout BSDFData bsdfData)
float3 ComputeDiffuseColor(float3 baseColor, float metallic)
bsdfData.diffuseColor = baseColor * (1.0 - metallic);
float val = DEFAULT_SPECULAR_VALUE;
bsdfData.fresnel0 = lerp(val.xxx, baseColor, metallic);
return baseColor * (1.0 - metallic);
void FillMaterialIdSSSData(float3 baseColor, inout BSDFData bsdfData)
float3 ComputeFresnel0(float3 baseColor, float metallic, float dielectricF0)
bsdfData.diffuseColor = baseColor;
bsdfData.fresnel0 = SKIN_SPECULAR_VALUE; // TODO take from subsurfaceProfile instead
return lerp(dielectricF0.xxx, baseColor, metallic);
void FillTransmissionData(int subsurfaceProfile, float subsurfaceRadius, float thickness, inout BSDFData bsdfData)
// Fills the data which may be accessed if MATERIALFEATUREFLAGS_LIT_SSS is set.
void FillMaterialIdSssData(int subsurfaceProfile, float radius, float thickness, uint transmissionMode,
inout BSDFData bsdfData)
bsdfData.subsurfaceProfile = subsurfaceProfile;
bsdfData.subsurfaceRadius = radius;
uint transmissionMode = BitFieldExtract(asuint(_TransmissionFlags), 2u, 2u * subsurfaceProfile);
bsdfData.subsurfaceProfile = subsurfaceProfile;
bsdfData.subsurfaceRadius = subsurfaceRadius;
bsdfData.thickness = _ThicknessRemaps[subsurfaceProfile].x + _ThicknessRemaps[subsurfaceProfile].y * thickness;
bsdfData.thickness = _ThicknessRemaps[subsurfaceProfile].x + _ThicknessRemaps[subsurfaceProfile].y * thickness;
if (_UseDisneySSS != 0)
{

}
}
// Returns the modified albedo (diffuse color) for materials with subsurface scattering.
// Ref: Advanced Techniques for Realistic Real-Time Skin Rendering.
float3 ApplyDiffuseTexturingMode(BSDFData bsdfData)
{
float3 albedo = bsdfData.diffuseColor;
if (bsdfData.materialId == MATERIALID_LIT_SSS)
{
#if defined(SHADERPASS) && (SHADERPASS == SHADERPASS_SUBSURFACE_SCATTERING)
// If the SSS pass is executed, we know we have SSS enabled.
bool enableSssAndTransmission = true;
#else
bool enableSssAndTransmission = _EnableSSSAndTransmission != 0;
#endif
if (enableSssAndTransmission)
{
bool performPostScatterTexturing = IsBitSet(asuint(_TexturingModeFlags), bsdfData.subsurfaceProfile);
if (performPostScatterTexturing)
{
// Post-scatter texturing mode: the albedo is only applied during the SSS pass.
#if !defined(SHADERPASS) || (SHADERPASS != SHADERPASS_SUBSURFACE_SCATTERING)
albedo = float3(1, 1, 1);
#endif
}
else
{
// Pre- and pos- scatter texturing mode.
albedo = sqrt(albedo);
}
}
}
return albedo;
}
void FillMaterialIdClearCoatData(float3 coatNormalWS, float coatCoverage, float coatIOR, inout BSDFData bsdfData)
{
bsdfData.coatNormalWS = lerp(bsdfData.normalWS, coatNormalWS, coatCoverage);

#endif
}
SSSData ConvertSurfaceDataToSSSData(SurfaceData surfaceData)
{
SSSData sssData;
sssData.diffuseColor = surfaceData.baseColor;
sssData.subsurfaceRadius = surfaceData.subsurfaceRadius;
sssData.subsurfaceProfile = surfaceData.subsurfaceProfile;
return sssData;
}
//-----------------------------------------------------------------------------
// conversion function for forward
//-----------------------------------------------------------------------------

// IMPORTANT: In case of foward or gbuffer pass we must know what we are statically, so compiler can do compile time optimization
if (bsdfData.materialId == MATERIALID_LIT_STANDARD)
{
FillMaterialIdStandardData(surfaceData.baseColor, surfaceData.metallic, bsdfData);
bsdfData.diffuseColor = ComputeDiffuseColor(surfaceData.baseColor, surfaceData.metallic);
bsdfData.fresnel0 = ComputeFresnel0(surfaceData.baseColor, surfaceData.metallic, DEFAULT_SPECULAR_VALUE);
bsdfData.materialId = MATERIALID_LIT_STANDARD;
bsdfData.materialId = MATERIALID_LIT_STANDARD;
bsdfData.fresnel0 = surfaceData.specularColor;
bsdfData.fresnel0 = surfaceData.specularColor;
FillMaterialIdSSSData(surfaceData.baseColor, bsdfData);
FillTransmissionData(surfaceData.subsurfaceProfile, surfaceData.subsurfaceRadius, surfaceData.thickness, bsdfData);
bsdfData.diffuseColor = surfaceData.baseColor;
bsdfData.fresnel0 = SKIN_SPECULAR_VALUE; // TODO: take from the SSS profile
uint transmissionMode = BitFieldExtract(asuint(_TransmissionFlags), 2u, 2u * surfaceData.subsurfaceProfile);
FillMaterialIdSssData(surfaceData.subsurfaceProfile,
surfaceData.subsurfaceRadius,
surfaceData.thickness,
transmissionMode, bsdfData);
FillMaterialIdStandardData(surfaceData.baseColor, surfaceData.metallic, bsdfData);
bsdfData.tangentWS = surfaceData.tangentWS;
bsdfData.bitangentWS = cross(bsdfData.normalWS, bsdfData.tangentWS);
bsdfData.diffuseColor = ComputeDiffuseColor(surfaceData.baseColor, surfaceData.metallic);
bsdfData.fresnel0 = ComputeFresnel0(surfaceData.baseColor, surfaceData.metallic, DEFAULT_SPECULAR_VALUE);
bsdfData.tangentWS = surfaceData.tangentWS;
bsdfData.bitangentWS = cross(bsdfData.normalWS, bsdfData.tangentWS);
bsdfData.diffuseColor = ComputeDiffuseColor(surfaceData.baseColor, surfaceData.metallic);
bsdfData.fresnel0 = ComputeFresnel0(surfaceData.baseColor, surfaceData.metallic, DEFAULT_SPECULAR_VALUE);
FillMaterialIdStandardData(surfaceData.baseColor, surfaceData.metallic, bsdfData);
FillMaterialIdClearCoatData(surfaceData.coatNormalWS, surfaceData.coatCoverage, surfaceData.coatIOR, bsdfData);
}

}
else if (surfaceData.materialId == MATERIALID_LIT_SSS)
{
outGBuffer2 = float4(surfaceData.subsurfaceRadius, surfaceData.thickness, 0.0, PackByte(surfaceData.subsurfaceProfile));
// Special case: For SSS we will store the profile id and the subsurface radius at the location of the specular occlusion (in alpha channel of GBuffer0)
// and we will move the specular occlusion in GBuffer2. This is an optimization for SSSSS and have no other side effect as specular occlusion is always used
// during lighting pass when other buffer (Gbuffer0, 1, 2) and read anyway.
EncodeIntoSSSBuffer(ConvertSurfaceDataToSSSData(surfaceData), positionSS, outGBuffer0);
outGBuffer2 = float4(surfaceData.specularOcclusion, surfaceData.thickness, 0.0, 0.0); // Thickness is use for transmission
}
else if (surfaceData.materialId == MATERIALID_LIT_ANISO)
{

bsdfData.materialId = MATERIALID_LIT_CLEAR_COAT;
}
float metallic = 0;
float dielectricF0 = DEFAULT_SPECULAR_VALUE;
bool specularColorMode = false;
// We avoid divergent evaluation of the GGX, as that nearly doubles the cost.
// If the tile has anisotropy, all the pixels within the tile are evaluated as anisotropic.
if (HasMaterialFeatureFlag(MATERIALFEATUREFLAGS_LIT_ANISO))

if (bsdfData.materialId == MATERIALID_LIT_ANISO)
{
float metallic;
int octTangentSign;
UnpackFloatInt8bit(inGBuffer2.a, 4.0, metallic, octTangentSign);

bsdfData.anisotropy = inGBuffer2.b * 2 - 1;
bsdfData.tangentWS = UnpackNormalOctEncode(inGBuffer2.rg);
FillMaterialIdStandardData(baseColor, metallic, bsdfData);
}
bsdfData.bitangentWS = cross(bsdfData.normalWS, bsdfData.tangentWS);

if (HasMaterialFeatureFlag(MATERIALFEATUREFLAGS_LIT_SSS))
{
float subsurfaceRadius = 0;
int subsurfaceProfile = SSS_NEUTRAL_PROFILE_ID;
uint transmissionMode = SSS_TRSM_MODE_NONE;
float radius = 0;
int subsurfaceProfile = SSS_NEUTRAL_PROFILE_ID;
subsurfaceRadius = inGBuffer2.x;
thickness = inGBuffer2.y;
subsurfaceProfile = UnpackByte(inGBuffer2.w);
// Reminder: when using SSS we exchange specular occlusion and subsurfaceRadius/profileID
bsdfData.specularOcclusion = inGBuffer2.r;
FillMaterialIdSSSData(baseColor, bsdfData);
SSSData sssData;
DecodeFromSSSBuffer(inGBuffer0, positionSS, sssData);
subsurfaceProfile = sssData.subsurfaceProfile;
transmissionMode = BitFieldExtract(asuint(_TransmissionFlags), 2u, 2u * subsurfaceProfile);
radius = sssData.subsurfaceRadius;
thickness = inGBuffer2.g;
dielectricF0 = SKIN_SPECULAR_VALUE; // TODO: take from the SSS profile
FillTransmissionData(subsurfaceProfile, subsurfaceRadius, thickness, bsdfData);
FillMaterialIdSssData(subsurfaceProfile, radius, thickness, transmissionMode, bsdfData);
float metallic;
[flatten] if (materialIdExtent == GBUFFER_LIT_STANDARD_SPECULAR_COLOR_ID)
{
// Note: Specular is not a material id but just a way to parameterize the standard materialid, thus we reset materialId to MATERIALID_LIT_STANDARD
// For material classification it will be consider as Standard as well, thus no need to create special case
bsdfData.diffuseColor = baseColor;
bsdfData.fresnel0 = inGBuffer2.rgb;
}
else // GBUFFER_LIT_STANDARD_REGULAR_ID
{
FillMaterialIdStandardData(baseColor, metallic, bsdfData);
}
specularColorMode = (materialIdExtent == GBUFFER_LIT_STANDARD_SPECULAR_COLOR_ID);
}
else if (bsdfData.materialId == MATERIALID_LIT_CLEAR_COAT && HasMaterialFeatureFlag(MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{

float coatCoverage = inGBuffer2.b;
float coatIOR;
int metallic;
UnpackFloatInt8bit(inGBuffer2.a, 16.0, coatIOR, metallic);
int metallic15;
UnpackFloatInt8bit(inGBuffer2.a, 16.0, coatIOR, metallic15);
metallic = metallic15 / 15.0;
FillMaterialIdStandardData(baseColor, metallic / 15.0f, bsdfData);
if (specularColorMode)
{
// Note: Specular is not a material id but just a way to parameterize the standard materialid, thus we reset materialId to MATERIALID_LIT_STANDARD
// For material classification it will be consider as Standard as well, thus no need to create special case
bsdfData.diffuseColor = baseColor;
bsdfData.fresnel0 = inGBuffer2.rgb;
}
else
{
bsdfData.diffuseColor = ComputeDiffuseColor(baseColor, metallic);
bsdfData.fresnel0 = ComputeFresnel0(baseColor, metallic, dielectricF0);
}
bakeDiffuseLighting = inGBuffer3.rgb;
}

// This function require the 3 structure surfaceData, builtinData, bsdfData because it may require both the engine side data, and data that will not be store inside the gbuffer.
float3 GetBakedDiffuseLigthing(SurfaceData surfaceData, BuiltinData builtinData, BSDFData bsdfData, PreLightData preLightData)
{
bsdfData.diffuseColor = ApplyDiffuseTexturingMode(bsdfData);
if (bsdfData.materialId == MATERIALID_LIT_SSS)
{
bsdfData.diffuseColor = ApplyDiffuseTexturingMode(bsdfData.diffuseColor, bsdfData.subsurfaceProfile);
}
// Premultiply bake diffuse lighting information with DisneyDiffuse pre-integration
return builtinData.bakeDiffuseLighting * preLightData.diffuseFGD * surfaceData.ambientOcclusion * bsdfData.diffuseColor + builtinData.emissiveColor;

lighting.specular *= intensity * lightData.specularScale;
}
[branch] if (bsdfData.enableTransmission)
[flatten] if (bsdfData.enableTransmission)
{
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
lighting.diffuse += EvaluateTransmission(bsdfData, NdotL, preLightData.NdotV, attenuation * lightData.diffuseScale);

// None of the outputs are premultiplied.
void EvaluateLight_Punctual(LightLoopContext lightLoopContext, PositionInputs posInput,
LightData lightData, BakeLightingData bakeLightingData,
float3 N, float3 L, float distSq,
float3 N, float3 L, float dist, float distSq,
out float3 color, out float attenuation)
{
float3 positionWS = posInput.positionWS;

{
// TODO: make projector lights cast shadows.
float3 offset = float3(0.0, 0.0, 0.0); // GetShadowPosOffset(nDotL, normal);
float4 L_dist = float4(L, sqrt(distSq));
float4 L_dist = float4(L, dist);
shadow = GetPunctualShadowAttenuation(lightLoopContext.shadowContext, positionWS + offset, N, lightData.shadowIndex, L_dist, posInput.positionSS);
#ifdef SHADOWS_SHADOWMASK
// Note: Legacy Unity have two shadow mask mode. ShadowMask (ShadowMask contain static objects shadow and ShadowMap contain only dynamic objects shadow, final result is the minimun of both value)

float3 lightToSample = posInput.positionWS - lightData.positionWS;
int lightType = lightData.lightType;
float3 unL = (lightType != GPULIGHTTYPE_PROJECTOR_BOX) ? -lightToSample : -lightData.forward;
float distSq = dot(unL, unL);
float3 N = bsdfData.normalWS;
float3 L = unL * rsqrt(distSq);
float NdotL = dot(N, L);
float3 unL = (lightType != GPULIGHTTYPE_PROJECTOR_BOX) ? -lightToSample : -lightData.forward;
float distSq = dot(unL, unL);
float distRcp = rsqrt(distSq);
float dist = distSq * distRcp;
float3 N = bsdfData.normalWS;
float3 L = unL * distRcp;
float NdotL = dot(N, L);
[flatten] if (bsdfData.useThickObjectMode && NdotL < 0)
{

float3 color; float attenuation;
EvaluateLight_Punctual(lightLoopContext, posInput, lightData, bakeLightingData, N, L, distSq,
EvaluateLight_Punctual(lightLoopContext, posInput, lightData, bakeLightingData, N, L, dist, distSq,
color, attenuation);
float intensity = attenuation * saturate(NdotL);

lighting.specular *= intensity * lightData.specularScale;
}
[branch] if (bsdfData.enableTransmission)
[flatten] if (bsdfData.enableTransmission)
{
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
lighting.diffuse += EvaluateTransmission(bsdfData, NdotL, preLightData.NdotV, attenuation * lightData.diffuseScale);

lerp(_AmbientOcclusionParam.rgb, float3(1.0, 1.0, 1.0), directAmbientOcclusion);
#endif
float3 modifiedDiffuseColor = ApplyDiffuseTexturingMode(bsdfData);
float3 modifiedDiffuseColor;
if (bsdfData.materialId == MATERIALID_LIT_SSS)
modifiedDiffuseColor = ApplyDiffuseTexturingMode(bsdfData.diffuseColor, bsdfData.subsurfaceProfile);
else
modifiedDiffuseColor = bsdfData.diffuseColor;
// Apply the albedo to the direct diffuse lighting (only once). The indirect (baked)
// diffuse lighting has already had the albedo applied in GetBakedDiffuseLigthing().

19
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader


// This shader support vertex modification
#define HAVE_VERTEX_MODIFICATION
// If we use subsurface scattering, enable output split lighting (for forward pass)
#if defined(_MATID_SSS) && !defined(_SURFACE_TYPE_TRANSPARENT)
#define OUTPUT_SPLIT_LIGHTING
#endif
//-------------------------------------------------------------------------------------
// Include
//-------------------------------------------------------------------------------------

Name "Forward" // Name is not used
Tags { "LightMode" = "Forward" } // This will be only for transparent object based on the RenderQueue index
Stencil
{
Ref[_StencilRef]
Comp Always
Pass Replace
}
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
Cull [_CullMode]

{
Name "ForwardDebugDisplay" // Name is not used
Tags{ "LightMode" = "ForwardDebugDisplay" } // This will be only for transparent object based on the RenderQueue index
Stencil
{
Ref[_StencilRef]
Comp Always
Pass Replace
}
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]

19
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader


#define HAVE_VERTEX_MODIFICATION
#define HAVE_TESSELLATION_MODIFICATION
// If we use subsurface scattering, enable output split lighting (for forward pass)
#if defined(_MATID_SSS) && !defined(_SURFACE_TYPE_TRANSPARENT)
#define OUTPUT_SPLIT_LIGHTING
#endif
//-------------------------------------------------------------------------------------
// Include
//-------------------------------------------------------------------------------------

Name "Forward" // Name is not used
Tags { "LightMode" = "Forward" } // This will be only for transparent object based on the RenderQueue index
Stencil
{
Ref[_StencilRef]
Comp Always
Pass Replace
}
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
Cull [_CullMode]

{
Name "ForwardDebugDisplay" // Name is not used
Tags{ "LightMode" = "ForwardDebugDisplay" } // This will be only for transparent object based on the RenderQueue index
Stencil
{
Ref[_StencilRef]
Comp Always
Pass Replace
}
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]

120
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CopyStencilBuffer.shader


[HideInInspector] _StencilRef("_StencilRef", Int) = 1
}
HLSLINCLUDE
#pragma target 4.5
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#include "ShaderLibrary/Common.hlsl"
#include "ShaderLibrary/Packing.hlsl"
#include "../../../ShaderVariables.hlsl"
#include "../../../Lighting/LightDefinition.cs.hlsl"
int _StencilRef;
RW_TEXTURE2D(float, _HTile); // DXGI_FORMAT_R8_UINT is not supported by Unity
struct Attributes
{
uint vertexID : SV_VertexID;
};
struct Varyings
{
float4 positionCS : SV_Position;
};
Varyings Vert(Attributes input)
{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
return output;
}
#pragma vertex Vert
ENDHLSL
Name "Pass 0 - Copy stencilRef to output"
Stencil
{
Ref [_StencilRef]

Blend Off
HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma multi_compile _ EXPORT_HTILE
// #pragma enable_d3d11_debug_symbols
#pragma vertex Vert
#include "ShaderLibrary/Packing.hlsl"
#include "../../../ShaderVariables.hlsl"
#include "../../../Lighting/LightDefinition.cs.hlsl"
// Force the stencil test before the UAV write.
[earlydepthstencil]
float4 Frag(Varyings input) : SV_Target // use SV_StencilRef in D3D 11.3+
{
return PackByte(_StencilRef);
}
int _StencilRef;
RW_TEXTURE2D(float, _HTile); // DXGI_FORMAT_R8_UINT is not supported by Unity
ENDHLSL
}
struct Attributes
Pass
{
Name "Pass 1 - Write 1 if value different from stencilRef to output"
Stencil
uint vertexID : SV_VertexID;
};
Ref [_StencilRef]
Comp NotEqual
Pass Keep
}
Cull Off
ZTest Always
ZWrite Off
Blend Off
struct Varyings
HLSLPROGRAM
#pragma fragment Frag
// Force the stencil test before the UAV write.
[earlydepthstencil]
float4 Frag(Varyings input) : SV_Target // use SV_StencilRef in D3D 11.3+
float4 positionCS : SV_Position;
};
return float4(1.0, 0.0, 0.0, 0.0); // 1.0 for true as it passes the condition
}
ENDHLSL
}
Varyings Vert(Attributes input)
Pass
{
Name "Pass 2 - Export HTILE for stencilRef to output"
Stencil
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
return output;
Ref [_StencilRef]
Comp Equal
Pass Keep
Cull Off
ZTest Always
ZWrite Off
Blend Off
ColorMask 0
HLSLPROGRAM
#pragma fragment Frag
// There's no need for atomics as we are always writing the same value.
// Note: the GCN tile size is 8x8 pixels.
_HTile[positionNDC / 8] = _StencilRef;
#ifdef EXPORT_HTILE
// There's no need for atomics as we are always writing the same value.
// Note: the GCN tile size is 8x8 pixels.
_HTile[positionNDC / 8] = _StencilRef;
#endif
return float4(0.0, 0.0, 0.0, 0.0);
}
return PackByte(_StencilRef);
}
ENDHLSL
}
}

27
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.compute


// Included headers
//--------------------------------------------------------------------------------------------------
#include "ShaderLibrary/Common.hlsl"
#include "ShaderLibrary\Fibonacci.hlsl"
#define UNITY_MATERIAL_LIT
#include "../../../Material/Material.hlsl"
#include "../../SubsurfaceScattering/SubsurfaceScattering.hlsl"
//--------------------------------------------------------------------------------------------------
// Inputs & outputs

[branch] if (!passedStencilTest || isOffScreen) { return; }
PositionInputs posInput = GetPositionInput(pixelCoord, _ScreenSize.zw);
PositionInputs posInput = GetPositionInput(pixelCoord, _ScreenSize.zw);
BSDFData bsdfData;
float3 unused;
DECODE_FROM_GBUFFER(pixelCoord, MATERIALFEATUREFLAGS_LIT_SSS, bsdfData, unused);
SSSData sssData;
DECODE_FROM_SSSBUFFER(posInput.positionSS, sssData);
int profileID = bsdfData.subsurfaceProfile;
float distScale = bsdfData.subsurfaceRadius;
int profileID = sssData.subsurfaceProfile;
float distScale = sssData.subsurfaceRadius;
float3 shapeParam = _ShapeParams[profileID].rgb;
float maxDistance = _ShapeParams[profileID].a;

// divergence of execution across the warp.
float maxDistInPixels = maxDistance * max(pixelsPerMm.x, pixelsPerMm.y);
float3 albedo = ApplyDiffuseTexturingMode(bsdfData);
float3 albedo = ApplyDiffuseTexturingMode(sssData.diffuseColor, profileID);
[branch] if (distScale == 0 || maxDistInPixels < 1)
{

float4x4 viewMatrix, projMatrix;
GetLeftHandedViewSpaceMatrices(viewMatrix, projMatrix);
// TODO: Since we have moved to forward SSS, we don't support anymore a bsdfData.normalWS.
// Once we include normal+roughness rendering during the prepass, we will have a buffer to bind here and we will be able to reuse this part of the algorithm on demand.
#if SSS_USE_TANGENT_PLANE
#error ThisWillNotCompile_SeeComment
#else
float3 normalVS = float3(0, 0, 0);
float3 tangentX = float3(0, 0, 0);
float3 tangentY = float3(0, 0, 0);
#endif
#if SSS_DEBUG_NORMAL_VS
// We expect the normal to be front-facing.

21
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.shader


#include "ShaderLibrary/Common.hlsl"
#include "../../../ShaderVariables.hlsl"
#define UNITY_MATERIAL_LIT // Needs to be defined before including Material.hlsl
#include "../../../Material/Material.hlsl"
#include "../../SubsurfaceScattering/SubsurfaceScattering.hlsl"
//-------------------------------------------------------------------------------------
// Inputs & outputs

float4 Frag(Varyings input) : SV_Target
{
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw);
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw);
// Note: When we are in this SubsurfaceScattering shader we know that we are a SSS material. This shader is strongly coupled with the deferred Lit.shader.
// We can use the material classification facility to help the compiler to know we use SSS material and optimize the code (and don't require to read gbuffer with materialId).
uint featureFlags = MATERIALFEATUREFLAGS_LIT_SSS;
// Note: When we are in this SubsurfaceScattering shader we know that we are a SSS material.
SSSData sssData;
DECODE_FROM_SSSBUFFER(posInput.positionSS, sssData);
BSDFData bsdfData;
float3 unused;
DECODE_FROM_GBUFFER(posInput.positionSS, featureFlags, bsdfData, unused);
int profileID = bsdfData.subsurfaceProfile;
float distScale = bsdfData.subsurfaceRadius;
int profileID = sssData.subsurfaceProfile;
float distScale = sssData.subsurfaceRadius;
float maxDistance = _FilterKernelsBasic[profileID][SSS_BASIC_N_SAMPLES - 1].a;
// Take the first (central) sample.

float halfRcpVariance = _HalfRcpWeightedVariances[profileID].a;
#endif
float3 albedo = ApplyDiffuseTexturingMode(bsdfData);
float3 albedo = ApplyDiffuseTexturingMode(sssData.diffuseColor, profileID);
#ifndef SSS_FILTER_HORIZONTAL_AND_COMBINE
albedo = float3(1, 1, 1);

2
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader


#define USE_LEGACY_UNITY_MATRIX_VARIABLES
#include "../../ShaderVariables.hlsl"
#ifdef SSS_MODEL_BASIC
#include "../../Material/Lit/SubsurfaceScatteringSettings.cs.hlsl"
#include "../../Material/SubsurfaceScattering/SubsurfaceScatteringSettings.cs.hlsl"
#endif
//-------------------------------------------------------------------------------------

1
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader


#include "ShaderLibrary/CommonMaterial.hlsl"
#define USE_LEGACY_UNITY_MATRIX_VARIABLES
#include "../../ShaderVariables.hlsl"
#include "../../Material/SubsurfaceScattering/CommonSubsurfaceScattering.hlsl"
//-------------------------------------------------------------------------------------
// Inputs & outputs

29
ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassForward.hlsl


#endif // TESSELLATION_ON
void Frag(PackedVaryingsToPS packedInput,
out float4 outColor : SV_Target0
#ifdef _DEPTHOFFSET_ON
, out float outputDepth : SV_Depth
#endif
#ifdef OUTPUT_SPLIT_LIGHTING
out float4 outColor : SV_Target0, // outSpecularLighting
out float4 outDiffuseLighting : SV_Target1,
OUTPUT_SSSBUFFER(outSSSBuffer)
#else
out float4 outColor : SV_Target0
#endif
#ifdef _DEPTHOFFSET_ON
, out float outputDepth : SV_Depth
#endif
)
{
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);

bakeLightingData.bakeShadowMask = float4(builtinData.shadowMask0, builtinData.shadowMask1, builtinData.shadowMask2, builtinData.shadowMask3);
#endif
LightLoop(V, posInput, preLightData, bsdfData, bakeLightingData, featureFlags, diffuseLighting, specularLighting);
#ifdef OUTPUT_SPLIT_LIGHTING
if (_EnableSSSAndTransmission != 0)
{
outColor = float4(specularLighting, 1.0);
outDiffuseLighting = float4(TagLightingForSSS(diffuseLighting), 1.0);
}
else
{
outColor = float4(diffuseLighting + specularLighting, 1.0);
outDiffuseLighting = 0;
}
ENCODE_INTO_SSSBUFFER(surfaceData, posInput.positionSS, outSSSBuffer);
#else
#endif
}
#ifdef _DEPTHOFFSET_ON

3
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SSSProfile.meta


fileFormatVersion: 2
guid: a0ba759eadcfdcc44bc08adad4960ed0
folderAsset: yes
timeCreated: 1493162006
licenseType: Pro
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

4
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SSSProfile/SSS Settings.asset.meta


fileFormatVersion: 2
guid: 873499ce7a6f749408981f512a9683f7
timeCreated: 1507649491
licenseType: Pro
guid: c4d57f106d34d0046a33b3e66da29a72
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000

82
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SSSProfile/SSS Settings.asset


m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 3418a08abd15e9a49af3ccbc9e15b5ea, type: 3}
m_Script: {fileID: 11500000, guid: b2686e09ec7aef44bad2843e4416f057, type: 3}
m_Name: SSS Settings
m_EditorClassIdentifier:
useDisneySSS: 1

scatterDistance1: {r: 0.3, g: 0.3, b: 0.3, a: 0}
scatterDistance2: {r: 0.5, g: 0.5, b: 0.5, a: 0}
lerpWeight: 1
- name: Profile 8
scatteringDistance: {r: 0.5, g: 0.5, b: 0.5, a: 1}
transmissionTint: {r: 1, g: 1, b: 1, a: 1}
texturingMode: 0
transmissionMode: 0
thicknessRemap: {x: 0, y: 5}
worldScale: 1
scatterDistance1: {r: 0.3, g: 0.3, b: 0.3, a: 0}
scatterDistance2: {r: 0.5, g: 0.5, b: 0.5, a: 0}
lerpWeight: 1
- name: Profile 9
scatteringDistance: {r: 0.5, g: 0.5, b: 0.5, a: 1}
transmissionTint: {r: 1, g: 1, b: 1, a: 1}
texturingMode: 0
transmissionMode: 0
thicknessRemap: {x: 0, y: 5}
worldScale: 1
scatterDistance1: {r: 0.3, g: 0.3, b: 0.3, a: 0}
scatterDistance2: {r: 0.5, g: 0.5, b: 0.5, a: 0}
lerpWeight: 1
- name: Profile 10
scatteringDistance: {r: 0.5, g: 0.5, b: 0.5, a: 1}
transmissionTint: {r: 1, g: 1, b: 1, a: 1}
texturingMode: 0
transmissionMode: 0
thicknessRemap: {x: 0, y: 5}
worldScale: 1
scatterDistance1: {r: 0.3, g: 0.3, b: 0.3, a: 0}
scatterDistance2: {r: 0.5, g: 0.5, b: 0.5, a: 0}
lerpWeight: 1
- name: Profile 11
scatteringDistance: {r: 0.5, g: 0.5, b: 0.5, a: 1}
transmissionTint: {r: 1, g: 1, b: 1, a: 1}
texturingMode: 0
transmissionMode: 0
thicknessRemap: {x: 0, y: 5}
worldScale: 1
scatterDistance1: {r: 0.3, g: 0.3, b: 0.3, a: 0}
scatterDistance2: {r: 0.5, g: 0.5, b: 0.5, a: 0}
lerpWeight: 1
- name: Profile 12
scatteringDistance: {r: 0.5, g: 0.5, b: 0.5, a: 1}
transmissionTint: {r: 1, g: 1, b: 1, a: 1}
texturingMode: 0
transmissionMode: 0
thicknessRemap: {x: 0, y: 5}
worldScale: 1
scatterDistance1: {r: 0.3, g: 0.3, b: 0.3, a: 0}
scatterDistance2: {r: 0.5, g: 0.5, b: 0.5, a: 0}
lerpWeight: 1
- name: Profile 13
scatteringDistance: {r: 0.5, g: 0.5, b: 0.5, a: 1}
transmissionTint: {r: 1, g: 1, b: 1, a: 1}
texturingMode: 0
transmissionMode: 0
thicknessRemap: {x: 0, y: 5}
worldScale: 1
scatterDistance1: {r: 0.3, g: 0.3, b: 0.3, a: 0}
scatterDistance2: {r: 0.5, g: 0.5, b: 0.5, a: 0}
lerpWeight: 1
- name: Profile 14
scatteringDistance: {r: 0.5, g: 0.5, b: 0.5, a: 1}
transmissionTint: {r: 1, g: 1, b: 1, a: 1}
texturingMode: 0
transmissionMode: 0
thicknessRemap: {x: 0, y: 5}
worldScale: 1
scatterDistance1: {r: 0.3, g: 0.3, b: 0.3, a: 0}
scatterDistance2: {r: 0.5, g: 0.5, b: 0.5, a: 0}
lerpWeight: 1
- name: Profile 15
scatteringDistance: {r: 0.5, g: 0.5, b: 0.5, a: 1}
transmissionTint: {r: 1, g: 1, b: 1, a: 1}
texturingMode: 0
transmissionMode: 0
thicknessRemap: {x: 0, y: 5}
worldScale: 1
scatterDistance1: {r: 0.3, g: 0.3, b: 0.3, a: 0}
scatterDistance2: {r: 0.5, g: 0.5, b: 0.5, a: 0}
lerpWeight: 1

144
ScriptableRenderPipeline/Core/Volume/Editor/Drawers/FloatParameterDrawer.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering
{
[VolumeParameterDrawer(typeof(MinFloatParameter))]
sealed class MinFloatParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Float)
return false;
var o = parameter.GetObjectRef<MinFloatParameter>();
float v = EditorGUILayout.FloatField(title, value.floatValue);
value.floatValue = Mathf.Max(v, o.min);
return true;
}
}
[VolumeParameterDrawer(typeof(NoInterpMinFloatParameter))]
sealed class NoInterpMinFloatParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Float)
return false;
var o = parameter.GetObjectRef<NoInterpMinFloatParameter>();
float v = EditorGUILayout.FloatField(title, value.floatValue);
value.floatValue = Mathf.Max(v, o.min);
return true;
}
}
[VolumeParameterDrawer(typeof(MaxFloatParameter))]
sealed class MaxFloatParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Float)
return false;
var o = parameter.GetObjectRef<MaxFloatParameter>();
float v = EditorGUILayout.FloatField(title, value.floatValue);
value.floatValue = Mathf.Min(v, o.max);
return true;
}
}
[VolumeParameterDrawer(typeof(NoInterpMaxFloatParameter))]
sealed class NoInterpMaxFloatParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Float)
return false;
var o = parameter.GetObjectRef<NoInterpMaxFloatParameter>();
float v = EditorGUILayout.FloatField(title, value.floatValue);
value.floatValue = Mathf.Min(v, o.max);
return true;
}
}
[VolumeParameterDrawer(typeof(ClampedFloatParameter))]
sealed class ClampedFloatParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Float)
return false;
var o = parameter.GetObjectRef<ClampedFloatParameter>();
EditorGUILayout.Slider(value, o.min, o.max, title);
value.floatValue = Mathf.Clamp(value.floatValue, o.min, o.max);
return true;
}
}
[VolumeParameterDrawer(typeof(NoInterpClampedFloatParameter))]
sealed class NoInterpClampedFloatParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Float)
return false;
var o = parameter.GetObjectRef<NoInterpClampedFloatParameter>();
EditorGUILayout.Slider(value, o.min, o.max, title);
value.floatValue = Mathf.Clamp(value.floatValue, o.min, o.max);
return true;
}
}
[VolumeParameterDrawer(typeof(FloatRangeParameter))]
sealed class FloatRangeParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Vector2)
return false;
var o = parameter.GetObjectRef<FloatRangeParameter>();
var v = value.vector2Value;
// The layout system breaks alignement when mixing inspector fields with custom layouted
// fields as soon as a scrollbar is needed in the inspector, so we'll do the layout
// manually instead
const int kFloatFieldWidth = 50;
const int kSeparatorWidth = 5;
float indentOffset = EditorGUI.indentLevel * 15f;
var lineRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
lineRect.xMin += 4f;
lineRect.y += 2f;
var labelRect = new Rect(lineRect.x, lineRect.y, EditorGUIUtility.labelWidth - indentOffset, lineRect.height);
var floatFieldLeft = new Rect(labelRect.xMax, lineRect.y, kFloatFieldWidth + indentOffset, lineRect.height);
var sliderRect = new Rect(floatFieldLeft.xMax + kSeparatorWidth - indentOffset, lineRect.y, lineRect.width - labelRect.width - kFloatFieldWidth * 2 - kSeparatorWidth * 2, lineRect.height);
var floatFieldRight = new Rect(sliderRect.xMax + kSeparatorWidth - indentOffset, lineRect.y, kFloatFieldWidth + indentOffset, lineRect.height);
EditorGUI.PrefixLabel(labelRect, title);
v.x = EditorGUI.FloatField(floatFieldLeft, v.x);
EditorGUI.MinMaxSlider(sliderRect, ref v.x, ref v.y, o.min, o.max);
v.y = EditorGUI.FloatField(floatFieldRight, v.y);
value.vector2Value = v;
return true;
}
}
}

107
ScriptableRenderPipeline/Core/Volume/Editor/Drawers/IntParameterDrawer.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering
{
[VolumeParameterDrawer(typeof(MinIntParameter))]
sealed class MinIntParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Integer)
return false;
var o = parameter.GetObjectRef<MinIntParameter>();
int v = EditorGUILayout.IntField(title, value.intValue);
value.intValue = Mathf.Max(v, o.min);
return true;
}
}
[VolumeParameterDrawer(typeof(NoInterpMinIntParameter))]
sealed class NoInterpMinIntParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Integer)
return false;
var o = parameter.GetObjectRef<NoInterpMinIntParameter>();
int v = EditorGUILayout.IntField(title, value.intValue);
value.intValue = Mathf.Max(v, o.min);
return true;
}
}
[VolumeParameterDrawer(typeof(MaxIntParameter))]
sealed class MaxIntParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Integer)
return false;
var o = parameter.GetObjectRef<MaxIntParameter>();
int v = EditorGUILayout.IntField(title, value.intValue);
value.intValue = Mathf.Min(v, o.max);
return true;
}
}
[VolumeParameterDrawer(typeof(NoInterpMaxIntParameter))]
sealed class NoInterpMaxIntParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Integer)
return false;
var o = parameter.GetObjectRef<NoInterpMaxIntParameter>();
int v = EditorGUILayout.IntField(title, value.intValue);
value.intValue = Mathf.Min(v, o.max);
return true;
}
}
[VolumeParameterDrawer(typeof(ClampedIntParameter))]
sealed class ClampedIntParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Integer)
return false;
var o = parameter.GetObjectRef<ClampedIntParameter>();
EditorGUILayout.IntSlider(value, o.min, o.max, title);
value.intValue = Mathf.Clamp(value.intValue, o.min, o.max);
return true;
}
}
[VolumeParameterDrawer(typeof(NoInterpClampedIntParameter))]
sealed class NoInterpClampedIntParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Integer)
return false;
var o = parameter.GetObjectRef<NoInterpClampedIntParameter>();
EditorGUILayout.IntSlider(value, o.min, o.max, title);
value.intValue = Mathf.Clamp(value.intValue, o.min, o.max);
return true;
}
}
}

8
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering.meta


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

61
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/CommonSubsurfaceScattering.hlsl


// ----------------------------------------------------------------------------
// SSS/Transmittance helper
// ----------------------------------------------------------------------------
// Computes the fraction of light passing through the object.
// Evaluate Int{0, inf}{2 * Pi * r * R(sqrt(r^2 + d^2))}, where R is the diffusion profile.
// Note: 'volumeAlbedo' should be premultiplied by 0.25.
// Ref: Approximate Reflectance Profiles for Efficient Subsurface Scattering by Pixar (BSSRDF only).
float3 ComputeTransmittanceDisney(float3 S, float3 volumeAlbedo, float thickness, float radiusScale)
{
// Thickness and SSS radius are decoupled for artists.
// In theory, we should modify the thickness by the inverse of the radius scale of the profile.
// thickness /= radiusScale;
#if 0
float3 expOneThird = exp(((-1.0 / 3.0) * thickness) * S);
#else
// Help the compiler.
float k = (-1.0 / 3.0) * LOG2_E;
float3 p = (k * thickness) * S;
float3 expOneThird = exp2(p);
#endif
// Premultiply & optimize: T = (1/4 * A) * (e^(-t * S) + 3 * e^(-1/3 * t * S))
return volumeAlbedo * (expOneThird * expOneThird * expOneThird + 3 * expOneThird);
}
// Evaluates transmittance for a linear combination of two normalized 2D Gaussians.
// Ref: Real-Time Realistic Skin Translucency (2010), equation 9 (modified).
// Note: 'volumeAlbedo' should be premultiplied by 0.25, correspondingly 'lerpWeight' by 4,
// and 'halfRcpVariance1' should be prescaled by (0.1 * SssConstants.SSS_BASIC_DISTANCE_SCALE)^2.
float3 ComputeTransmittanceJimenez(float3 halfRcpVariance1, float lerpWeight1,
float3 halfRcpVariance2, float lerpWeight2,
float3 volumeAlbedo, float thickness, float radiusScale)
{
// Thickness and SSS radius are decoupled for artists.
// In theory, we should modify the thickness by the inverse of the radius scale of the profile.
// thickness /= radiusScale;
float t2 = thickness * thickness;
// T = A * lerp(exp(-t2 * halfRcpVariance1), exp(-t2 * halfRcpVariance2), lerpWeight2)
return volumeAlbedo * (exp(-t2 * halfRcpVariance1) * lerpWeight1 + exp(-t2 * halfRcpVariance2) * lerpWeight2);
}
// In order to support subsurface scattering, we need to know which pixels have an SSS material.
// It can be accomplished by reading the stencil buffer.
// A faster solution (which avoids an extra texture fetch) is to simply make sure that
// all pixels which belong to an SSS material are not black (those that don't always are).
// We choose the blue color channel since it's perceptually the least noticeable.
float3 TagLightingForSSS(float3 subsurfaceLighting)
{
subsurfaceLighting.b = max(subsurfaceLighting.b, HALF_MIN);
return subsurfaceLighting;
}
// See TagLightingForSSS() for details.
bool TestLightingForSSS(float3 subsurfaceLighting)
{
return subsurfaceLighting.b > 0;
}

9
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/CommonSubsurfaceScattering.hlsl.meta


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

8
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/Editor.meta


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

11
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/Editor/SubsurfaceScatteringSettingsEditor.Styles.cs.meta


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

11
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/Editor/SubsurfaceScatteringSettingsEditor.cs.meta


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

99
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl


#include "SubsurfaceScatteringSettings.cs.hlsl"
#include "ShaderLibrary\Packing.hlsl"
#include "CommonSubsurfaceScattering.hlsl"
// Subsurface scattering constant
#define SSS_WRAP_ANGLE (PI/12) // 15 degrees
#define SSS_WRAP_LIGHT cos(PI/2 - SSS_WRAP_ANGLE)
CBUFFER_START(UnitySSSParameters)
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.
// Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader.
uint _EnableSSSAndTransmission; // Globally toggles subsurface and transmission scattering on/off
float _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
float _TransmissionFlags; // 2 bit/profile; 0 = inf. thick, 1 = thin, 2 = regular
// Old SSS Model >>>
uint _UseDisneySSS;
float4 _HalfRcpVariancesAndWeights[SSS_N_PROFILES][2]; // 2x Gaussians in RGB, A is interpolation weights
// <<< Old SSS Model
// Use float4 to avoid any packing issue between compute and pixel shaders
float4 _ThicknessRemaps[SSS_N_PROFILES]; // R: start, G = end - start, BA unused
float4 _ShapeParams[SSS_N_PROFILES]; // RGB = S = 1 / D, A = filter radius
float4 _TransmissionTints[SSS_N_PROFILES]; // RGB = 1/4 * color, A = unused
float4 _WorldScales[SSS_N_PROFILES]; // X = meters per world unit; Y = world units per meter
CBUFFER_END
// ----------------------------------------------------------------------------
// helper functions
// ----------------------------------------------------------------------------
// Returns the modified albedo (diffuse color) for materials with subsurface scattering.
// Ref: Advanced Techniques for Realistic Real-Time Skin Rendering.
float3 ApplyDiffuseTexturingMode(float3 color, int subsurfaceProfile)
{
#if defined(SHADERPASS) && (SHADERPASS == SHADERPASS_SUBSURFACE_SCATTERING)
// If the SSS pass is executed, we know we have SSS enabled.
bool enableSssAndTransmission = true;
#else
bool enableSssAndTransmission = _EnableSSSAndTransmission != 0;
#endif
if (enableSssAndTransmission)
{
bool performPostScatterTexturing = IsBitSet(asuint(_TexturingModeFlags), subsurfaceProfile);
if (performPostScatterTexturing)
{
// Post-scatter texturing mode: the albedo is only applied during the SSS pass.
#if !defined(SHADERPASS) || (SHADERPASS != SHADERPASS_SUBSURFACE_SCATTERING)
color = float3(1, 1, 1);
#endif
}
else
{
// Pre- and post- scatter texturing mode.
color = sqrt(color);
}
}
return color;
}
// ----------------------------------------------------------------------------
// Encoding/decoding SSS buffer functions
// ----------------------------------------------------------------------------
struct SSSData
{
float3 diffuseColor;
float subsurfaceRadius;
int subsurfaceProfile;
};
#define SSSBufferType0 float4
// SSSBuffer texture declaration
TEXTURE2D(_SSSBufferTexture0);
void EncodeIntoSSSBuffer(SSSData sssData, uint2 positionSS, out SSSBufferType0 outSSSBuffer0)
{
outSSSBuffer0 = float4(sssData.diffuseColor, PackFloatInt8bit(sssData.subsurfaceRadius, sssData.subsurfaceProfile, 16.0));
}
void DecodeFromSSSBuffer(float4 sssBuffer, uint2 positionSS, out SSSData sssData)
{
sssData.diffuseColor = sssBuffer.rgb;
UnpackFloatInt8bit(sssBuffer.a, 16.0, sssData.subsurfaceRadius, sssData.subsurfaceProfile);
}
void DecodeFromSSSBuffer(uint2 positionSS, out SSSData sssData)
{
float4 sssBuffer = LOAD_TEXTURE2D(_SSSBufferTexture0, positionSS);
DecodeFromSSSBuffer(sssBuffer, positionSS, sssData);
}
// OUTPUT_SSSBUFFER start from SV_Target2 as SV_Target0 and SV_Target1 are used for lighting buffer
#define OUTPUT_SSSBUFFER(NAME) out GBufferType0 MERGE_NAME(NAME, 0) : SV_Target2
#define ENCODE_INTO_SSSBUFFER(SURFACE_DATA, UNPOSITIONSS, NAME) EncodeIntoSSSBuffer(ConvertSurfaceDataToSSSData(SURFACE_DATA), UNPOSITIONSS, MERGE_NAME(NAME, 0))
#define DECODE_FROM_SSSBUFFER(UNPOSITIONSS, SSS_DATA) DecodeFromSSSBuffer(UNPOSITIONSS, SSS_DATA)

9
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl.meta


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

47
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs


using UnityEngine.Rendering;
using System;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class SubsurfaceScatteringManager
{
// Currently we only support SSSBuffer with one buffer. If the shader code change, it may require to update the shader manager
public const int k_MaxSSSBuffer = 1;
readonly int m_SSSBuffer0;
readonly RenderTargetIdentifier m_SSSBuffer0RT;
public int sssBufferCount { get { return k_MaxSSSBuffer; } }
RenderTargetIdentifier[] m_ColorMRTs;
RenderTargetIdentifier[] m_RTIDs = new RenderTargetIdentifier[k_MaxSSSBuffer];
public SubsurfaceScatteringManager()
{
m_SSSBuffer0RT = new RenderTargetIdentifier(m_SSSBuffer0);
}
// In case of deferred, we must be in sync with SubsurfaceScattering.hlsl and lit.hlsl files and setup the correct buffers
// for SSS
public void InitGBuffers(int width, int height, GBufferManager gbufferManager, CommandBuffer cmd)
{
m_RTIDs[0] = gbufferManager.GetGBuffers()[0];
}
// In case of full forward we must allocate the render target for forward SSS (or reuse one already existing)
// TODO: Provide a way to reuse a render target
public void InitGBuffers(int width, int height, CommandBuffer cmd)
{
m_RTIDs[0] = m_SSSBuffer0RT;
cmd.ReleaseTemporaryRT(m_SSSBuffer0);
cmd.GetTemporaryRT(m_SSSBuffer0, width, height, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
}
public RenderTargetIdentifier GetSSSBuffers(int index)
{
Debug.Assert(index < sssBufferCount);
return m_RTIDs[index];
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs.meta


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

9
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringSettings.cs.hlsl.meta


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

11
ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringSettings.cs.meta


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

77
ScriptableRenderPipeline/Core/Volume/Editor/Drawers/ClampedFloatParameterDrawer.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering
{
[VolumeParameterDrawer(typeof(ClampedFloatParameter))]
sealed class ClampedFloatParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Float)
return false;
var o = parameter.GetObjectRef<ClampedFloatParameter>();
if (o.clampMode == ParameterClampMode.MinMax)
{
EditorGUILayout.Slider(value, o.min, o.max, title);
value.floatValue = Mathf.Clamp(value.floatValue, o.min, o.max);
}
else if (o.clampMode == ParameterClampMode.Min)
{
float v = EditorGUILayout.FloatField(title, value.floatValue);
value.floatValue = Mathf.Max(v, o.min);
}
else if (o.clampMode == ParameterClampMode.Max)
{
float v = EditorGUILayout.FloatField(title, value.floatValue);
value.floatValue = Mathf.Min(v, o.max);
}
else
{
return false;
}
return true;
}
}
[VolumeParameterDrawer(typeof(InstantClampedFloatParameter))]
sealed class InstantClampedFloatParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Float)
return false;
var o = parameter.GetObjectRef<InstantClampedFloatParameter>();
if (o.clampMode == ParameterClampMode.MinMax)
{
EditorGUILayout.Slider(value, o.min, o.max, title);
value.floatValue = Mathf.Clamp(value.floatValue, o.min, o.max);
}
else if (o.clampMode == ParameterClampMode.Min)
{
float v = EditorGUILayout.FloatField(title, value.floatValue);
value.floatValue = Mathf.Max(v, o.min);
}
else if (o.clampMode == ParameterClampMode.Max)
{
float v = EditorGUILayout.FloatField(title, value.floatValue);
value.floatValue = Mathf.Min(v, o.max);
}
else
{
return false;
}
return true;
}
}
}

77
ScriptableRenderPipeline/Core/Volume/Editor/Drawers/ClampedIntParameterDrawer.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering
{
[VolumeParameterDrawer(typeof(ClampedIntParameter))]
sealed class ClampedIntParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Integer)
return false;
var o = parameter.GetObjectRef<ClampedIntParameter>();
if (o.clampMode == ParameterClampMode.MinMax)
{
EditorGUILayout.IntSlider(value, o.min, o.max, title);
value.intValue = Mathf.Clamp(value.intValue, o.min, o.max);
}
else if (o.clampMode == ParameterClampMode.Min)
{
int v = EditorGUILayout.IntField(title, value.intValue);
value.intValue = Mathf.Max(v, o.min);
}
else if (o.clampMode == ParameterClampMode.Max)
{
int v = EditorGUILayout.IntField(title, value.intValue);
value.intValue = Mathf.Min(v, o.max);
}
else
{
return false;
}
return true;
}
}
[VolumeParameterDrawer(typeof(InstantClampedIntParameter))]
sealed class InstantClampedIntParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Integer)
return false;
var o = parameter.GetObjectRef<InstantClampedIntParameter>();
if (o.clampMode == ParameterClampMode.MinMax)
{
EditorGUILayout.IntSlider(value, o.min, o.max, title);
value.intValue = Mathf.Clamp(value.intValue, o.min, o.max);
}
else if (o.clampMode == ParameterClampMode.Min)
{
int v = EditorGUILayout.IntField(title, value.intValue);
value.intValue = Mathf.Max(v, o.min);
}
else if (o.clampMode == ParameterClampMode.Max)
{
int v = EditorGUILayout.IntField(title, value.intValue);
value.intValue = Mathf.Min(v, o.max);
}
else
{
return false;
}
return true;
}
}
}

42
ScriptableRenderPipeline/Core/Volume/Editor/Drawers/RangeParameterDrawer.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering
{
[VolumeParameterDrawer(typeof(RangeParameter))]
sealed class RangeParameterDrawer : VolumeParameterDrawer
{
public override bool OnGUI(SerializedDataParameter parameter, GUIContent title)
{
var value = parameter.value;
if (value.propertyType != SerializedPropertyType.Vector2)
return false;
var o = parameter.GetObjectRef<RangeParameter>();
var v = value.vector2Value;
// The layout system breaks alignement when mixing inspector fields with custom layouted
// fields as soon as a scrollbar is needed in the inspector, so we'll do the layout
// manually instead
const int kFloatFieldWidth = 50;
const int kSeparatorWidth = 5;
float indentOffset = EditorGUI.indentLevel * 15f;
var lineRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
lineRect.xMin += 4f;
lineRect.y += 2f;
var labelRect = new Rect(lineRect.x, lineRect.y, EditorGUIUtility.labelWidth - indentOffset, lineRect.height);
var floatFieldLeft = new Rect(labelRect.xMax, lineRect.y, kFloatFieldWidth + indentOffset, lineRect.height);
var sliderRect = new Rect(floatFieldLeft.xMax + kSeparatorWidth - indentOffset, lineRect.y, lineRect.width - labelRect.width - kFloatFieldWidth * 2 - kSeparatorWidth * 2, lineRect.height);
var floatFieldRight = new Rect(sliderRect.xMax + kSeparatorWidth - indentOffset, lineRect.y, kFloatFieldWidth + indentOffset, lineRect.height);
EditorGUI.PrefixLabel(labelRect, title);
v.x = EditorGUI.FloatField(floatFieldLeft, v.x);
EditorGUI.MinMaxSlider(sliderRect, ref v.x, ref v.y, o.min, o.max);
v.y = EditorGUI.FloatField(floatFieldRight, v.y);
value.vector2Value = v;
return true;
}
}
}

11
ScriptableRenderPipeline/Core/Volume/Editor/Drawers/RangeParameterDrawer.cs.meta


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

13
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/SubsurfaceScatteringSettingsEditor.Styles.cs.meta


fileFormatVersion: 2
guid: 95517c3b2f4a014468289c3f5eb6d03c
timeCreated: 1507562538
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

13
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/SubsurfaceScatteringSettingsEditor.cs.meta


fileFormatVersion: 2
guid: a61a2437dcee4e54393f8f65ccf726ab
timeCreated: 1507562486
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

13
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs.meta


fileFormatVersion: 2
guid: 3418a08abd15e9a49af3ccbc9e15b5ea
timeCreated: 1507538042
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

10
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs.hlsl.meta


fileFormatVersion: 2
guid: 86fe0068e2ac49e4d99882aaa40fa522
timeCreated: 1507935155
licenseType: Pro
ShaderImporter:
externalObjects: {}
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

/ScriptableRenderPipeline/Core/Volume/Editor/Drawers/ClampedIntParameterDrawer.cs.meta → /ScriptableRenderPipeline/Core/Volume/Editor/Drawers/IntParameterDrawer.cs.meta

/ScriptableRenderPipeline/Core/Volume/Editor/Drawers/ClampedFloatParameterDrawer.cs.meta → /ScriptableRenderPipeline/Core/Volume/Editor/Drawers/FloatParameterDrawer.cs.meta

/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/SubsurfaceScatteringSettingsEditor.cs → /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/Editor/SubsurfaceScatteringSettingsEditor.cs

/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/SubsurfaceScatteringSettingsEditor.Styles.cs → /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/Editor/SubsurfaceScatteringSettingsEditor.Styles.cs

/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SSSProfile.meta → /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SSSProfile.meta

/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SSSProfile → /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SSSProfile

/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs.hlsl → /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringSettings.cs.hlsl

/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs → /ScriptableRenderPipeline/HDRenderPipeline/Material/SubsurfaceScattering/SubsurfaceScatteringSettings.cs

正在加载...
取消
保存