Oliver Schnabel 6 年前
当前提交
ecdbdcab
共有 67 个文件被更改,包括 1020 次插入308 次删除
  1. 5
      com.unity.render-pipelines.core/CoreRP/Editor/ShaderGenerator/ShaderTypeGeneration.cs
  2. 2
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl
  3. 5
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonMaterial.hlsl
  4. 34
      com.unity.render-pipelines.high-definition/CHANGELOG.md
  5. 5
      com.unity.render-pipelines.high-definition/HDRP/Debug/ColorPickerDebug.cs
  6. 24
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugColorPicker.shader
  7. 33
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.cs
  8. 1
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugViewMaterialGBuffer.shader
  9. 1
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugViewTiles.shader
  10. 1
      com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs
  11. 9
      com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs.hlsl
  12. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.Styles.cs
  13. 18
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/ReflectionMenuItem.cs
  14. 3
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs
  15. 21
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalUI.cs
  16. 16
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitShaderPreprocessor.cs
  17. 21
      com.unity.render-pipelines.high-definition/HDRP/HDRenderPipelineAsset.asset
  18. 24
      com.unity.render-pipelines.high-definition/HDRP/Lighting/DeferredDirectionalShadow.compute
  19. 8
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoop.cs
  20. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DBufferManager.cs
  21. 14
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs
  22. 31
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.shader
  23. 35
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalData.hlsl
  24. 9
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProjectorComponent.cs
  25. 73
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalSystem.cs
  26. 9
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalUtilities.hlsl
  27. 10
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/ShaderPass/DecalSharePass.hlsl
  28. 12
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLit.shader
  29. 12
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitTessellation.shader
  30. 112
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.hlsl
  31. 12
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.shader
  32. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitBuiltinData.hlsl
  33. 12
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitTessellation.shader
  34. 38
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.hlsl
  35. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.shader
  36. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLitData.hlsl
  37. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl
  38. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/Unlit.hlsl
  39. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/Unlit.shader
  40. 106
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipeline.cs
  41. 13
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDStringConstants.cs
  42. 3
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPass.cs
  43. 3
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPass.cs.hlsl
  44. 30
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDBuffer.hlsl
  45. 15
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDepthOnly.hlsl
  46. 2
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForward.hlsl
  47. 2
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForwardUnlit.hlsl
  48. 2
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassGBuffer.hlsl
  49. 2
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassLightTransport.hlsl
  50. 160
      com.unity.render-pipelines.lightweight/CHANGELOG.md
  51. 14
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightPBRExtraPasses.template
  52. 11
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightPBRForwardPass.template
  53. 14
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightUnlitExtraPasses.template
  54. 11
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightUnlitPass.template
  55. 2
      com.unity.render-pipelines.lightweight/LWRP/Shaders/Terrain/LightweightStandardTerrain.shader
  56. 6
      com.unity.render-pipelines.lightweight/LWRP/Shaders/Terrain/LightweightStandardTerrainBase.shader
  57. 82
      com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsFrontFaceNode.cs
  58. 5
      com.unity.shadergraph/Editor/Data/Util/PropertyCollector.cs
  59. 5
      com.unity.shadergraph/Editor/Data/Util/ShaderGenerator.cs
  60. 11
      CONTRIBUTING
  61. 21
      com.unity.render-pipelines.high-definition/HDRP/Debug/FalseColorDebug.cs
  62. 11
      com.unity.render-pipelines.high-definition/HDRP/Debug/FalseColorDebug.cs.meta
  63. 55
      com.unity.render-pipelines.high-definition/HDRP/Material/NormalBuffer.hlsl
  64. 9
      com.unity.render-pipelines.high-definition/HDRP/Material/NormalBuffer.hlsl.meta
  65. 81
      com.unity.render-pipelines.high-definition/HDRP/Material/NormalBufferManager.cs
  66. 11
      com.unity.render-pipelines.high-definition/HDRP/Material/NormalBufferManager.cs.meta
  67. 9
      issue_template.md

5
com.unity.render-pipelines.core/CoreRP/Editor/ShaderGenerator/ShaderTypeGeneration.cs


}
}
shaderText += "\treturn value." + acc.name + swizzle + ";\n";
shaderText +=
//"\t"
" " // unity convention use space instead of tab...
+ "return value." + acc.name + swizzle + ";\n";
shaderText += "}\n";
}

2
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl


return (x * x) * (x * x);
}
TEMPLATE_3_FLT(RangeRemap, min, max, t, return saturate((t - min) / (max - min)))
// ----------------------------------------------------------------------------
// Texture utilities
// ----------------------------------------------------------------------------

5
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonMaterial.hlsl


return sqrt(roughness);
}
real RoughnessToPerceptualSmoothness(real roughness)
{
return 1.0 - sqrt(roughness);
}
real PerceptualSmoothnessToRoughness(real perceptualSmoothness)
{
return (1.0 - perceptualSmoothness) * (1.0 - perceptualSmoothness);

34
com.unity.render-pipelines.high-definition/CHANGELOG.md


# Changelog
## [2018.2 undecided]
## [2018.3]
### Improvements
### Changed, Removals and deprecations
### Bug fixes
## [2018.2 / next ]
- Add Light -> Planar Reflection Probe command
- Added a false color mode in rendering debug
- Add support for mesh decals
- Add flag to disable projector decals on transparent geometry to save performance and decal texture atlas space
- Add ability to use decal diffuse map as mask only
- Add visualize all shadow masks in lighting debug
- Add export of normal and roughness buffer for forwardOnly and when in supportOnlyForward mode for forward
- Provide a define in lit.hlsl (FORWARD_MATERIAL_READ_FROM_WRITTEN_NORMAL_BUFFER) when output buffer normal is used to read the normal and roughness instead of caclulating it (can save performance, but lower quality due to compression)
### Improvements
### Changed, Removals and deprecations
- Change Render -> Planar Reflection creation to 3D Object -> Mirror
- Change "Enable Reflector" name on SpotLight to "Angle Affect Intensity"
- Change prototype of BSDFData ConvertSurfaceDataToBSDFData(SurfaceData surfaceData) to BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData surfaceData)
### Bug fixes
- Fix issue with StackLit in deferred mode with deferredDirectionalShadow due to GBuffer not being cleared. Gbuffer is still not clear and issue was fix with the new Output of normal buffer.
## [2018.2 / 2.0.1-preview]
### Improvements
- Add stripper of shader variant when building a player. Save shader compile time.

### Changed, Removals and deprecations
- Removed GlobalLightLoopSettings.maxPlanarReflectionProbes and instead use value of GlobalLightLoopSettings.planarReflectionProbeCacheSize
- Changed SupportForwardOnly to SupportOnlyForward in render pipeline settings
- Remove EmissiveIntensity parameter and change EmissiveColor to be HDR (Matching Builtin Unity behavior) - Data need to be updated
- Remove EmissiveIntensity parameter and change EmissiveColor to be HDR (Matching Builtin Unity behavior) - Data need to be updated - Launch Edit -> Single Step Upgrade Script -> Upgrade all Materials emissionColor
- Changed versioning variable name in HDAdditionalXXXData from m_version to version
- Create unique name when creating a game object in the rendering menu (i.e Density Volume(2))
- Re-organize various files and folder location to clean the repository

- Fix warning when creating Planar reflection
- Fix specular lighting debug mode (was rendering black)
- Allow projector decal with null material to allow to configure decal when HDRP is not set
- Decal atlas texture offset/scale is updated after allocations (used to be before so it was using date from previous frame)
## [2018.1 undecided]

5
com.unity.render-pipelines.high-definition/HDRP/Debug/ColorPickerDebug.cs


public ColorPickerDebugMode colorPickerMode = ColorPickerDebugMode.None;
public Color fontColor = new Color(1.0f, 0.0f, 0.0f);
public float colorThreshold0 = 0.0f;
public float colorThreshold1 = 200.0f;
public float colorThreshold2 = 9000.0f;
public float colorThreshold3 = 10000.0f;
public void OnValidate()
{
}

24
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugColorPicker.shader


float3 _ColorPickerFontColor;
float _ApplyLinearToSRGB;
float _RequireToFlipInputTexture;
int _FalseColor;
float4 _FalseColorThresholds; // 4 increasing threshold
struct Attributes
{

output.texcoord = GetNormalizedFullScreenTriangleTexCoord(input.vertexID);
return output;
}
float3 FasleColorRemap(float lum, float4 thresholds)
{
//Gradient from 0 to 240 deg of HUE gradient
const float l = DegToRad(240) / TWO_PI;
float t = lerp(0.0, l / 3, RangeRemap(thresholds.x, thresholds.y, lum))
+ lerp(0.0, l / 3, RangeRemap(thresholds.y, thresholds.z, lum))
+ lerp(0.0, l / 3, RangeRemap(thresholds.z, thresholds.w, lum));
return HsvToRgb(float3(l - t, 1, 1));
}
float4 DisplayPixelInformationAtMousePosition(Varyings input, float4 result, float4 mouseResult, float4 mousePixelCoord)

}
float4 result = SAMPLE_TEXTURE2D(_DebugColorPickerTexture, sampler_DebugColorPickerTexture, input.texcoord);
//result.rgb = GetColorCodeFunction(result.x, _ColorPickerParam);
float4 mousePixelCoord = _MousePixelCoord;
if (_RequireToFlipInputTexture > 0.0)

// _DebugExposure will be set to zero if the debug view does not need it so we don't need to make a special case here. It's handled in only one place in C#
mouseResult = mouseResult / exp2(_DebugExposure);
float4 finalResult = DisplayPixelInformationAtMousePosition(input, result, mouseResult, mousePixelCoord);
if (_FalseColor)
result.rgb = FasleColorRemap(Luminance(result.rgb), _FalseColorThresholds);
float4 finalResult = result;
if (_ColorPickerMode != COLORPICKERDEBUGMODE_NONE)
finalResult = DisplayPixelInformationAtMousePosition(input, result, mouseResult, mousePixelCoord);
return finalResult;
}

33
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.cs


public LightingDebugSettings lightingDebugSettings = new LightingDebugSettings();
public MipMapDebugSettings mipMapDebugSettings = new MipMapDebugSettings();
public ColorPickerDebugSettings colorPickerDebugSettings = new ColorPickerDebugSettings();
public FalseColorDebugSettings falseColorDebugSettings = new FalseColorDebugSettings();
public DecalsDebugSettings decalsDebugSettings = new DecalsDebugSettings();
public static GUIContent[] lightingFullScreenDebugStrings = null;

