Nerites 6 年前
当前提交
4c6e512a
共有 137 个文件被更改,包括 2480 次插入1110 次删除
  1. 2
      com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugWindow.cs
  2. 8
      com.unity.render-pipelines.core/CoreRP/Shadow/AdditionalShadowData.cs
  3. 21
      com.unity.render-pipelines.high-definition/CHANGELOG.md
  4. 38
      com.unity.render-pipelines.high-definition/HDRP/Camera/HDAdditionalCameraData.cs
  5. 4
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.cs
  6. 35
      com.unity.render-pipelines.high-definition/HDRP/Editor/Camera/HDCameraEditor.cs
  7. 30
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.cs
  8. 11
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/EditorReflectionSystem.cs
  9. 6
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/EditorReflectionSystemGUI.cs
  10. 196
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Handles.cs
  11. 21
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.ProbeUtility.cs
  12. 14
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs
  13. 55
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditorUtility.cs
  14. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.Drawers.cs
  15. 4
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs
  16. 5
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs
  17. 162
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalUI.cs
  18. 1
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/GlobalDecalSettingsUI.cs
  19. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedGlobalDecalSettings.cs
  20. 4
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDPBRPass.template
  21. 4
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDUnlitPassForward.template
  22. 6
      com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/HDRPVersion.cs
  23. 35
      com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/UpgradeMenuItem.cs
  24. 27
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Light/HDAdditionalLightData.cs
  25. 63
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoopDef.hlsl
  26. 4
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoopSettings.cs
  27. 8
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/cleardispatchindirect.compute
  28. 23
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/HDAdditionalReflectionData.cs
  29. 22
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/PlanarReflectionProbe.cs
  30. 2
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/PlanarReflectionProbe.cs.meta
  31. 2
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/Volumes/ReflectionProxyVolumeComponent.cs.meta
  32. 22
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DBufferManager.cs
  33. 23
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs
  34. 42
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs.hlsl
  35. 134
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.hlsl
  36. 422
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.shader
  37. 42
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalData.hlsl
  38. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProjectorComponent.cs
  39. 32
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalSystem.cs
  40. 103
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalUtilities.hlsl
  41. 1
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/GlobalDecalSettings.cs
  42. 3
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLit.shader
  43. 3
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitTessellation.shader
  44. 11
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.cs
  45. 3
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.shader
  46. 3
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitTessellation.shader
  47. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Material.hlsl
  48. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/PreIntegratedFGD/PreIntegratedFGD.cs
  49. 11
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.cs
  50. 6
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.shader
  51. 20
      com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl
  52. 35
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipeline.cs
  53. 20
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDStringConstants.cs
  54. 10
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/Settings/FrameSettings.cs
  55. 81
      com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset
  56. 94
      com.unity.render-pipelines.high-definition/HDRP/ShaderVariables.hlsl
  57. 10
      com.unity.render-pipelines.high-definition/HDRP/ShaderVariablesFunctions.hlsl
  58. 3
      com.unity.render-pipelines.high-definition/HDRP/ShaderVariablesMatrixDefsHDCamera.hlsl
  59. 2
      com.unity.render-pipelines.high-definition/HDRP/ShaderVariablesMatrixDefsLegacyUnity.hlsl
  60. 183
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/LightWeightPBRSubShader.cs
  61. 183
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/LightWeightUnlitSubShader.cs
  62. 44
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightPBRExtraPasses.template
  63. 44
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/lightweightUnlitExtraPasses.template
  64. 28
      com.unity.shadergraph/CHANGELOG.md
  65. 2
      com.unity.shadergraph/Editor/Data/Graphs/TextureShaderProperty.cs
  66. 13
      com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromTextureNode.cs
  67. 10
      com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DArrayNode.cs
  68. 2
      com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture3DNode.cs
  69. 12
      com.unity.shadergraph/Editor/Data/Util/ShaderGenerator.cs
  70. 2
      com.unity.shadergraph/Editor/Drawing/Views/Slots/TextureSlotControlView.cs
  71. 2
      com.unity.shadergraph/Editor/Importers/ShaderGraphImporter.cs
  72. 6
      com.unity.render-pipelines.high-definition/HDRP/Lighting/AtmosphericScattering/OpaqueAtmosphericScattering.shader
  73. 2
      com.unity.render-pipelines.high-definition/HDRP/Lighting/AtmosphericScattering/AtmosphericScattering.cs.meta
  74. 8
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Icons.meta
  75. 188
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Gizmos.cs
  76. 11
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Gizmos.cs.meta
  77. 39
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Skin.cs
  78. 11
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Skin.cs.meta
  79. 8
      com.unity.render-pipelines.high-definition/HDRP/Lighting/AtmosphericScattering.meta
  80. 68
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl
  81. 9
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl.meta
  82. 8
      com.unity.render-pipelines.high-definition/HDRP/Lighting/ScreenSpaceLighting.meta
  83. 5
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/ShaderVariablesDecal.hlsl
  84. 9
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/ShaderVariablesDecal.hlsl.meta
  85. 18
      com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl
  86. 9
      com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl.meta
  87. 3
      com.unity.shadergraph/.data/normal_derive_nodes.PNG
  88. 3
      com.unity.shadergraph/.data/texel_size_node.PNG
  89. 436
      com.unity.shadergraph/.data/wave_form_nodes.PNG
  90. 131
      com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromHeightNode.cs
  91. 11
      com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromHeightNode.cs.meta
  92. 39
      com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalReconstructZNode.cs
  93. 11
      com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalReconstructZNode.cs.meta
  94. 52
      com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/TexelSizeNode.cs
  95. 11
      com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/TexelSizeNode.cs.meta
  96. 8
      com.unity.shadergraph/Editor/Data/Nodes/Math/Wave.meta

2
com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugWindow.cs


s_TypeMapDirty = false;
}
[MenuItem("Window/General/Render Pipeline Debug", priority = 112)] // 112 is hardcoded number given by the UxTeam to fit correctly in the Windows menu
[MenuItem("Window/Analysis/Render Pipeline Debug", priority = 112)] // 112 is hardcoded number given by the UxTeam to fit correctly in the Windows menu
static void Init()
{
var window = GetWindow<DebugWindow>();

8
com.unity.render-pipelines.core/CoreRP/Shadow/AdditionalShadowData.cs


[RequireComponent(typeof(Light))]
public class AdditionalShadowData : MonoBehaviour
{
[HideInInspector]
public float version = 1.0f;
// Currently m_Version is not used and produce a warning, remove these pragmas at the next version incrementation
#pragma warning disable 414
[SerializeField]
[UnityEngine.Serialization.FormerlySerializedAs("version")]
private int m_Version = 1;
#pragma warning restore 414
public const int DefaultShadowResolution = 512;

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


The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [unreleased]
### Added
- Decal now support per channel selection mask. There is now two mode. One with BaseColor, Normal and Smoothness and another one more expensive with BaseColor, Normal, Smoothness, Metal and AO. Control is on HDRP Asset. This may require to launch an update script for old scene: 'Edit/Render Pipeline/Single step upgrade script/Upgrade all DecalMaterial MaskBlendMode'.
### Fixed
- Fixed an issue with PreIntegratedFGD texture being sometimes destroyed and not regenerated causing rendering to break
- PostProcess input buffers are not copied anymore on PC if the viewport size matches the final render target size
- Fixed an issue when manipulating a lot of decals, it was displaying a lot of errors in the inspector
- Fixed capture material with reflection probe
- Refactored Constant Buffers to avoid hitting the maximum number of bound CBs in some cases.
- Fixed the light range affecting the transform scale when changed.
### Changed
- Movde Render Pipeline Debug "Windows from Windows->General-> Render Pipeline debug windows" to "Windows from Windows->Analysis-> Render Pipeline debug windows"
### Added
- Added support for RendererPriority on Renderer. This allow to control order of transparent rendering manually. HDRP have now two stage of sorting for transparent in addition to bact to front. Material have a priority then Renderer have a priority.
- Add Coupling of (HD)Camera and HDAdditionalCameraData for reset and remove in inspector contextual menu of Camera
- Add macro to forbid unity_ObjectToWorld/unity_WorldToObject to be use as it doesn't handle camera relative rendering
## [3.0.0-preview]

38
com.unity.render-pipelines.high-definition/HDRP/Camera/HDAdditionalCameraData.cs


using UnityEngine.Serialization;
using UnityEngine.Assertions;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

{
[HideInInspector]
public float version = 1.0f;
const int currentVersion = 1;
[SerializeField, FormerlySerializedAs("version")]
int m_Version;
// The light culling use standard projection matrices (non-oblique)
// If the user overrides the projection matrix with an oblique one

public Color backgroundColorHDR = new Color(0.025f, 0.07f, 0.19f, 0.0f);
public bool clearDepth = true;
public RenderingPath renderingPath;
public RenderingPath renderingPath = RenderingPath.Default;
[Tooltip("Layer Mask used for the volume interpolation for this camera.")]
public LayerMask volumeLayerMask = -1;

bool m_IsDebugRegistered = false;
string m_CameraRegisterName;
// When we are a preview, there is no way inside Unity to make a disctinctoin between camera preview and material preview.
// When we are a preview, there is no way inside Unity to make a distinction between camera preview and material preview.
// This is use to copy data into camera for the Reset() workflow in camera editor
public void CopyTo(HDAdditionalCameraData data)
{
data.clearColorMode = clearColorMode;
data.backgroundColorHDR = backgroundColorHDR;
data.clearDepth = clearDepth;
data.renderingPath = renderingPath;
data.volumeLayerMask = volumeLayerMask;
data.aperture = aperture;
data.shutterSpeed = shutterSpeed;
data.iso = iso;
m_FrameSettings.CopyTo(data.m_FrameSettings);
m_FrameSettingsRuntime.CopyTo(data.m_FrameSettingsRuntime);
data.m_frameSettingsIsDirty = true; // Let's be sure it is dirty for update
// We must not copy the following
//data.m_IsDebugRegistered = m_IsDebugRegistered;
//data.m_CameraRegisterName = m_CameraRegisterName;
//data.isEditorCameraPreview = isEditorCameraPreview;
}
// This is the function use outside to access FrameSettings. It return the current state of FrameSettings for the camera
// taking into account the customization via the debug menu

// When FrameSettings are manipulated or RenderPath change we reset them to reflect the change, discarding all the Debug Windows change.
// Tag as dirty so frameSettings are correctly initialize at next HDRenderPipeline.Render() call
m_frameSettingsIsDirty = true;
if(m_Version != currentVersion)
{
// Add here data migration code
m_Version = currentVersion;
}
}
// This is called at the creation of the HD Additional Camera Data, to convert the legacy camera settings to HD

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


{
m_DebugDisplayStatsItems = new DebugUI.Widget[]
{
new DebugUI.Value { displayName = "Frame Rate", getter = () => 1f / Time.smoothDeltaTime, refreshRate = 1f / 30f },
new DebugUI.Value { displayName = "Frame Rate (ms)", getter = () => Time.smoothDeltaTime * 1000f, refreshRate = 1f / 30f }
new DebugUI.Value { displayName = "Frame Rate (fps)", getter = () => 1f / Time.smoothDeltaTime, refreshRate = 1f / 30f },
new DebugUI.Value { displayName = "Frame Time (ms)", getter = () => Time.smoothDeltaTime * 1000f, refreshRate = 1f / 30f }
};
var panel = DebugManager.instance.GetPanel(k_PanelDisplayStats, true);

35
com.unity.render-pipelines.high-definition/HDRP/Editor/Camera/HDCameraEditor.cs


[CanEditMultipleObjects]
partial class HDCameraEditor : Editor
{
[MenuItem("CONTEXT/Camera/Remove HD Camera", false, 0)]
static void RemoveLight(MenuCommand menuCommand)
[MenuItem("CONTEXT/Camera/Remove Component", false, 0)]
static void RemoveCamera(MenuCommand menuCommand)
Camera camera = go.GetComponent<Camera>();
HDAdditionalCameraData cameraAdditionalData = go.GetComponent<HDAdditionalCameraData>();
Assert.IsNotNull(camera);
Assert.IsNotNull(cameraAdditionalData);
Undo.DestroyObjectImmediate(go.GetComponent<Camera>());
Undo.DestroyObjectImmediate(go.GetComponent<HDAdditionalCameraData>());
Undo.DestroyObjectImmediate(camera);
Undo.DestroyObjectImmediate(cameraAdditionalData);
}
[MenuItem("CONTEXT/Camera/Reset", false, 0)]
static void ResetCamera(MenuCommand menuCommand)
{
GameObject go = ((Camera)menuCommand.context).gameObject;
Assert.IsNotNull(go);
Camera camera = go.GetComponent<Camera>();
HDAdditionalCameraData cameraAdditionalData = go.GetComponent<HDAdditionalCameraData>();
Assert.IsNotNull(camera);
Assert.IsNotNull(cameraAdditionalData);
Undo.SetCurrentGroupName("Reset HD Camera");
Undo.RecordObjects(new UnityEngine.Object[] { camera, cameraAdditionalData }, "Reset HD Camera");
camera.Reset();
// To avoid duplicating init code we copy default settings to Reset additional data
// Note: we can't call this code inside the HDAdditionalCameraData, thus why we don't wrap it in a Reset() function
HDUtils.s_DefaultHDAdditionalCameraData.CopyTo(cameraAdditionalData);
}
SerializedHDCamera m_SerializedCamera;

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


if (hdLightData != null)
hdLightData.UpdateAreaLightEmissiveMesh();
};
// If the light is disabled in the editor we force the light upgrade from his inspector
foreach (var additionalLightData in m_AdditionalLightDatas)
additionalLightData.UpgradeLight();
}
public override void OnInspectorGUI()

if (m_UpdateAreaLightEmissiveMeshComponents)
UpdateAreaLightEmissiveMeshComponents();
// If the light is disabled in the editor we force the light upgrade from his inspector
foreach (var additionalLightData in m_AdditionalLightDatas)
additionalLightData.UpgradeLight();
}
void DrawFoldout(SerializedProperty foldoutProperty, string title, Action func)

if (EditorGUI.EndChangeCheck())
{
UpdateLightScale();
m_UpdateAreaLightEmissiveMeshComponents = true;
((Light)target).SetLightDirty(); // Should be apply only to parameter that's affect GI, but make the code cleaner
}

m_AdditionalLightData.lightUnit.enumValueIndex = (int)DirectionalLightUnit.Lux;
else
m_AdditionalLightData.lightUnit.enumValueIndex = (int)LightUnit.Lumen;
}
// Refect light size changes on transform local scale
void UpdateLightScale()
{
foreach (var hdLightData in m_AdditionalLightDatas)
{
switch (m_LightShape)
{
case LightShape.Line:
hdLightData.transform.localScale = new Vector3(m_AdditionalLightData.shapeWidth.floatValue, 0, 0);
break;
case LightShape.Rectangle:
hdLightData.transform.localScale = new Vector3(m_AdditionalLightData.shapeWidth.floatValue, m_AdditionalLightData.shapeHeight.floatValue, 0);
break;
case LightShape.Point:
case LightShape.Spot:
hdLightData.transform.localScale = Vector3.one * settings.range.floatValue;
break;
}
}
}
LightUnit LightIntensityUnitPopup(LightShape shape)

11
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/EditorReflectionSystem.cs


{
public static class EditorReflectionSystem
{
static int _Cubemap = Shader.PropertyToID("_Cubemap");
const HideFlags k_ReflectionSystemDictionaryHideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector | HideFlags.DontSaveInBuild;
public static bool IsCollidingWithOtherProbes(string targetPath, ReflectionProbe targetProbe, out ReflectionProbe collidingProbe)

if (!UnityEditor.Lightmapping.BakeReflectionProbe(probe, path))
Debug.LogError("Failed to bake reflection probe to " + path);
EditorUtility.ClearProgressBar();
}
public static void ResetProbeSceneTextureInMaterial(ReflectionProbe p)
{
var renderer = p.GetComponent<Renderer>();
renderer.sharedMaterial.SetTexture(_Cubemap, p.texture);
}
public static void ResetProbeSceneTextureInMaterial(PlanarReflectionProbe p)
{
}
static MethodInfo k_Lightmapping_BakeReflectionProbeSnapshot = typeof(UnityEditor.Lightmapping).GetMethod("BakeReflectionProbeSnapshot", BindingFlags.Static | BindingFlags.NonPublic);

6
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/EditorReflectionSystemGUI.cs


if (probe != null)
{
EditorReflectionSystem.BakeCustomReflectionProbe(probe, false);
EditorReflectionSystem.ResetProbeSceneTextureInMaterial(probe);
EditorReflectionSystem.ResetProbeSceneTextureInMaterial(planarProbe);
}
}
},

{
EditorReflectionSystem.BakeCustomReflectionProbe(probe, true);
EditorReflectionSystem.ResetProbeSceneTextureInMaterial(probe);
EditorReflectionSystem.ResetProbeSceneTextureInMaterial(planarProbe);
}
GUIUtility.ExitGUI();
}

if (probe != null)
{
EditorReflectionSystem.BakeReflectionProbeSnapshot(probe);
EditorReflectionSystem.ResetProbeSceneTextureInMaterial(probe);
EditorReflectionSystem.ResetProbeSceneTextureInMaterial(planarProbe);
}
GUIUtility.ExitGUI();
}

196
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Handles.cs


Normal
}
internal static Color k_GizmoThemeColorExtent = new Color(255f / 255f, 229f / 255f, 148f / 255f, 80f / 255f);
internal static Color k_GizmoThemeColorExtentFace = new Color(255f / 255f, 229f / 255f, 148f / 255f, 45f / 255f);
internal static Color k_GizmoThemeColorInfluenceBlend = new Color(83f / 255f, 255f / 255f, 95f / 255f, 75f / 255f);
internal static Color k_GizmoThemeColorInfluenceBlendFace = new Color(83f / 255f, 255f / 255f, 95f / 255f, 17f / 255f);
internal static Color k_GizmoThemeColorInfluenceNormalBlend = new Color(0f / 255f, 229f / 255f, 255f / 255f, 80f / 255f);
internal static Color k_GizmoThemeColorInfluenceNormalBlendFace = new Color(0f / 255f, 229f / 255f, 255f / 255f, 36f / 255f);
internal static Color k_GizmoThemeColorProjection = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static Color k_GizmoThemeColorProjectionFace = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static Color k_GizmoThemeColorDisabled = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static Color k_GizmoThemeColorDisabledFace = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static readonly Color[][] k_handlesColor = new Color[][]
{
new Color[]
{
Color.red,
Color.green,
Color.blue
},
new Color[]
{
new Color(.5f, 0f, 0f, 1f),
new Color(0f, .5f, 0f, 1f),
new Color(0f, 0f, .5f, 1f)
}
};
void OnSceneGUI()
{
var s = m_UIState;

EditorUtility.SetDirty(p);
s.UpdateOldLocalSpace(p);
}
}
[DrawGizmo(GizmoType.Active)]
static void RenderGizmo(ReflectionProbe reflectionProbe, GizmoType gizmoType)
{
var e = GetEditorFor(reflectionProbe);
if (e == null || !e.sceneViewEditing)
return;
var reflectionData = reflectionProbe.GetComponent<HDAdditionalReflectionData>();
switch (EditMode.editMode)
{
// Influence editing
case EditMode.SceneViewEditMode.ReflectionProbeBox:
Gizmos_Influence(reflectionProbe, reflectionData, e, true);
break;
// Influence fade editing
case EditMode.SceneViewEditMode.GridBox:
Gizmos_InfluenceFade(reflectionProbe, reflectionData, e, InfluenceType.Standard, true);
break;
// Influence normal fade editing
case EditMode.SceneViewEditMode.Collider:
Gizmos_InfluenceFade(reflectionProbe, reflectionData, e, InfluenceType.Normal, true);
break;
}
}
[DrawGizmo(GizmoType.Selected)]
static void DrawSelectedGizmo(ReflectionProbe reflectionProbe, GizmoType gizmoType)
{
var e = GetEditorFor(reflectionProbe);
if (e == null || !e.sceneViewEditing)
return;
var reflectionData = reflectionProbe.GetComponent<HDAdditionalReflectionData>();
//Gizmos_Influence(reflectionProbe, reflectionData, e, false);
Gizmos_InfluenceFade(reflectionProbe, reflectionData, null, InfluenceType.Standard, false);
Gizmos_InfluenceFade(reflectionProbe, reflectionData, null, InfluenceType.Normal, false);
DrawVerticalRay(reflectionProbe.transform);
HDReflectionProbeEditorUtility.ChangeVisibility(reflectionProbe, true);
}
[DrawGizmo(GizmoType.NonSelected)]
static void DrawNonSelectedGizmo(ReflectionProbe reflectionProbe, GizmoType gizmoType)
{
var e = GetEditorFor(reflectionProbe);
if (e == null || !e.sceneViewEditing)
return;
var reflectionData = reflectionProbe.GetComponent<HDAdditionalReflectionData>();
if (reflectionData != null)
HDReflectionProbeEditorUtility.ChangeVisibility(reflectionProbe, false);
}
static void Gizmos_InfluenceFade(ReflectionProbe p, HDAdditionalReflectionData a, HDReflectionProbeEditor e, InfluenceType type, bool isEdit)
{
var col = Gizmos.color;
var mat = Gizmos.matrix;
Gizmo6FacesBoxContained box;
Vector3 boxCenterOffset;
Vector3 boxSizeOffset;
float sphereRadiusOffset;
Color color;
switch (type)
{
default:
case InfluenceType.Standard:
{
box = e != null ? e.m_UIState.alternativeBoxBlendHandle : null;
boxCenterOffset = a.boxBlendCenterOffset;
boxSizeOffset = a.boxBlendSizeOffset;
sphereRadiusOffset = a.sphereBlendRadiusOffset;
color = isEdit ? k_GizmoThemeColorInfluenceBlendFace : k_GizmoThemeColorInfluenceBlend;
break;
}
case InfluenceType.Normal:
{
box = e != null ? e.m_UIState.alternativeBoxBlendNormalHandle : null;
boxCenterOffset = a.boxBlendNormalCenterOffset;
boxSizeOffset = a.boxBlendNormalSizeOffset;
sphereRadiusOffset = a.sphereBlendNormalRadiusOffset;
color = isEdit ? k_GizmoThemeColorInfluenceNormalBlendFace : k_GizmoThemeColorInfluenceNormalBlend;
break;
}
}
Gizmos.matrix = HDReflectionProbeEditorUtility.GetLocalSpace(p);
switch (a.influenceShape)
{
case ShapeType.Box:
{
Gizmos.color = color;
if(e != null) // e == null may occure when editor have still not been created at selection while the tool is not used for this part
{
box.DrawHull(isEdit);
}
else
{
if (isEdit)
Gizmos.DrawCube(p.center + boxCenterOffset, p.size + boxSizeOffset);
else
Gizmos.DrawWireCube(p.center + boxCenterOffset, p.size + boxSizeOffset);
}
break;
}
case ShapeType.Sphere:
{
Gizmos.color = color;
if (isEdit)
Gizmos.DrawSphere(p.center, a.influenceSphereRadius + sphereRadiusOffset);
else
Gizmos.DrawWireSphere(p.center, a.influenceSphereRadius + sphereRadiusOffset);
break;
}
}
Gizmos.matrix = mat;
Gizmos.color = col;
}
static void Gizmos_Influence(ReflectionProbe p, HDAdditionalReflectionData a, HDReflectionProbeEditor e, bool isEdit)
{
var col = Gizmos.color;
var mat = Gizmos.matrix;
Gizmos.matrix = HDReflectionProbeEditorUtility.GetLocalSpace(p);
switch (a.influenceShape)
{
case ShapeType.Box:
{
Gizmos.color = k_GizmoThemeColorExtentFace;
e.m_UIState.alternativeBoxInfluenceHandle.DrawHull(isEdit);
break;
}
case ShapeType.Sphere:
{
Gizmos.color = k_GizmoThemeColorExtentFace;
if (isEdit)
Gizmos.DrawSphere(p.center, a.influenceSphereRadius);
else
Gizmos.DrawWireSphere(p.center, a.influenceSphereRadius);
break;
}
}
Gizmos.matrix = mat;
Gizmos.color = col;
}
static void DrawVerticalRay(Transform transform)
{
Ray ray = new Ray(transform.position, Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Handles.color = Color.green;
Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual;
Handles.DrawLine(transform.position - Vector3.up * 0.5f, hit.point);
Handles.DrawWireDisc(hit.point, hit.normal, 0.5f);
Handles.color = Color.red;
Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater;
Handles.DrawLine(transform.position, hit.point);
Handles.DrawWireDisc(hit.point, hit.normal, 0.5f);
}
}
}

21
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.ProbeUtility.cs


{
partial class HDReflectionProbeEditor
{
void ChangeVisibilityOfAllTargets(bool visibility)
{
if (targets.Length == 0) return;
for (var i = 0; i < targets.Length; ++i)
{
if (targets[i] != null)
{
var p = (ReflectionProbe)targets[i];
HDReflectionProbeEditorUtility.ChangeVisibility(p, visibility);
}
}
}
for (var i = 0; i < targets.Length; ++i)
{
var p = (ReflectionProbe)targets[i];
var a = (HDAdditionalReflectionData)m_AdditionalDataSerializedObject.targetObjects[i];
HDReflectionProbeEditorUtility.InitializeProbe(p, a);
}
// For an unknown reason, newly created probes sometype have the type "Quad" (value = 1)
// This type of probe is not supported by Unity since 5.4
// But we need to force it here so it does not bake into a 2D texture but a Cubemap

14
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs


Undo.SetCurrentGroupName("Remove HD Reflection Probe");
Undo.DestroyObjectImmediate(go.GetComponent<ReflectionProbe>());
Undo.DestroyObjectImmediate(go.GetComponent<HDAdditionalReflectionData>());
Undo.DestroyObjectImmediate(go.GetComponent<MeshRenderer>());
Undo.DestroyObjectImmediate(go.GetComponent<MeshFilter>());
}
static Dictionary<ReflectionProbe, HDReflectionProbeEditor> s_ReflectionProbeEditors = new Dictionary<ReflectionProbe, HDReflectionProbeEditor>();

}
InitializeAllTargetProbes();
ChangeVisibilityOfAllTargets(true);
void OnDisable()
{
ChangeVisibilityOfAllTargets(false);
}
public override void OnInspectorGUI()
{

var flags = visible ? HideFlags.None : HideFlags.HideInInspector;
for (var i = 0; i < targets.Length; ++i)
{
var target = targets[i];
var p = (ReflectionProbe)target;
var meshRenderer = p.GetComponent<MeshRenderer>();
var meshFilter = p.GetComponent<MeshFilter>();
meshRenderer.hideFlags = flags;
meshFilter.hideFlags = flags;
}
}

55
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditorUtility.cs


{
public static class HDReflectionProbeEditorUtility
{
static int _Cubemap = Shader.PropertyToID("_Cubemap");
static Material s_PreviewMaterial;
static Mesh s_SphereMesh;
[InitializeOnLoadMethod]
static void Initialize()
{
s_SphereMesh = Resources.GetBuiltinResource(typeof(Mesh), "New-Sphere.fbx") as Mesh;
}
public static Matrix4x4 GetLocalSpace(ReflectionProbe probe)
{
var t = probe.transform.position;

return true;
}
public static void ResetProbeSceneTextureInMaterial(ReflectionProbe p)
{
var renderer = p.GetComponent<Renderer>();
renderer.sharedMaterial.SetTexture(_Cubemap, p.texture);
}
public static float CalculateSphereMaxBlendDistance(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor o)
{
return p.influenceSphereRadius.floatValue;

{
return p.boxSize.vector3Value * 0.5f;
}
internal static void InitializeProbe(ReflectionProbe p, HDAdditionalReflectionData data)
{
var meshFilter = p.GetComponent<MeshFilter>() ?? p.gameObject.AddComponent<MeshFilter>();
var meshRenderer = p.GetComponent<MeshRenderer>() ?? p.gameObject.AddComponent<MeshRenderer>();
meshFilter.sharedMesh = s_SphereMesh;
// Lazy evaluation attempt to avoid shader compil error issue in Editor (The shader is not found the first time
// we load after deleting Library folder)
if (s_PreviewMaterial == null)
{
s_PreviewMaterial = new Material(Shader.Find("Debug/ReflectionProbePreview"))
{
hideFlags = HideFlags.HideAndDontSave
};
}
var material = meshRenderer.sharedMaterial;
if (material == null
|| material == s_PreviewMaterial
|| material.shader != s_PreviewMaterial.shader)
{
material = Object.Instantiate(s_PreviewMaterial);
material.SetTexture(_Cubemap, p.texture);
material.hideFlags = HideFlags.HideAndDontSave;
meshRenderer.material = material;
}
meshRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
meshRenderer.motionVectorGenerationMode = MotionVectorGenerationMode.ForceNoMotion;
}
internal static void ChangeVisibility(ReflectionProbe p, bool visible)
{
var meshRenderer = p.GetComponent<MeshRenderer>() ?? p.gameObject.AddComponent<MeshRenderer>();
meshRenderer.enabled = visible;
}
}
}

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.Drawers.cs


if (EditorGUI.EndChangeCheck())
{
s.SetModeTarget(p.mode.intValue);
foreach (var targetObject in p.so.targetObjects)
HDReflectionProbeEditorUtility.ResetProbeSceneTextureInMaterial((ReflectionProbe)targetObject);
}
}

4
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs


var maxFaceDistance = d.sphereBaseRadius.floatValue;
EditorGUILayout.PropertyField(d.sphereBaseRadius, _.GetContent("Radius"));
//EditorGUILayout.PropertyField(d.sphereBaseOffset, _.GetContent("Offset"));
EditorGUILayout.Slider(d.sphereInfluenceFade, 0, maxFaceDistance, _.GetContent("Influence Fade"));
EditorGUILayout.Slider(d.sphereInfluenceNormalFade, 0, maxFaceDistance, _.GetContent("Influence Normal Fade"));
EditorGUILayout.Slider(d.sphereInfluenceFade, 0, maxFaceDistance, _.GetContent("Blend Distance"));
}
}
}

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


m_DecalProjectorComponent.OnMaterialChange -= OnMaterialChange;
}
private void OnDestroy()
{
DestroyImmediate(m_MaterialEditor);
}
public void OnMaterialChange()
{
// Update material editor with the new material

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


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

{
public static string InputsText = "Inputs";
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 baseColorText = new GUIContent("BaseColor (RGB) and Opacity (A)", "BaseColor (RGB) and Opacity (A)");
public static GUIContent baseColorText2 = new GUIContent("Opacity(A)", "Opacity (A)");
public static GUIContent maskMapText = new GUIContent("Mask Map - M(R), AO(G), D(B), S(A)", "Mask map");
public static GUIContent decalBlendText = new GUIContent("Decal Blend", "Whole decal blend");
public static GUIContent BlendText = new GUIContent("Decal Blend", "Whole decal blend");
public static GUIContent AlbedoModeText = new GUIContent("Albedo contribution", "Base color + Blend, Blend only");
public static GUIContent decalBlendText = new GUIContent("Global Opacity", "Whole decal Opacity");
public static GUIContent AlbedoModeText = new GUIContent("Affect BaseColor", "Base color + Opacity, Opacity only");
public static GUIContent[] maskMapText =
{
new GUIContent("Error", "Mask map"), // Not possible
new GUIContent("Mask Map - M(R), Opacity(B)", "Mask map - Metal(R), Opacity(B)"), // Decal.MaskBlendFlags.Metal:
new GUIContent("Mask Map - AO(G), Opacity(B)", "Mask map - Ambient Occlusion(G), Opacity(B)"), // Decal.MaskBlendFlags.AO:
new GUIContent("Mask Map - M(R), AO(G), Opacity(B)", "Mask map - Metal(R), Ambient Occlusion(G), Opacity(B)"), // Decal.MaskBlendFlags.Metal | Decal.MaskBlendFlags.AO:
new GUIContent("Mask Map - Opacity(B), S(A)", "Mask map - Opacity(B), Smoothness(A)"), // Decal.MaskBlendFlags.Smoothness:
new GUIContent("Mask Map - M(R), Opacity(B), S(A)", "Mask map - Metal(R), Opacity(B), Smoothness(A)"), // Decal.MaskBlendFlags.Metal | Decal.MaskBlendFlags.Smoothness:
new GUIContent("Mask Map - AO(G), Opacity(B), S(A)", "Mask map - Ambient Occlusion(G), Opacity(B), Smoothness(A)"), // Decal.MaskBlendFlags.AO | Decal.MaskBlendFlags.Smoothness:
new GUIContent("Mask Map - M(R), AO(G), Opacity(B), S(A)", "Mask map - Metal(R), Ambient Occlusion(G), Opacity(B), Smoothness(A)") // Decal.MaskBlendFlags.Metal | Decal.MaskBlendFlags.AO | Decal.MaskBlendFlags.Smoothness:
};
}
enum BlendSource
{
BaseColorMapAlpha,
MaskMapBlue
protected string[] blendSourceNames = Enum.GetNames(typeof(BlendSource));
protected string[] blendModeNames = Enum.GetNames(typeof(BlendMode));
protected MaterialProperty baseColorMap = new MaterialProperty();
protected const string kBaseColorMap = "_BaseColorMap";

protected MaterialProperty albedoMode = new MaterialProperty();
protected const string kAlbedoMode = "_AlbedoMode";
protected MaterialProperty normalBlendSrc = new MaterialProperty();
protected const string kNormalBlendSrc = "_NormalBlendSrc";
protected MaterialProperty maskBlendSrc = new MaterialProperty();
protected const string kMaskBlendSrc = "_MaskBlendSrc";
protected MaterialProperty maskBlendMode = new MaterialProperty();
protected const string kMaskBlendMode = "_MaskBlendMode";
protected MaterialProperty maskmapMetal = new MaterialProperty();
protected const string kMaskmapMetal = "_MaskmapMetal";
protected MaterialProperty maskmapAO = new MaterialProperty();
protected const string kMaskmapAO = "_MaskmapAO";
protected MaterialProperty maskmapSmoothness = new MaterialProperty();
protected const string kMaskmapSmoothness = "_MaskmapSmoothness";
protected MaterialEditor m_MaterialEditor;

maskMap = FindProperty(kMaskMap, props);
decalBlend = FindProperty(kDecalBlend, props);
albedoMode = FindProperty(kAlbedoMode, props);
normalBlendSrc = FindProperty(kNormalBlendSrc, props);
maskBlendSrc = FindProperty(kMaskBlendSrc, props);
maskBlendMode = FindProperty(kMaskBlendMode, props);
maskmapMetal = FindProperty(kMaskmapMetal, props);
maskmapAO = FindProperty(kMaskmapAO, props);
maskmapSmoothness = FindProperty(kMaskmapSmoothness, props);
// always instanced
SerializedProperty instancing = m_MaterialEditor.serializedObject.FindProperty("m_EnableInstancingVariants");
instancing.boolValue = true;

static public void SetupMaterialKeywordsAndPass(Material material)
{
Decal.MaskBlendFlags blendMode = (Decal.MaskBlendFlags)material.GetFloat(kMaskBlendMode);
CoreUtils.SetKeyword(material, "_MASKMAP", material.GetTexture(kMaskMap));
CoreUtils.SetKeyword(material, "_MASKMAP", material.GetTexture(kMaskMap));
CoreUtils.SetKeyword(material, "_NORMAL_BLEND_SRC_B", material.GetFloat(kNormalBlendSrc) == 1.0f);
CoreUtils.SetKeyword(material, "_MASK_BLEND_SRC_B", material.GetFloat(kMaskBlendSrc) == 1.0f);
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsMStr, false);
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsAOStr, false);
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsMAOStr, false);
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsSStr, false);
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsMSStr, false);
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsAOSStr, false);
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsMAOSStr, false);
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecals3RTStr, true);
switch (blendMode)
{
case Decal.MaskBlendFlags.Metal:
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsMStr, true);
break;
case Decal.MaskBlendFlags.AO:
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsAOStr, true);
break;
case Decal.MaskBlendFlags.Metal | Decal.MaskBlendFlags.AO:
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsMAOStr, true);
break;
case Decal.MaskBlendFlags.Smoothness:
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsSStr, true);
break;
case Decal.MaskBlendFlags.Metal | Decal.MaskBlendFlags.Smoothness:
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsMSStr, true);
break;
case Decal.MaskBlendFlags.AO | Decal.MaskBlendFlags.Smoothness:
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsAOSStr, true);
break;
case Decal.MaskBlendFlags.Metal | Decal.MaskBlendFlags.AO | Decal.MaskBlendFlags.Smoothness:
material.SetShaderPassEnabled(HDShaderPassNames.s_MeshDecalsMAOSStr, true);
break;
}
}
protected void SetupMaterialKeywordsAndPassInternal(Material material)

{
// Use default labelWidth
EditorGUIUtility.labelWidth = 0f;
float normalBlendSrcValue = normalBlendSrc.floatValue;
float maskBlendSrcValue = maskBlendSrc.floatValue;
Decal.MaskBlendFlags maskBlendFlags = (Decal.MaskBlendFlags)maskBlendMode.floatValue;
HDRenderPipelineAsset hdrp = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
bool perChannelMask = hdrp.renderPipelineSettings.decalSettings.perChannelMask;
// Detect any changes to the material
EditorGUI.BeginChangeCheck();

EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(albedoMode, Styles.AlbedoModeText);
if (material.GetFloat(kAlbedoMode) == 1.0f)
m_MaterialEditor.TexturePropertySingleLine((material.GetFloat(kAlbedoMode) == 1.0f) ? Styles.baseColorText : Styles.baseColorText2, baseColorMap, baseColor);
if (material.GetTexture(kBaseColorMap))
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText, baseColorMap, baseColor);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(albedoMode, Styles.AlbedoModeText);
EditorGUI.indentLevel--;
}
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, normalMap);
if (material.GetTexture(kNormalMap))
{
EditorGUI.indentLevel++;
normalBlendSrcValue = EditorGUILayout.Popup("Normal Opacity channel", (int)normalBlendSrcValue, blendSourceNames);
EditorGUI.indentLevel--;
else
m_MaterialEditor.TexturePropertySingleLine(Styles.maskMapText[(int)maskBlendFlags], maskMap);
if (material.GetTexture(kMaskMap))
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText2, baseColorMap, baseColor);
EditorGUI.indentLevel++;
maskBlendSrcValue = EditorGUILayout.Popup("Mask Opacity channel", (int) maskBlendSrcValue, blendSourceNames);
if (perChannelMask)
{
// Following condition force users to always have at least one attribute enabled
m_MaterialEditor.ShaderProperty(maskmapMetal, "Affect Metal");
if ((maskmapMetal.floatValue == 0.0f) && (maskmapAO.floatValue == 0.0f) && (maskmapSmoothness.floatValue == 0.0f))
maskmapMetal.floatValue = 1.0f;
m_MaterialEditor.ShaderProperty(maskmapAO, "Affect AO");
if ((maskmapMetal.floatValue == 0.0f) && (maskmapAO.floatValue == 0.0f) && (maskmapSmoothness.floatValue == 0.0f))
maskmapAO.floatValue = 1.0f;
m_MaterialEditor.ShaderProperty(maskmapSmoothness, "Affect Smoothness");
if ((maskmapMetal.floatValue == 0.0f) && (maskmapAO.floatValue == 0.0f) && (maskmapSmoothness.floatValue == 0.0f))
maskmapSmoothness.floatValue = 1.0f;
if (maskmapMetal.floatValue == 1.0f)
maskBlendFlags |= Decal.MaskBlendFlags.Metal;
if (maskmapAO.floatValue == 1.0f)
maskBlendFlags |= Decal.MaskBlendFlags.AO;
if (maskmapSmoothness.floatValue == 1.0f)
maskBlendFlags |= Decal.MaskBlendFlags.Smoothness;
}
EditorGUI.indentLevel--;
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, normalMap);
m_MaterialEditor.TexturePropertySingleLine(Styles.maskMapText, maskMap);
EditorGUILayout.HelpBox(
"Control of AO and Metal is based on option 'Enable Metal and AO properties' in HDRP Asset.\nThere is a performance cost of enabling this option.",
MessageType.Info);
normalBlendSrc.floatValue = normalBlendSrcValue;
maskBlendSrc.floatValue = maskBlendSrcValue;
maskBlendMode.floatValue = (float) maskBlendFlags;
foreach (var obj in m_MaterialEditor.targets)
SetupMaterialKeywordsAndPassInternal((Material)obj);
}