RegisterDecalsDebug();
}
void RefreshRenderingDebug<T>(DebugUI.Field<T> field, T value)
{
UnregisterDebugItems(k_PanelRendering, m_DebugRenderingItems);
RegisterRenderingDebug();
}
public void RegisterLightingDebug()
{
var list = new List<DebugUI.Widget>();

public void RegisterRenderingDebug()
{
m_DebugRenderingItems = new DebugUI.Widget[]
var widgetList = new List<DebugUI.Widget>();
widgetList.AddRange(new DebugUI.Widget[]
{
new DebugUI.EnumField { displayName = "Fullscreen Debug Mode", getter = () => (int)fullScreenDebugMode, setter = value => fullScreenDebugMode = (FullScreenDebugMode)value, enumNames = renderingFullScreenDebugStrings, enumValues = renderingFullScreenDebugValues },
new DebugUI.EnumField { displayName = "MipMaps", getter = () => (int)mipMapDebugSettings.debugMipMapMode, setter = value => SetMipMapMode((DebugMipMapMode)value), autoEnum = typeof(DebugMipMapMode) },

children =
{
new DebugUI.EnumField { displayName = "Debug Mode", getter = () => (int)colorPickerDebugSettings.colorPickerMode, setter = value => colorPickerDebugSettings.colorPickerMode = (ColorPickerDebugMode)value, autoEnum = typeof(ColorPickerDebugMode) },
new DebugUI.FloatField { displayName = "Range Threshold 0", getter = () => colorPickerDebugSettings.colorThreshold0, setter = value => colorPickerDebugSettings.colorThreshold0 = value },
new DebugUI.FloatField { displayName = "Range Threshold 1", getter = () => colorPickerDebugSettings.colorThreshold1, setter = value => colorPickerDebugSettings.colorThreshold1 = value },
new DebugUI.FloatField { displayName = "Range Threshold 2", getter = () => colorPickerDebugSettings.colorThreshold2, setter = value => colorPickerDebugSettings.colorThreshold2 = value },
new DebugUI.FloatField { displayName = "Range Threshold 3", getter = () => colorPickerDebugSettings.colorThreshold3, setter = value => colorPickerDebugSettings.colorThreshold3 = value },
};
});
widgetList.Add(new DebugUI.BoolField { displayName = "False Color Mode", getter = () => falseColorDebugSettings.falseColor, setter = value => falseColorDebugSettings.falseColor = value, onValueChanged = RefreshRenderingDebug });
if (falseColorDebugSettings.falseColor)
{
widgetList.Add(new DebugUI.Container{
flags = DebugUI.Flags.EditorOnly,
children =
{
new DebugUI.FloatField { displayName = "Range Threshold 0", getter = () => falseColorDebugSettings.colorThreshold0, setter = value => falseColorDebugSettings.colorThreshold0 = Mathf.Min(value, falseColorDebugSettings.colorThreshold1) },
new DebugUI.FloatField { displayName = "Range Threshold 1", getter = () => falseColorDebugSettings.colorThreshold1, setter = value => falseColorDebugSettings.colorThreshold1 = Mathf.Clamp(value, falseColorDebugSettings.colorThreshold0, falseColorDebugSettings.colorThreshold2) },
new DebugUI.FloatField { displayName = "Range Threshold 2", getter = () => falseColorDebugSettings.colorThreshold2, setter = value => falseColorDebugSettings.colorThreshold2 = Mathf.Clamp(value, falseColorDebugSettings.colorThreshold1, falseColorDebugSettings.colorThreshold3) },
new DebugUI.FloatField { displayName = "Range Threshold 3", getter = () => falseColorDebugSettings.colorThreshold3, setter = value => falseColorDebugSettings.colorThreshold3 = Mathf.Max(value, falseColorDebugSettings.colorThreshold2) },
}
});
}
m_DebugRenderingItems = widgetList.ToArray();
var panel = DebugManager.instance.GetPanel(k_PanelRendering, true);
panel.children.Add(m_DebugRenderingItems);
}

1
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugViewMaterialGBuffer.shader


Pass
{
ZWrite Off
Cull Off
HLSLPROGRAM
#pragma target 4.5

1
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugViewTiles.shader


Pass
{
ZWrite Off
Cull Off
ZTest Always
Blend SrcAlpha OneMinusSrcAlpha

1
com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs


SpecularLighting,
LuxMeter,
VisualizeCascade,
VisualizeShadowMasks,
IndirectDiffuseOcclusion,
IndirectSpecularOcclusion,
ScreenSpaceTracingRefraction,

9
com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs.hlsl


#define DEBUGLIGHTINGMODE_SPECULAR_LIGHTING (2)
#define DEBUGLIGHTINGMODE_LUX_METER (3)
#define DEBUGLIGHTINGMODE_VISUALIZE_CASCADE (4)
#define DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_OCCLUSION (5)
#define DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_OCCLUSION (6)
#define DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFRACTION (7)
#define DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFLECTION (8)
#define DEBUGLIGHTINGMODE_VISUALIZE_SHADOW_MASKS (5)
#define DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_OCCLUSION (6)
#define DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_OCCLUSION (7)
#define DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFRACTION (8)
#define DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFLECTION (9)
//
// UnityEngine.Experimental.Rendering.HDPipeline.DebugScreenSpaceTracing: static fields

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.Styles.cs


public readonly GUIContent shape = new GUIContent("Type", "Specifies the current type of light. Possible types are Directional, Spot, Point, Rectangle and Line lights.");
public readonly GUIContent[] shapeNames;
public readonly GUIContent enableSpotReflector = new GUIContent("Enable spot reflector", "When true it simulate a spot light with reflector (mean the intensity of the light will be more focus with narrower angle), otherwise light outside of the cone is simply absorbed (mean intensity is constent whatever the size of the cone).");
public readonly GUIContent enableSpotReflector = new GUIContent("Angle affect intensity", "When true it simulate a spot light with reflector (mean the intensity of the light will be more focus with narrower angle), otherwise light outside of the cone is simply absorbed (mean intensity is constent whatever the size of the cone).");
// Additional shadow data
public readonly GUIContent shadowResolution = new GUIContent("Resolution", "Controls the rendered resolution of the shadow maps. A higher resolution will increase the fidelity of shadows at the cost of GPU performance and memory usage.");

18
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/ReflectionMenuItem.cs


{
public class ReflectionMenuItems
{
[MenuItem("GameObject/Rendering/Planar Reflection", priority = CoreUtils.gameObjectMenuPriority)]
static void CreatePlanarReflectionGameObject(MenuCommand menuCommand)
[MenuItem("GameObject/3D Object/Mirror", priority = CoreUtils.gameObjectMenuPriority)]
static void CreateMirrorGameObject(MenuCommand menuCommand)
{
GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
GameObjectUtility.SetParentAndAlign(plane, menuCommand.context as GameObject);

{
plane.GetComponent<MeshRenderer>().sharedMaterial = material;
}
}
[MenuItem("GameObject/Light/Planar Reflection Probe", priority = CoreUtils.gameObjectMenuPriority)]
static void CreatePlanarReflectionGameObject(MenuCommand menuCommand)
{
var parent = menuCommand.context as GameObject;
var go = CoreEditorUtils.CreateGameObject(parent, "Planar Reflection");
var planarProbe = go.AddComponent<PlanarReflectionProbe>();
planarProbe.influenceVolume.boxBaseSize = new Vector3(1, 0.01f, 1);
// Ensure it gets re-parented if this was a context click (otherwise does nothing)
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject);
// Register the creation in the undo system
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
Selection.activeObject = go;
}
}
}

3
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs


private SerializedProperty m_FadeScaleProperty;
private SerializedProperty m_UVScaleProperty;
private SerializedProperty m_UVBiasProperty;
private SerializedProperty m_AffectsTransparencyProperty;
public class DecalBoundsHandle : BoxBoundsHandle
{

m_FadeScaleProperty = serializedObject.FindProperty("m_FadeScale");
m_UVScaleProperty = serializedObject.FindProperty("m_UVScale");
m_UVBiasProperty = serializedObject.FindProperty("m_UVBias");
m_AffectsTransparencyProperty = serializedObject.FindProperty("m_AffectsTransparency");
}
private void OnDisable()

EditorGUILayout.Slider(m_FadeScaleProperty, 0.0f, 1.0f, new GUIContent("Fade scale"));
EditorGUILayout.PropertyField(m_UVScaleProperty);
EditorGUILayout.PropertyField(m_UVBiasProperty);
EditorGUILayout.PropertyField(m_AffectsTransparencyProperty);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();

21
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalUI.cs


{
public static string InputsText = "Inputs";
public static GUIContent baseColorText = new GUIContent("Base Color + Blend", "Albedo (RGB) and Blend Factor (A)");
public static GUIContent baseColorText = new GUIContent("Albedo (RGB) and Blend Factor (A)", "Albedo (RGB) and Blend Factor (A)");
public static GUIContent baseColorText2 = new GUIContent("Blend Factor (A)", "Blend Factor (A)");
public static GUIContent BlendText = new GUIContent("Decal Blend", "Whole decal blend");
public static GUIContent AlbedoModeText = new GUIContent("Albedo contribution", "Base color + Blend, Blend only");
}
protected MaterialProperty baseColorMap = new MaterialProperty();

protected MaterialProperty decalBlend = new MaterialProperty();
protected const string kDecalBlend = "_DecalBlend";
protected MaterialProperty albedoMode = new MaterialProperty();
protected const string kAlbedoMode = "_AlbedoMode";
protected MaterialEditor m_MaterialEditor;

normalMap = FindProperty(kNormalMap, props);
maskMap = FindProperty(kMaskMap, props);
decalBlend = FindProperty(kDecalBlend, props);
albedoMode = FindProperty(kAlbedoMode, props);
// always instanced
SerializedProperty instancing = m_MaterialEditor.serializedObject.FindProperty("m_EnableInstancingVariants");
instancing.boolValue = true;

static public void SetupMaterialKeywordsAndPass(Material material)
{
CoreUtils.SetKeyword(material, "_ALBEDOCONTRIBUTION", material.GetFloat(kAlbedoMode) == 1.0f);
CoreUtils.SetKeyword(material, "_COLORMAP", material.GetTexture(kBaseColorMap));
CoreUtils.SetKeyword(material, "_NORMALMAP", material.GetTexture(kNormalMap));
CoreUtils.SetKeyword(material, "_MASKMAP", material.GetTexture(kMaskMap));

EditorGUILayout.LabelField(Styles.InputsText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText, baseColorMap);
m_MaterialEditor.ShaderProperty(albedoMode, Styles.AlbedoModeText);
if (material.GetFloat(kAlbedoMode) == 1.0f)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText, baseColorMap);
}
else
{
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText2, baseColorMap);
}
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, normalMap);
m_MaterialEditor.TexturePropertySingleLine(Styles.maskMapText, maskMap);
m_MaterialEditor.ShaderProperty(decalBlend, Styles.decalBlendText);

16
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitShaderPreprocessor.cs


using UnityEditor.Build;
using UnityEditor.Rendering;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering.HDPipeline

protected ShaderKeyword m_WriteNormalBuffer;
public LitShaderPreprocessor()
{
m_WriteNormalBuffer = new ShaderKeyword("WRITE_NORMAL_BUFFER");
}
bool LitShaderStripper(HDRenderPipelineAsset hdrpAsset, Shader shader, ShaderSnippetData snippet, ShaderCompilerData inputData)
{
if (CommonShaderStripper(hdrpAsset, shader, snippet, inputData))

bool isForwardPass = snippet.passName == "Forward";
bool isDepthOnlyPass = snippet.passName == "DepthOnly";
bool isTransparentForwardPass = snippet.passName == "TransparentDepthPostpass" || snippet.passName == "TransparentBackface" || snippet.passName == "TransparentDepthPrepass";
// When using forward only, we never need GBuffer pass (only Forward)

// When we are in deferred (i.e !hdrpAsset.renderPipelineSettings.supportOnlyForward), we only support tile lighting
if (!hdrpAsset.renderPipelineSettings.supportOnlyForward && inputData.shaderKeywordSet.IsEnabled(m_ClusterLighting))
return true;
if (isDepthOnlyPass)
{
// When we are full forward, we don't have depth prepass without writeNormalBuffer
if (hdrpAsset.renderPipelineSettings.supportOnlyForward && !inputData.shaderKeywordSet.IsEnabled(m_WriteNormalBuffer))
return true;
}
if (!hdrpAsset.renderPipelineSettings.supportOnlyForward)
{

21
com.unity.render-pipelines.high-definition/HDRP/HDRenderPipelineAsset.asset


--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1

m_EditorClassIdentifier:
version: 1
m_RenderPipelineResources: {fileID: 11400000, guid: 3ce144cff5783da45aa5d4fdc2da14b7,
type: 2}
m_FrameSettings:

enableSSAO: 1
enableSubsurfaceScattering: 1
enableTransmission: 1
enableAtmosphericScattering: 1
enableVolumetric: 1
diffuseGlobalDimmer: 1
specularGlobalDimmer: 1
enableForwardRenderingOnly: 0

enableObjectMotionVectors: 1
enableDBuffer: 1
enableAtmosphericScattering: 1
enableRoughRefraction: 1
enableTransparentPostpass: 1
enableDistortion: 1

enableOpaqueObjects: 1
enableTransparentObjects: 1
enableMSAA: 0
enableShadowMask: 0
enableShadowMask: 1
lightLoopSettings:
enableTileAndCluster: 1
enableComputeLightEvaluation: 1

supportSSR: 1
supportSSAO: 1
supportSubsurfaceScattering: 1
supportForwardOnly: 0
supportOnlyForward: 0
supportVolumetric: 1
supportRuntimeDebugDisplay: 1
supportDBuffer: 1
supportMSAA: 0
msaaSampleCount: 1

cookieTexArraySize: 16
pointCookieSize: 512
cubeCookieTexArraySize: 16
reflectionProbeCacheSize: 128
reflectionCubemapSize: 128
reflectionProbeCacheSize: 128
reflectionCubemapSize: 128
maxPlanarReflectionProbes: 128
skyReflectionSize: 256
skyLightingOverrideLayerMask:
serializedVersion: 2

shadowAtlasHeight: 4096
decalSettings:
drawDistance: 1000
atlasSize: 8192
atlasWidth: 4096
atlasHeight: 4096
allowShaderVariantStripping: 1
diffusionProfileSettings: {fileID: 11400000, guid: 404820c4cf36ad944862fa59c56064f0,
type: 2}

24
com.unity.render-pipelines.high-definition/HDRP/Lighting/DeferredDirectionalShadow.compute


// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel DeferredDirectionalShadow DEFERRED_DIRECTIONAL=DeferredDirectionalShadow
#pragma kernel DeferredDirectionalShadow_Contact DEFERRED_DIRECTIONAL=DeferredDirectionalShadow_Contact ENABLE_CONTACT_SHADOWS
#pragma kernel DeferredDirectionalShadow_Normals DEFERRED_DIRECTIONAL=DeferredDirectionalShadow_Normals ENABLE_NORMALS
#pragma kernel DeferredDirectionalShadow_Contact_Normals DEFERRED_DIRECTIONAL=DeferredDirectionalShadow_Contact_Normals ENABLE_CONTACT_SHADOWS ENABLE_NORMALS
#ifdef ENABLE_NORMALS
# define LIGHTLOOP_TILE_PASS 1
# define USE_FPTL_LIGHTLIST 1 // deferred opaque always use FPTL
# define UNITY_MATERIAL_LIT
#else
# define SHADOW_USE_ONLY_VIEW_BASED_BIASING 1 // Enable only light view vector based biasing. If undefined, biasing will be based on the normal and calling code must provide a valid normal.
#endif
#ifdef SHADER_API_PSSL
# pragma argument( scheduler=minpressure ) // instruct the shader compiler to prefer minimizing vgpr usage

#include "../ShaderVariables.hlsl"
#include "../Material/NormalBuffer.hlsl"
#include "Lighting.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal switch

PositionInputs posInput = GetPositionInput(pixelCoord.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, tileCoord);
#ifdef ENABLE_NORMALS
BSDFData bsdfData;
BakeLightingData unused;
DECODE_FROM_GBUFFER(posInput.positionSS, UINT_MAX, bsdfData, unused.bakeDiffuseLighting);
float3 nrm = bsdfData.normalWS;
#else
float3 nrm = 0.0.xxx;
#endif
NormalData normalData;
DecodeFromNormalBuffer(posInput.positionSS, normalData);
float3 normalWS = normalData.normalWS;
float shadow = GetDirectionalShadowAttenuation(shadowContext, posInput.positionWS, nrm, _DirectionalShadowIndex, _LightDirection);
float shadow = GetDirectionalShadowAttenuation(shadowContext, posInput.positionWS, normalWS, _DirectionalShadowIndex, _LightDirection);
#ifdef ENABLE_CONTACT_SHADOWS
float contactShadow = 1.0f;

8
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoop.cs


static int s_deferredDirectionalShadowKernel;
static int s_deferredDirectionalShadow_Contact_Kernel;
static int s_deferredDirectionalShadow_Normals_Kernel;
static int s_deferredDirectionalShadow_Contact_Normals_Kernel;
static ComputeBuffer s_LightVolumeDataBuffer = null;
static ComputeBuffer s_ConvexBoundsBuffer = null;

s_deferredDirectionalShadowKernel = deferredDirectionalShadowComputeShader.FindKernel("DeferredDirectionalShadow");
s_deferredDirectionalShadow_Contact_Kernel = deferredDirectionalShadowComputeShader.FindKernel("DeferredDirectionalShadow_Contact");
s_deferredDirectionalShadow_Normals_Kernel = deferredDirectionalShadowComputeShader.FindKernel("DeferredDirectionalShadow_Normals");
s_deferredDirectionalShadow_Contact_Normals_Kernel = deferredDirectionalShadowComputeShader.FindKernel("DeferredDirectionalShadow_Contact_Normals");
for (int variant = 0; variant < LightDefinitions.s_NumFeatureVariants; variant++)
{

bool enableContactShadows = m_FrameSettings.enableContactShadows && contactShadows.enable && contactShadows.length > 0.0f;
int kernel;
if (enableContactShadows)
kernel = m_FrameSettings.enableForwardRenderingOnly ? s_deferredDirectionalShadow_Contact_Kernel : s_deferredDirectionalShadow_Contact_Normals_Kernel;
kernel = s_deferredDirectionalShadow_Contact_Kernel;
kernel = m_FrameSettings.enableForwardRenderingOnly ? s_deferredDirectionalShadowKernel : s_deferredDirectionalShadow_Normals_Kernel;
kernel = s_deferredDirectionalShadowKernel;
m_ShadowMgr.BindResources(cmd, deferredDirectionalShadowComputeShader, kernel);

4
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DBufferManager.cs


{
public class DBufferManager : MRTBufferManager
{
public int vsibleDecalCount { get; set; }
public bool EnableDBUffer { get; set; }
RTHandleSystem.RTHandle m_HTile;

{
if (hdCamera.frameSettings.enableDBuffer)
{
cmd.SetGlobalInt(HDShaderIDs._EnableDBuffer, vsibleDecalCount > 0 ? 1 : 0);
cmd.SetGlobalInt(HDShaderIDs._EnableDBuffer, EnableDBUffer ? 1 : 0);
cmd.SetGlobalVector(HDShaderIDs._DecalAtlasResolution, new Vector2(HDUtils.hdrpSettings.decalSettings.atlasWidth, HDUtils.hdrpSettings.decalSettings.atlasHeight));
BindBufferAsTextures(cmd);
}

14
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs


sRGBFlags = m_sRGBFlags;
}
}
// normalToWorld.m03 - total blend factor
// normalToWorld.m13 - diffuse texture index in atlas
// normalToWorld.m23 - normal texture index in atlas
// normalToWorld.m33 - mask texture index in atlas
// normal to world only uses 3x3 for actual matrix so some data is packed in the unused space
// blend:
// float decalBlend = decalData.normalToWorld[0][3];
// albedo contribution on/off:
// float albedoContribution = decalData.normalToWorld[1][3];
// tiling:
// float2 uvScale = float2(decalData.normalToWorld[3][0], decalData.normalToWorld[3][1]);
// float2 uvBias = float2(decalData.normalToWorld[3][2], decalData.normalToWorld[3][3]);
[GenerateHLSL]
public struct DecalData
{

31
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.shader


_NormalMap("NormalMap", 2D) = "bump" {} // Tangent space normal map
_MaskMap("MaskMap", 2D) = "white" {}
_DecalBlend("_DecalBlend", Range(0.0, 1.0)) = 0.5
[ToggleUI] _AlbedoMode("_AlbedoMode", Range(0.0, 1.0)) = 1.0
}
HLSLINCLUDE

#pragma shader_feature _COLORMAP
#pragma shader_feature _NORMALMAP
#pragma shader_feature _MASKMAP
#pragma shader_feature _ALBEDOCONTRIBUTION
#pragma multi_compile_instancing
//-------------------------------------------------------------------------------------

Pass
{
Name "DBuffer" // Name is not used
Tags { "LightMode" = "DBuffer" } // This will be only for opaque object based on the RenderQueue index
Name "DBufferProjector" // Name is not used
Tags { "LightMode" = "DBufferProjector" } // This will be only for opaque object based on the RenderQueue index
// back faces with zfail, for cases when camera is inside the decal volume
Cull Front

HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER
#define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"

ENDHLSL
}
Pass
{
Name "DBufferMesh" // Name is not used
Tags{"LightMode" = "DBufferMesh"} // This will be only for opaque object based on the RenderQueue index
Cull Back
ZWrite Off
ZTest LEqual
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_MESH
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
}
CustomEditor "Experimental.Rendering.HDPipeline.DecalUI"
}

35
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalData.hlsl


//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/Packing.hlsl"
#include "CoreRP/ShaderLibrary/Sampling/SampleUVMapping.hlsl"
#include "CoreRP/ShaderLibrary/EntityLighting.hlsl"
#include "../MaterialUtilities.hlsl"
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
void GetSurfaceData(FragInputs input, out DecalSurfaceData surfaceData)
#endif
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
texCoordDS = texCoordDS * scale + offset;
float2 texCoords = texCoordDS * scale + offset;
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
float totalBlend = _DecalBlend;
float2 texCoords = input.texCoord0;
#endif
surfaceData.baseColor = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, texCoordDS.xy);
surfaceData.baseColor = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, texCoords);
surfaceData.HTileMask |= DBUFFERHTILEBIT_DIFFUSE;
#if _ALBEDOCONTRIBUTION
surfaceData.HTileMask |= DBUFFERHTILEBIT_DIFFUSE;
#else
surfaceData.baseColor.w = 0; // dont blend any albedo
#endif
surfaceData.normalWS.xyz = mul((float3x3)normalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoordDS))) * 0.5f + 0.5f;
float3 normalTS = UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoords));
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
float3 normalWS = mul((float3x3)normalToWorld, normalTS);
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
float3 normalWS;
GetNormalWS(input, 0, normalTS, normalWS);
#endif
surfaceData.normalWS.xyz = normalWS * 0.5f + 0.5f;
surfaceData.mask = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, texCoordDS.xy);
surfaceData.mask = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, texCoords);
surfaceData.mask.z = surfaceData.mask.w;
surfaceData.mask.w = totalBlend;
surfaceData.HTileMask |= DBUFFERHTILEBIT_MASK;

9
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProjectorComponent.cs


public float m_FadeScale = 0.9f;
public Vector2 m_UVScale = new Vector2(1, 1);
public Vector2 m_UVBias = new Vector2(0, 0);
public bool m_AffectsTransparency = false;
private Material m_OldMaterial = null;
private DecalSystem.DecalHandle m_Handle = null;

}
Vector4 uvScaleBias = new Vector4(m_UVScale.x, m_UVScale.y, m_UVBias.x, m_UVBias.y);
m_Handle = DecalSystem.instance.AddDecal(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_Material);
m_Handle = DecalSystem.instance.AddDecal(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_AffectsTransparency, m_Material);
}
public void OnDisable()

if (m_Handle != null)
DecalSystem.instance.RemoveDecal(m_Handle);
Vector4 uvScaleBias = new Vector4(m_UVScale.x, m_UVScale.y, m_UVBias.x, m_UVBias.y);
m_Handle = DecalSystem.instance.AddDecal(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_Material);
m_Handle = DecalSystem.instance.AddDecal(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_AffectsTransparency, m_Material);
m_OldMaterial = m_Material;
// notify the editor that material has changed so it can update the shader foldout

if (transform.hasChanged == true)
{
Vector4 uvScaleBias = new Vector4(m_UVScale.x, m_UVScale.y, m_UVBias.x, m_UVBias.y);
DecalSystem.instance.UpdateCachedData(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_Handle);
DecalSystem.instance.UpdateCachedData(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_AffectsTransparency, m_Handle);
transform.hasChanged = false;
}
}

DrawGizmo(true);
// if this object is selected there is a chance the transform was changed so update culling info
Vector4 uvScaleBias = new Vector4(m_UVScale.x, m_UVScale.y, m_UVBias.x, m_UVBias.y);
DecalSystem.instance.UpdateCachedData(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_Handle);
DecalSystem.instance.UpdateCachedData(transform, m_DrawDistance, m_FadeScale, uvScaleBias, m_AffectsTransparency, m_Handle);
}
public void OnDrawGizmos()

73
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalSystem.cs