1
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/GlobalDecalSettingsUI.cs


EditorGUILayout.PropertyField(d.drawDistance, _.GetContent("Draw Distance"));
EditorGUILayout.PropertyField(d.atlasWidth, _.GetContent("Atlas Width"));
EditorGUILayout.PropertyField(d.atlasHeight, _.GetContent("Atlas Height"));
EditorGUILayout.PropertyField(d.perChannelMask, _.GetContent("Enable Metal and AO properties"));
--EditorGUI.indentLevel;
}
}

2
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedGlobalDecalSettings.cs


public SerializedProperty drawDistance;
public SerializedProperty atlasWidth;
public SerializedProperty atlasHeight;
public SerializedProperty perChannelMask;
public SerializedGlobalDecalSettings(SerializedProperty root)
{

atlasWidth = root.Find((GlobalDecalSettings s) => s.atlasWidth);
atlasHeight = root.Find((GlobalDecalSettings s) => s.atlasHeight);
perChannelMask = root.Find((GlobalDecalSettings s) => s.perChannelMask);
}
}
}

4
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDPBRPass.template


ZERO_INITIALIZE(SurfaceDescriptionInputs, output);
$SurfaceDescriptionInputs.WorldSpaceNormal: output.WorldSpaceNormal = normalize(input.worldToTangent[2].xyz);
$SurfaceDescriptionInputs.ObjectSpaceNormal: output.ObjectSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) unity_ObjectToWorld); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_I_V); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.ObjectSpaceNormal: output.ObjectSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_M); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_I_V); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
$SurfaceDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = input.worldToTangent[0].xyz;
$SurfaceDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = TransformWorldToObjectDir(output.WorldSpaceTangent);

4
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDUnlitPassForward.template


ZERO_INITIALIZE(SurfaceDescriptionInputs, output);
$SurfaceDescriptionInputs.WorldSpaceNormal: output.WorldSpaceNormal = normalize(input.worldToTangent[2].xyz);
$SurfaceDescriptionInputs.ObjectSpaceNormal: output.ObjectSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) unity_ObjectToWorld); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_I_V); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.ObjectSpaceNormal: output.ObjectSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_M); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_I_V); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
$SurfaceDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = input.worldToTangent[0].xyz;
$SurfaceDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = TransformWorldToObjectDir(output.WorldSpaceTangent);

6
com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/HDRPVersion.cs


[InitializeOnLoad]
public class HDRPVersion
{
static public int hdrpVersion = 1;
// 1 changed emissive color
// 2 add decal mode in decal material
static public int hdrpVersion = 2;
static public int GetCurrentHDRPProjectVersion()
{

static HDRPVersion()
{
// Compare project version with current version - Trigger an upgrade if user ask for it
if (GetCurrentHDRPProjectVersion() < hdrpVersion)
if (false) //GetCurrentHDRPProjectVersion() < hdrpVersion) // TODO: Disable for now as it doesn't work correctly
{
if (EditorUtility.DisplayDialog("A newer version of HDRP has been detected",
"Do you want to upgrade your materials to newer version?\n You can also upgrade manually materials in 'Edit -> Render Pipeline' submenu", "Yes", "No"))

35
com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/UpgradeMenuItem.cs


return;
}
// Update decal material after we added AO and metal selection. It was default to 0 and need to default to 4 now.
static bool UpdateMaterial_DecalBlendMode(string path, Material mat)
{
if (mat.shader.name == "HDRenderPipeline/Decal")
{
float maskBlendMode = mat.GetFloat("_MaskBlendMode");
if (maskBlendMode == 0.0f)
{
mat.SetFloat("_MaskBlendMode", 4.0f);
return true;
}
}
return false;
}
delegate bool UpdateMaterial(string path, Material mat);
delegate void UpdateMaterialFile(string path);

mat.shader.name == "HDRenderPipeline/LayeredLit" ||
mat.shader.name == "HDRenderPipeline/LayeredLitTessellation" ||
mat.shader.name == "HDRenderPipeline/StackLit" ||
mat.shader.name == "HDRenderPipeline/Unlit"
mat.shader.name == "HDRenderPipeline/Unlit" ||
mat.shader.name == "HDRenderPipeline/Decal"
)
{
// Need to be processed in order - All function here should be re-entrant (i.e after upgrade it can be recall)

UpdateMaterialToNewerVersion("(EmissiveColor)", UpdateMaterial_EmissiveColor, UpdateMaterialFile_EmissiveColor);
}
[MenuItem("Edit/Render Pipeline/Single step upgrade script/Upgrade all DecalMaterial MaskBlendMode", priority = CoreUtils.editMenuPriority3)]
static public void UpdateMaterialToNewerVersionDecalMaterialMaskBlendMode()
{
UpdateMaterialToNewerVersion("(DecalMaterial)", UpdateMaterial_DecalBlendMode);
}
[MenuItem("Edit/Render Pipeline/Upgrade all Materials to latest version", priority = CoreUtils.editMenuPriority3)]
static public void UpdateMaterialToNewerVersion()
{

float currentVersion = HDRPVersion.GetCurrentHDRPProjectVersion();
if (currentVersion < 1.0)
int currentVersion = HDRPVersion.GetCurrentHDRPProjectVersion();
if (currentVersion < 1)
}
if (currentVersion < 2)
{
// Appear in hdrp version 2.0
UpdateMaterialToNewerVersion("(DecalMaterial)", UpdateMaterial_DecalBlendMode);
}
}
}

27
com.unity.render-pipelines.high-definition/HDRP/Lighting/Light/HDAdditionalLightData.cs


[ExecuteInEditMode]
public class HDAdditionalLightData : MonoBehaviour, ISerializationCallbackReceiver
{
public const float currentVersion = 1.1f;
private const int currentVersion = 2;
[HideInInspector]
[HideInInspector, SerializeField]
public float version = currentVersion;
[System.Obsolete("version is deprecated, use m_Version instead")]
private float version = currentVersion;
// Currently m_Version is not used and produce a warning, remove these pragmas at the next version incrementation
#pragma warning disable 414
[SerializeField]
private int m_Version = currentVersion;
#pragma warning restore 414
// To be able to have correct default values for our lights and to also control the conversion of intensity from the light editor (so it is compatible with GI)
// we add intensity (for each type of light we want to manage).

public void OnAfterDeserialize()
{
// If we are deserializing an old version, convert the light intensity to the new system
// Note: the field version is deprecated but we keep it for retro-compatibility reasons, you should use m_Version instead
#pragma warning disable 0618
#pragma warning restore 0618
{
// Note: We can't access to the light component in OnAfterSerialize as it is not init() yet,
// so instead we use a boolean to do the upgrade in OnEnable().

public void UpgradeLight()
{
// Disable the warning generated by deprecated fields (areaIntensity, directionalIntensity, ...)
#pragma warning disable 0618
// If we are deserializing an old version, convert the light intensity to the new system
// Pragma to disable the warning got by using deprecated properties (areaIntensity, directionalIntensity, ...)
#pragma warning disable 0618
switch (lightTypeExtent)
{
case LightTypeExtent.Punctual:

intensity = areaIntensity;
break;
}
#pragma warning restore 0618
needsIntensityUpdate_1_0 = false;
m_Version = currentVersion;
#pragma warning restore 0618
}
}
}

63
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoopDef.hlsl


#include "LightLoop.cs.hlsl"
#include "../../Sky/SkyVariables.hlsl"
StructuredBuffer<uint> g_vLightListGlobal; // don't support Buffer yet in unity
#define MAX_ENV2D_LIGHT 32
CBUFFER_START(UnityTilePass)
uint _NumTileFtplX;
uint _NumTileFtplY;
// these uniforms are only needed for when OPAQUES_ONLY is NOT defined
// but there's a problem with our front-end compilation of compute shaders with multiple kernels causing it to error
//#ifdef USE_CLUSTERED_LIGHTLIST
float4x4 g_mInvScrProjection; // TODO: remove, unused in HDRP
float g_fClustScale;
float g_fClustBase;
float g_fNearPlane;
float g_fFarPlane;
int g_iLog2NumClusters; // We need to always define these to keep constant buffer layouts compatible
uint g_isLogBaseBufferEnabled;
//#endif
//#ifdef USE_CLUSTERED_LIGHTLIST
uint _NumTileClusteredX;
uint _NumTileClusteredY;
CBUFFER_END
StructuredBuffer<uint> g_vLayeredOffsetsBuffer; // don't support Buffer yet in unity
StructuredBuffer<float> g_logBaseBuffer; // don't support Buffer yet in unity
//#endif
#ifdef USE_INDIRECT
StructuredBuffer<uint> g_TileFeatureFlags;
#endif
StructuredBuffer<DirectionalLightData> _DirectionalLightDatas;
StructuredBuffer<LightData> _LightDatas;
StructuredBuffer<EnvLightData> _EnvLightDatas;
StructuredBuffer<ShadowData> _ShadowDatas;
// Used by directional and spot lights
TEXTURE2D_ARRAY(_CookieTextures);
// Used by point lights
TEXTURECUBE_ARRAY_ABSTRACT(_CookieCubeTextures);
// Use texture array for reflection (or LatLong 2D array for mobile)
TEXTURECUBE_ARRAY_ABSTRACT(_EnvCubemapTextures);
TEXTURE2D_ARRAY(_Env2DTextures);
float4x4 _Env2DCaptureVP[MAX_ENV2D_LIGHT];
// XRTODO: Need to stereo-ize access
TEXTURE2D(_DeferredShadowTexture);
CBUFFER_START(UnityPerLightLoop)
uint _DirectionalLightCount;
uint _PunctualLightCount;
uint _AreaLightCount;
uint _EnvLightCount;
uint _EnvProxyCount;
int _EnvLightSkyEnabled; // TODO: make it a bool
CBUFFER_END
// LightLoopContext is not visible from Material (user should not use these properties in Material file)
// It allow the lightloop to have transmit sampling information (do we use atlas, or texture array etc...)

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


{
widgets.AddRange(new[]
{
new DebugUI.Container
new DebugUI.Foldout
displayName = "Lighting Settings",
displayName = "Light Loop Settings",
children =
{
// Uncomment if you re-enable LIGHTLOOP_SINGLE_PASS multi_compile in lit*.shader

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


RWBuffer<uint> g_DispatchIndirectBuffer : register( u0 ); // Indirect arguments have to be in a _buffer_, not a structured buffer
#include "LightLoop.cs.hlsl"
// On iOS, we get a GPU hang/reset based upon the execution of the ClearDispatchIndirect kernel.
// The buffer is created using the 'NUM_FEATURE_VARIANTS' constant but we're dispatching a threadgroup of 64 threads, so we are presumably going out of bounds (Metal GPU errors are not terribly descriptive, but this is a common cause).
// In DirectX out-of-bounds reads are always zero and out-of-bounds writes are are a no op.
if (dispatchThreadId >= NUM_FEATURE_VARIANTS)
return;
g_DispatchIndirectBuffer[dispatchThreadId * 3 + 0] = 0; // ThreadGroupCountX
g_DispatchIndirectBuffer[dispatchThreadId * 3 + 1] = 1; // ThreadGroupCountY
g_DispatchIndirectBuffer[dispatchThreadId * 3 + 2] = 1; // ThreadGroupCountZ

23
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/HDAdditionalReflectionData.cs


using UnityEngine.Serialization;
using UnityEngine.Experimental.Rendering.HDPipeline;
using System;
[RequireComponent(typeof(ReflectionProbe), typeof(MeshFilter), typeof(MeshRenderer))]
public class HDAdditionalReflectionData : MonoBehaviour
[RequireComponent(typeof(ReflectionProbe))]
public class HDAdditionalReflectionData : MonoBehaviour, ISerializationCallbackReceiver
public float version = 1.0f;
const int currentVersion = 1;
[SerializeField, FormerlySerializedAs("version")]
int m_Version;
public ShapeType influenceShape;
[FormerlySerializedAsAttribute("dimmer")]

public float sphereBlendRadiusOffset { get { return -blendDistancePositive.x; } }
public float sphereBlendNormalRadiusOffset { get { return -blendNormalDistancePositive.x; } }
public void OnBeforeSerialize()
{
}
public void OnAfterDeserialize()
{
if (m_Version != currentVersion)
{
// Add here data migration code
m_Version = currentVersion;
}
}
}
}

22
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/PlanarReflectionProbe.cs


using UnityEngine.Serialization;
using UnityEngine.Rendering;
using System;
public class PlanarReflectionProbe : MonoBehaviour
public class PlanarReflectionProbe : MonoBehaviour, ISerializationCallbackReceiver
[HideInInspector]
const int currentVersion = 1;
[SerializeField, FormerlySerializedAs("version")]
int m_Version;
public enum CapturePositionMode
{
Static,

if (isActiveAndEnabled)
ReflectionSystem.RegisterProbe(this);
}
public void OnBeforeSerialize()
{
}
public void OnAfterDeserialize()
{
if (m_Version != currentVersion)
{
// Add here data migration code
m_Version = currentVersion;
}
}
}
}

2
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/PlanarReflectionProbe.cs.meta


serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
icon: {fileID: 2800000, guid: 3b77af68825357f47ae9f6d0b9d30f2d, type: 3}
userData:
assetBundleName:
assetBundleVariant:

2
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/Volumes/ReflectionProxyVolumeComponent.cs.meta


serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
icon: {fileID: 2800000, guid: a9ddbc20ff7d25948976df9d0f76eaf7, type: 3}
userData:
assetBundleName:
assetBundleVariant:

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


RTHandles.Release(m_HTile);
}
public void ClearTargets(CommandBuffer cmd, HDCamera camera)
public void ClearAndSetTargets(CommandBuffer cmd, HDCamera camera, bool rtCount4, RTHandleSystem.RTHandle cameraDepthStencilBuffer)
RenderTargetIdentifier[] RTIDs = new RenderTargetIdentifier[rtCount4 ? 4 :3];
// this clears the targets
Color clearColorAOSBlend = new Color(1.0f, 1.0f, 1.0f, 1.0f);
// names IDs have to be set every frame, because they can change
RTIDs[0] = m_RTs[0].nameID;
RTIDs[1] = m_RTs[1].nameID;
RTIDs[2] = m_RTs[2].nameID;
if (rtCount4)
{
HDUtils.SetRenderTarget(cmd, camera, m_RTs[3], ClearFlag.Color, clearColorAOSBlend);
RTIDs[3] = m_RTs[3].nameID;
}
}
public void SetHTile(int bindSlot, CommandBuffer cmd)
{
cmd.SetRandomWriteTarget(bindSlot, m_HTile);
// this actually sets the MRTs and HTile RWTexture, this is done separately because we do not have an api to clear MRTs to different colors
HDUtils.SetRenderTarget(cmd, camera, RTIDs, cameraDepthStencilBuffer); // do not clear anymore
cmd.SetRandomWriteTarget(rtCount4 ? 4 : 3, m_HTile);
}
public void UnSetHTile(CommandBuffer cmd)

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


using System;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline

public Vector4 normalWS;
[SurfaceDataAttributes("Mask", true)]
public Vector4 mask;
[SurfaceDataAttributes("AOSBlend", true)]
public Vector2 MAOSBlend;
[SurfaceDataAttributes("HTileMask")]
public uint HTileMask;
};

{
// Note: This count doesn't include the velocity buffer. On shader and csharp side the velocity buffer will be added by the framework
Count = 3
{
Count = 4
};
[GenerateHLSL(PackingRules.Exact)]

// should this be combined into common class shared with Lit.cs???
static public int GetMaterialDBufferCount() { return (int)DBufferMaterial.Count; }
static RenderTextureFormat[] m_RTFormat = { RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32 };
static bool[] m_sRGBFlags = { true, false, false };
static RenderTextureFormat[] m_RTFormat = { RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32, RenderTextureFormat.RG16 };
static bool[] m_sRGBFlags = { true, false, false, false };
static public void GetMaterialDBufferDescription(out RenderTextureFormat[] RTFormat, out bool[] sRGBFlags)
{

// relies on the order shader passes are declared in decal.shader
[Flags]
public enum MaskBlendFlags
{
Metal = 1 << 0,
AO = 1 << 1,
Smoothness = 1 << 2,
}
}
// normal to world only uses 3x3 for actual matrix so some data is packed in the unused space

public Vector4 normalScaleBias;
public Vector4 maskScaleBias;
public Vector4 baseColor;
public Vector3 blendParams; // x normal blend source, y mask blend source, z mask blend mode
};
}

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


#define DEBUGVIEW_DECAL_DECALSURFACEDATA_BASE_COLOR (200)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_NORMAL (201)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_MASK (202)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_HTILE_MASK (203)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_AOSBLEND (203)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_HTILE_MASK (204)
#define DBUFFERMATERIAL_COUNT (3)
#define DBUFFERMATERIAL_COUNT (4)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Decal+DBufferHTileBit: static fields

float4 baseColor;
float4 normalWS;
float4 mask;
float2 MAOSBlend;
uint HTileMask;
};

float4 normalScaleBias;
float4 maskScaleBias;
float4 baseColor;
float3 blendParams;
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.DecalData
//
float4x4 GetWorldToDecal(DecalData value)
{
return value.worldToDecal;
}
float4x4 GetNormalToWorld(DecalData value)
{
return value.normalToWorld;
}
float4 GetDiffuseScaleBias(DecalData value)
{
return value.diffuseScaleBias;
}
float4 GetNormalScaleBias(DecalData value)
{
return value.normalScaleBias;
}
float4 GetMaskScaleBias(DecalData value)
{
return value.maskScaleBias;
}
float4 GetBaseColor(DecalData value)
{
return value.baseColor;
}
float3 GetBlendParams(DecalData value)
{
return value.blendParams;
}
//
// Debug functions
//
void GetGeneratedDecalSurfaceDataDebug(uint paramId, DecalSurfaceData decalsurfacedata, inout float3 result, inout bool needLinearToSRGB)

break;
case DEBUGVIEW_DECAL_DECALSURFACEDATA_MASK:
result = decalsurfacedata.mask.xyz;
break;
case DEBUGVIEW_DECAL_DECALSURFACEDATA_AOSBLEND:
result = float3(decalsurfacedata.MAOSBlend, 0.0);
break;
case DEBUGVIEW_DECAL_DECALSURFACEDATA_HTILE_MASK:
result = GetIndexColor(decalsurfacedata.HTileMask);

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


#define DBufferType0 float4
#define DBufferType1 float4
#define DBufferType2 float4
#define DBufferType3 float4
#ifdef DBUFFERMATERIAL_COUNT
#ifdef _DECALS_4RT
#define DBufferType3 float2
#if DBUFFERMATERIAL_COUNT == 1
#define OUTPUT_DBUFFER(NAME) \
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \
out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2, \
out DBufferType3 MERGE_NAME(NAME, 3) : SV_Target3
#define OUTPUT_DBUFFER(NAME) \
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0
#define DECLARE_DBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0)); \
TEXTURE2D(MERGE_NAME(NAME, 1)); \
TEXTURE2D(MERGE_NAME(NAME, 2)); \
TEXTURE2D(MERGE_NAME(NAME, 3));
#define DECLARE_DBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0));
#define FETCH_DBUFFER(NAME, TEX, unCoord2) \
DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), unCoord2); \
DBufferType1 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 1), unCoord2); \
DBufferType2 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 2), unCoord2); \
DBufferType3 MERGE_NAME(NAME, 3) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 3), unCoord2);
#define FETCH_DBUFFER(NAME, TEX, unCoord2) \
DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), unCoord2);
#define ENCODE_INTO_DBUFFER(DECAL_SURFACE_DATA, NAME) EncodeIntoDBuffer(DECAL_SURFACE_DATA, MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2), MERGE_NAME(NAME,3))
#define DECODE_FROM_DBUFFER(NAME, DECAL_SURFACE_DATA) DecodeFromDBuffer(MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2), MERGE_NAME(NAME,3), DECAL_SURFACE_DATA)
#define ENCODE_INTO_DBUFFER(DECAL_SURFACE_DATA, NAME) EncodeIntoDBuffer(DECAL_SURFACE_DATA, MERGE_NAME(NAME,0))
#define DECODE_FROM_DBUFFER(NAME, DECAL_SURFACE_DATA) DecodeFromDBuffer(MERGE_NAME(NAME,0), DECAL_SURFACE_DATA)
#else
#define OUTPUT_DBUFFER(NAME) \
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \
out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2
#elif DBUFFERMATERIAL_COUNT == 2
#define OUTPUT_DBUFFER(NAME) \
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1
#define DECLARE_DBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0)); \
TEXTURE2D(MERGE_NAME(NAME, 1));
#define FETCH_DBUFFER(NAME, TEX, unCoord2) \
DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), unCoord2); \
DBufferType1 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 1), unCoord2);
#define ENCODE_INTO_DBUFFER(DECAL_SURFACE_DATA, NAME) EncodeIntoDBuffer(DECAL_SURFACE_DATA, MERGE_NAME(NAME,0), MERGE_NAME(NAME,1))
#define DECODE_FROM_DBUFFER(NAME, DECAL_SURFACE_DATA) DecodeFromDBuffer(MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), DECAL_SURFACE_DATA)
#elif DBUFFERMATERIAL_COUNT == 3
#define OUTPUT_DBUFFER(NAME) \
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \
out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2
#define DECLARE_DBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0)); \
TEXTURE2D(MERGE_NAME(NAME, 1)); \
TEXTURE2D(MERGE_NAME(NAME, 2));
#define DECLARE_DBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0)); \
TEXTURE2D(MERGE_NAME(NAME, 1)); \
TEXTURE2D(MERGE_NAME(NAME, 2));
#define FETCH_DBUFFER(NAME, TEX, unCoord2) \
DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), unCoord2); \
DBufferType1 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 1), unCoord2); \
DBufferType2 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 2), unCoord2);
#define FETCH_DBUFFER(NAME, TEX, unCoord2) \
DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), unCoord2); \
DBufferType1 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 1), unCoord2); \
DBufferType2 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 2), unCoord2);
#elif DBUFFERMATERIAL_COUNT == 4
#define OUTPUT_DBUFFER(NAME) \
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \
out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2, \
out DBufferType3 MERGE_NAME(NAME, 3) : SV_Target3
#define DECLARE_DBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0)); \
TEXTURE2D(MERGE_NAME(NAME, 1)); \
TEXTURE2D(MERGE_NAME(NAME, 2)); \
TEXTURE2D(MERGE_NAME(NAME, 3));
#define FETCH_DBUFFER(NAME, TEX, unCoord2) \
DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), unCoord2); \
DBufferType1 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 1), unCoord2); \
DBufferType2 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 2), unCoord2); \
DBufferType3 MERGE_NAME(NAME, 3) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 3), unCoord2);
#define ENCODE_INTO_DBUFFER(DECAL_SURFACE_DATA, NAME) EncodeIntoDBuffer(DECAL_SURFACE_DATA, MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2), MERGE_NAME(NAME,3))
#define DECODE_FROM_DBUFFER(NAME, DECAL_SURFACE_DATA) DecodeFromDBuffer(MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2), MERGE_NAME(NAME,3), DECAL_SURFACE_DATA)
#endif // #ifdef DBUFFERMATERIAL_COUNT
CBUFFER_START(UnityDecalParameters)
uint _EnableDBuffer;
float2 _DecalAtlasResolution;
CBUFFER_END
UNITY_INSTANCING_BUFFER_START(Decal)
UNITY_DEFINE_INSTANCED_PROP(float4x4, _NormalToWorld)

SAMPLER(_trilinear_clamp_sampler_DecalAtlas2D);
// Must be in sync with RT declared in HDRenderPipeline.cs ::Rebuild
void EncodeIntoDBuffer( DecalSurfaceData surfaceData,
out DBufferType0 outDBuffer0,
out DBufferType1 outDBuffer1,
out DBufferType2 outDBuffer2
void EncodeIntoDBuffer( DecalSurfaceData surfaceData
, out DBufferType0 outDBuffer0
, out DBufferType1 outDBuffer1
, out DBufferType2 outDBuffer2
#ifdef _DECALS_4RT
, out DBufferType3 outDBuffer3
#endif
#ifdef _DECALS_4RT
outDBuffer3 = surfaceData.MAOSBlend;
#endif
DBufferType0 inDBuffer0,
DBufferType1 inDBuffer1,
DBufferType2 inDBuffer2,
out DecalSurfaceData surfaceData
DBufferType0 inDBuffer0
, DBufferType1 inDBuffer1
, DBufferType2 inDBuffer2
#ifdef _DECALS_4RT
, DBufferType3 inDBuffer3
#endif
, out DecalSurfaceData surfaceData
)
{
ZERO_INITIALIZE(DecalSurfaceData, surfaceData);

surfaceData.mask = inDBuffer2;
#ifdef _DECALS_4RT
surfaceData.MAOSBlend = inDBuffer3;
#else
surfaceData.MAOSBlend = float2(surfaceData.mask.w, surfaceData.mask.w);
#endif
}

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


_MaskMap("MaskMap", 2D) = "white" {}
_DecalBlend("_DecalBlend", Range(0.0, 1.0)) = 0.5
[ToggleUI] _AlbedoMode("_AlbedoMode", Range(0.0, 1.0)) = 1.0
[HideInInspector] _NormalBlendSrc("_NormalBlendSrc", Float) = 0.0
[HideInInspector] _MaskBlendSrc("_MaskBlendSrc", Float) = 1.0
[HideInInspector] _MaskBlendMode("_MaskBlendMode", Float) = 4.0 // smoothness 3RT default
[ToggleUI] _MaskmapMetal("_MaskmapMetal", Range(0.0, 1.0)) = 0.0
[ToggleUI] _MaskmapAO("_MaskmapAO", Range(0.0, 1.0)) = 0.0
[ToggleUI] _MaskmapSmoothness("_MaskmapSmoothness", Range(0.0, 1.0)) = 1.0
}
HLSLINCLUDE

#pragma shader_feature _MASKMAP
#pragma shader_feature _ALBEDOCONTRIBUTION
#pragma shader_feature _NORMAL_BLEND_SRC_B
#pragma shader_feature _MASK_BLEND_SRC_B
#pragma multi_compile _ _DECALS_4RT
//-------------------------------------------------------------------------------------
// Define
//-------------------------------------------------------------------------------------

{
Tags{ "RenderPipeline" = "HDRenderPipeline"}
// c# code relies on the order in which the passes are declared, any change will need to be reflected in DecalUI.cs
// pass 0 is mesh 3RT mode
Pass
{
Name "DBufferMesh_3RT" // Name is not used
Tags{"LightMode" = "DBufferMesh_3RT"} // Smoothness
ZWrite Off
ZTest LEqual
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
ColorMask BA 2 // smoothness/smoothness alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_MESH
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
// enum MaskBlendFlags
//{
// Metal = 1 << 0,
// AO = 1 << 1,
// Smoothness = 1 << 2,
//}
// Projectors
//
// 1 - Metal
// 2 - AO
// 3 - Metal + AO
// 4 - Smoothness also 3RT
// 5 - Metal + Smoothness
// 6 - AO + Smoothness
// 7 - Metal + AO + Smoothness
//
Pass
{
Name "DBufferProjector_M" // Name is not used
Tags{"LightMode" = "DBufferProjector_M"} // Metalness
// back faces with zfail, for cases when camera is inside the decal volume
Cull Front
ZWrite Off
ZTest Greater
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
ColorMask R 2 // metal
ColorMask R 3 // metal alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferProjector_AO" // Name is not used
Tags{"LightMode" = "DBufferProjector_AO"} // AO only
// back faces with zfail, for cases when camera is inside the decal volume
Cull Front
ZWrite Off
ZTest Greater
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
ColorMask G 2 // ao
ColorMask G 3 // ao alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferProjector_MAO" // Name is not used
Tags{"LightMode" = "DBufferProjector_MAO"} // AO + Metalness
// back faces with zfail, for cases when camera is inside the decal volume
Cull Front
ZWrite Off
ZTest Greater
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
ColorMask RG 2 // metalness + ao
ColorMask RG 3 // metalness alpha + ao alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferProjector_S" // Name is not used
Tags{"LightMode" = "DBufferProjector_S"} // Smoothness
// back faces with zfail, for cases when camera is inside the decal volume
Cull Front
ZWrite Off
ZTest Greater
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
ColorMask BA 2 // smoothness/smoothness alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferProjector_MS" // Name is not used
Tags{"LightMode" = "DBufferProjector_MS"} // Smoothness and Metalness
// back faces with zfail, for cases when camera is inside the decal volume
Cull Front
ZWrite Off
ZTest Greater
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
ColorMask RBA 2 // metal/smoothness/smoothness alpha
ColorMask R 3 // metal alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferProjector_AOS" // Name is not used
Tags{"LightMode" = "DBufferProjector_AOS"} // AO + Smoothness
// back faces with zfail, for cases when camera is inside the decal volume
Cull Front
ZWrite Off
ZTest Greater
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
ColorMask GBA 2 // ao, smoothness, smoothness alpha
ColorMask G 3 // ao alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Name "DBufferProjector" // Name is not used
Tags { "LightMode" = "DBufferProjector" } // This will be only for opaque object based on the RenderQueue index
Name "DBufferProjector_MAOS" // Name is not used
Tags { "LightMode" = "DBufferProjector_MAOS" } // Metalness AO and Smoothness
Blend SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
HLSLPROGRAM

ENDHLSL
}
// Mesh
// 8 - Metal
// 9 - AO
// 10 - Metal + AO
// 11 - Smoothness
// 12 - Metal + Smoothness
// 13 - AO + Smoothness
// 14 - Metal + AO + Smoothness
Name "DBufferMesh" // Name is not used
Tags{"LightMode" = "DBufferMesh"} // This will be only for opaque object based on the RenderQueue index
Cull Back
Name "DBufferMesh_M" // Name is not used
Tags{"LightMode" = "DBufferMesh_M"} // Metalness
ZWrite Off
ZTest LEqual
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
ColorMask R 2 // metal
ColorMask R 3 // metal alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_MESH
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferMesh_AO" // Name is not used
Tags{"LightMode" = "DBufferMesh_AO"} // AO only
ZWrite Off
ZTest LEqual
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
ColorMask G 2 // ao
ColorMask G 3 // ao alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_MESH
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferMesh_MAO" // Name is not used
Tags{"LightMode" = "DBufferMesh_MAO"} // AO + Metalness
ZWrite Off
ZTest LEqual
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
ColorMask RG 2 // metalness + ao
ColorMask RG 3 // metalness alpha + ao alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_MESH
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferMesh_S" // Name is not used
Tags{"LightMode" = "DBufferMesh_S"} // Smoothness
ZWrite Off
ZTest LEqual
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
ColorMask BA 2 // smoothness/smoothness alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_MESH
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferMesh_MS" // Name is not used
Tags{"LightMode" = "DBufferMesh_MS"} // Smoothness and Metalness
ZWrite Off
ZTest LEqual
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
ColorMask RBA 2 // metal/smoothness/smoothness alpha
ColorMask R 3 // metal alpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_MESH
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferMesh_AOS" // Name is not used
Tags{"LightMode" = "DBufferMesh_AOS"} // AO + Smoothness
Blend SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
ColorMask GBA 2 // ao, smoothness, smoothness alpha
ColorMask G 3 // ao alpha
HLSLPROGRAM

ENDHLSL
}
}
Pass
{
Name "DBufferMesh_MAOS" // Name is not used
Tags{"LightMode" = "DBufferMesh_MAOS"} // Metalness AO and Smoothness
ZWrite Off
ZTest LEqual
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
Blend 3 Zero OneMinusSrcColor
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"
}

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


surfaceData.baseColor = _BaseColor;
surfaceData.normalWS = float4(0,0,0,0);
surfaceData.mask = float4(0,0,0,0);
surfaceData.MAOSBlend = float2(0, 0);
float totalBlend = clamp(normalToWorld[0][3], 0.0f, 1.0f);
float albedoMapBlend = clamp(normalToWorld[0][3], 0.0f, 1.0f);
float totalBlend = _DecalBlend;
float albedoMapBlend = _DecalBlend;
float2 texCoords = input.texCoord0;
#endif

surfaceData.baseColor.w *= totalBlend;
totalBlend = surfaceData.baseColor.w; // base alpha affects all other channels;
surfaceData.baseColor.w *= albedoMapBlend;
albedoMapBlend = surfaceData.baseColor.w;
// outside _COLORMAP because we still have base color
#if _ALBEDOCONTRIBUTION
surfaceData.HTileMask |= DBUFFERHTILEBIT_DIFFUSE;

float maskMapBlend;
#if _MASKMAP
surfaceData.mask = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, texCoords);
maskMapBlend = surfaceData.mask.z * _DecalBlend; // store before overwriting with smoothness
surfaceData.mask.z = surfaceData.mask.w;
surfaceData.HTileMask |= DBUFFERHTILEBIT_MASK;
#if _MASK_BLEND_SRC_B
surfaceData.mask.w = maskMapBlend;
#else
surfaceData.mask.w = albedoMapBlend;
#endif
#endif
// needs to be after mask, because blend source could be in the mask map blue
#if _NORMALMAP
float3 normalTS = UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoords));
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)

GetNormalWS(input, 0, normalTS, normalWS);
#endif
surfaceData.normalWS.xyz = normalWS * 0.5f + 0.5f;
surfaceData.normalWS.w = totalBlend;
surfaceData.HTileMask |= DBUFFERHTILEBIT_NORMAL;
surfaceData.normalWS.xyz = normalWS * 0.5f + 0.5f;
surfaceData.HTileMask |= DBUFFERHTILEBIT_NORMAL;
#if _NORMAL_BLEND_SRC_B
surfaceData.normalWS.w = maskMapBlend;
#else
surfaceData.normalWS.w = albedoMapBlend;
#endif
#if _MASKMAP
surfaceData.mask = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, texCoords);
surfaceData.mask.z = surfaceData.mask.w;
surfaceData.mask.w = totalBlend;
surfaceData.HTileMask |= DBUFFERHTILEBIT_MASK;
#endif
surfaceData.MAOSBlend.xy = float2(surfaceData.mask.w, surfaceData.mask.w);
}

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


}
}
public void Update()
public void LateUpdate()
{
if (m_Handle != null)
{

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


}
}
public bool perChannelMask
{
get
{
HDRenderPipelineAsset hdrp = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
if (hdrp != null)
{
return hdrp.renderPipelineSettings.decalSettings.perChannelMask;
}
return false;
}
}
public Camera CurrentCamera
{
get

m_Blend = m_Material.GetFloat("_DecalBlend");
m_AlbedoContribution = m_Material.GetFloat("_AlbedoMode");
m_BaseColor = m_Material.GetVector("_BaseColor");
m_BlendParams = new Vector3(m_Material.GetFloat("_NormalBlendSrc"), m_Material.GetFloat("_MaskBlendSrc"), m_Material.GetFloat("_MaskBlendMode"));
}
public DecalSet(Material material)

Vector3 cameraPos = instance.CurrentCamera.transform.position;
Matrix4x4 worldToView = LightLoop.WorldToCamera(instance.CurrentCamera);
bool perChannelMask = instance.perChannelMask;
for (int resultIndex = 0; resultIndex < m_NumResults; resultIndex++)
{
int decalIndex = m_ResultIndices[resultIndex];

m_DecalDatas[m_DecalDatasCount].worldToDecal = decalToWorldBatch[instanceCount].inverse;
m_DecalDatas[m_DecalDatasCount].normalToWorld = normalToWorldBatch[instanceCount];
m_DecalDatas[m_DecalDatasCount].baseColor = m_BaseColor;
m_DecalDatas[m_DecalDatasCount].blendParams = m_BlendParams;
if(!perChannelMask)
{
m_DecalDatas[m_DecalDatasCount].blendParams.z = (float)Decal.MaskBlendFlags.Smoothness;
}
// 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;

return;
int batchIndex = 0;
int totalToDraw = m_NumResults;
HDRenderPipelineAsset hdrp = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
bool perChannelMask = hdrp.renderPipelineSettings.decalSettings.perChannelMask;
int shaderPass = perChannelMask ? (int)m_Material.GetFloat("_MaskBlendMode") : (int)Decal.MaskBlendFlags.Smoothness; // relies on the order shader passes are declared in decal.shader and decalUI.cs
cmd.DrawMeshInstanced(m_DecalMesh, 0, KeyMaterial, 0, m_DecalToWorld[batchIndex], kDrawIndexedBatchSize, m_PropertyBlock);
cmd.DrawMeshInstanced(m_DecalMesh, 0, m_Material, shaderPass, m_DecalToWorld[batchIndex], kDrawIndexedBatchSize, m_PropertyBlock);
totalToDraw -= kDrawIndexedBatchSize;
}

cmd.DrawMeshInstanced(m_DecalMesh, 0, KeyMaterial, 0, m_DecalToWorld[batchIndex], totalToDraw, m_PropertyBlock);
cmd.DrawMeshInstanced(m_DecalMesh, 0, m_Material, shaderPass, m_DecalToWorld[batchIndex], totalToDraw, m_PropertyBlock);
}
}

private float m_Blend = 0;
private float m_AlbedoContribution = 0;
private Vector4 m_BaseColor;
private Vector3 m_BlendParams;
TextureScaleBias m_Diffuse = new TextureScaleBias();
TextureScaleBias m_Normal = new TextureScaleBias();

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