static public DecalData[] m_DecalDatas = new DecalData[kDecalBlockSize];
static public SFiniteLightBound[] m_Bounds = new SFiniteLightBound[kDecalBlockSize];
static public LightVolumeData[] m_LightVolumes = new LightVolumeData[kDecalBlockSize];
static public TextureScaleBias[] m_DiffuseTextureScaleBias = new TextureScaleBias[kDecalBlockSize];
static public TextureScaleBias[] m_NormalTextureScaleBias = new TextureScaleBias[kDecalBlockSize];
static public TextureScaleBias[] m_MaskTextureScaleBias = new TextureScaleBias[kDecalBlockSize];
static public int m_DecalDatasCount = 0;
static public float[] m_BoundingDistances = new float[1];

m_Normal.m_Texture = m_Material.GetTexture("_NormalMap");
m_Mask.m_Texture = m_Material.GetTexture("_MaskMap");
m_Blend = m_Material.GetFloat("_DecalBlend");
m_AlbedoContribution = m_Material.GetFloat("_AlbedoMode");
}
public DecalSet(Material material)

return res;
}
public void UpdateCachedData(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, DecalHandle handle)
public void UpdateCachedData(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, bool affectsTransparency, DecalHandle handle)
{
if (m_Material == null)
return;

: instance.DrawDistance;
m_CachedDrawDistances[index].y = fadeScale;
m_CachedUVScaleBias[index] = uvScaleBias;
m_CachedAffectsTransparency[index] = affectsTransparency;
public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, int materialID)
public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, bool affectsTransparency, int materialID)
{
// increase array size if no space left
if (m_DecalsCount == m_Handles.Length)

Matrix4x4[] newCachedNormalToWorld = new Matrix4x4[m_DecalsCount + kDecalBlockSize];
Vector2[] newCachedDrawDistances = new Vector2[m_DecalsCount + kDecalBlockSize];
Vector4[] newCachedUVScaleBias = new Vector4[m_DecalsCount + kDecalBlockSize];
bool[] newCachedAffectsTransparency = new bool[m_DecalsCount + kDecalBlockSize];
m_ResultIndices = new int[m_DecalsCount + kDecalBlockSize];
m_Handles.CopyTo(newHandles, 0);

m_CachedDrawDistances.CopyTo(newCachedDrawDistances, 0);
m_CachedUVScaleBias.CopyTo(newCachedUVScaleBias, 0);
m_CachedAffectsTransparency.CopyTo(newCachedAffectsTransparency, 0);
m_Handles = newHandles;
m_BoundingSpheres = newSpheres;

m_CachedUVScaleBias = newCachedUVScaleBias;
m_CachedAffectsTransparency = newCachedAffectsTransparency;
UpdateCachedData(transform, drawDistance, fadeScale, uvScaleBias, decalHandle);
UpdateCachedData(transform, drawDistance, fadeScale, uvScaleBias, affectsTransparency, decalHandle);
m_DecalsCount++;
return decalHandle;
}

m_CachedNormalToWorld[removeAtIndex] = m_CachedNormalToWorld[m_DecalsCount - 1];
m_CachedDrawDistances[removeAtIndex] = m_CachedDrawDistances[m_DecalsCount - 1];
m_CachedUVScaleBias[removeAtIndex] = m_CachedUVScaleBias[m_DecalsCount - 1];
m_CachedAffectsTransparency[removeAtIndex] = m_CachedAffectsTransparency[m_DecalsCount - 1];
m_DecalsCount--;
handle.m_Index = kInvalidIndex;
}

return;
if (m_NumResults == 0)
return;
// only add if anything in this decal set is visible.
AddToTextureList(ref instance.m_TextureList);
bool anyAffectTransparency = false;
AssignCurrentBatches(ref decalToWorldBatch, ref normalToWorldBatch, batchCount);

normalToWorldBatch[instanceCount] = m_CachedNormalToWorld[decalIndex];
float fadeFactor = Mathf.Clamp((cullDistance - distanceToDecal) / (cullDistance * (1.0f - m_CachedDrawDistances[decalIndex].y)), 0.0f, 1.0f);
normalToWorldBatch[instanceCount].m03 = fadeFactor * m_Blend; // vector3 rotation matrix so bottom row and last column can be used for other data to save space
normalToWorldBatch[instanceCount].m13 = m_AlbedoContribution;
m_DecalDatas[m_DecalDatasCount].worldToDecal = decalToWorldBatch[instanceCount].inverse;
m_DecalDatas[m_DecalDatasCount].normalToWorld = normalToWorldBatch[instanceCount];
m_DecalDatas[m_DecalDatasCount].diffuseScaleBias = m_Diffuse.m_ScaleBias;
m_DecalDatas[m_DecalDatasCount].normalScaleBias = m_Normal.m_ScaleBias;
m_DecalDatas[m_DecalDatasCount].maskScaleBias = m_Mask.m_ScaleBias;
GetDecalVolumeDataAndBound(decalToWorldBatch[instanceCount], worldToView);
m_DecalDatasCount++;
if(m_CachedAffectsTransparency[decalIndex])
{
m_DecalDatas[m_DecalDatasCount].worldToDecal = decalToWorldBatch[instanceCount].inverse;
m_DecalDatas[m_DecalDatasCount].normalToWorld = normalToWorldBatch[instanceCount];
// we have not allocated the textures in atlas yet, so only store references to them
m_DiffuseTextureScaleBias[m_DecalDatasCount] = m_Diffuse;
m_NormalTextureScaleBias[m_DecalDatasCount] = m_Normal;
m_MaskTextureScaleBias[m_DecalDatasCount] = m_Mask;
GetDecalVolumeDataAndBound(decalToWorldBatch[instanceCount], worldToView);
m_DecalDatasCount++;
anyAffectTransparency = true;
}
instanceCount++;
if (instanceCount == kDrawIndexedBatchSize)

AssignCurrentBatches(ref decalToWorldBatch, ref normalToWorldBatch, batchCount);
}
}
}
// only add if any projectors in this decal set affect transparency, doesn't actually allocate textures in the atlas yet, this is because we want all the textures in the list so we can optimize the packing
if( anyAffectTransparency)
{
AddToTextureList(ref instance.m_TextureList);
}
}

private Matrix4x4[] m_CachedNormalToWorld = new Matrix4x4[kDecalBlockSize];
private Vector2[] m_CachedDrawDistances = new Vector2[kDecalBlockSize]; // x - draw distance, y - fade scale
private Vector4[] m_CachedUVScaleBias = new Vector4[kDecalBlockSize]; // xy - scale, zw bias
private bool[] m_CachedAffectsTransparency = new bool[kDecalBlockSize];
private float m_AlbedoContribution = 0;
TextureScaleBias m_Diffuse = new TextureScaleBias();
TextureScaleBias m_Normal = new TextureScaleBias();

public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, Material material)
public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, bool affectsTransparency, Material material)
{
DecalSet decalSet = null;
int key = material != null ? material.GetInstanceID() : kNullMaterialIndex;

m_DecalSets.Add(key, decalSet);
}
return decalSet.AddDecal(transform, drawDistance, fadeScale, uvScaleBias, key);
return decalSet.AddDecal(transform, drawDistance, fadeScale, uvScaleBias, affectsTransparency, key);
}
public void RemoveDecal(DecalHandle handle)

}
}
public void UpdateCachedData(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, DecalHandle handle)
public void UpdateCachedData(Transform transform, float drawDistance, float fadeScale, Vector4 uvScaleBias, bool affectsTransparency, DecalHandle handle)
{
if (!DecalHandle.IsValid(handle))
return;

if (m_DecalSets.TryGetValue(key, out decalSet))
{
decalSet.UpdateCachedData(transform, drawDistance, fadeScale, uvScaleBias, handle);
decalSet.UpdateCachedData(transform, drawDistance, fadeScale, uvScaleBias, affectsTransparency, handle);
}
}

}
}
private void UpdateDecalDatasWithAtlasInfo()
{
for (int decalDataIndex = 0; decalDataIndex < m_DecalDatasCount; decalDataIndex++)
{
m_DecalDatas[decalDataIndex].diffuseScaleBias = m_DiffuseTextureScaleBias[decalDataIndex].m_ScaleBias;
m_DecalDatas[decalDataIndex].normalScaleBias = m_NormalTextureScaleBias[decalDataIndex].m_ScaleBias;
m_DecalDatas[decalDataIndex].maskScaleBias = m_MaskTextureScaleBias[decalDataIndex].m_ScaleBias;
}
}
public void UpdateTextureAtlas(CommandBuffer cmd)
{
m_AllocationSuccess = true;

}
}
m_PrevAllocationSuccess = m_AllocationSuccess;
// now that textures have been stored in the atlas we can update their location info in decal data
UpdateDecalDatasWithAtlasInfo();
}
public void CreateDrawData()

m_DecalDatas = new DecalData[newDecalDatasSize];
m_Bounds = new SFiniteLightBound[newDecalDatasSize];
m_LightVolumes = new LightVolumeData[newDecalDatasSize];
m_DiffuseTextureScaleBias = new TextureScaleBias[newDecalDatasSize];
m_NormalTextureScaleBias = new TextureScaleBias[newDecalDatasSize];
m_MaskTextureScaleBias = new TextureScaleBias[newDecalDatasSize];
}
foreach (var pair in m_DecalSets)
{

9
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalUtilities.hlsl


if((decalData.diffuseScaleBias.x > 0) && (decalData.diffuseScaleBias.y > 0))
{
ApplyBlendDiffuse(DBuffer0, mask, sampleDiffuse, DBUFFERHTILEBIT_DIFFUSE, decalBlend, lodDiffuse);
alpha = alpha < decalBlend ? decalBlend : alpha; // use decal alpha if it is higher than transparent alpha
ApplyBlendDiffuse(DBuffer0, mask, sampleDiffuse, DBUFFERHTILEBIT_DIFFUSE, decalBlend, lodDiffuse);
float albedoContribution = decalData.normalToWorld[1][3];
if (albedoContribution == 0.0f)
{
mask = 0; // diffuse will not get modified
}
alpha = alpha < decalBlend ? decalBlend : alpha; // use decal alpha if it is higher than transparent alpha
}
if ((decalData.normalScaleBias.x > 0) && (decalData.normalScaleBias.y > 0))

10
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/ShaderPass/DecalSharePass.hlsl


#error Undefine_SHADERPASS
#endif
#if (SHADERPASS == SHADERPASS_DBUFFER_MESH)
#define ATTRIBUTES_NEED_NORMAL
#define ATTRIBUTES_NEED_TANGENT // Always present as we require it also in case of anisotropic lighting
#define ATTRIBUTES_NEED_TEXCOORD0
#define VARYINGS_NEED_POSITION_WS
#define VARYINGS_NEED_TANGENT_TO_WORLD
#define VARYINGS_NEED_TEXCOORD0
#endif
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"

12
com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLit.shader


ZWrite On
ColorMask 0
HLSLPROGRAM
HLSLPROGRAM
// In deferred, depth only pass don't output anything.
// In forward it output the normal buffer
#pragma multi_compile _ WRITE_NORMAL_BUFFER
#ifdef WRITE_NORMAL_BUFFER // If enabled we need all regular interpolator
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#else
#endif
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"

12
com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitTessellation.shader


ZWrite On
ColorMask 0
// In deferred, depth only pass don't output anything.
// In forward it output the normal buffer
#pragma multi_compile _ WRITE_NORMAL_BUFFER
#ifdef WRITE_NORMAL_BUFFER // If enabled we need all regular interpolator
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#else
#endif
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"

112
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.hlsl


// SurfaceData is define in Lit.cs which generate Lit.cs.hlsl
#include "Lit.cs.hlsl"
#include "../SubsurfaceScattering/SubsurfaceScattering.hlsl"
#include "../NormalBuffer.hlsl"
#include "CoreRP/ShaderLibrary/VolumeRendering.hlsl"
//-----------------------------------------------------------------------------

#define CLEAR_COAT_IETA (1.0 / CLEAR_COAT_IOR) // IETA is the inverse eta which is the ratio of IOR of two interface
#define CLEAR_COAT_F0 0.04 // IORToFresnel0(CLEAR_COAT_IOR)
#define CLEAR_COAT_ROUGHNESS 0.001
#define CLEAR_COAT_PERCEPTUAL_SMOOTHNESS RoughnessToPerceptualSmoothness(CLEAR_COAT_ROUGHNESS)
#define CLEAR_COAT_PERCEPTUAL_ROUGHNESS RoughnessToPerceptualRoughness(CLEAR_COAT_ROUGHNESS)
//-----------------------------------------------------------------------------

// #define LIT_DISPLAY_REFERENCE_AREA
// #define LIT_DISPLAY_REFERENCE_IBL
#endif
// In forward we can chose between reading the normal from the normalBufferTexture or computing it again
// This is tradeoff between performance and quality. As we store the normal conpressed, recomputing again is higher quality.
// Uncomment this to get speed (to measure), let it comment to get quality
// #define FORWARD_MATERIAL_READ_FROM_WRITTEN_NORMAL_BUFFER
//-----------------------------------------------------------------------------
// Ligth and material classification for the deferred rendering path

return sssData;
}
NormalData ConvertSurfaceDataToNormalData(SurfaceData surfaceData)
{
NormalData normalData;
// Note: We can't handle clear coat material here, we have only one slot to store smoothness
// and the buffer is the GBuffer1.
normalData.normalWS = surfaceData.normalWS;
normalData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness);
return normalData;
}
void UpdateSurfaceDataFromNormalData(uint2 positionSS, inout BSDFData bsdfData)
{
NormalData normalData;
DecodeFromNormalBuffer(positionSS, normalData);
bsdfData.normalWS = normalData.normalWS;
bsdfData.perceptualRoughness = normalData.perceptualRoughness;
}
BSDFData ConvertSurfaceDataToBSDFData(SurfaceData surfaceData)
BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData surfaceData)
{
BSDFData bsdfData;
ZERO_INITIALIZE(BSDFData, bsdfData);

bsdfData.specularOcclusion = surfaceData.specularOcclusion;
bsdfData.normalWS = surfaceData.normalWS;
bsdfData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness);
// Check if we read value of normal and roughness from buffer. This is a tradeoff
#ifdef FORWARD_MATERIAL_READ_FROM_WRITTEN_NORMAL_BUFFER
#if (SHADERPASS == SHADERPASS_FORWARD) && !defined(_SURFACE_TYPE_TRANSPARENT)
UpdateSurfaceDataFromNormalData(positionSS, bsdfData);
#endif
#endif
// There is no metallic with SSS and specular color mode
float metallic = HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR | MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION) ? 0.0 : surfaceData.metallic;