matMask |= mapMask;
}
void ApplyBlendMask(inout float4 dst, inout int matMask, float2 texCoords, int mapMask, float blend, float lod)
// albedoBlend is overall decal blend combined with distance fade and albedo alpha
// decalBlend is decal blend with distance fade to be able to construct normal and mask blend if they come from mask map blue channel
// normalBlend is calculated in this function and used later to blend the normal
// blendParams are material settings to determing blend source and mode for normal and mask map
void ApplyBlendMask(inout float4 dbuffer2, inout float2 dbuffer3, inout int matMask, float2 texCoords, int mapMask, float albedoBlend, float lod, float decalBlend, inout float normalBlend, float3 blendParams) // too many blends!!!
src.z = src.w;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);
float maskBlend;
if (blendParams.x == 1.0f) // normal blend source is mask blue channel
normalBlend = src.z * decalBlend;
else
normalBlend = albedoBlend; // normal blend source is albedo alpha
if (blendParams.y == 1.0f) // mask blend source is mask blue channel
maskBlend = src.z * decalBlend;
else
maskBlend = albedoBlend; // mask blend siurce is albedo alpha
src.z = src.w; // remap so smoothness goes to blue and mask blend goes to alpha
src.w = maskBlend;
float4 dbuffer2Mask;
float2 dbuffer3Mask;
if (blendParams.z == 0)
{
dbuffer2Mask = float4(1, 1, 1, 1); // M, AO, S, S alpha
dbuffer3Mask = float2(1, 1); // M alpha, AO alpha
}
else if (blendParams.z == 1)
{
dbuffer2Mask = float4(1, 0, 0, 0); // M, _, _, _
dbuffer3Mask = float2(1, 0); // M alpha, _
}
else if (blendParams.z == 2)
{
dbuffer2Mask = float4(0, 1, 0, 0); // _, AO, _, _
dbuffer3Mask = float2(0, 1); // _, AO alpha
}
else if (blendParams.z == 3)
{
dbuffer2Mask = float4(1, 1, 0, 0); // M, AO, _, _
dbuffer3Mask = float2(1, 1); // M Alpha, AO alpha
}
else if (blendParams.z == 4)
{
dbuffer2Mask = float4(0, 0, 1, 1); // _, _, S, S alpha
dbuffer3Mask = float2(0, 0); // _, _
}
else if (blendParams.z == 5)
{
dbuffer2Mask = float4(1, 0, 1, 1); // M, _, S, S alpha
dbuffer3Mask = float2(1, 0); // M alpha, _
}
else if (blendParams.z == 6)
{
dbuffer2Mask = float4(0, 1, 1, 1); // _, AO, S, S alpha
dbuffer3Mask = float2(0, 1); // _, AO alpha
}
else if (blendParams.z == 7)
{
dbuffer2Mask = float4(1, 1, 1, 1); // M, AO, S, S alpha
dbuffer3Mask = float2(1, 1); // M alpha, AO alpha
}
dbuffer2.xyz = (dbuffer2Mask.xyz == 1) ? src.xyz * src.w + dbuffer2.xyz * (1.0f - src.w) : dbuffer2.xyz;
dbuffer2.w = (dbuffer2Mask.w == 1) ? dbuffer2.w * (1.0f - src.w) : dbuffer2.w;
dbuffer3.xy = (dbuffer3Mask.xy == 1) ? dbuffer3.xy * (1.0f - src.w) : dbuffer3.xy;
matMask |= mapMask;
}

DBuffer0 = float4(0.0f, 0.0f, 0.0f, 1.0f);
DBuffer1 = float4(0.5f, 0.5f, 0.5f, 1.0f);
DBuffer2 = float4(0.0f, 0.0f, 0.0f, 1.0f);
#ifdef _DECALS_4RT
DBuffer3 = float2(1.0f, 1.0f);
#else
float2 DBuffer3 = float2(1.0f, 1.0f);
#endif
#ifdef LIGHTLOOP_TILE_PASS
GetCountAndStart(posInput, LIGHTCATEGORY_DECAL, decalStart, decalCount);

float2 sampleMaskDdy = positionDSDdy.xz * decalData.maskScaleBias.xy;
float lodMask = ComputeTextureLOD(sampleMaskDdx, sampleMaskDdy, _DecalAtlasResolution);
float decalBlend = decalData.normalToWorld[0][3];
float albedoBlend = decalData.normalToWorld[0][3];
ApplyBlendDiffuse(DBuffer0, mask, sampleDiffuse, src, DBUFFERHTILEBIT_DIFFUSE, decalBlend, lodDiffuse, diffuseTextureBound);
alpha = alpha < decalBlend ? decalBlend : alpha; // use decal alpha if it is higher than transparent alpha
ApplyBlendDiffuse(DBuffer0, mask, sampleDiffuse, src, DBUFFERHTILEBIT_DIFFUSE, albedoBlend, lodDiffuse, diffuseTextureBound);
alpha = alpha < albedoBlend ? albedoBlend : alpha; // use decal alpha if it is higher than transparent alpha
float albedoContribution = decalData.normalToWorld[1][3];
if (albedoContribution == 0.0f)

float normalBlend = albedoBlend;
if ((decalData.maskScaleBias.x > 0) && (decalData.maskScaleBias.y > 0))
{
ApplyBlendMask(DBuffer2, DBuffer3, mask, sampleMask, DBUFFERHTILEBIT_MASK, albedoBlend, lodMask, decalData.normalToWorld[0][3], normalBlend, decalData.blendParams);
}
ApplyBlendNormal(DBuffer1, mask, sampleNormal, DBUFFERHTILEBIT_NORMAL, (float3x3)decalData.normalToWorld, decalBlend, lodNormal);
}
if ((decalData.maskScaleBias.x > 0) && (decalData.maskScaleBias.y > 0))
{
ApplyBlendMask(DBuffer2, mask, sampleMask, DBUFFERHTILEBIT_MASK, decalBlend, lodMask);
ApplyBlendNormal(DBuffer1, mask, sampleNormal, DBUFFERHTILEBIT_NORMAL, (float3x3)decalData.normalToWorld, normalBlend, lodNormal);
}
}
}

}
if(mask & DBUFFERHTILEBIT_MASK)
{
surfaceData.metallic = surfaceData.metallic * decalSurfaceData.mask.w + decalSurfaceData.mask.x;
surfaceData.ambientOcclusion = surfaceData.ambientOcclusion * decalSurfaceData.mask.w + decalSurfaceData.mask.y;
#ifdef _DECALS_4RT // only smoothness in 3RT mode
surfaceData.metallic = surfaceData.metallic * decalSurfaceData.MAOSBlend.x + decalSurfaceData.mask.x;
surfaceData.ambientOcclusion = surfaceData.ambientOcclusion * decalSurfaceData.MAOSBlend.y + decalSurfaceData.mask.y;
#endif
surfaceData.perceptualSmoothness = surfaceData.perceptualSmoothness * decalSurfaceData.mask.w + decalSurfaceData.mask.z;
}
}

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


public int drawDistance = 1000;
public int atlasWidth = 4096;
public int atlasHeight = 4096;
public bool perChannelMask = false;
}
}

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


// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
// decal 3RT or 4RT toggle
#pragma multi_compile _ _DECALS_4RT
//enable GPU instancing support
#pragma multi_compile_instancing

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


// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
// decal 3RT or 4RT toggle
#pragma multi_compile _ _DECALS_4RT
// enable GPU instancing
#pragma multi_compile_instancing

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


// Init precomputed texture
//-----------------------------------------------------------------------------
bool m_isInit;
public Lit() {}
public override void Build(HDRenderPipelineAsset hdAsset)

m_isInit = false;
}
public override void Cleanup()

m_isInit = false;
if (m_isInit)
return;
m_isInit = true;
}
public override void Bind()

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


// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
// decal 3RT or 4RT toggle
#pragma multi_compile _ _DECALS_4RT
//enable GPU instancing support
#pragma multi_compile_instancing

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


// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
// decal 3RT or 4RT toggle
#pragma multi_compile _ _DECALS_4RT
//enable GPU instancing support
#pragma multi_compile_instancing

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


#include "CoreRP/ShaderLibrary/CommonMaterial.hlsl"
#include "CoreRP/ShaderLibrary/EntityLighting.hlsl"
#include "CoreRP/ShaderLibrary/ImageBasedLighting.hlsl"
#include "../Sky/AtmosphericScattering/AtmosphericScattering.hlsl"
#include "HDRP/Lighting/AtmosphericScattering/AtmosphericScattering.hlsl"
// Guidelines for Material Keyword.
// There is a set of Material Keyword that a HD shaders must define (or not define). We call them system KeyWord.

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


public void RenderInit(FGDIndex index, CommandBuffer cmd)
{
if (m_isInit[(int)index])
// Here we have to test IsCreated because in some circumstances (like loading RenderDoc), the texture is internally destroyed but we don't know from C# side.
// In this case IsCreated will return false, allowing us to re-render the texture (setting the texture as current RT during DrawFullScreen will automatically re-create it internally)
if (m_isInit[(int)index] && m_PreIntegratedFGD[(int)index].IsCreated())
return;
using (new ProfilingSample(cmd, "PreIntegratedFGD Material Generation"))

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


// Init precomputed textures
//-----------------------------------------------------------------------------
bool m_isInit;
public StackLit() {}
public override void Build(HDRenderPipelineAsset hdAsset)

m_isInit = false;
}
public override void Cleanup()

m_isInit = false;
if (m_isInit)
return;
m_isInit = true;
}
public override void Bind()

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


_DetailNormalScale("DetailNormal Scale", Range(0.0, 2.0)) = 1
[HideInInspector] _DetailSmoothnessMapShow("DetailSmoothness Map Show", Float) = 0
_DetailSmoothnessMap("DetailSmoothness Map", 2D) = "grey" {} // Neutral is 0.5 for detail map
_DetailSmoothnessMap("DetailSmoothness Map", 2D) = "lineargrey" {} // Neutral is 0.5 for detail map
_DetailSmoothnessMapUV("DetailSmoothness Map UV", Float) = 0.0
_DetailSmoothnessMapUVLocal("DetailSmoothness Map UV Local", Float) = 0.0
_DetailSmoothnessMapChannel("DetailSmoothness Map Channel", Float) = 0.0

#pragma shader_feature _STACKLIT_DEBUG
// decal 3RT or 4RT toggle
#pragma multi_compile _ _DECALS_4RT
//enable GPU instancing support
#pragma multi_compile_instancing

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


#include "../DiffusionProfile/DiffusionProfile.hlsl"
// ----------------------------------------------------------------------------
// constant buffer declaration
// ----------------------------------------------------------------------------
CBUFFER_START(UnitySSSAndTransmissionParameters)
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.
// Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader.
uint _EnableSubsurfaceScattering; // Globally toggles subsurface and transmission scattering on/off
float _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
float _TransmissionFlags; // 1 bit/profile; 0 = regular, 1 = thin
// Old SSS Model >>>
float4 _HalfRcpVariancesAndWeights[DIFFUSION_PROFILE_COUNT][2]; // 2x Gaussians in RGB, A is interpolation weights
// <<< Old SSS Model
// Use float4 to avoid any packing issue between compute and pixel shaders
float4 _ThicknessRemaps[DIFFUSION_PROFILE_COUNT]; // R: start, G = end - start, BA unused
float4 _ShapeParams[DIFFUSION_PROFILE_COUNT]; // RGB = S = 1 / D, A = filter radius
float4 _TransmissionTintsAndFresnel0[DIFFUSION_PROFILE_COUNT]; // RGB = 1/4 * color, A = fresnel0
float4 _WorldScales[DIFFUSION_PROFILE_COUNT]; // X = meters per world unit; Y = world units per meter
CBUFFER_END
// ----------------------------------------------------------------------------
// helper functions
// ----------------------------------------------------------------------------

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


rendererSupportsLightProbeProxyVolumes = true,
rendererSupportsMotionVectors = true,
rendererSupportsReceiveShadows = false,
rendererSupportsReflectionProbes = true
rendererSupportsReflectionProbes = true,
rendererSupportsRendererPriority = true
};
Lightmapping.SetDelegate(GlobalIlluminationUtils.hdLightsDelegate);

var drawSettings = new DrawRendererSettings(hdCamera.camera, HDShaderPassNames.s_EmptyName)
{
rendererConfiguration = rendererConfiguration,
sorting = { flags = SortFlags.CommonTransparent }
sorting = { flags = SortFlags.CommonTransparent | SortFlags.RendererPriority }
};
for (int i = 0; i < passNames.Length; ++i)

// We need to copy depth buffer texture if we want to bind it at this stage
CopyDepthBufferIfNeeded(cmd);
bool rtCount4 = m_Asset.GetRenderPipelineSettings().decalSettings.perChannelMask;
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);
m_DbufferManager.ClearAndSetTargets(cmd, hdCamera, rtCount4, m_CameraDepthStencilBuffer);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Clear();

sorting = { flags = SortFlags.CommonOpaque }
};
drawSettings.SetShaderPassName(0, HDShaderPassNames.s_MeshDecalsName);
if(rtCount4)
{
drawSettings.SetShaderPassName(0, HDShaderPassNames.s_MeshDecalsMName);
drawSettings.SetShaderPassName(1, HDShaderPassNames.s_MeshDecalsAOName);
drawSettings.SetShaderPassName(2, HDShaderPassNames.s_MeshDecalsMAOName);
drawSettings.SetShaderPassName(3, HDShaderPassNames.s_MeshDecalsSName);
drawSettings.SetShaderPassName(4, HDShaderPassNames.s_MeshDecalsMSName);
drawSettings.SetShaderPassName(5, HDShaderPassNames.s_MeshDecalsAOSName);
drawSettings.SetShaderPassName(6, HDShaderPassNames.s_MeshDecalsMAOSName);
}
else
{
drawSettings.SetShaderPassName(0, HDShaderPassNames.s_MeshDecals3RTName);
}
renderContext.DrawRenderers(cullResults.visibleRenderers, ref drawSettings, filterRenderersSettings);
CoreUtils.SetKeyword(cmd, "_DECALS_4RT", m_Asset.GetRenderPipelineSettings().decalSettings.perChannelMask);
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

RenderTargetIdentifier source = m_CameraColorBuffer;
// For console we are not allowed to resize the windows, so don't use our hack.
bool tempHACK = !IsConsolePlatform();
// We also don't do the copy if viewport size and render texture size match.
bool viewportAndRTSameSize = (hdcamera.actualWidth == m_CameraColorBuffer.rt.width && hdcamera.actualHeight == m_CameraColorBuffer.rt.height);
bool tempHACK = !IsConsolePlatform() && !viewportAndRTSameSize;
if (tempHACK)
{

20
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";
public static readonly string s_MeshDecalsMStr = "DBufferMesh_M";
public static readonly string s_MeshDecalsSStr = "DBufferMesh_S";
public static readonly string s_MeshDecalsMSStr = "DBufferMesh_MS";
public static readonly string s_MeshDecalsAOStr = "DBufferMesh_AO";
public static readonly string s_MeshDecalsMAOStr = "DBufferMesh_MAO";
public static readonly string s_MeshDecalsAOSStr = "DBufferMesh_AOS";
public static readonly string s_MeshDecalsMAOSStr = "DBufferMesh_MAOS";
public static readonly string s_MeshDecals3RTStr = "DBufferMesh_3RT";
// ShaderPass name
public static readonly ShaderPassName s_EmptyName = new ShaderPassName(s_EmptyStr);
public static readonly ShaderPassName s_ForwardName = new ShaderPassName(s_ForwardStr);

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);
public static readonly ShaderPassName s_MeshDecalsMName = new ShaderPassName(s_MeshDecalsMStr);
public static readonly ShaderPassName s_MeshDecalsSName = new ShaderPassName(s_MeshDecalsSStr);
public static readonly ShaderPassName s_MeshDecalsMSName = new ShaderPassName(s_MeshDecalsMSStr);
public static readonly ShaderPassName s_MeshDecalsAOName = new ShaderPassName(s_MeshDecalsAOStr);
public static readonly ShaderPassName s_MeshDecalsMAOName = new ShaderPassName(s_MeshDecalsMAOStr);
public static readonly ShaderPassName s_MeshDecalsAOSName = new ShaderPassName(s_MeshDecalsAOSStr);
public static readonly ShaderPassName s_MeshDecalsMAOSName = new ShaderPassName(s_MeshDecalsMAOSStr);
public static readonly ShaderPassName s_MeshDecals3RTName = new ShaderPassName(s_MeshDecals3RTStr);
// Legacy name
public static readonly ShaderPassName s_AlwaysName = new ShaderPassName("Always");

10
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/Settings/FrameSettings.cs


{
List<DebugUI.Widget> widgets = new List<DebugUI.Widget>();
widgets.AddRange(
new DebugUI.Widget[]
new DebugUI.Widget[]
new DebugUI.Container
new DebugUI.Foldout
{
displayName = "Rendering Passes",
children =

new DebugUI.BoolField { displayName = "Enable Postprocess", getter = () => frameSettings.enablePostprocess, setter = value => frameSettings.enablePostprocess = value },
}
},
new DebugUI.Container
new DebugUI.Foldout
{
displayName = "Rendering Settings",
children =

new DebugUI.BoolField { displayName = "Enable MSAA", getter = () => frameSettings.enableMSAA, setter = value => frameSettings.enableMSAA = value },
}
},
new DebugUI.Container
new DebugUI.Foldout
{
displayName = "XR Settings",
children =

},
new DebugUI.Container
new DebugUI.Foldout
{
displayName = "Lighting Settings",
children =

81
com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset


m_Name: HDRenderPipelineResources
m_EditorClassIdentifier:
version: 1
defaultDiffuseMaterial: {fileID: 2100000, guid: 73c176f402d2c2f4d929aa5da7585d17,
type: 2}
defaultMirrorMaterial: {fileID: 2100000, guid: 6b17274157b33bc45b6a40e7d4ff51fe,
type: 2}
defaultDecalMaterial: {fileID: 2100000, guid: 500e733574922d04ea961553b1b26a63,
type: 2}
defaultDiffuseMaterial: {fileID: 2100000, guid: 73c176f402d2c2f4d929aa5da7585d17, type: 2}
defaultMirrorMaterial: {fileID: 2100000, guid: 6b17274157b33bc45b6a40e7d4ff51fe, type: 2}
defaultDecalMaterial: {fileID: 2100000, guid: 500e733574922d04ea961553b1b26a63, type: 2}
debugDisplayLatlongShader: {fileID: 4800000, guid: c1d1d149a043a5349ba367da6c2051ba,
type: 3}
debugViewMaterialGBufferShader: {fileID: 4800000, guid: 439949ea1bfa91b4ba0d04269fcde33d,
type: 3}
debugViewTilesShader: {fileID: 4800000, guid: c7c2bd17b06ceb4468e14081aaf1b96f,
type: 3}
debugFullScreenShader: {fileID: 4800000, guid: e874aca2df8300a488258738c31f85cf,
type: 3}
debugColorPickerShader: {fileID: 4800000, guid: 8137b807709e178498f22ed710864bb0,
type: 3}
debugDisplayLatlongShader: {fileID: 4800000, guid: c1d1d149a043a5349ba367da6c2051ba, type: 3}
debugViewMaterialGBufferShader: {fileID: 4800000, guid: 439949ea1bfa91b4ba0d04269fcde33d, type: 3}
debugViewTilesShader: {fileID: 4800000, guid: c7c2bd17b06ceb4468e14081aaf1b96f, type: 3}
debugFullScreenShader: {fileID: 4800000, guid: e874aca2df8300a488258738c31f85cf, type: 3}
debugColorPickerShader: {fileID: 4800000, guid: 8137b807709e178498f22ed710864bb0, type: 3}
deferredShader: {fileID: 4800000, guid: 00dd221e34a6ab349a1196b0f2fab693, type: 3}
colorPyramidCS: {fileID: 7200000, guid: 4e3267a1135742441a14298d8dcac04a, type: 3}
depthPyramidCS: {fileID: 7200000, guid: 64a553bb564274041906f78ffba955e4, type: 3}

clearDispatchIndirectShader: {fileID: 7200000, guid: fc1f553acb80a6446a32d33e403d0656,
type: 3}
buildDispatchIndirectShader: {fileID: 7200000, guid: 4eb1b418be7044c40bb5200496c50f14,
type: 3}
buildScreenAABBShader: {fileID: 7200000, guid: 728dce960f8a9c44bbc3abb3b851d8f6,
type: 3}
buildPerTileLightListShader: {fileID: 7200000, guid: 65af3444cbf4b3747a4dead7ee00cfee,
type: 3}
buildPerBigTileLightListShader: {fileID: 7200000, guid: 5ee1f9d6e09abe045b2f5e0b784b9072,
type: 3}
buildPerVoxelLightListShader: {fileID: 7200000, guid: 0bb1b7e0ddcd5c44baf3ddc7456eb196,
type: 3}
buildMaterialFlagsShader: {fileID: 7200000, guid: fb3eda953cd6e634e877fb777be2cd08,
type: 3}
deferredComputeShader: {fileID: 7200000, guid: 0b64f79746d2daf4198eaf6eab9af259,
type: 3}
screenSpaceShadowComputeShader: {fileID: 7200000, guid: 3e6900e06dc185a4380af4dacb4db0a4,
type: 3}
volumeVoxelizationCS: {fileID: 7200000, guid: c20b371db720da244b73830ec74a343a,
type: 3}
volumetricLightingCS: {fileID: 7200000, guid: b4901a10df2d1e24282725e9fbc77c97,
type: 3}
subsurfaceScatteringCS: {fileID: 7200000, guid: b06a7993621def248addd55d0fe931b1,
type: 3}
subsurfaceScattering: {fileID: 4800000, guid: 867b36db983aa0548889a66f8d685ff6,
type: 3}
clearDispatchIndirectShader: {fileID: 7200000, guid: fc1f553acb80a6446a32d33e403d0656, type: 3}
buildDispatchIndirectShader: {fileID: 7200000, guid: 4eb1b418be7044c40bb5200496c50f14, type: 3}
buildScreenAABBShader: {fileID: 7200000, guid: 728dce960f8a9c44bbc3abb3b851d8f6, type: 3}
buildPerTileLightListShader: {fileID: 7200000, guid: 65af3444cbf4b3747a4dead7ee00cfee, type: 3}
buildPerBigTileLightListShader: {fileID: 7200000, guid: 5ee1f9d6e09abe045b2f5e0b784b9072, type: 3}
buildPerVoxelLightListShader: {fileID: 7200000, guid: 0bb1b7e0ddcd5c44baf3ddc7456eb196, type: 3}
buildMaterialFlagsShader: {fileID: 7200000, guid: fb3eda953cd6e634e877fb777be2cd08, type: 3}
deferredComputeShader: {fileID: 7200000, guid: 0b64f79746d2daf4198eaf6eab9af259, type: 3}
screenSpaceShadowComputeShader: {fileID: 7200000, guid: 3e6900e06dc185a4380af4dacb4db0a4, type: 3}
volumeVoxelizationCS: {fileID: 7200000, guid: c20b371db720da244b73830ec74a343a, type: 3}
volumetricLightingCS: {fileID: 7200000, guid: b4901a10df2d1e24282725e9fbc77c97, type: 3}
subsurfaceScatteringCS: {fileID: 7200000, guid: b06a7993621def248addd55d0fe931b1, type: 3}
subsurfaceScattering: {fileID: 4800000, guid: 867b36db983aa0548889a66f8d685ff6, type: 3}
combineLighting: {fileID: 4800000, guid: 2e37131331fbdca449b1a2bc47a639ca, type: 3}
cameraMotionVectors: {fileID: 4800000, guid: 035941b63024d1943af48811c1db20d9, type: 3}
copyStencilBuffer: {fileID: 4800000, guid: 3d1574f1cdfa0ce4995f9bc79ed7f8ec, type: 3}

buildProbabilityTables: {fileID: 7200000, guid: b9f26cf340afe9145a699753531b2a4c,
type: 3}
computeGgxIblSampleData: {fileID: 7200000, guid: 764a24bb47ef5ba4781d9ae82ca07445,
type: 3}
buildProbabilityTables: {fileID: 7200000, guid: b9f26cf340afe9145a699753531b2a4c, type: 3}
computeGgxIblSampleData: {fileID: 7200000, guid: 764a24bb47ef5ba4781d9ae82ca07445, type: 3}
opaqueAtmosphericScattering: {fileID: 4800000, guid: 326059e48e5735e46a98047eff4f0295,
type: 3}
opaqueAtmosphericScattering: {fileID: 4800000, guid: 32f724728cf19904291226f239ec16f0, type: 3}
preIntegratedFGD_GGXDisneyDiffuse: {fileID: 4800000, guid: 123f13d52852ef547b2962de4bd9eaad,
type: 3}
preIntegratedFGD_CharlieClothLambert: {fileID: 4800000, guid: 3b3bf235775cf8b4baae7f3306787ab0,
type: 3}
preIntegratedFGD_GGXDisneyDiffuse: {fileID: 4800000, guid: 123f13d52852ef547b2962de4bd9eaad, type: 3}
preIntegratedFGD_CharlieClothLambert: {fileID: 4800000, guid: 3b3bf235775cf8b4baae7f3306787ab0, type: 3}
debugShadowMapShader: {fileID: 4800000, guid: ee25e539f5594f44085e0a9000c15d9b,
type: 3}
debugShadowMapShader: {fileID: 4800000, guid: ee25e539f5594f44085e0a9000c15d9b, type: 3}

94
com.unity.render-pipelines.high-definition/HDRP/ShaderVariables.hlsl


// ----------------------------------------------------------------------------
CBUFFER_START(UnityPerFrame)
float4 glstate_lightmodel_ambient;
float4 unity_AmbientSky;
float4 unity_AmbientEquator;
float4 unity_AmbientGround;
float4 unity_IndirectSpecColor;
#if !defined(USING_STEREO_MATRICES)
float4x4 glstate_matrix_projection;
float4x4 unity_MatrixV;
float4x4 unity_MatrixInvV;
float4x4 unity_MatrixVP;
float4 unity_StereoScaleOffset;
int unity_StereoEyeIndex;
#endif
float4 unity_ShadowColor;
CBUFFER_END
// ----------------------------------------------------------------------------
// These are the samplers available in the HDRenderPipeline.
// Avoid declaring extra samplers as they are 4x SGPR each on GCN.
SAMPLER(s_point_clamp_sampler);

// ----------------------------------------------------------------------------
// Define that before including all the sub systems ShaderVariablesXXX.hlsl files in order to include constant buffer properties.
#define SHADER_VARIABLES_INCLUDE_CB
CBUFFER_START(UnityPerView)
CBUFFER_START(UnityGlobal)
// ================================
// PER FRAME CONSTANTS
// ================================
#if !defined(USING_STEREO_MATRICES)
float4x4 glstate_matrix_projection;
float4x4 unity_MatrixV;
float4x4 unity_MatrixInvV;
float4x4 unity_MatrixVP;
float4 unity_StereoScaleOffset;
int unity_StereoEyeIndex;
#endif
// ================================
// PER VIEW CONSTANTS
// ================================
// TODO: all affine matrices should be 3x4.
float4x4 _ViewMatrix;
float4x4 _InvViewMatrix;

float4 _VBufferPrevUvScaleAndLimit;
float4 _VBufferPrevDepthEncodingParams;
float4 _VBufferPrevDepthDecodingParams;
CBUFFER_END
CBUFFER_START(UnityLightingParameters)
// Buffer pyramid
float4 _ColorPyramidSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size
float4 _DepthPyramidSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size
float4 _CameraMotionVectorsSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size
float4 _ColorPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused
float4 _DepthPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused
float4 _CameraMotionVectorsScale; // (x,y) = Screen Scale, z = lod count, w = unused
#include "Lighting/LightLoop/ShaderVariablesLightLoop.hlsl"
#include "Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.hlsl"
#include "Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl"
#include "Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl"
#include "Material/Decal/ShaderVariablesDecal.hlsl"
// Screen space lighting
float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback
float _SSReflectionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback
int _SSReflectionEnabled;
int _SSReflectionProjectionModel;
int _SSReflectionHiZRayMarchBehindObject;
int _SSRefractionHiZRayMarchBehindObject;
// Ambiant occlusion
float4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght
// Rough refraction texture
// Color pyramid (width, height, lodcount, Unused)
TEXTURE2D(_ColorPyramidTexture);
// Depth pyramid (width, height, lodcount, Unused)
TEXTURE2D(_DepthPyramidTexture);
// Ambient occlusion texture
TEXTURE2D(_AmbientOcclusionTexture);
TEXTURE2D(_CameraMotionVectorsTexture);
// Undef in order to include all textures and buffers declarations
#undef SHADER_VARIABLES_INCLUDE_CB
#include "Lighting/LightLoop/ShaderVariablesLightLoop.hlsl"
#include "Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl"
#include "Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.hlsl"
#include "Material/Decal/ShaderVariablesDecal.hlsl"
#include "Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl"
// Custom generated by HDRP, not from Unity Engine (passed in via HDCamera)
#if defined(USING_STEREO_MATRICES)

#endif
}
// Define Model Matrix Macro
// Note: In order to be able to define our macro to forbid usage of unity_ObjectToWorld/unity_WorldToObject
// We need to declare inline function. Using uniform directly mean they are expand with the macro
float4x4 GetUnityObjectToWorld() { return unity_ObjectToWorld; }
float4x4 GetUnityWorldToObject() { return unity_WorldToObject; }
#define UNITY_MATRIX_M ApplyCameraTranslationToMatrix(GetUnityObjectToWorld())
#define UNITY_MATRIX_I_M ApplyCameraTranslationToInverseMatrix(GetUnityWorldToObject())
#define unity_ObjectToWorld Use_Macro_UNITY_MATRIX_M_instead_of_unity_ObjectToWorld
#define unity_WorldToObject Use_Macro_UNITY_MATRIX_I_M_instead_of_unity_WorldToObject
// Define View/Projection matrix macro
// This define allow to tell to unity instancing that we will use our camera relative functions (ApplyCameraTranslationToMatrix and ApplyCameraTranslationToInverseMatrix) for the model view matrix
#define MODIFY_MATRIX_FOR_CAMERA_RELATIVE_RENDERING

10
com.unity.render-pipelines.high-definition/HDRP/ShaderVariablesFunctions.hlsl


return _ScreenToTargetScale.zw;
}
float4 SampleSkyTexture(float3 texCoord)
{
return SAMPLE_TEXTURECUBE(_SkyTexture, s_trilinear_clamp_sampler, texCoord);
}
float4 SampleSkyTexture(float3 texCoord, float lod)
{
return SAMPLE_TEXTURECUBE_LOD(_SkyTexture, s_trilinear_clamp_sampler, texCoord, lod);
}
#endif // UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED

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


#ifndef UNITY_SHADER_VARIABLES_MATRIX_DEFS_HDCAMERA_INCLUDED
#define UNITY_SHADER_VARIABLES_MATRIX_DEFS_HDCAMERA_INCLUDED
#define UNITY_MATRIX_M ApplyCameraTranslationToMatrix(unity_ObjectToWorld)
#define UNITY_MATRIX_I_M ApplyCameraTranslationToInverseMatrix(unity_WorldToObject)
#if defined(USING_STEREO_MATRICES)
#define UNITY_MATRIX_V _ViewMatrixStereo[unity_StereoEyeIndex]

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


#ifndef UNITY_SHADER_VARIABLES_MATRIX_DEFS_LEGACY_UNITY_INCLUDED
#define UNITY_SHADER_VARIABLES_MATRIX_DEFS_LEGACY_UNITY_INCLUDED
#define UNITY_MATRIX_M ApplyCameraTranslationToMatrix(unity_ObjectToWorld)
#define UNITY_MATRIX_I_M ApplyCameraTranslationToInverseMatrix(unity_WorldToObject)
#define UNITY_MATRIX_V unity_MatrixV
#define UNITY_MATRIX_I_V unity_MatrixInvV
#define UNITY_MATRIX_P OptimizeProjectionMatrix(glstate_matrix_projection)

183
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/LightWeightPBRSubShader.cs


}
};
Pass m_DepthShadowPass = new Pass()
{
Name = "",
PixelShaderSlots = new List<int>()
{
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
}
};
public string GetSubshader(IMasterNode inMasterNode, GenerationMode mode, List<string> sourceAssetDependencyPaths = null)
{
if (sourceAssetDependencyPaths != null)

mode,
materialOptions));
subShader.AppendLines(GetExtraPassesFromTemplate(extraTemplate, masterNode, pass, mode, materialOptions));
subShader.AppendLines(GetShaderPassFromTemplate(
extraTemplate,
masterNode,
m_DepthShadowPass,
mode,
materialOptions));
}
return subShader.ToString();

resultPass = resultPass.Replace("${PixelShader}", pixelShader.ToString());
resultPass = resultPass.Replace("${PixelShaderSurfaceInputs}", pixelShaderSurfaceInputs.ToString());
resultPass = resultPass.Replace("${PixelShaderSurfaceRemap}", pixelShaderSurfaceRemap.ToString());
return resultPass;
}
static string GetExtraPassesFromTemplate(string template, PBRMasterNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions)
{
// ----------------------------------------------------- //
// SETUP //
// ----------------------------------------------------- //
// -------------------------------------
// String builders
var dummyBuilder = new ShaderStringBuilder(0);
var shaderProperties = new PropertyCollector();
var functionBuilder = new ShaderStringBuilder(1);
var functionRegistry = new FunctionRegistry(functionBuilder);
var defines = new ShaderStringBuilder(2);
var graph = new ShaderStringBuilder(0);
var vertexDescriptionInputStruct = new ShaderStringBuilder(1);
var vertexDescriptionStruct = new ShaderStringBuilder(1);
var vertexDescriptionFunction = new ShaderStringBuilder(1);
var vertexInputStruct = new ShaderStringBuilder(1);
var vertexShader = new ShaderStringBuilder(2);
var vertexDescriptionInputs = new ShaderStringBuilder(2);
// -------------------------------------
// Get Slot and Node lists per stage
var vertexSlots = pass.VertexShaderSlots.Select(masterNode.FindSlot<MaterialSlot>).ToList();
var vertexNodes = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots);
// -------------------------------------
// Get requirements
var vertexRequirements = ShaderGraphRequirements.FromNodes(vertexNodes, ShaderStageCapability.Vertex, false);
var modelRequiements = ShaderGraphRequirements.none;
modelRequiements.requiresNormal |= m_VertexCoordinateSpace;
modelRequiements.requiresPosition |= m_VertexCoordinateSpace;
modelRequiements.requiresMeshUVs.Add(UVChannel.UV1);
// ----------------------------------------------------- //
// START SHADER GENERATION //
// ----------------------------------------------------- //
// -------------------------------------
// Calculate material options
var cullingBuilder = new ShaderStringBuilder(1);
materialOptions.GetCull(cullingBuilder);
// -------------------------------------
// Generate defines
if (masterNode.IsSlotConnected(PBRMasterNode.AlphaThresholdSlotId))
defines.AppendLine("#define _AlphaClip 1");
// ----------------------------------------------------- //
// START VERTEX DESCRIPTION //
// ----------------------------------------------------- //
// -------------------------------------
// Generate Input structure for Vertex Description function
// TODO - Vertex Description Input requirements are needed to exclude intermediate translation spaces
vertexDescriptionInputStruct.AppendLine("struct VertexDescriptionInputs");
using (vertexDescriptionInputStruct.BlockSemicolonScope())
{
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresNormal, InterpolatorType.Normal, vertexDescriptionInputStruct);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresTangent, InterpolatorType.Tangent, vertexDescriptionInputStruct);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresBitangent, InterpolatorType.BiTangent, vertexDescriptionInputStruct);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresViewDir, InterpolatorType.ViewDirection, vertexDescriptionInputStruct);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresPosition, InterpolatorType.Position, vertexDescriptionInputStruct);
if (vertexRequirements.requiresVertexColor)
vertexDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.VertexColor);
if (vertexRequirements.requiresScreenPosition)
vertexDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.ScreenPosition);
foreach (var channel in vertexRequirements.requiresMeshUVs.Distinct())
vertexDescriptionInputStruct.AppendLine("half4 {0};", channel.GetUVName());
}
// -------------------------------------
// Generate Output structure for Vertex Description function
GraphUtil.GenerateVertexDescriptionStruct(vertexDescriptionStruct, vertexSlots);
// -------------------------------------
// Generate Vertex Description function
GraphUtil.GenerateVertexDescriptionFunction(
masterNode.owner as AbstractMaterialGraph,
vertexDescriptionFunction,
functionRegistry,
shaderProperties,
mode,
vertexNodes,
vertexSlots);
// ----------------------------------------------------- //
// GENERATE VERTEX > PIXEL PIPELINE //
// ----------------------------------------------------- //
// -------------------------------------
// Generate Input structure for Vertex shader
GraphUtil.GenerateApplicationVertexInputs(vertexRequirements.Union(modelRequiements), vertexInputStruct);
// -------------------------------------
// Generate standard transformations
// This method ensures all required transform data is available in vertex and pixel stages
ShaderGenerator.GenerateStandardTransforms(
3,
10,
dummyBuilder,
vertexShader,
vertexDescriptionInputs,
dummyBuilder,
dummyBuilder,
dummyBuilder,
ShaderGraphRequirements.none,
ShaderGraphRequirements.none,
modelRequiements,
vertexRequirements,
CoordinateSpace.World);
// ----------------------------------------------------- //
// FINALIZE //
// ----------------------------------------------------- //
// -------------------------------------
// Combine Graph sections
graph.AppendLine(shaderProperties.GetPropertiesDeclaration(1));
graph.AppendLine(vertexDescriptionInputStruct.ToString());
graph.AppendLine(functionBuilder.ToString());
graph.AppendLine(vertexDescriptionStruct.ToString());
graph.AppendLine(vertexDescriptionFunction.ToString());
graph.AppendLine(vertexInputStruct.ToString());
// -------------------------------------
// Generate final subshader
var resultPass = template.Replace("${Culling}", cullingBuilder.ToString());
resultPass = resultPass.Replace("${Defines}", defines.ToString());
resultPass = resultPass.Replace("${Graph}", graph.ToString());
resultPass = resultPass.Replace("${VertexShader}", vertexShader.ToString());
resultPass = resultPass.Replace("${VertexShaderDescriptionInputs}", vertexDescriptionInputs.ToString());
return resultPass;
}

183
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGraph/LightWeightUnlitSubShader.cs


}
};
Pass m_DepthShadowPass = new Pass()
{
Name = "",
PixelShaderSlots = new List<int>()
{
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
},
VertexShaderSlots = new List<int>()
{
PBRMasterNode.PositionSlotId
}
};
public string GetSubshader(IMasterNode inMasterNode, GenerationMode mode, List<string> sourceAssetDependencyPaths = null)
{
if (sourceAssetDependencyPaths != null)

mode,
materialOptions));
subShader.AppendLines(GetExtraPassesFromTemplate(extraTemplate, masterNode, pass, mode, materialOptions));
subShader.AppendLines(GetShaderPassFromTemplate(
extraTemplate,
masterNode,
m_DepthShadowPass,
mode,
materialOptions));
}
return subShader.ToString();