// Warning: the contents are later overwritten for Standard and SSS!
outGBuffer0 = float4(surfaceData.baseColor, surfaceData.specularOcclusion);
// The sign of the Z component of the normal MUST round-trip through the G-Buffer, otherwise
// the reconstruction of the tangent frame for anisotropic GGX creates a seam along the Z axis.
// The constant was eye-balled to not cause artifacts.
// TODO: find a proper solution. E.g. we could re-shuffle the faces of the octahedron
// s.t. the sign of the Z component round-trips.
const float seamThreshold = 1.0/1024.0;
surfaceData.normalWS.z = CopySign(max(seamThreshold, abs(surfaceData.normalWS.z)), surfaceData.normalWS.z);
// RT1 - 8:8:8:8
// Our tangent encoding is based on our normal.
float2 octNormalWS = PackNormalOctQuadEncode(surfaceData.normalWS);
float3 packNormalWS = PackFloat2To888(saturate(octNormalWS * 0.5 + 0.5));
// We store perceptualRoughness instead of roughness because it is perceptually linear.
outGBuffer1 = float4(packNormalWS, PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness));
// This encode normalWS and PerceptualSmoothness into GBuffer1
EncodeIntoNormalBuffer(ConvertSurfaceDataToNormalData(surfaceData), positionSS, outGBuffer1);
// RT2 - 8:8:8:8
uint materialFeatureId;

// Decompress feature-agnostic data from the G-Buffer.
float3 baseColor = inGBuffer0.rgb;
float3 packNormalWS = inGBuffer1.rgb;
float2 octNormalWS = Unpack888ToFloat2(packNormalWS);
bsdfData.normalWS = UnpackNormalOctQuadEncode(octNormalWS * 2.0 - 1.0);
bsdfData.perceptualRoughness = inGBuffer1.a;
NormalData normalData;
DecodeFromNormalBuffer(inGBuffer1, positionSS, normalData);
bsdfData.normalWS = normalData.normalWS;
bsdfData.perceptualRoughness = normalData.perceptualRoughness;
bakeDiffuseLighting = inGBuffer3.rgb;

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

// TODO: Fade pixels marked as foreground in stencil
float weight = weightNDC.x * weightNDC.y * hitWeight;
float hitDeviceDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, hit.positionSS, 0).r;
float hitLinearDepth = LinearEyeDepth(hitDeviceDepth, _ZBufferParams);
float hitDeviceDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, hit.positionSS, 0).r;
float hitLinearDepth = LinearEyeDepth(hitDeviceDepth, _ZBufferParams);
float2 samplingPositionNDC = hit.positionNDC;
#if HAS_REFRACTION
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION
&& hitLinearDepth < posInput.linearDepth)
samplingPositionNDC = posInput.positionNDC;
#endif
// Reproject color pyramid
float4 hitVelocityBuffer = LOAD_TEXTURE2D_LOD(
_CameraMotionVectorsTexture,
hit.positionSS,
0.0
);
float2 hitVelocityNDC;
DecodeVelocity(hitVelocityBuffer, hitVelocityNDC);
float2 hitVelocityNDC = 0;
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
{
// Reproject color pyramid
float4 hitVelocityBuffer = LOAD_TEXTURE2D_LOD(
_CameraMotionVectorsTexture,
hit.positionSS,
0.0
);
DecodeVelocity(hitVelocityBuffer, hitVelocityNDC);
}
(hit.positionNDC - hitVelocityNDC) * _ColorPyramidScale.xy + _ColorPyramidSize.zw * 0.5,
(samplingPositionNDC - hitVelocityNDC) * _ColorPyramidScale.xy + _ColorPyramidSize.zw * 0.5,
if (projectionModel == PROJECTIONMODEL_HI_Z)
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION && projectionModel == PROJECTIONMODEL_HI_Z)
{
float4 currentVelocityBuffer = LOAD_TEXTURE2D_LOD(
_CameraMotionVectorsTexture,

if (_DebugLightingSubMode != DEBUGSCREENSPACETRACING_COLOR)
diffuseLighting = lighting.indirect.specularReflected;
break;
case DEBUGLIGHTINGMODE_VISUALIZE_SHADOW_MASKS:
#ifdef SHADOWS_SHADOWMASK
diffuseLighting = float3(
bakeLightingData.bakeShadowMask.r / 2 + bakeLightingData.bakeShadowMask.g / 2,
bakeLightingData.bakeShadowMask.g / 2 + bakeLightingData.bakeShadowMask.b / 2,
bakeLightingData.bakeShadowMask.b / 2 + bakeLightingData.bakeShadowMask.a / 2
);
specularLighting = float3(0, 0, 0);
#endif
break ;
}
}
else if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)

12
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.shader


ZWrite On
ColorMask 0
HLSLPROGRAM
HLSLPROGRAM
// In deferred, depth only pass don't output anything.
// In forward it output the normal buffer
#pragma multi_compile _ WRITE_NORMAL_BUFFER
#ifdef WRITE_NORMAL_BUFFER // If enabled we need all regular interpolator
#include "ShaderPass/LitSharePass.hlsl"
#else
#endif
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitBuiltinData.hlsl


// It is safe to call this function here as surfaceData have been filled
// We want to know if we must enable transmission on GI for SSS material, if the material have no SSS, this code will be remove by the compiler.
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// For now simply recall the function with inverted normal, the compiler should be able to optimize the lightmap case to not resample the directional lightmap

12
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitTessellation.shader


ZWrite On
ColorMask 0
// In deferred, depth only pass don't output anything.
// In forward it output the normal buffer
#pragma multi_compile _ WRITE_NORMAL_BUFFER
#ifdef WRITE_NORMAL_BUFFER // If enabled we need all regular interpolator
#include "ShaderPass/LitSharePass.hlsl"
#else
#endif
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"

38
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.hlsl


// SurfaceData is defined in StackLit.cs which generates StackLit.cs.hlsl
#include "StackLit.cs.hlsl"
#include "../SubsurfaceScattering/SubsurfaceScattering.hlsl"
#include "../NormalBuffer.hlsl"
//#include "CoreRP/ShaderLibrary/VolumeRendering.hlsl"
//NEWLITTODO : wireup CBUFFERs for ambientocclusion, and other uniforms and samplers used:

//-----------------------------------------------------------------------------
// Definition
//-----------------------------------------------------------------------------
// Required for SSS
#define GBufferType0 float4
// Needed for MATERIAL_FEATURE_MASK_FLAGS.
#include "../../Lighting/LightLoop/LightLoop.cs.hlsl"

return sssData;
}
NormalData ConvertSurfaceDataToNormalData(SurfaceData surfaceData)
{
NormalData normalData;
// When using clear cloat we want to use the coat normal for the various deferred effect
// as it is the most dominant one
if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_COAT))
{
normalData.normalWS = surfaceData.coatNormalWS;
normalData.perceptualRoughness = surfaceData.coatPerceptualSmoothness;
}
else
{
normalData.normalWS = surfaceData.normalWS;
// Do average mix in case of dual lobe
normalData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(lerp(surfaceData.perceptualSmoothnessA, surfaceData.perceptualSmoothnessB, surfaceData.lobeMix));
}
return normalData;
}
BSDFData ConvertSurfaceDataToBSDFData(SurfaceData surfaceData)
BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData surfaceData)
{
BSDFData bsdfData;
ZERO_INITIALIZE(BSDFData, bsdfData);

//if (_DebugLightingSubMode != DEBUGSCREENSPACETRACING_COLOR)
// diffuseLighting = lighting.indirect.specularReflected;
break;
case DEBUGLIGHTINGMODE_VISUALIZE_SHADOW_MASKS:
#ifdef SHADOWS_SHADOWMASK
diffuseLighting = float3(
bakeLightingData.bakeShadowMask.r / 2 + bakeLightingData.bakeShadowMask.g / 2,
bakeLightingData.bakeShadowMask.g / 2 + bakeLightingData.bakeShadowMask.b / 2,
bakeLightingData.bakeShadowMask.b / 2 + bakeLightingData.bakeShadowMask.a / 2
);
specularLighting = float3(0, 0, 0);
#endif
break ;
}
}
else if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)

4
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.shader


HLSLPROGRAM
#define WRITE_NORMAL_BUFFER
#include "ShaderPass/StackLitDepthPass.hlsl"
// As we enabled WRITE_NORMAL_BUFFER we need all regular interpolator
#include "ShaderPass/StackLitSharePass.hlsl"
#include "StackLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"

2
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLitData.hlsl


// It is safe to call this function here as surfaceData have been filled
// We want to know if we must enable transmission on GI for SSS material, if the material have no SSS, this code will be remove by the compiler.
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION))
{
// For now simply recall the function with inverted normal, the compiler should be able to optimize the lightmap case to not resample the directional lightmap

4
com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl


uint diffusionProfile;
};
#define SSSBufferType0 float4
#define SSSBufferType0 float4 // Must match GBufferType0 in deferred
// SSSBuffer texture declaration
TEXTURE2D(_SSSBufferTexture0);

}
// 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 OUTPUT_SSSBUFFER(NAME) out SSSBufferType0 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)

2
com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/Unlit.hlsl


// conversion function for forward
//-----------------------------------------------------------------------------
BSDFData ConvertSurfaceDataToBSDFData(SurfaceData data)
BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData data)
{
BSDFData output;
output.color = data.color;

2
com.unity.render-pipelines.high-definition/HDRP/Material/Unlit/Unlit.shader


ZWrite On
ColorMask 0 // We don't have WRITE_NORMAL_BUFFER for unlit, but as we bind a buffer we shouldn't write into it.
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DEPTH_ONLY

106
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipeline.cs


readonly GBufferManager m_GbufferManager;
readonly DBufferManager m_DbufferManager;
readonly SubsurfaceScatteringManager m_SSSBufferManager = new SubsurfaceScatteringManager();
readonly NormalBufferManager m_NormalBufferManager = new NormalBufferManager();
// Renderer Bake configuration can vary depends on if shadow mask is enabled or no
RendererConfiguration m_currentRendererConfigurationBakedLighting = HDUtils.k_RendererConfigurationBakedLighting;

m_DbufferManager = new DBufferManager();
m_SSSBufferManager.Build(asset);
m_NormalBufferManager.Build(asset);
// Initialize various compute shader resources
m_applyDistortionKernel = m_applyDistortionCS.FindKernel("KMain");

m_DbufferManager.CreateBuffers();
m_SSSBufferManager.InitSSSBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
m_NormalBufferManager.InitNormalBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
m_CameraColorBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, enableRandomWrite: true, enableMSAA: true, name: "CameraColor");
m_CameraSssDiffuseLightingBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.RGB111110Float, sRGB: false, enableRandomWrite: true, enableMSAA: true, name: "CameraSSSDiffuseLighting");