resultPass = resultPass.Replace("${PixelShader}", pixelShader.ToString());
resultPass = resultPass.Replace("${PixelShaderSurfaceInputs}", pixelShaderSurfaceInputs.ToString());
resultPass = resultPass.Replace("${PixelShaderSurfaceRemap}", pixelShaderSurfaceRemap.ToString());
return resultPass;
}
static string GetExtraPassesFromTemplate(string template, UnlitMasterNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions)
{
// ----------------------------------------------------- //
// SETUP //
// ----------------------------------------------------- //
// -------------------------------------
// String builders
var dummyBuilder = new ShaderStringBuilder(0);
var shaderProperties = new PropertyCollector();
var functionBuilder = new ShaderStringBuilder(1);
var functionRegistry = new FunctionRegistry(functionBuilder);
var defines = new ShaderStringBuilder(2);
var graph = new ShaderStringBuilder(0);
var vertexDescriptionInputStruct = new ShaderStringBuilder(1);
var vertexDescriptionStruct = new ShaderStringBuilder(1);
var vertexDescriptionFunction = new ShaderStringBuilder(1);
var vertexInputStruct = new ShaderStringBuilder(1);
var vertexShader = new ShaderStringBuilder(2);
var vertexDescriptionInputs = new ShaderStringBuilder(2);
// -------------------------------------
// Get Slot and Node lists per stage
var vertexSlots = pass.VertexShaderSlots.Select(masterNode.FindSlot<MaterialSlot>).ToList();
var vertexNodes = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots);
// -------------------------------------
// Get requirements
var vertexRequirements = ShaderGraphRequirements.FromNodes(vertexNodes, ShaderStageCapability.Vertex, false);
var modelRequiements = ShaderGraphRequirements.none;
modelRequiements.requiresNormal |= m_VertexCoordinateSpace;
modelRequiements.requiresPosition |= m_VertexCoordinateSpace;
modelRequiements.requiresMeshUVs.Add(UVChannel.UV1);
// ----------------------------------------------------- //
// START SHADER GENERATION //
// ----------------------------------------------------- //
// -------------------------------------
// Calculate material options
var cullingBuilder = new ShaderStringBuilder(1);
materialOptions.GetCull(cullingBuilder);
// -------------------------------------
// Generate defines
if (masterNode.IsSlotConnected(PBRMasterNode.AlphaThresholdSlotId))
defines.AppendLine("#define _AlphaClip 1");
// ----------------------------------------------------- //
// START VERTEX DESCRIPTION //
// ----------------------------------------------------- //
// -------------------------------------
// Generate Input structure for Vertex Description function
// TODO - Vertex Description Input requirements are needed to exclude intermediate translation spaces
vertexDescriptionInputStruct.AppendLine("struct VertexDescriptionInputs");
using (vertexDescriptionInputStruct.BlockSemicolonScope())
{
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresNormal, InterpolatorType.Normal, vertexDescriptionInputStruct);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresTangent, InterpolatorType.Tangent, vertexDescriptionInputStruct);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresBitangent, InterpolatorType.BiTangent, vertexDescriptionInputStruct);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresViewDir, InterpolatorType.ViewDirection, vertexDescriptionInputStruct);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresPosition, InterpolatorType.Position, vertexDescriptionInputStruct);
if (vertexRequirements.requiresVertexColor)
vertexDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.VertexColor);
if (vertexRequirements.requiresScreenPosition)
vertexDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.ScreenPosition);
foreach (var channel in vertexRequirements.requiresMeshUVs.Distinct())
vertexDescriptionInputStruct.AppendLine("half4 {0};", channel.GetUVName());
}
// -------------------------------------
// Generate Output structure for Vertex Description function
GraphUtil.GenerateVertexDescriptionStruct(vertexDescriptionStruct, vertexSlots);
// -------------------------------------
// Generate Vertex Description function
GraphUtil.GenerateVertexDescriptionFunction(
masterNode.owner as AbstractMaterialGraph,
vertexDescriptionFunction,
functionRegistry,
shaderProperties,
mode,
vertexNodes,
vertexSlots);
// ----------------------------------------------------- //
// GENERATE VERTEX > PIXEL PIPELINE //
// ----------------------------------------------------- //
// -------------------------------------
// Generate Input structure for Vertex shader
GraphUtil.GenerateApplicationVertexInputs(vertexRequirements.Union(modelRequiements), vertexInputStruct);
// -------------------------------------
// Generate standard transformations
// This method ensures all required transform data is available in vertex and pixel stages
ShaderGenerator.GenerateStandardTransforms(
3,
10,
dummyBuilder,
vertexShader,
vertexDescriptionInputs,
dummyBuilder,
dummyBuilder,
dummyBuilder,
ShaderGraphRequirements.none,
ShaderGraphRequirements.none,
modelRequiements,
vertexRequirements,
CoordinateSpace.World);
// ----------------------------------------------------- //
// FINALIZE //
// ----------------------------------------------------- //
// -------------------------------------
// Combine Graph sections
graph.AppendLine(shaderProperties.GetPropertiesDeclaration(1));
graph.AppendLine(vertexDescriptionInputStruct.ToString());
graph.AppendLine(functionBuilder.ToString());
graph.AppendLine(vertexDescriptionStruct.ToString());
graph.AppendLine(vertexDescriptionFunction.ToString());
graph.AppendLine(vertexInputStruct.ToString());
// -------------------------------------
// Generate final subshader
var resultPass = template.Replace("${Culling}", cullingBuilder.ToString());
resultPass = resultPass.Replace("${Defines}", defines.ToString());
resultPass = resultPass.Replace("${Graph}", graph.ToString());
resultPass = resultPass.Replace("${VertexShader}", vertexShader.ToString());
resultPass = resultPass.Replace("${VertexShaderDescriptionInputs}", vertexDescriptionInputs.ToString());
return resultPass;
}

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


{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
// Interpolators defined by graph
${VertexOutputStruct}
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};

VertexDescription vd = PopulateVertexData(vdi);
v.vertex.xyz = vd.Position;
o.uv = uv1;
// Vertex shader outputs defined by graph
${VertexShaderOutputs}
float3 positionWS = TransformObjectToWorld(v.vertex.xyz);
float3 normalWS = TransformObjectToWorldDir(v.normal);

half4 ShadowPassFragment(VertexOutput IN) : SV_TARGET
{
UNITY_SETUP_INSTANCE_ID(IN);
// Pixel transformations performed by graph
${PixelShader}
SurfaceDescriptionInputs surfaceInput = (SurfaceDescriptionInputs)0;
// Surface description inputs defined by graph
${PixelShaderSurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float Alpha = 1;
float AlphaClipThreshold = 0;
// Surface description remap performed by graph
${PixelShaderSurfaceRemap}
#if _AlphaClip
clip(Alpha - AlphaClipThreshold);
#endif
return 0;
}

{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
// Interpolators defined by graph
${VertexOutputStruct}
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};

VertexDescription vd = PopulateVertexData(vdi);
v.vertex.xyz = vd.Position;
o.uv = uv1;
// Vertex shader outputs defined by graph
${VertexShaderOutputs}
o.clipPos = TransformObjectToHClip(v.vertex.xyz);
return o;
}

UNITY_SETUP_INSTANCE_ID(IN);
// Pixel transformations performed by graph
${PixelShader}
SurfaceDescriptionInputs surfaceInput = (SurfaceDescriptionInputs)0;
// Surface description inputs defined by graph
${PixelShaderSurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float Alpha = 1;
float AlphaClipThreshold = 0;
// Surface description remap performed by graph
${PixelShaderSurfaceRemap}
#if _AlphaClip
clip(Alpha - AlphaClipThreshold);
#endif
return 0;
}
ENDHLSL

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


{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
// Interpolators defined by graph
${VertexOutputStruct}
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};

VertexDescription vd = PopulateVertexData(vdi);
v.vertex.xyz = vd.Position;
o.uv = uv1;
// Vertex shader outputs defined by graph
${VertexShaderOutputs}
float3 positionWS = TransformObjectToWorld(v.vertex.xyz);
float3 normalWS = TransformObjectToWorldDir(v.normal);

half4 ShadowPassFragment(VertexOutput IN) : SV_TARGET
{
UNITY_SETUP_INSTANCE_ID(IN);
// Pixel transformations performed by graph
${PixelShader}
SurfaceDescriptionInputs surfaceInput = (SurfaceDescriptionInputs)0;
// Surface description inputs defined by graph
${PixelShaderSurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float Alpha = 1;
float AlphaClipThreshold = 0;
// Surface description remap performed by graph
${PixelShaderSurfaceRemap}
#if _AlphaClip
clip(Alpha - AlphaClipThreshold);
#endif
return 0;
}

{
float2 uv : TEXCOORD0;
float4 clipPos : SV_POSITION;
// Interpolators defined by graph
${VertexOutputStruct}
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};

VertexDescription vd = PopulateVertexData(vdi);
v.vertex.xyz = vd.Position;
o.uv = uv1;
// Vertex shader outputs defined by graph
${VertexShaderOutputs}
o.clipPos = TransformObjectToHClip(v.vertex.xyz);
return o;
}

UNITY_SETUP_INSTANCE_ID(IN);
// Pixel transformations performed by graph
${PixelShader}
SurfaceDescriptionInputs surfaceInput = (SurfaceDescriptionInputs)0;
// Surface description inputs defined by graph
${PixelShaderSurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float Alpha = 1;
float AlphaClipThreshold = 0;
// Surface description remap performed by graph
${PixelShaderSurfaceRemap}
#if _AlphaClip
clip(Alpha - AlphaClipThreshold);
#endif
return 0;
}
ENDHLSL

28
com.unity.shadergraph/CHANGELOG.md


This adds gradient functionality via two new nodes. The Sample Gradient node samples a gradient given a Time parameter. You can define this gradient on the Gradient slot control view. The Gradient Asset node defines a gradient that can be sampled by multiple Sample Gradient nodes using different Time parameters.
### Waveform nodes
![](.data/wave_form_nodes.png)
Math nodes now have a Waves category. The category has four different nodes: Triangle wave, Sawtooth wave, Square wave, and Noise Sine wave.
The Triangle, Sawtooth, and Square wave nodes output a waveform with a range of -1 to 1 over a period of 1.
The Noise Sine wave outputs a standard Sine wave with a range of -1 to 1 over a period of 2 * pi. For variance, random noise is added to the amplitude of the Sine wave, within a determined range.
## Normal Derive Nodes
![](.data/normal_derive_nodes.png)
There are two Normal Derive Nodes: `Normal From Height` and `Normal Reconstruct Z`.
`Normal From Height` uses Vector1 input to derive a normal map. `Normal Reconstruct Z` uses the X and Y components in Vector2 input to derive the proper Z value for a normal map.
### Sphere Mask Node
![](.data/sphereMask.png)

This adds a new node for LOD functionality on a Texture 2D Sample. Sample Texture 2D LOD uses the exact same input and output slots as Sample Texture 2D, but also includes an input for level of detail adjustments via a Vector1 slot.
### Texel Size Node
![](.data/texel_size_node.png)
With this node, you can get the special texture properties of a Texture 2D Asset via the `{texturename}_TexelSize` variable. Based on input from the Texture 2D Asset, the node outputs the width and height of the texel size in Vector1 format.
**Note:** Do not use the default input to reference your texture Asset. It makes your graph perform worse. Connect this node to a separate Texture 2D Asset node per image example.
### Show generated code
![](.data/show_generated_code.gif)

- Sub graphs are now suffixed with (sub), so you can tell them apart from other nodes.
- Boolean and Texture type properties now function correctly in sub-graphs.
- The preview of a node does not obstruct the selection outliner anymore.
- The Texture type default input now accepts render textures.
- The Dielectric Specular node no longer resets its control values.
- HD PBR subshader no longer duplicates surface description code into vertex shader.
- You can now copy, paste, and duplicate sub-graph nodes with vector type input ports.

- The Lightweight PBR subshader now normalizes normal, tangent, and view direction correctly.
- Texture 2D Array and Texture 3D nodes can no longer be used in the vertex shader.
- Shader graphs using alpha clip now generate correct depth and shadow passes.
- `Normal Create` node has been renamed to `Normal From Texture`.

2
com.unity.shadergraph/Editor/Data/Graphs/TextureShaderProperty.cs


public override string GetPropertyDeclarationString(string delimiter = ";")
{
return string.Format("TEXTURE2D({0}){1} SAMPLER(sampler{0}){1}", referenceName, delimiter);
return string.Format("TEXTURE2D({0}){1} SAMPLER(sampler{0}); float4 {0}_TexelSize{1}", referenceName, delimiter);
}
public override string GetPropertyAsArgumentString()

13
com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromTextureNode.cs


namespace UnityEditor.ShaderGraph
{
[Title("Artistic", "Normal", "Normal Create")]
public class NormalCreateNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IGenerateProperties, IMayRequireMeshUV
[FormerName("UnityEditor.ShaderGraph.NormalCreateNode")]
[Title("Artistic", "Normal", "Normal From Texture")]
public class NormalFromTextureNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IGenerateProperties, IMayRequireMeshUV
{
public const int TextureInputId = 0;
public const int UVInputId = 1;

const string k_StrengthInputName = "Strength";
const string k_OutputSlotName = "Out";
public NormalCreateNode()
public NormalFromTextureNode()
name = "Normal Create";
name = "Normal From Texture";
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Normal-Create-Node"; }
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Normal-From-Texture-Node"; }
return string.Format("Unity_NormalCreate_{0}", precision);
return string.Format("Unity_NormalFromTexture_{0}", precision);
}
public override bool hasPreview { get { return true; } }

10
com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DArrayNode.cs


public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector4MaterialSlot(OutputSlotRGBAId, kOutputSlotRGBAName, kOutputSlotRGBAName, SlotType.Output, Vector4.zero));
AddSlot(new Vector1MaterialSlot(OutputSlotRId, kOutputSlotRName, kOutputSlotRName, SlotType.Output, 0));
AddSlot(new Vector1MaterialSlot(OutputSlotGId, kOutputSlotGName, kOutputSlotGName, SlotType.Output, 0));
AddSlot(new Vector1MaterialSlot(OutputSlotBId, kOutputSlotBName, kOutputSlotBName, SlotType.Output, 0));
AddSlot(new Vector1MaterialSlot(OutputSlotAId, kOutputSlotAName, kOutputSlotAName, SlotType.Output, 0));
AddSlot(new Vector4MaterialSlot(OutputSlotRGBAId, kOutputSlotRGBAName, kOutputSlotRGBAName, SlotType.Output, Vector4.zero, ShaderStageCapability.Fragment));
AddSlot(new Vector1MaterialSlot(OutputSlotRId, kOutputSlotRName, kOutputSlotRName, SlotType.Output, 0, ShaderStageCapability.Fragment));
AddSlot(new Vector1MaterialSlot(OutputSlotGId, kOutputSlotGName, kOutputSlotGName, SlotType.Output, 0, ShaderStageCapability.Fragment));
AddSlot(new Vector1MaterialSlot(OutputSlotBId, kOutputSlotBName, kOutputSlotBName, SlotType.Output, 0, ShaderStageCapability.Fragment));
AddSlot(new Vector1MaterialSlot(OutputSlotAId, kOutputSlotAName, kOutputSlotAName, SlotType.Output, 0, ShaderStageCapability.Fragment));
AddSlot(new Texture2DArrayInputMaterialSlot(TextureInputId, kTextureInputName, kTextureInputName));
AddSlot(new Vector1MaterialSlot(IndexInputId, kIndexInputName, kIndexInputName, SlotType.Input, 0));
AddSlot(new UVMaterialSlot(UVInput, kUVInputName, kUVInputName, UVChannel.UV0));

2
com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture3DNode.cs


public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero));
AddSlot(new Vector4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero, ShaderStageCapability.Fragment));
AddSlot(new Texture3DInputMaterialSlot(TextureInputId, kTextureInputName, kTextureInputName));
AddSlot(new Vector3MaterialSlot(UVInput, kUVInputName, kUVInputName, SlotType.Input, Vector3.zero));
AddSlot(new SamplerStateMaterialSlot(SamplerInput, kSamplerInputName, kSamplerInputName, SlotType.Input));

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


if (combinedRequirements.requiresNormal > 0 || combinedRequirements.requiresBitangent > 0)
{
var name = preferredCoordinateSpace.ToVariableName(InterpolatorType.Normal);
vertexShader.AppendLine("float3 {0} = {1};", name, ConvertBetweenSpace("v.normal", CoordinateSpace.Object, preferredCoordinateSpace, InputType.Normal));
vertexShader.AppendLine("float3 {0} = normalize({1});", name, ConvertBetweenSpace("v.normal", CoordinateSpace.Object, preferredCoordinateSpace, InputType.Normal));
pixelShader.AppendLine("float3 {0} = normalize(IN.{0});", name);
pixelShader.AppendLine("float3 {0} = IN.{0};", name);
interpolatorIndex++;
}
}