CoreUtils.Destroy(m_ErrorMaterial);
m_SSSBufferManager.Cleanup();
m_NormalBufferManager.Cleanup();
m_SkyManager.Cleanup();
m_VolumetricLightingSystem.Cleanup();
m_IBLFilterGGX.Cleanup();

m_ReflectionProbeCullResults.Cull();
m_DbufferManager.vsibleDecalCount = 0;
m_DbufferManager.EnableDBUffer = false;
m_DbufferManager.vsibleDecalCount = DecalSystem.m_DecalsVisibleThisFrame;
m_DbufferManager.EnableDBUffer = true; // mesh decals are renderers managed by c++ runtime and we have no way to query if any are visible, so set to true
DecalSystem.instance.UpdateCachedMaterialData(); // textures, alpha or fade distances could've changed
DecalSystem.instance.CreateDrawData(); // prepare data is separate from draw
DecalSystem.instance.UpdateTextureAtlas(cmd); // as this is only used for transparent pass, would've been nice not to have to do this if no transparent renderers are visible, needs to happen after CreateDrawData

ClearBuffers(hdCamera, cmd);
// TODO: Add stereo occlusion mask
bool forcePrepassForDecals = m_DbufferManager.vsibleDecalCount > 0;
RenderDepthPrepass(m_CullResults, hdCamera, renderContext, cmd, forcePrepassForDecals);
RenderDepthPrepass(m_CullResults, hdCamera, renderContext, cmd, m_DbufferManager.EnableDBUffer);
RenderDBuffer(hdCamera, cmd);
RenderDBuffer(hdCamera, cmd, renderContext, m_CullResults);
// We can now bind the normal buffer to be use by any effect
m_NormalBufferManager.BindNormalBuffers(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);
RenderDepthPyramid(hdCamera, cmd, renderContext, FullScreenDebugMode.DepthPyramid);

// by using the pass "ForwardOnly". In this case the .shader should not have "Forward" but only a "ForwardOnly" pass.
// It must also have a "DepthForwardOnly" and no "DepthOnly" pass as forward material (either deferred or forward only rendering) have always a depth pass.
// If a forward material have no depth prepass, then lighting can be incorrect (deferred sahdowing, SSAO), this may be acceptable depends on usage
bool addFullDepthPrepass = forcePrepass || hdCamera.frameSettings.enableForwardRenderingOnly || hdCamera.frameSettings.enableDepthPrepassWithDeferredRendering;
// Whatever the configuration we always render first the opaque object as opaque alpha tested are more costly to render and could be reject by early-z
// (but not Hi-z as it is disable with clip instruction). This is handled automatically with the RenderQueue value (OpaqueAlphaTested have a different value and thus are sorted after Opaque)
using (new ProfilingSample(cmd, !addFullDepthPrepass ? "Depth Prepass alpha test" : "Depth Prepass", CustomSamplerId.DepthPrepass.GetSampler()))
// Forward material always output normal buffer (unless they don't participate to shading)
// Deferred material never output normal buffer
// Note: Unlit object use a ForwardOnly pass and don't have normal, they will write 0 in the normal buffer. This should be safe
// as they will not use the result of lighting anyway. However take care of effect that will try to filter normal buffer.
// TODO: maybe we can use a stencil to tag when Forward unlit touch normal buffer
if (hdCamera.frameSettings.enableForwardRenderingOnly)
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraDepthStencilBuffer);
if (addFullDepthPrepass) // Always true in case of forward rendering, use in case of deferred rendering if requesting a full depth prepass
using (new ProfilingSample(cmd, "Depth Prepass (forward)", CustomSamplerId.DepthPrepass.GetSampler()))
// We render first the opaque object as opaque alpha tested are more costly to render and could be reject by early-z (but not Hi-z as it is disable with clip instruction)
// This is handled automatically with the RenderQueue value (OpaqueAlphaTested have a different value and thus are sorted after Opaque)
cmd.EnableShaderKeyword("WRITE_NORMAL_BUFFER");
HDUtils.SetRenderTarget(cmd, hdCamera, m_NormalBufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer);
// Full forward: Output normal buffer for both forward and forwardOnly
else // Deferred rendering with partial depth prepass
}
else if (hdCamera.frameSettings.enableDepthPrepassWithDeferredRendering || forcePrepass)
{
using (new ProfilingSample(cmd, "Depth Prepass (deferred)", CustomSamplerId.DepthPrepass.GetSampler()))
// We always do a DepthForwardOnly pass with all the opaque (including alpha test)
cmd.DisableShaderKeyword("WRITE_NORMAL_BUFFER"); // Note: This only disable the output of normal buffer for Lit shader, not the other shader that don't use multicompile
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraDepthStencilBuffer);
// First deferred material
RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
HDUtils.SetRenderTarget(cmd, hdCamera, m_NormalBufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer);
// Then forward only material that output normal buffer
}
}
else // Deferred with partial depth prepass
{
using (new ProfilingSample(cmd, "Depth Prepass (deferred incomplete)", CustomSamplerId.DepthPrepass.GetSampler()))
{
cmd.DisableShaderKeyword("WRITE_NORMAL_BUFFER");
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraDepthStencilBuffer);
// Alpha tested materials always have a prepass.
// First deferred alpha tested materials. Alpha tested object have always a prepass even if enableDepthPrepassWithDeferredRendering is disabled
HDUtils.SetRenderTarget(cmd, hdCamera, m_NormalBufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer);
// Then forward only material that output normal buffer
RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthForwardOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
}
}

}
}
void RenderDBuffer(HDCamera hdCamera, CommandBuffer cmd)
void RenderDBuffer(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, CullResults cullResults)
{
if (!hdCamera.frameSettings.enableDBuffer)
return;

m_DbufferManager.ClearTargets(cmd, hdCamera);
HDUtils.SetRenderTarget(cmd, hdCamera, m_DbufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer); // do not clear anymore
m_DbufferManager.SetHTile(m_DbufferManager.bufferCount, cmd);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Clear();
DrawRendererSettings drawSettings = new DrawRendererSettings(hdCamera.camera, HDShaderPassNames.s_EmptyName)
{
rendererConfiguration = 0,
sorting = { flags = SortFlags.CommonOpaque }
};
drawSettings.SetShaderPassName(0, HDShaderPassNames.s_MeshDecalsName);
FilterRenderersSettings filterRenderersSettings = new FilterRenderersSettings(true)
{
renderQueueRange = HDRenderQueue.k_RenderQueue_AllOpaque
};
renderContext.DrawRenderers(cullResults.visibleRenderers, ref drawSettings, filterRenderersSettings);
DecalSystem.instance.RenderIntoDBuffer(cmd);
m_DbufferManager.UnSetHTile(cmd);
m_DbufferManager.SetHTileTexture(cmd); // mask per 8x8 tile used for optimization when looking up dbuffer values

// 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 (hdCamera.frameSettings.enableSubsurfaceScattering)
{
RenderTargetIdentifier[] m_MRTWithSSS =
new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];
RenderTargetIdentifier[] m_MRTWithSSS = new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];
m_MRTWithSSS[0] = m_CameraColorBuffer; // Store the specular color
m_MRTWithSSS[1] = m_CameraSssDiffuseLightingBuffer;
for (int i = 0; i < m_SSSBufferManager.sssBufferCount; ++i)

else
{
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer);
if ((hdCamera.frameSettings.enableDBuffer) && (DecalSystem.m_DecalsVisibleThisFrame > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
if ((hdCamera.frameSettings.enableDBuffer) && (DecalSystem.m_DecalDatasCount > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
// decal datas count is 0 if no decals affect transparency
{
DecalSystem.instance.SetAtlas(cmd); // for clustered decals
}

public void PushColorPickerDebugTexture(CommandBuffer cmd, RTHandleSystem.RTHandle textureID, HDCamera hdCamera)
{
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None || m_DebugDisplaySettings.falseColorDebugSettings.falseColor)
{
using (new ProfilingSample(cmd, "Push To Color Picker"))
{

// TODO TEMP: Not sure I want to keep this special case. Gotta see how to get rid of it (not sure it will work correctly for non-full viewports.
public void PushColorPickerDebugTexture(HDCamera hdCamera, CommandBuffer cmd, RenderTargetIdentifier textureID)
{
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None || m_DebugDisplaySettings.falseColorDebugSettings.falseColor)
{
using (new ProfilingSample(cmd, "Push To Color Picker"))
{

DecalSystem.instance.RenderDebugOverlay(hdCamera, cmd, m_CurrentDebugDisplaySettings, ref x, ref y, overlaySize, hdCamera.actualWidth);
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None || m_CurrentDebugDisplaySettings.falseColorDebugSettings.falseColor)
FalseColorDebugSettings falseColorDebugSettings = m_CurrentDebugDisplaySettings.falseColorDebugSettings;
var falseColorThresholds = new Vector4(falseColorDebugSettings.colorThreshold0, falseColorDebugSettings.colorThreshold1, falseColorDebugSettings.colorThreshold2, falseColorDebugSettings.colorThreshold3);
// Here we have three cases:
// - Material debug is enabled, this is the buffer we display

cmd.SetGlobalTexture(HDShaderIDs._DebugColorPickerTexture, m_DebugColorPickerBuffer); // No SetTexture with RenderTarget identifier... so use SetGlobalTexture
// TODO: Replace with command buffer call when available
m_DebugColorPicker.SetColor(HDShaderIDs._ColorPickerFontColor, colorPickerDebugSettings.fontColor);
var colorPickerParam = new Vector4(colorPickerDebugSettings.colorThreshold0, colorPickerDebugSettings.colorThreshold1, colorPickerDebugSettings.colorThreshold2, colorPickerDebugSettings.colorThreshold3);
m_DebugColorPicker.SetVector(HDShaderIDs._ColorPickerParam, colorPickerParam);
m_DebugColorPicker.SetInt(HDShaderIDs._FalseColorEnabled, falseColorDebugSettings.falseColor ? 1 : 0);
m_DebugColorPicker.SetVector(HDShaderIDs._FalseColorThresholds, falseColorThresholds);
// The material display debug perform sRGBToLinear conversion as the final blit currently hardcode a linearToSrgb conversion. As when we read with color picker this is not done,
// we perform it inside the color picker shader. But we shouldn't do it for HDR buffer.
m_DebugColorPicker.SetFloat(HDShaderIDs._ApplyLinearToSRGB, m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled() ? 1.0f : 0.0f);

13
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDStringConstants.cs


public static readonly string s_TransparentDepthPostpassStr = "TransparentDepthPostpass";
public static readonly string s_MetaStr = "Meta";
public static readonly string s_ShadowCasterStr = "ShadowCaster";
public static readonly string s_MeshDecalsStr = "DBufferMesh";
// ShaderPass name
public static readonly ShaderPassName s_EmptyName = new ShaderPassName(s_EmptyStr);

public static readonly ShaderPassName s_TransparentDepthPrepassName = new ShaderPassName(s_TransparentDepthPrepassStr);
public static readonly ShaderPassName s_TransparentBackfaceName = new ShaderPassName(s_TransparentBackfaceStr);
public static readonly ShaderPassName s_TransparentDepthPostpassName = new ShaderPassName(s_TransparentDepthPostpassStr);
public static readonly ShaderPassName s_MeshDecalsName = new ShaderPassName(s_MeshDecalsStr);
// Legacy name
public static readonly ShaderPassName s_AlwaysName = new ShaderPassName("Always");

Shader.PropertyToID("_SSSBufferTexture3"),
};
public static readonly int[] _NormalBufferTexture =
{
Shader.PropertyToID("_NormalBufferTexture0"),
Shader.PropertyToID("_NormalBufferTexture1"),
Shader.PropertyToID("_NormalBufferTexture2"),
Shader.PropertyToID("_NormalBufferTexture3"),
};
public static readonly int _SSRefractionRayMarchBehindObjects = Shader.PropertyToID("_SSRefractionRayMarchBehindObjects");
public static readonly int _SSRefractionRayMaxScreenDistance = Shader.PropertyToID("_SSRefractionRayMaxScreenDistance");
public static readonly int _SSRefractionRayBlendScreenDistance = Shader.PropertyToID("_SSRefractionRayBlendScreenDistance");

public static readonly int _DepthPyramidScale = Shader.PropertyToID("_DepthPyramidScale");
public static readonly int _DebugColorPickerTexture = Shader.PropertyToID("_DebugColorPickerTexture");
public static readonly int _ColorPickerParam = Shader.PropertyToID("_ColorPickerParam");
public static readonly int _FalseColorEnabled = Shader.PropertyToID("_FalseColor");
public static readonly int _FalseColorThresholds = Shader.PropertyToID("_FalseColorThresholds");
public static readonly int _DebugFullScreenTexture = Shader.PropertyToID("_DebugFullScreenTexture");
public static readonly int _BlitTexture = Shader.PropertyToID("_BlitTexture");

3
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPass.cs


SubsurfaceScattering,
VolumeVoxelization,
VolumetricLighting,
DBuffer
DbufferProjector,
DbufferMesh
}
}

3
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPass.cs.hlsl


#define SHADERPASS_SUBSURFACE_SCATTERING (9)
#define SHADERPASS_VOLUME_VOXELIZATION (10)
#define SHADERPASS_VOLUMETRIC_LIGHTING (11)
#define SHADERPASS_DBUFFER (12)
#define SHADERPASS_DBUFFER_PROJECTOR (12)
#define SHADERPASS_DBUFFER_MESH (13)
#endif

30
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDBuffer.hlsl


#if SHADERPASS != SHADERPASS_DBUFFER
#if (SHADERPASS != SHADERPASS_DBUFFER_PROJECTOR) && (SHADERPASS != SHADERPASS_DBUFFER_MESH)
#error SHADERPASS_is_not_correctly_define
#endif

)
{
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, input.positionSS.xy).x;
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V);
DecalSurfaceData surfaceData;
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
float depth = LOAD_TEXTURE2D(_CameraDepthTexture, input.positionSS.xy).x;
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V);
// Transform from world space to decal space (DS) to clip the decal.
// For this we must use absolute position.
// There is no lose of precision here as it doesn't involve the camera matrix

clip(positionDS); // clip negative value
clip(1.0 - positionDS); // Clip value above one
DecalSurfaceData surfaceData;
// have to do explicit test since compiler behavior is not defined for RW resources and discard instructions
if ((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f)))
{
// have to do explicit test since compiler behavior is not defined for RW resources and discard instructions
if((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f)))
{
uint oldVal = UnpackByte(_DecalHTile[posInput.positionSS.xy / 8]);
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
GetSurfaceData(input, surfaceData);
#endif
uint oldVal = UnpackByte(_DecalHTile[input.positionSS.xy / 8]);
_DecalHTile[posInput.positionSS.xy / 8] = PackByte(oldVal);
_DecalHTile[input.positionSS.xy / 8] = PackByte(oldVal);
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
#endif
ENCODE_INTO_DBUFFER(surfaceData, outDBuffer);
}

15
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDepthOnly.hlsl


#endif // TESSELLATION_ON
void Frag( PackedVaryingsToPS packedInput,
#ifdef WRITE_NORMAL_BUFFER
OUTPUT_NORMALBUFFER(outNormalBuffer)
#else
#endif
#ifdef _DEPTHOFFSET_ON
, out float outputDepth : SV_Depth
#endif

BuiltinData builtinData;
GetSurfaceAndBuiltinData(input, V, posInput, surfaceData, builtinData);
// TODO: handle cubemap shadow
outColor = float4(0.0, 0.0, 0.0, 0.0);
#ifdef WRITE_NORMAL_BUFFER
ENCODE_INTO_NORMALBUFFER(surfaceData, posInput.positionSS, outNormalBuffer);
#elif defined(SCENESELECTIONPASS)
#ifdef SCENESELECTIONPASS
outColor = float4(_ObjectId, _PassValue, 1, 1);
outColor = float4(_ObjectId, _PassValue, 1.0, 1.0);
#else
outColor = float4(0.0, 0.0, 0.0, 0.0);
#endif
}

2
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForward.hlsl


ApplyDebugToSurfaceData(input.worldToTangent, surfaceData);
#endif
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
PreLightData preLightData = GetPreLightData(V, posInput, bsdfData);

2
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForwardUnlit.hlsl


GetSurfaceAndBuiltinData(input, V, posInput, surfaceData, builtinData);
// Not lit here (but emissive is allowed)
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
// TODO: we must not access bsdfData here, it break the genericity of the code!
float4 outColor = ApplyBlendMode(bsdfData.color + builtinData.emissiveColor, builtinData.opacity);

2
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassGBuffer.hlsl


ApplyDebugToSurfaceData(input.worldToTangent, surfaceData);
#endif
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
PreLightData preLightData = GetPreLightData(V, posInput, bsdfData);

2
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassLightTransport.hlsl


// no debug apply during light transport pass
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
LightTransportData lightTransportData = GetLightTransportData(surfaceData, builtinData, bsdfData);
// This shader is call two times. Once for getting emissiveColor, the other time to get diffuseColor

160
com.unity.render-pipelines.lightweight/CHANGELOG.md


# Changelog
All notable changes to this package will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [2.0.1-preview]
### Fixed
- VR Single Pass Instancing shadows
## [2.0.0-preview]
### Added
- Explicit render target load/store actions were added to improve tile utilization
- Camera opaque color can be requested on the pipeline asset. It can be accessed in the shader by defining a _CameraOpaqueTexture. This can be used as an alternative to GrabPass.
- Dynamic Batching can be enabled in the pipeline asset
- Pipeline now strips unused or invalid variants and passes based on selected pipeline capabilities in the asset. This reduces build and memory consuption on target.
- Shader stripping settings were added to pipeline asset
### Changed
#### Pipeline
- Pipeline code is now more modular and extensible. A ForwardRenderer class is initialized by the pipeline with RenderingData and it's responsible for enqueueing and executing passes. In the future pluggable renderers will be supported.
- On mobile 1 directional light + up to 4 local lights (point or spot) are computed
- On other platforms 1 directional light + up to 8 local lights are computed
- Multiple shadow casting lights are supported. Currently only 1 directional + 4 spots light shadows.
#### Shading Framework
- Directional Lights are always considered a main light in shader. They have a fast shading path with no branching and no indexing.
- GetMainLight() is provided in shader to initialize Light struct with main light shading data.
- Directional lights have a dedicated shadowmap for performance reasons. Shadow coord always comes from interpolator.
- MainLigthRealtimeShadowAttenuation(float4 shadowCoord) is provided to compute main light realtime shadows.
- Spot and Point lights are always shaded in the light loop. Branching on uniform and indexing happens when shading them.
- GetLight(half index, float3 positionWS) is provided in shader to initialize Light struct for spot and point lights.
- Spot light shadows are baked into a single shadow atlas.
- Shadow coord for spot lights is always computed on fragment.
- Use LocalLightShadowAttenuation(int lightIndex, float3 positionWS) to comppute realtime shadows for spot lights.
### Fixed
- Issue that was causing VR on Android to render black
- Camera viewport issues
- UWP build issues
- Prevent nested camera rendering in the pipeline
### Improvements
### Added
### Bugfixes
- Fixed SRP Shader library issue that was causing all constants to be highp in mobile
- Fixed shader error that prevented LWRP to build to UWP
- Fixed shader compilation errors in Linux due to case sensitive includes
- Fixed Rendering Texture flipping issue
- Fixed Standard Particles shader cutout and blending modes
- Fixed crash caused by using projectors
- Fixed issue that was causing Shadow Strength to not be computed on mobile
- Fixed Material Upgrader issue that caused editor to SoftLocks
- Fixed GI in Unlit shader
- Fixed null reference in the Unlit material shader GUI
### Fixed
- SRP Shader library issue that was causing all constants to be highp in mobile
- shader error that prevented LWRP to build to UWP
- shader compilation errors in Linux due to case sensitive includes
- Rendering Texture flipping issue
- Standard Particles shader cutout and blending modes
- crash caused by using projectors
- issue that was causing Shadow Strength to not be computed on mobile
- Material Upgrader issue that caused editor to SoftLocks
- GI in Unlit shader
- Null reference in the Unlit material shader GUI
### Improvements
### Changed
### Bugfixes
- Fixed shadows on GLES 2.0
- Fixed CPU performance regression in shadow rendering
- Fixed alpha clip shadow issues
- Fixed unmatched command buffer error message
- Fixed null reference exception caused by missing resource in LWRP
- Fixed issue that was causing Camera clear flags was being ignored in mobile
### Fixed
- Shadows on GLES 2.0
- CPU performance regression in shadow rendering
- Alpha clip shadow issues
- Unmatched command buffer error message
- Null reference exception caused by missing resource in LWRP
- Issue that was causing Camera clear flags was being ignored in mobile
### Improvements
### Added
- Shadowmap uses 16bit format instead of 32bit.
### Changed
- Shadowmap uses 16bit format instead of 32bit.
### Bugfixes
- Fixed Subtractive Mode
### Fixed
- Subtractive Mode
### Improvements
- Refactored lightweight standard shaders and shader library to improve ease of use.
### Added
- HDR RT now uses what format is configured in Tier settings.
- Optimized tile LOAD op on mobile.
### Changed
- HDR RT now uses what format is configured in Tier settings.
- Refactored lightweight standard shaders and shader library to improve ease of use.
- Optimized tile LOAD op on mobile.
### Bugfixes
- Fixed realtime shadows on OpenGL
- Fixed shader compiler errors in GLES 2.0
- Fixed issue sorting issues when BeforeTransparent custom fx was enabled.
- Fixed VR single pass rendering.
- Fixed viewport rendering issues when rendering to backbuffer.
- Fixed viewport rendering issues when rendering to with MSAA turned off.
- Fixed multi-camera rendering.
### Fixed
- Realtime shadows on OpenGL
- Shader compiler errors in GLES 2.0
- Issue sorting issues when BeforeTransparent custom fx was enabled.
- VR single pass rendering.
- Viewport rendering issues when rendering to backbuffer.
- Viewport rendering issues when rendering to with MSAA turned off.
- Multi-camera rendering.
### Improvements
- Shaders ported to the new SRP shader library.
- Constant Buffer Refactor to use new Batcher
### Added
- UI Improvements (Rendering features not supported by LW are hidden)
### Changed
- Shaders were ported to the new SRP shader library.
- Constant Buffer refactor to use new Batcher
- UI Improvements (Rendering features not supported by LW are hidden)
### Bugfixes
### Fixed
### Improvements
- Realtime shadow filtering was improved.
### Added
### Bugfixes
### Changed
- Realtime shadow filtering was improved.
### Fixed

14
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightPBRExtraPasses.template


{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
// x: global clip space bias, y: normal world space bias

{
VertexOutput o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}

return o;
}
half4 ShadowPassFragment() : SV_TARGET
half4 ShadowPassFragment(VertexOutput IN) : SV_TARGET
UNITY_SETUP_INSTANCE_ID(IN);
return 0;
}

{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
VertexOutput vert(GraphVertexInput v)

UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}

return o;
}
half4 frag() : SV_TARGET
half4 frag(VertexOutput IN) : SV_TARGET
UNITY_SETUP_INSTANCE_ID(IN);
return 0;
}
ENDHLSL

11
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightPBRForwardPass.template


// Interpolators defined by graph
${VertexOutputStruct}
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}
VertexDescriptionInputs vdi = (VertexDescriptionInputs)0;