if (combinedRequirements.requiresTangent > 0 || combinedRequirements.requiresBitangent > 0)
{
var name = preferredCoordinateSpace.ToVariableName(InterpolatorType.Tangent);
vertexShader.AppendLine("float3 {0} = {1};", name, ConvertBetweenSpace("v.tangent.xyz", CoordinateSpace.Object, preferredCoordinateSpace, InputType.Vector));
vertexShader.AppendLine("float3 {0} = normalize({1});", name, ConvertBetweenSpace("v.tangent.xyz", CoordinateSpace.Object, preferredCoordinateSpace, InputType.Vector));
if (graphModelRequirements.requiresTangent > 0 || graphModelRequirements.requiresBitangent > 0)
{
vertexOutputStruct.AppendLine("float3 {0} : TEXCOORD{1};", name, interpolatorIndex);

if (combinedRequirements.requiresBitangent > 0)
{
var name = preferredCoordinateSpace.ToVariableName(InterpolatorType.BiTangent);
vertexShader.AppendLine("float3 {0} = normalize(cross({1}, {2}.xyz) * {3});",
vertexShader.AppendLine("float3 {0} = cross({1}, {2}.xyz) * {3};",
name,
preferredCoordinateSpace.ToVariableName(InterpolatorType.Normal),
preferredCoordinateSpace.ToVariableName(InterpolatorType.Tangent),

if (combinedRequirements.requiresViewDir > 0)
{
var name = preferredCoordinateSpace.ToVariableName(InterpolatorType.ViewDirection);
const string worldSpaceViewDir = "SafeNormalize(_WorldSpaceCameraPos.xyz - mul(GetObjectToWorldMatrix(), float4(v.vertex.xyz, 1.0)).xyz)";
const string worldSpaceViewDir = "_WorldSpaceCameraPos.xyz - mul(GetObjectToWorldMatrix(), float4(v.vertex.xyz, 1.0)).xyz";
var preferredSpaceViewDir = ConvertBetweenSpace(worldSpaceViewDir, CoordinateSpace.World, preferredCoordinateSpace, InputType.Vector);
vertexShader.AppendLine("float3 {0} = {1};", name, preferredSpaceViewDir);
if (graphModelRequirements.requiresViewDir > 0)

pixelShader.AppendLine("float3 {0} = normalize(IN.{0});", name);
pixelShader.AppendLine("float3 {0} = IN.{0};", name);
interpolatorIndex++;
}
}

2
com.unity.shadergraph/Editor/Drawing/Views/Slots/TextureSlotControlView.cs


void OnValueChanged(ChangeEvent<Object> evt)
{
var texture = evt.newValue as Texture2D;
var texture = evt.newValue as Texture;
if (texture != m_Slot.texture)
{
m_Slot.owner.owner.owner.RegisterCompleteObjectUndo("Change Texture");

2
com.unity.shadergraph/Editor/Importers/ShaderGraphImporter.cs


namespace UnityEditor.ShaderGraph
{
[ScriptedImporter(16, ShaderGraphExtension)]
[ScriptedImporter(17, ShaderGraphExtension)]
public class ShaderGraphImporter : ScriptedImporter
{
public const string ShaderGraphExtension = "shadergraph";

6
com.unity.render-pipelines.high-definition/HDRP/Lighting/AtmosphericScattering/OpaqueAtmosphericScattering.shader


#pragma vertex Vert
#pragma fragment Frag
#pragma multi_compile _ DEBUG_DISPLAY
// #pragma enable_d3d11_debug_symbols

#include "../ShaderVariables.hlsl"
#include "AtmosphericScattering/AtmosphericScattering.hlsl"
#include "HDRP/ShaderVariables.hlsl"
#include "HDRP/Lighting/AtmosphericScattering/AtmosphericScattering.hlsl"
struct Attributes
{

2
com.unity.render-pipelines.high-definition/HDRP/Lighting/AtmosphericScattering/AtmosphericScattering.cs.meta


fileFormatVersion: 2
guid: 953beb541740ddc499d005ee80c9ff29
timeCreated: 1507718592
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2

8
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Icons.meta


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

188
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Gizmos.cs


using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering
{
partial class HDReflectionProbeEditor
{
static Mesh sphere;
static Material material;
[DrawGizmo(GizmoType.Active)]
static void RenderGizmo(ReflectionProbe reflectionProbe, GizmoType gizmoType)
{
var e = GetEditorFor(reflectionProbe);
if (e == null || !e.sceneViewEditing)
return;
var reflectionData = reflectionProbe.GetComponent<HDAdditionalReflectionData>();
switch (EditMode.editMode)
{
// Influence editing
case EditMode.SceneViewEditMode.ReflectionProbeBox:
Gizmos_Influence(reflectionProbe, reflectionData, e, true);
break;
// Influence fade editing
case EditMode.SceneViewEditMode.GridBox:
Gizmos_InfluenceFade(reflectionProbe, reflectionData, e, InfluenceType.Standard, true);
break;
// Influence normal fade editing
case EditMode.SceneViewEditMode.Collider:
Gizmos_InfluenceFade(reflectionProbe, reflectionData, e, InfluenceType.Normal, true);
break;
}
}
[DrawGizmo(GizmoType.Selected)]
static void DrawSelectedGizmo(ReflectionProbe reflectionProbe, GizmoType gizmoType)
{
var e = GetEditorFor(reflectionProbe);
if (e == null)
return;
var reflectionData = reflectionProbe.GetComponent<HDAdditionalReflectionData>();
Gizmos_CapturePoint(reflectionProbe, reflectionData, e);
if (!e.sceneViewEditing)
return;
//Gizmos_Influence(reflectionProbe, reflectionData, e, false);
Gizmos_InfluenceFade(reflectionProbe, reflectionData, null, InfluenceType.Standard, false);
Gizmos_InfluenceFade(reflectionProbe, reflectionData, null, InfluenceType.Normal, false);
DrawVerticalRay(reflectionProbe.transform);
}
static void Gizmos_InfluenceFade(ReflectionProbe p, HDAdditionalReflectionData a, HDReflectionProbeEditor e, InfluenceType type, bool isEdit)
{
var col = Gizmos.color;
var mat = Gizmos.matrix;
Gizmo6FacesBoxContained box;
Vector3 boxCenterOffset;
Vector3 boxSizeOffset;
float sphereRadiusOffset;
Color color;
switch (type)
{
default:
case InfluenceType.Standard:
{
box = e != null ? e.m_UIState.alternativeBoxBlendHandle : null;
boxCenterOffset = a.boxBlendCenterOffset;
boxSizeOffset = a.boxBlendSizeOffset;
sphereRadiusOffset = a.sphereBlendRadiusOffset;
color = isEdit ? k_GizmoThemeColorInfluenceBlendFace : k_GizmoThemeColorInfluenceBlend;
break;
}
case InfluenceType.Normal:
{
box = e != null ? e.m_UIState.alternativeBoxBlendNormalHandle : null;
boxCenterOffset = a.boxBlendNormalCenterOffset;
boxSizeOffset = a.boxBlendNormalSizeOffset;
sphereRadiusOffset = a.sphereBlendNormalRadiusOffset;
color = isEdit ? k_GizmoThemeColorInfluenceNormalBlendFace : k_GizmoThemeColorInfluenceNormalBlend;
break;
}
}
Gizmos.matrix = HDReflectionProbeEditorUtility.GetLocalSpace(p);
switch (a.influenceShape)
{
case ShapeType.Box:
{
Gizmos.color = color;
if (e != null) // e == null may occure when editor have still not been created at selection while the tool is not used for this part
{
box.DrawHull(isEdit);
}
else
{
if (isEdit)
Gizmos.DrawCube(p.center + boxCenterOffset, p.size + boxSizeOffset);
else
Gizmos.DrawWireCube(p.center + boxCenterOffset, p.size + boxSizeOffset);
}
break;
}
case ShapeType.Sphere:
{
Gizmos.color = color;
if (isEdit)
Gizmos.DrawSphere(p.center, a.influenceSphereRadius + sphereRadiusOffset);
else
Gizmos.DrawWireSphere(p.center, a.influenceSphereRadius + sphereRadiusOffset);
break;
}
}
Gizmos.matrix = mat;
Gizmos.color = col;
}
static void Gizmos_Influence(ReflectionProbe p, HDAdditionalReflectionData a, HDReflectionProbeEditor e, bool isEdit)
{
var col = Gizmos.color;
var mat = Gizmos.matrix;
Gizmos.matrix = HDReflectionProbeEditorUtility.GetLocalSpace(p);
switch (a.influenceShape)
{
case ShapeType.Box:
{
Gizmos.color = k_GizmoThemeColorExtentFace;
e.m_UIState.alternativeBoxInfluenceHandle.DrawHull(isEdit);
break;
}
case ShapeType.Sphere:
{
Gizmos.color = k_GizmoThemeColorExtentFace;
if (isEdit)
Gizmos.DrawSphere(p.center, a.influenceSphereRadius);
else
Gizmos.DrawWireSphere(p.center, a.influenceSphereRadius);
break;
}
}
Gizmos.matrix = mat;
Gizmos.color = col;
}
static void DrawVerticalRay(Transform transform)
{
Ray ray = new Ray(transform.position, Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Handles.color = Color.green;
Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual;
Handles.DrawLine(transform.position - Vector3.up * 0.5f, hit.point);
Handles.DrawWireDisc(hit.point, hit.normal, 0.5f);
Handles.color = Color.red;
Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater;
Handles.DrawLine(transform.position, hit.point);
Handles.DrawWireDisc(hit.point, hit.normal, 0.5f);
}
}
static void Gizmos_CapturePoint(ReflectionProbe p, HDAdditionalReflectionData a, HDReflectionProbeEditor e)
{
if(sphere == null)
{
sphere = Resources.GetBuiltinResource<Mesh>("New-Sphere.fbx");
}
if(material == null)
{
material = new Material(Shader.Find("Debug/ReflectionProbePreview"));
}
material.SetTexture("_Cubemap", p.texture);
material.SetPass(0);
Graphics.DrawMeshNow(sphere, Matrix4x4.TRS(p.transform.position, Quaternion.identity, Vector3.one));
}
}
}

11
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Gizmos.cs.meta


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

39
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Skin.cs


using System;
using UnityEditor.IMGUI.Controls;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering
{
partial class HDReflectionProbeEditor
{
internal static Color k_GizmoThemeColorExtent = new Color(255f / 255f, 229f / 255f, 148f / 255f, 80f / 255f);
internal static Color k_GizmoThemeColorExtentFace = new Color(255f / 255f, 229f / 255f, 148f / 255f, 45f / 255f);
internal static Color k_GizmoThemeColorInfluenceBlend = new Color(83f / 255f, 255f / 255f, 95f / 255f, 75f / 255f);
internal static Color k_GizmoThemeColorInfluenceBlendFace = new Color(83f / 255f, 255f / 255f, 95f / 255f, 17f / 255f);
internal static Color k_GizmoThemeColorInfluenceNormalBlend = new Color(0f / 255f, 229f / 255f, 255f / 255f, 80f / 255f);
internal static Color k_GizmoThemeColorInfluenceNormalBlendFace = new Color(0f / 255f, 229f / 255f, 255f / 255f, 36f / 255f);
internal static Color k_GizmoThemeColorProjection = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static Color k_GizmoThemeColorProjectionFace = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static Color k_GizmoThemeColorDisabled = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static Color k_GizmoThemeColorDisabledFace = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static readonly Color[][] k_handlesColor = new Color[][]
{
new Color[]
{
Color.red,
Color.green,
Color.blue
},
new Color[]
{
new Color(.5f, 0f, 0f, 1f),
new Color(0f, .5f, 0f, 1f),
new Color(0f, 0f, .5f, 1f)
}
};
}
}

11
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Skin.cs.meta


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

8
com.unity.render-pipelines.high-definition/HDRP/Lighting/AtmosphericScattering.meta


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

68
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl


#ifdef SHADER_VARIABLES_INCLUDE_CB
#define MAX_ENV2D_LIGHT 32
uint _DirectionalLightCount;
uint _PunctualLightCount;
uint _AreaLightCount;
uint _EnvLightCount;
uint _EnvProxyCount;
int _EnvLightSkyEnabled; // TODO: make it a bool
uint _NumTileFtplX;
uint _NumTileFtplY;
// these uniforms are only needed for when OPAQUES_ONLY is NOT defined
// but there's a problem with our front-end compilation of compute shaders with multiple kernels causing it to error
//#ifdef USE_CLUSTERED_LIGHTLIST
float4x4 g_mInvScrProjection; // TODO: remove, unused in HDRP
float g_fClustScale;
float g_fClustBase;
float g_fNearPlane;
float g_fFarPlane;
int g_iLog2NumClusters; // We need to always define these to keep constant buffer layouts compatible
uint g_isLogBaseBufferEnabled;
//#endif
//#ifdef USE_CLUSTERED_LIGHTLIST
uint _NumTileClusteredX;
uint _NumTileClusteredY;
float4x4 _Env2DCaptureVP[MAX_ENV2D_LIGHT];
#else
#include "HDRP/Lighting/LightDefinition.cs.hlsl"
#include "CoreRP/Shadow/ShadowBase.cs.hlsl"
StructuredBuffer<uint> g_vLightListGlobal; // don't support Buffer yet in unity
StructuredBuffer<uint> g_vLayeredOffsetsBuffer; // don't support Buffer yet in unity
StructuredBuffer<float> g_logBaseBuffer; // don't support Buffer yet in unity
//#endif
#ifdef USE_INDIRECT
StructuredBuffer<uint> g_TileFeatureFlags;
#endif
StructuredBuffer<DirectionalLightData> _DirectionalLightDatas;
StructuredBuffer<LightData> _LightDatas;
StructuredBuffer<EnvLightData> _EnvLightDatas;
StructuredBuffer<ShadowData> _ShadowDatas;
// Used by directional and spot lights
TEXTURE2D_ARRAY(_CookieTextures);
// Used by point lights
TEXTURECUBE_ARRAY_ABSTRACT(_CookieCubeTextures);
// Use texture array for reflection (or LatLong 2D array for mobile)
TEXTURECUBE_ARRAY_ABSTRACT(_EnvCubemapTextures);
TEXTURE2D_ARRAY(_Env2DTextures);
// XRTODO: Need to stereo-ize access
TEXTURE2D(_DeferredShadowTexture);
#endif

9
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl.meta


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

8
com.unity.render-pipelines.high-definition/HDRP/Lighting/ScreenSpaceLighting.meta


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

5
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/ShaderVariablesDecal.hlsl


#ifdef SHADER_VARIABLES_INCLUDE_CB
uint _EnableDBuffer;
float2 _DecalAtlasResolution;
#else
#endif

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


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

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


#ifdef SHADER_VARIABLES_INCLUDE_CB
#include "HDRP/Material/DiffusionProfile/DiffusionProfileSettings.cs.hlsl"
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.
// Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader.
uint _EnableSubsurfaceScattering; // Globally toggles subsurface and transmission scattering on/off
float _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
float _TransmissionFlags; // 1 bit/profile; 0 = regular, 1 = thin
// Old SSS Model >>>
float4 _HalfRcpVariancesAndWeights[DIFFUSION_PROFILE_COUNT][2]; // 2x Gaussians in RGB, A is interpolation weights
// <<< Old SSS Model
// Use float4 to avoid any packing issue between compute and pixel shaders
float4 _ThicknessRemaps[DIFFUSION_PROFILE_COUNT]; // R: start, G = end - start, BA unused
float4 _ShapeParams[DIFFUSION_PROFILE_COUNT]; // RGB = S = 1 / D, A = filter radius
float4 _TransmissionTintsAndFresnel0[DIFFUSION_PROFILE_COUNT]; // RGB = 1/4 * color, A = fresnel0
float4 _WorldScales[DIFFUSION_PROFILE_COUNT]; // X = meters per world unit; Y = world units per meter
#else
#endif

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


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

3
com.unity.shadergraph/.data/normal_derive_nodes.PNG


version https://git-lfs.github.com/spec/v1
oid sha256:2c14e830338ddf74ff5479bb56e8aa4a4d0f9274e96390d9897d97228f281d8e
size 54715

3
com.unity.shadergraph/.data/texel_size_node.PNG


version https://git-lfs.github.com/spec/v1
oid sha256:7502c3fdf5b201b4460a317b577d4e0490e500a6926ba35c53e236afa15ab76a
size 82906

436
com.unity.shadergraph/.data/wave_form_nodes.PNG

之前 之后
宽度: 1187  |  高度: 747  |  大小: 85 KiB

131
com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromHeightNode.cs


using System;
using System.Collections.Generic;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
public enum OutputSpace
{
Tangent,
World
};
[Title("Artistic", "Normal", "Normal From Height")]
public class NormalFromHeightNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireTangent, IMayRequireBitangent, IMayRequireNormal, IMayRequirePosition
{
public NormalFromHeightNode()
{
name = "Normal From Height";
UpdateNodeAfterDeserialization();
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Normal-From-Heightmap-Node"; }
}
[SerializeField]
private OutputSpace m_OutputSpace = OutputSpace.Tangent;
[EnumControl("Output Space")]
public OutputSpace outputSpace
{
get { return m_OutputSpace; }
set
{
if (m_OutputSpace == value)
return;
m_OutputSpace = value;
Dirty(ModificationScope.Graph);
}
}
const int InputSlotId = 0;
const int OutputSlotId = 1;
const string kInputSlotName = "In";
const string kOutputSlotName = "Out";
public override bool hasPreview
{
get { return true; }
}
string GetFunctionName()
{
return string.Format("Unity_NormalFromHeight_{0}", outputSpace.ToString());
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector1MaterialSlot(InputSlotId, kInputSlotName, kInputSlotName, SlotType.Input, 0));
AddSlot(new Vector3MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { InputSlotId, OutputSlotId });
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
var sb = new ShaderStringBuilder();
var inputValue = GetSlotValue(InputSlotId, generationMode);
var outputValue = GetSlotValue(OutputSlotId, generationMode);
sb.AppendLine("{0} {1};", FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision), GetVariableNameForSlot(OutputSlotId));
sb.AppendLine("{0}3x3 _{1}_TangentMatrix = {0}3x3(IN.{2}SpaceTangent, IN.{2}SpaceBiTangent, IN.{2}SpaceNormal);", precision, GetVariableNameForNode(), NeededCoordinateSpace.World.ToString());
sb.AppendLine("{0}3 _{1}_Position = IN.{2}SpacePosition;", precision, GetVariableNameForNode(), NeededCoordinateSpace.World.ToString());
sb.AppendLine("{0}({1},_{2}_Position,_{2}_TangentMatrix, {3});", GetFunctionName(), inputValue, GetVariableNameForNode(), outputValue);
visitor.AddShaderChunk(sb.ToString(), false);
}
public void GenerateNodeFunction(FunctionRegistry registry, GraphContext graphContext, GenerationMode generationMode)
{
registry.ProvideFunction(GetFunctionName(), s =>
{
s.AppendLine("void {0}({2} In, {1}3 Position, {1}3x3 TangentMatrix, out {3} Out)",
GetFunctionName(),
precision,
FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType.ToString(precision),
FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision));
using (s.BlockScope())
{
s.AppendLine("{0}3 worldDirivativeX = ddx(Position * 100);", precision);
s.AppendLine("{0}3 worldDirivativeY = ddy(Position * 100);", precision);
s.AppendNewLine();
s.AppendLine("{0}3 crossX = cross(TangentMatrix[2].xyz, worldDirivativeX);", precision);
s.AppendLine("{0}3 crossY = cross(TangentMatrix[2].xyz, worldDirivativeY);", precision);
s.AppendLine("{0}3 d = abs(dot(crossY, worldDirivativeX));", precision);
s.AppendLine("{0}3 inToNormal = ((((In + ddx(In)) - In) * crossY) + (((In + ddy(In)) - In) * crossX)) * sign(d);", precision);
s.AppendLine("inToNormal.y *= -1.0;", precision);
s.AppendNewLine();
s.AppendLine("Out = normalize((d * TangentMatrix[2].xyz) - inToNormal);", precision);
if(outputSpace == OutputSpace.Tangent)
s.AppendLine("Out = TransformWorldToTangent(Out, TangentMatrix);");
}
});
}
public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability)
{
return NeededCoordinateSpace.World;
}
public NeededCoordinateSpace RequiresBitangent(ShaderStageCapability stageCapability)
{
return NeededCoordinateSpace.World;
}
public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability)
{
return NeededCoordinateSpace.World;
}
public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability)
{
return NeededCoordinateSpace.World;
}
}
}

11
com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromHeightNode.cs.meta


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

39
com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalReconstructZNode.cs


using System.Reflection;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Title("Artistic", "Normal", "Normal Reconstruct Z")]
public class NormalReconstructZNode : CodeFunctionNode
{
public NormalReconstructZNode()
{
name = "Normal Reconstruct Z";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Normal-Reconstruct-Z-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("NormalReconstructZ", BindingFlags.Static | BindingFlags.NonPublic);
}
static string NormalReconstructZ(
[Slot(0, Binding.None)] Vector2 In,
[Slot(2, Binding.None, ShaderStageCapability.Fragment)] out Vector3 Out)
{
Out = Vector3.zero;
return
@"
{
{precision} reconstructZ = sqrt(1 - ( In.x * In.x + In.y * In.y));
{precision}3 normalVector = {precision}3(In.x, In.y, reconstructZ);
Out = normalize(normalVector);
}";
}
}
}

11
com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalReconstructZNode.cs.meta


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

52
com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/TexelSizeNode.cs


using System.Linq;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{
[Title("Input", "Texture", "Texel Size")]
public class Texture2DPropertiesNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequireMeshUV
{
public const int OutputSlotWId = 0;
public const int OutputSlotHId = 2;
public const int TextureInputId = 1;
const string kOutputSlotWName = "Width";
const string kOutputSlotHName = "Height";
const string kTextureInputName = "Texture";
public override bool hasPreview { get { return false; } }
public Texture2DPropertiesNode()
{
name = "Texel Size";
UpdateNodeAfterDeserialization();
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Texel-Size-Node"; }
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector1MaterialSlot(OutputSlotWId, kOutputSlotWName, kOutputSlotWName, SlotType.Output, 0, ShaderStageCapability.Fragment));
AddSlot(new Vector1MaterialSlot(OutputSlotHId, kOutputSlotHName, kOutputSlotHName, SlotType.Output, 0, ShaderStageCapability.Fragment));
AddSlot(new Texture2DInputMaterialSlot(TextureInputId, kTextureInputName, kTextureInputName));
RemoveSlotsNameNotMatching(new[] { OutputSlotWId, OutputSlotHId, TextureInputId });
}
// Node generations
public virtual void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
visitor.AddShaderChunk(string.Format("{0}2 {1} = {2}_TexelSize.z;", precision, GetVariableNameForSlot(OutputSlotWId), GetSlotValue(TextureInputId, generationMode)), true);
visitor.AddShaderChunk(string.Format("{0}2 {1} = {2}_TexelSize.w;", precision, GetVariableNameForSlot(OutputSlotHId), GetSlotValue(TextureInputId, generationMode)), true);
}
public bool RequiresMeshUV(UVChannel channel, ShaderStageCapability stageCapability)
{
return true;
}
}
}

11
com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/TexelSizeNode.cs.meta


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

8
com.unity.shadergraph/Editor/Data/Nodes/Math/Wave.meta


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

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

正在加载...
取消
保存