VertexDescription vd = PopulateVertexData(vdi);
v.vertex.xyz = vd.Position;
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
// Vertex shader outputs defined by graph
${VertexShaderOutputs}

14
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightUnlitExtraPasses.template


{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
// x: global clip space bias, y: normal world space bias

{
VertexOutput o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}

return o;
}
half4 ShadowPassFragment() : SV_TARGET
half4 ShadowPassFragment(VertexOutput IN) : SV_TARGET
UNITY_SETUP_INSTANCE_ID(IN);
return 0;
}

{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
VertexOutput vert(GraphVertexInput v)

UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}

return o;
}
half4 frag() : SV_TARGET
half4 frag(VertexOutput IN) : SV_TARGET
UNITY_SETUP_INSTANCE_ID(IN);
return 0;
}
ENDHLSL

11
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightUnlitPass.template


// Interpolators defined by graph
${VertexOutputStruct}
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Vertex transformations performed by graph
${VertexShader}
VertexDescriptionInputs vdi = (VertexDescriptionInputs)0;

VertexDescription vd = PopulateVertexData(vdi);
v.vertex.xyz = vd.Position;
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
o.position = TransformObjectToHClip(v.vertex.xyz);
// Vertex shader outputs defined by graph

2
com.unity.render-pipelines.lightweight/LWRP/Shaders/Terrain/LightweightStandardTerrain.shader


SubShader
{
Tags { "Queue" = "Geometry-100" "RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline" "IgnoreProjector" = "True"}
Tags { "Queue" = "Geometry-100" "RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline" "IgnoreProjector" = "False"}
Pass
{

6
com.unity.render-pipelines.lightweight/LWRP/Shaders/Terrain/LightweightStandardTerrainBase.shader


Pass
{
Name "ShadowCaster"
Tags{"LightMode" = "ShadowCaster"}
ZWrite On

Pass
{
Name "DepthOnly"
Tags{"LightMode" = "DepthOnly"}
ZWrite On

// This pass it not used during regular rendering, only for lightmap baking.
Pass
{
Name "Meta"
Cull Off
#pragma target 2.0
#pragma vertex LightweightVertexMeta
#pragma fragment LightweightFragmentMeta

82
com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsFrontFaceNode.cs


using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Title("Utility", "Logic", "Is Front Face")]
public class IsFrontFaceNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequireFaceSign
{
public IsFrontFaceNode()
{
name = "Is Front Face";
UpdateNodeAfterDeserialization();
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Is-Front-Face-Node"; }
}
public override bool hasPreview { get { return false; } }
public const int OutputSlotId = 0;
private const string kOutputSlotName = "Out";
public override void UpdateNodeAfterDeserialization()
{
AddSlot(new BooleanMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, true, ShaderStageCapability.Fragment));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
visitor.AddShaderChunk(string.Format("{0} {1} = max(0, IN.{2});", precision, GetVariableNameForSlot(OutputSlotId), ShaderGeneratorNames.FaceSign), true);
}
public bool RequiresFaceSign(ShaderStageCapability stageCapability = ShaderStageCapability.Fragment)
{
return true;
}
}
}
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Title("Utility", "Logic", "Is Front Face")]
public class IsFrontFaceNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequireFaceSign
{
public IsFrontFaceNode()
{
name = "Is Front Face";
UpdateNodeAfterDeserialization();
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Is-Front-Face-Node"; }
}
public override bool hasPreview { get { return false; } }
public const int OutputSlotId = 0;
private const string kOutputSlotName = "Out";
public override void UpdateNodeAfterDeserialization()
{
AddSlot(new BooleanMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, true, ShaderStageCapability.Fragment));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
visitor.AddShaderChunk(string.Format("{0} {1} = max(0, IN.{2});", precision, GetVariableNameForSlot(OutputSlotId), ShaderGeneratorNames.FaceSign), true);
}
public bool RequiresFaceSign(ShaderStageCapability stageCapability = ShaderStageCapability.Fragment)
{
return true;
}
}
}

5
com.unity.shadergraph/Editor/Data/Util/PropertyCollector.cs


foreach (var prop in m_Properties.Where(x => x.generatePropertyBlock))
{
for (var i = 0; i < baseIndentLevel; i++)
sb.Append("\t");
{
//sb.Append("\t");
sb.Append(" "); // unity convention use space instead of tab...
}
sb.AppendLine(prop.GetPropertyBlockString());
}
return sb.ToString();

5
com.unity.shadergraph/Editor/Data/Util/ShaderGenerator.cs


{
var line = lines[index];
for (var i = 0; i < shaderChunk.chunkIndentLevel + baseIndentLevel; i++)
sb.Append("\t");
{
//sb.Append("\t");
sb.Append(" "); // unity convention use space instead of tab...
}
sb.AppendLine(line);
appendedNewline = true;

11
CONTRIBUTING


# PR review process
- Any PR must have an entry in the corresponding changelog in a separate commit (CHANGELOG.MD file)
- Changelog follow these guidelines: https://github.com/Unity-Technologies/PostProcessing/blob/v2/CHANGELOG.md
- Each release branch (2018.1, 2018.2...) have a unique Changelog file
- when backporting, don't backport the changelog commit but update the branch changelog manually
- (optional) add reviewver from doc team
- Any more complex description of a change with future need to go in a release note file

21
com.unity.render-pipelines.high-definition/HDRP/Debug/FalseColorDebug.cs


using System.Collections.Generic;
using UnityEngine;
using System;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[Serializable]
public class FalseColorDebugSettings
{
public bool falseColor = false;
public float colorThreshold0 = 0.0f;
public float colorThreshold1 = 2.0f;
public float colorThreshold2 = 10.0f;
public float colorThreshold3 = 20.0f;
public void OnValidate()
{
}
}
}

11
com.unity.render-pipelines.high-definition/HDRP/Debug/FalseColorDebug.cs.meta


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

55
com.unity.render-pipelines.high-definition/HDRP/Material/NormalBuffer.hlsl


#include "CoreRP/ShaderLibrary/Packing.hlsl"
#include "CoreRP/ShaderLibrary/CommonMaterial.hlsl"
// ----------------------------------------------------------------------------
// Encoding/decoding normal buffer functions
// ----------------------------------------------------------------------------
struct NormalData
{
float3 normalWS;
float perceptualRoughness;
};
#define NormalBufferType0 float4 // Must match GBufferType1 in deferred
// SSSBuffer texture declaration
TEXTURE2D(_NormalBufferTexture0);
void EncodeIntoNormalBuffer(NormalData normalData, uint2 positionSS, out NormalBufferType0 outNormalBuffer0)
{
// The sign of the Z component of the normal MUST round-trip through the G-Buffer, otherwise
// the reconstruction of the tangent frame for anisotropic GGX creates a seam along the Z axis.
// The constant was eye-balled to not cause artifacts.
// TODO: find a proper solution. E.g. we could re-shuffle the faces of the octahedron
// s.t. the sign of the Z component round-trips.
const float seamThreshold = 1.0 / 1024.0;
normalData.normalWS.z = CopySign(max(seamThreshold, abs(normalData.normalWS.z)), normalData.normalWS.z);
// RT1 - 8:8:8:8
// Our tangent encoding is based on our normal.
float2 octNormalWS = PackNormalOctQuadEncode(normalData.normalWS);
float3 packNormalWS = PackFloat2To888(saturate(octNormalWS * 0.5 + 0.5));
// We store perceptualRoughness instead of roughness because it is perceptually linear.
outNormalBuffer0 = float4(packNormalWS, normalData.perceptualRoughness);
}
void DecodeFromNormalBuffer(float4 normalBuffer, uint2 positionSS, out NormalData normalData)
{
float3 packNormalWS = normalBuffer.rgb;
float2 octNormalWS = Unpack888ToFloat2(packNormalWS);
normalData.normalWS = UnpackNormalOctQuadEncode(octNormalWS * 2.0 - 1.0);
normalData.perceptualRoughness = normalBuffer.a;
}
void DecodeFromNormalBuffer(uint2 positionSS, out NormalData normalData)
{
float4 normalBuffer = LOAD_TEXTURE2D(_NormalBufferTexture0, positionSS);
DecodeFromNormalBuffer(normalBuffer, positionSS, normalData);
}
// OUTPUT_NORMAL_NORMALBUFFER start from SV_Target0 as it is used during depth prepass where there is no color buffer
#define OUTPUT_NORMALBUFFER(NAME) out NormalBufferType0 MERGE_NAME(NAME, 0) : SV_Target0
#define ENCODE_INTO_NORMALBUFFER(SURFACE_DATA, UNPOSITIONSS, NAME) EncodeIntoNormalBuffer(ConvertSurfaceDataToNormalData(SURFACE_DATA), UNPOSITIONSS, MERGE_NAME(NAME, 0))
#define DECODE_FROM_NORMALBUFFER(UNPOSITIONSS, NORMAL_DATA) DecodeFromNormalBuffer(UNPOSITIONSS, NORMAL_DATA)

9
com.unity.render-pipelines.high-definition/HDRP/Material/NormalBuffer.hlsl.meta


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

81
com.unity.render-pipelines.high-definition/HDRP/Material/NormalBufferManager.cs


using UnityEngine.Rendering;
using System;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class NormalBufferManager
{
// Currently we only support NormalBuffer with one buffer. If the shader code change, it may require to update the shader manager
public const int k_MaxNormalBuffer = 1;
public int normalBufferCount { get { return k_MaxNormalBuffer; } }
RTHandleSystem.RTHandle[] m_ColorMRTs = new RTHandleSystem.RTHandle[k_MaxNormalBuffer];
protected RenderTargetIdentifier[] m_RTIDs = new RenderTargetIdentifier[k_MaxNormalBuffer];
bool[] m_ExternalBuffer = new bool[k_MaxNormalBuffer];
RTHandleSystem.RTHandle m_HTile;
public NormalBufferManager()
{
}
public void InitNormalBuffers(GBufferManager gbufferManager, RenderPipelineSettings settings)
{
if (settings.supportOnlyForward)
{
// In case of full forward we must allocate the render target for normal buffer (or reuse one already existing)
// TODO: Provide a way to reuse a render target
m_ColorMRTs[0] = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGB32, sRGB: false, name: "NormalBuffer");
m_ExternalBuffer[0] = false;
}
else
{
// In case of deferred, we must be in sync with NormalBuffer.hlsl and lit.hlsl files and setup the correct buffers
m_ColorMRTs[0] = gbufferManager.GetBuffer(1); // Normal + Roughness is GBuffer(1)
m_ExternalBuffer[0] = true;
}
}
public RenderTargetIdentifier[] GetBuffersRTI()
{
// nameID can change from one frame to another depending on the msaa flag so so we need to update this array to be sure it's up to date.
for (int i = 0; i < normalBufferCount; ++i)
{
m_RTIDs[i] = m_ColorMRTs[i].nameID;
}
return m_RTIDs;
}
public RTHandleSystem.RTHandle GetNormalBuffer(int index)
{
Debug.Assert(index < normalBufferCount);
return m_ColorMRTs[index];
}
public void Build(HDRenderPipelineAsset hdAsset)
{
}
public void Cleanup()
{
for (int i = 0; i < k_MaxNormalBuffer; ++i)
{
if (!m_ExternalBuffer[i])
{
RTHandles.Release(m_ColorMRTs[i]);
}
}
}
public void BindNormalBuffers(CommandBuffer cmd)
{
// NormalBuffer can be access in forward shader, so need to set global texture
for (int i = 0; i < normalBufferCount; ++i)
{
cmd.SetGlobalTexture(HDShaderIDs._NormalBufferTexture[i], GetNormalBuffer(i));
}
}
}
}

11
com.unity.render-pipelines.high-definition/HDRP/Material/NormalBufferManager.cs.meta


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

9
issue_template.md


##### What happened?
##### Which package (Shader graph, LW, HDRP, Core...)?
##### Unity template or github source code?
##### Which package version or branch (1.1.8-preview, 2.0.0-preview, 2018.1, 2018.1-experiment, 2108.2...)?
##### Unity version, operating system, target platform (standalone windows, mac, iOS, PS4...)?
正在加载...
取消
保存