diff --git a/TestProjects/HDRP_DXR_Tests/ProjectSettings/HDRPProjectSettings.asset b/TestProjects/HDRP_DXR_Tests/ProjectSettings/HDRPProjectSettings.asset index 4934a5a49d6..e536bbd68e8 100644 --- a/TestProjects/HDRP_DXR_Tests/ProjectSettings/HDRPProjectSettings.asset +++ b/TestProjects/HDRP_DXR_Tests/ProjectSettings/HDRPProjectSettings.asset @@ -22,4 +22,4 @@ MonoBehaviour: m_WizardActiveTab: 0 m_WizardNeedRestartAfterChangingToDX12: 0 m_WizardNeedToRunFixAllAgainAfterDomainReload: 0 - m_LastMaterialVersion: 3 + m_LastMaterialVersion: 4 diff --git a/TestProjects/HDRP_HybridTests/ProjectSettings/HDRPProjectSettings.asset b/TestProjects/HDRP_HybridTests/ProjectSettings/HDRPProjectSettings.asset index fac89863d71..790b9e50395 100644 --- a/TestProjects/HDRP_HybridTests/ProjectSettings/HDRPProjectSettings.asset +++ b/TestProjects/HDRP_HybridTests/ProjectSettings/HDRPProjectSettings.asset @@ -22,4 +22,4 @@ MonoBehaviour: m_WizardActiveTab: 0 m_WizardNeedRestartAfterChangingToDX12: 0 m_WizardNeedToRunFixAllAgainAfterDomainReload: 0 - m_LastMaterialVersion: 3 + m_LastMaterialVersion: 4 diff --git a/TestProjects/HDRP_PerformanceTests/ProjectSettings/HDRPProjectSettings.asset b/TestProjects/HDRP_PerformanceTests/ProjectSettings/HDRPProjectSettings.asset index 6a7a46a27ef..474a353f44b 100644 --- a/TestProjects/HDRP_PerformanceTests/ProjectSettings/HDRPProjectSettings.asset +++ b/TestProjects/HDRP_PerformanceTests/ProjectSettings/HDRPProjectSettings.asset @@ -22,4 +22,4 @@ MonoBehaviour: m_WizardActiveTab: 0 m_WizardNeedRestartAfterChangingToDX12: 0 m_WizardNeedToRunFixAllAgainAfterDomainReload: 0 - m_LastMaterialVersion: 3 + m_LastMaterialVersion: 4 diff --git a/TestProjects/HDRP_RuntimeTests/ProjectSettings/HDRPProjectSettings.asset b/TestProjects/HDRP_RuntimeTests/ProjectSettings/HDRPProjectSettings.asset index f6d78544fab..c3b1e121026 100644 --- a/TestProjects/HDRP_RuntimeTests/ProjectSettings/HDRPProjectSettings.asset +++ b/TestProjects/HDRP_RuntimeTests/ProjectSettings/HDRPProjectSettings.asset @@ -22,4 +22,4 @@ MonoBehaviour: m_WizardActiveTab: 0 m_WizardNeedRestartAfterChangingToDX12: 0 m_WizardNeedToRunFixAllAgainAfterDomainReload: 0 - m_LastMaterialVersion: 3 + m_LastMaterialVersion: 4 diff --git a/TestProjects/HDRP_Tests/ProjectSettings/HDRPProjectSettings.asset b/TestProjects/HDRP_Tests/ProjectSettings/HDRPProjectSettings.asset index 6a7a46a27ef..474a353f44b 100644 --- a/TestProjects/HDRP_Tests/ProjectSettings/HDRPProjectSettings.asset +++ b/TestProjects/HDRP_Tests/ProjectSettings/HDRPProjectSettings.asset @@ -22,4 +22,4 @@ MonoBehaviour: m_WizardActiveTab: 0 m_WizardNeedRestartAfterChangingToDX12: 0 m_WizardNeedToRunFixAllAgainAfterDomainReload: 0 - m_LastMaterialVersion: 3 + m_LastMaterialVersion: 4 diff --git a/TestProjects/SRP_SmokeTest/ProjectSettings/HDRPProjectSettings.asset b/TestProjects/SRP_SmokeTest/ProjectSettings/HDRPProjectSettings.asset index 0594e99c931..1bcee60c90c 100644 --- a/TestProjects/SRP_SmokeTest/ProjectSettings/HDRPProjectSettings.asset +++ b/TestProjects/SRP_SmokeTest/ProjectSettings/HDRPProjectSettings.asset @@ -18,4 +18,4 @@ MonoBehaviour: m_ProjectSettingFolderPath: HDRPDefaultResources m_WizardPopupAtStart: 0 m_WizardActiveTab: 0 - m_LastMaterialVersion: 2 + m_LastMaterialVersion: 4 diff --git a/TestProjects/VisualEffectGraph/ProjectSettings/HDRPProjectSettings.asset b/TestProjects/VisualEffectGraph/ProjectSettings/HDRPProjectSettings.asset index 5e92057a1f7..1a57960fd77 100644 --- a/TestProjects/VisualEffectGraph/ProjectSettings/HDRPProjectSettings.asset +++ b/TestProjects/VisualEffectGraph/ProjectSettings/HDRPProjectSettings.asset @@ -21,4 +21,4 @@ MonoBehaviour: m_WizardActiveTab: 0 m_WizardNeedRestartAfterChangingToDX12: 0 m_WizardNeedToRunFixAllAgainAfterDomainReload: 0 - m_LastMaterialVersion: 3 + m_LastMaterialVersion: 4 diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs index 3724aad3c4d..1af4d13b30b 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs @@ -3,7 +3,9 @@ using System.Linq; using System.Reflection; using UnityEngine; +using UnityEditor.ShaderGraph; using UnityEngine.Rendering.HighDefinition; +using UnityEditor.Rendering.HighDefinition.ShaderGraph; // Material property names using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; @@ -129,7 +131,7 @@ static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAsse AssetVersion assetVersion = null; foreach (var subAsset in assetVersions) { - if (subAsset.GetType() == typeof(AssetVersion)) + if (subAsset != null && subAsset.GetType() == typeof(AssetVersion)) { assetVersion = subAsset as AssetVersion; break; @@ -190,6 +192,7 @@ static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAsse StencilRefactor, ZWriteForTransparent, RenderQueueUpgrade, + ShaderGraphStack, }; #region Migrations @@ -337,6 +340,59 @@ static void RenderQueueUpgrade(Material material, HDShaderUtils.ShaderID id) HDShaderUtils.ResetMaterialKeywords(material); } + // properties in this tab should be properties from Unlit or PBR cross pipeline shader + // that are suppose to be synchronize with the Material during upgrade + readonly static string[] s_ShadergraphStackFloatPropertiesToSynchronize = { + "_SurfaceType", + "_BlendMode", + "_DstBlend", + "_SrcBlend", + "_AlphaDstBlend", + "_AlphaSrcBlend", + "_AlphaCutoff", + "_AlphaCutoffEnable", + "_DoubleSidedEnable", + "_DoubleSidedNormalMode", + "_ZWrite", // Needed to fix older bug + "_RenderQueueType" // Needed as seems to not reset correctly + }; + + static void ShaderGraphStack(Material material, HDShaderUtils.ShaderID id) + { + Shader shader = material.shader; + + if (shader.IsShaderGraph()) + { + if (shader.TryGetMetadataOfType(out var obj)) + { + // Material coming from old cross pipeline shader (Unlit and PBR) are not synchronize correctly with their + // shader graph. This code below ensure it is + if (obj.migrateFromOldCrossPipelineSG) // come from PBR or Unlit cross pipeline SG? + { + var defaultProperties = new Material(material.shader); + + foreach (var floatToSync in s_ShadergraphStackFloatPropertiesToSynchronize) + if (material.HasProperty(floatToSync)) + material.SetFloat(floatToSync, defaultProperties.GetFloat(floatToSync)); + + defaultProperties = null; + + // Postprocess now that material is correctly sync + bool isTransparent = material.HasProperty("_SurfaceType") && material.GetFloat("_SurfaceType") > 0.0f; + bool alphaTest = material.HasProperty("_AlphaCutoffEnable") && material.GetFloat("_AlphaCutoffEnable") > 0.0f; + + material.renderQueue = isTransparent ? (int)HDRenderQueue.Priority.Transparent : + alphaTest ? (int)HDRenderQueue.Priority.OpaqueAlphaTest : (int)HDRenderQueue.Priority.Opaque; + + material.SetFloat("_RenderQueueType", isTransparent ? (float)HDRenderQueue.RenderQueueType.Transparent : (float)HDRenderQueue.RenderQueueType.Opaque); + } + + } + } + + HDShaderUtils.ResetMaterialKeywords(material); + } + #region Serialization_API //Methods in this region interact on the serialized material //without filtering on what used shader knows diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ShaderGraphMaterialsUpdater.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ShaderGraphMaterialsUpdater.cs index 14e5443ecf8..e8ea081b829 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ShaderGraphMaterialsUpdater.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ShaderGraphMaterialsUpdater.cs @@ -26,7 +26,7 @@ static void OnShaderGraphSaved(Shader shader, object saveContext) if (!(saveContext is HDSaveContext hdSaveContext)) return; - HDRenderPipeline.currentPipeline.ResetPathTracing(); + HDRenderPipeline.currentPipeline?.ResetPathTracing(); if (!hdSaveContext.updateMaterials) return; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/CreateDecalShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/CreateDecalShaderGraph.cs index 70548cdd527..3c5821bfb9a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/CreateDecalShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/CreateDecalShaderGraph.cs @@ -1,13 +1,33 @@ +using System; using UnityEditor.ShaderGraph; -namespace UnityEditor.Rendering.HighDefinition +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { static class CreateDecalShaderGraph { - [MenuItem("Assets/Create/Shader/HDRP/Decal Graph", false, 208)] - public static void CreateMaterialGraph() + [MenuItem("Assets/Create/Shader/HDRP/Decal Shader Graph", false, 208)] + public static void CreateDecalGraph() { - GraphUtil.CreateNewGraph(new DecalMasterNode()); + var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); + target.TrySetActiveSubTarget(typeof(DecalSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.NormalAlpha, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Smoothness, + HDBlockFields.SurfaceDescription.MAOSAlpha, + BlockFields.SurfaceDescription.Emission, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalData.cs new file mode 100644 index 00000000000..4007bbcaa99 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalData.cs @@ -0,0 +1,65 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class DecalData : HDTargetData + { + [SerializeField] + bool m_AffectsMetal = true; + public bool affectsMetal + { + get => m_AffectsMetal; + set => m_AffectsMetal = value; + } + + [SerializeField] + bool m_AffectsAO = true; + public bool affectsAO + { + get => m_AffectsAO; + set => m_AffectsAO = value; + } + + [SerializeField] + bool m_AffectsSmoothness = true; + public bool affectsSmoothness + { + get => m_AffectsSmoothness; + set => m_AffectsSmoothness = value; + } + + [SerializeField] + bool m_AffectsAlbedo = true; + public bool affectsAlbedo + { + get => m_AffectsAlbedo; + set => m_AffectsAlbedo = value; + } + + [SerializeField] + bool m_AffectsNormal = true; + public bool affectsNormal + { + get => m_AffectsNormal; + set => m_AffectsNormal = value; + } + + [SerializeField] + bool m_AffectsEmission = true; + public bool affectsEmission + { + get => m_AffectsEmission; + set => m_AffectsEmission = value; + } + + [SerializeField] + int m_DrawOrder; + public int drawOrder + { + get => m_DrawOrder; + set => m_DrawOrder = value; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeMasterNode.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalData.cs.meta similarity index 83% rename from com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeMasterNode.cs.meta rename to com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalData.cs.meta index b318bf6e40e..7ebb2ed24eb 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeMasterNode.cs.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalData.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 6a0059a0186c89043bc8f33cefe27333 +guid: a5fb01a9b33da32408818d36664adfc4 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalMasterNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalMasterNode.cs deleted file mode 100644 index f57e44a8859..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalMasterNode.cs +++ /dev/null @@ -1,471 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Rendering.HighDefinition.Drawing; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEditor.ShaderGraph.Internal; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEngine.Rendering.HighDefinition; -using UnityEditor.Rendering.HighDefinition.ShaderGraph; - -namespace UnityEditor.Rendering.HighDefinition -{ - [Serializable] - [Title("Master", "Decal (HDRP)")] - [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.DecalMasterNode")] - class DecalMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string PositionSlotName = "Vertex Position"; - public const string PositionSlotDisplayName = "Vertex Position"; - public const int PositionSlotId = 0; - - public const string AlbedoSlotName = "Albedo"; - public const string AlbedoDisplaySlotName = "BaseColor"; - public const int AlbedoSlotId = 1; - - public const string BaseColorOpacitySlotName = "AlphaAlbedo"; - public const string BaseColorOpacityDisplaySlotName = "BaseColor Opacity"; - public const int BaseColorOpacitySlotId = 2; - - public const string NormalSlotName = "Normal"; - public const int NormalSlotId = 3; - - public const string NormaOpacitySlotName = "AlphaNormal"; - public const string NormaOpacityDisplaySlotName = "Normal Opacity"; - public const int NormaOpacitySlotId = 4; - - public const string MetallicSlotName = "Metallic"; - public const int MetallicSlotId = 5; - - public const string AmbientOcclusionSlotName = "Occlusion"; - public const string AmbientOcclusionDisplaySlotName = "Ambient Occlusion"; - public const int AmbientOcclusionSlotId = 6; - - public const string SmoothnessSlotName = "Smoothness"; - public const int SmoothnessSlotId = 7; - - public const string MAOSOpacitySlotName = "MAOSOpacity"; - public const string MAOSOpacityDisplaySlotName = "MAOS Opacity"; - public const int MAOSOpacitySlotId = 8; - - public const string EmissionSlotName = "Emission"; - public const string EmissionDisplaySlotName = "Emission"; - public const int EmissionSlotId = 9; - - public const string VertexNormalSlotName = "Vertex Normal"; - public const int VertexNormalSlotID = 10; - - public const string VertexTangentSlotName = "Vertex Tangent"; - public const int VertexTangentSlotID = 11; - - [SerializeField] - SurfaceType m_SurfaceType; - - public SurfaceType surfaceType - { - get { return m_SurfaceType; } - set - { - if (m_SurfaceType == value) - return; - - m_SurfaceType = value; - Dirty(ModificationScope.Graph); - } - } - - // Just for convenience of doing simple masks. We could run out of bits of course. - [Flags] - enum SlotMask - { - None = 0, - Position = 1 << PositionSlotId, - VertexNormal = 1 << VertexNormalSlotID, - VertexTangent = 1 << VertexTangentSlotID, - Albedo = 1 << AlbedoSlotId, - AlphaAlbedo = 1 << BaseColorOpacitySlotId, - Normal = 1 << NormalSlotId, - AlphaNormal = 1 << NormaOpacitySlotId, - Metallic = 1 << MetallicSlotId, - Occlusion = 1 << AmbientOcclusionSlotId, - Smoothness = 1 << SmoothnessSlotId, - AlphaMAOS = 1 << MAOSOpacitySlotId, - Emission = 1 << EmissionSlotId - } - - const SlotMask decalParameter = SlotMask.Position | SlotMask.VertexNormal | SlotMask.VertexTangent | SlotMask.Albedo | SlotMask.AlphaAlbedo | SlotMask.Normal | SlotMask.AlphaNormal | SlotMask.Metallic | SlotMask.Occlusion | SlotMask.Smoothness | SlotMask.AlphaMAOS | SlotMask.Emission; - - - // This could also be a simple array. For now, catch any mismatched data. - SlotMask GetActiveSlotMask() - { - return decalParameter; - } - - bool MaterialTypeUsesSlotMask(SlotMask mask) - { - SlotMask activeMask = GetActiveSlotMask(); - return (activeMask & mask) != 0; - } - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public DecalMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - public override string documentationURL - { - get { return null; } - } - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "Decal Master"; - - List validSlots = new List(); - - // Position - if (MaterialTypeUsesSlotMask(SlotMask.Position)) - { - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionSlotDisplayName, PositionSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(PositionSlotId); - } - - //Normal in Vertex - if (MaterialTypeUsesSlotMask(SlotMask.VertexNormal)) - { - AddSlot(new NormalMaterialSlot(VertexNormalSlotID, VertexNormalSlotName, VertexNormalSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexNormalSlotID); - } - - //Tangent in Vertex - if (MaterialTypeUsesSlotMask(SlotMask.VertexTangent)) - { - AddSlot(new TangentMaterialSlot(VertexTangentSlotID, VertexTangentSlotName, VertexTangentSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexTangentSlotID); - } - - // Albedo - if (MaterialTypeUsesSlotMask(SlotMask.Albedo)) - { - AddSlot(new ColorRGBMaterialSlot(AlbedoSlotId, AlbedoDisplaySlotName, AlbedoSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(AlbedoSlotId); - } - - // AlphaAlbedo - if (MaterialTypeUsesSlotMask(SlotMask.AlphaAlbedo)) - { - AddSlot(new Vector1MaterialSlot(BaseColorOpacitySlotId, BaseColorOpacityDisplaySlotName, BaseColorOpacitySlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(BaseColorOpacitySlotId); - } - - // Normal - if (MaterialTypeUsesSlotMask(SlotMask.Normal)) - { - AddSlot(new NormalMaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(NormalSlotId); - } - - // AlphaNormal - if (MaterialTypeUsesSlotMask(SlotMask.AlphaNormal)) - { - AddSlot(new Vector1MaterialSlot(NormaOpacitySlotId, NormaOpacityDisplaySlotName, NormaOpacitySlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(NormaOpacitySlotId); - } - - // Metal - if (MaterialTypeUsesSlotMask(SlotMask.Metallic)) - { - AddSlot(new Vector1MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(MetallicSlotId); - } - - - // Ambient Occlusion - if (MaterialTypeUsesSlotMask(SlotMask.Occlusion)) - { - AddSlot(new Vector1MaterialSlot(AmbientOcclusionSlotId, AmbientOcclusionDisplaySlotName, AmbientOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AmbientOcclusionSlotId); - } - - // Smoothness - if (MaterialTypeUsesSlotMask(SlotMask.Smoothness)) - { - AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(SmoothnessSlotId); - } - - // Alpha MAOS - if (MaterialTypeUsesSlotMask(SlotMask.AlphaMAOS)) - { - AddSlot(new Vector1MaterialSlot(MAOSOpacitySlotId, MAOSOpacityDisplaySlotName, MAOSOpacitySlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(MAOSOpacitySlotId); - } - - // Alpha MAOS - if (MaterialTypeUsesSlotMask(SlotMask.Emission)) - { - AddSlot(new ColorRGBMaterialSlot(EmissionSlotId, EmissionDisplaySlotName, EmissionSlotName, SlotType.Input, Color.black, ColorMode.HDR, ShaderStageCapability.Fragment)); - validSlots.Add(EmissionSlotId); - } - - RemoveSlotsNameNotMatching(validSlots, true); - } - - public VisualElement CreateSettingsElement() - { - return new DecalSettingsView(this); - } - - public string renderQueueTag - { - get - { - return HDRenderQueue.GetShaderTagValue( - HDRenderQueue.ChangeType(HDRenderQueue.RenderQueueType.Opaque, drawOrder, false)); - } - } - - public string renderTypeTag => HDRenderTypeTags.Opaque.ToString(); - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PositionSlotId) || - IsSlotConnected(VertexNormalSlotID) || - IsSlotConnected(VertexTangentSlotID)), - new ConditionalField(Fields.GraphPixel, true), - - // Material - new ConditionalField(HDFields.AffectsAlbedo, affectsAlbedo.isOn), - new ConditionalField(HDFields.AffectsNormal, affectsNormal.isOn), - new ConditionalField(HDFields.AffectsEmission, affectsEmission.isOn), - new ConditionalField(HDFields.AffectsMetal, affectsMetal.isOn), - new ConditionalField(HDFields.AffectsAO, affectsAO.isOn), - new ConditionalField(HDFields.AffectsSmoothness, affectsSmoothness.isOn), - new ConditionalField(HDFields.AffectsMaskMap, affectsSmoothness.isOn || affectsMetal.isOn || affectsAO.isOn), - new ConditionalField(HDFields.DecalDefault, affectsAlbedo.isOn || affectsNormal.isOn || affectsMetal.isOn || - affectsAO.isOn || affectsSmoothness.isOn ), - }; - } - - public void ProcessPreviewMaterial(Material material) - { - - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) - { - Vector1ShaderProperty drawOrder = new Vector1ShaderProperty(); - drawOrder.overrideReferenceName = "_DrawOrder"; - drawOrder.displayName = "Draw Order"; - drawOrder.floatType = FloatType.Integer; - drawOrder.hidden = true; - drawOrder.value = 0; - collector.AddShaderProperty(drawOrder); - - Vector1ShaderProperty decalMeshDepthBias = new Vector1ShaderProperty(); - decalMeshDepthBias.overrideReferenceName = "_DecalMeshDepthBias"; - decalMeshDepthBias.displayName = "DecalMesh DepthBias"; - decalMeshDepthBias.hidden = true; - decalMeshDepthBias.floatType = FloatType.Default; - decalMeshDepthBias.value = 0; - collector.AddShaderProperty(decalMeshDepthBias); - - base.CollectShaderProperties(collector, generationMode); - } - - [SerializeField] - bool m_AffectsMetal = true; - - public ToggleData affectsMetal - { - get { return new ToggleData(m_AffectsMetal); } - set - { - if (m_AffectsMetal == value.isOn) - return; - m_AffectsMetal = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AffectsAO = true; - - public ToggleData affectsAO - { - get { return new ToggleData(m_AffectsAO); } - set - { - if (m_AffectsAO == value.isOn) - return; - m_AffectsAO = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AffectsSmoothness = true; - - public ToggleData affectsSmoothness - { - get { return new ToggleData(m_AffectsSmoothness); } - set - { - if (m_AffectsSmoothness == value.isOn) - return; - m_AffectsSmoothness = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AffectsAlbedo = true; - - public ToggleData affectsAlbedo - { - get { return new ToggleData(m_AffectsAlbedo); } - set - { - if (m_AffectsAlbedo == value.isOn) - return; - m_AffectsAlbedo = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AffectsNormal = true; - - public ToggleData affectsNormal - { - get { return new ToggleData(m_AffectsNormal); } - set - { - if (m_AffectsNormal == value.isOn) - return; - m_AffectsNormal = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AffectsEmission = true; - - public ToggleData affectsEmission - { - get { return new ToggleData(m_AffectsEmission); } - set - { - if (m_AffectsEmission == value.isOn) - return; - m_AffectsEmission = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - - [SerializeField] - int m_DrawOrder; - - public int drawOrder - { - get { return m_DrawOrder; } - set - { - if (m_DrawOrder == value) - return; - m_DrawOrder = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_DOTSInstancing = false; - - public ToggleData dotsInstancing - { - get { return new ToggleData(m_DOTSInstancing); } - set - { - if (m_DOTSInstancing == value.isOn) - return; - - m_DOTSInstancing = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - public bool supportsVirtualTexturing => false; - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalPass.template b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalPass.template index fee46a2acc1..111580143b7 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalPass.template +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalPass.template @@ -113,8 +113,8 @@ Pass // copy across graph values, if defined #if _MATERIAL_AFFECTS_ALBEDO - $SurfaceDescription.Albedo: surfaceData.baseColor.xyz = surfaceDescription.Albedo; - $SurfaceDescription.AlphaAlbedo: surfaceData.baseColor.w = surfaceDescription.AlphaAlbedo * fadeFactor; + $SurfaceDescription.BaseColor: surfaceData.baseColor.xyz = surfaceDescription.BaseColor; + $SurfaceDescription.Alpha: surfaceData.baseColor.w = surfaceDescription.Alpha * fadeFactor; if(surfaceData.baseColor.w > 0) { surfaceData.HTileMask |= DBUFFERHTILEBIT_DIFFUSE; @@ -123,26 +123,26 @@ Pass #if _MATERIAL_AFFECTS_NORMAL #if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR) - $SurfaceDescription.Normal: surfaceData.normalWS.xyz = mul((float3x3)normalToWorld, surfaceDescription.Normal); + $SurfaceDescription.NormalTS: surfaceData.normalWS.xyz = mul((float3x3)normalToWorld, surfaceDescription.NormalTS); #elif (SHADERPASS == SHADERPASS_DBUFFER_MESH) || (SHADERPASS == SHADERPASS_FORWARD_PREVIEW) // We need to normalize as we use mikkt tangent space and this is expected (tangent space is not normalize) - $SurfaceDescription.Normal: surfaceData.normalWS.xyz = normalize(TransformTangentToWorld(surfaceDescription.Normal, fragInputs.tangentToWorld)); + $SurfaceDescription.NormalTS: surfaceData.normalWS.xyz = normalize(TransformTangentToWorld(surfaceDescription.NormalTS, fragInputs.tangentToWorld)); #endif - $SurfaceDescription.AlphaNormal: surfaceData.normalWS.w = surfaceDescription.AlphaNormal * fadeFactor; + $SurfaceDescription.NormalAlpha: surfaceData.normalWS.w = surfaceDescription.NormalAlpha * fadeFactor; if(surfaceData.normalWS.w > 0) { surfaceData.HTileMask |= DBUFFERHTILEBIT_NORMAL; } #else #if (SHADERPASS == SHADERPASS_FORWARD_PREVIEW) // Default to vertex normal - $SurfaceDescription.Normal: surfaceData.normalWS.xyz = normalize(TransformTangentToWorld(float3(0.0, 0.0, 0.1), fragInputs.tangentToWorld)); + $SurfaceDescription.NormalTS: surfaceData.normalWS.xyz = normalize(TransformTangentToWorld(float3(0.0, 0.0, 0.1), fragInputs.tangentToWorld)); #endif #endif #if _MATERIAL_AFFECTS_MASKMAP $SurfaceDescription.Smoothness: surfaceData.mask.z = surfaceDescription.Smoothness; - $SurfaceDescription.MAOSOpacity: surfaceData.mask.w = surfaceDescription.MAOSOpacity * fadeFactor; + $SurfaceDescription.MAOSAlpha: surfaceData.mask.w = surfaceDescription.MAOSAlpha * fadeFactor; #ifdef DECALS_4RT $SurfaceDescription.Metallic: surfaceData.mask.x = surfaceDescription.Metallic; @@ -150,8 +150,8 @@ Pass #endif #ifdef DECALS_4RT - $SurfaceDescription.MAOSOpacity: surfaceData.MAOSBlend.x = surfaceDescription.MAOSOpacity * fadeFactor; - $SurfaceDescription.MAOSOpacity: surfaceData.MAOSBlend.y = surfaceDescription.MAOSOpacity * fadeFactor; + $SurfaceDescription.MAOSAlpha: surfaceData.MAOSBlend.x = surfaceDescription.MAOSAlpha * fadeFactor; + $SurfaceDescription.MAOSAlpha: surfaceData.MAOSBlend.y = surfaceDescription.MAOSAlpha * fadeFactor; #endif if (surfaceData.mask.w > 0) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalPropertyBlock.cs new file mode 100644 index 00000000000..f7ea757dacc --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalPropertyBlock.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.DecalSurfaceInputsUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.SurfaceOptionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class DecalPropertyBlock : SubTargetPropertyBlock + { + class Styles + { + public static GUIContent normalModeText = new GUIContent("Affect Normal", "TODO"); + public static GUIContent affectEmissionText = new GUIContent("Affect Emission", "TODO"); + } + + DecalData decalData; + + protected override string title => "Surface Settings"; + protected override int foldoutIndex => 4; + + public DecalPropertyBlock(DecalData decalData) => this.decalData = decalData; + + protected override void CreatePropertyGUI() + { + AddProperty(albedoModeText, () => decalData.affectsAlbedo, (newValue) => decalData.affectsAlbedo = newValue); + AddProperty(Styles.normalModeText, () => decalData.affectsNormal, (newValue) => decalData.affectsNormal = newValue); + AddProperty(affectMetalText, () => decalData.affectsMetal, (newValue) => decalData.affectsMetal = newValue); + AddProperty(affectAmbientOcclusionText, () => decalData.affectsAO, (newValue) => decalData.affectsAO = newValue); + AddProperty(affectSmoothnessText, () => decalData.affectsSmoothness, (newValue) => decalData.affectsSmoothness = newValue); + AddProperty(Styles.affectEmissionText, () => decalData.affectsEmission, (newValue) => decalData.affectsEmission = newValue); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalMasterNode.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalPropertyBlock.cs.meta similarity index 83% rename from com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalMasterNode.cs.meta rename to com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalPropertyBlock.cs.meta index 162e3680dd8..c316e4df613 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalMasterNode.cs.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalPropertyBlock.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: f1c866e3ebf1735468a917ea2cbebab5 +guid: 45a92369f76e2124582437d711355c96 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSettingsView.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSettingsView.cs deleted file mode 100644 index e3c1bc40a0f..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSettingsView.cs +++ /dev/null @@ -1,136 +0,0 @@ -using UnityEngine.UIElements; -using UnityEditor.Graphing.Util; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; - -namespace UnityEditor.Rendering.HighDefinition.Drawing -{ - class DecalSettingsView : MasterNodeSettingsView - { - DecalMasterNode m_Node; - - Label CreateLabel(string text, int indentLevel) - { - string label = ""; - for (var i = 0; i < indentLevel; i++) - { - label += " "; - } - return new Label(label + text); - } - - public DecalSettingsView(DecalMasterNode node) : base(node) - { - m_Node = node; - PropertySheet ps = new PropertySheet(); - - int indentLevel = 0; - - ps.Add(new PropertyRow(CreateLabel("Affect BaseColor", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.affectsAlbedo.isOn; - toggle.RegisterValueChangedCallback(ChangeAffectsAlbedo); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Affects Normal", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.affectsNormal.isOn; - toggle.RegisterValueChangedCallback(ChangeAffectsNormal); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Affects Metal", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.affectsMetal.isOn; - toggle.RegisterValueChangedCallback(ChangeAffectsMetal); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Affects AO", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.affectsAO.isOn; - toggle.RegisterValueChangedCallback(ChangeAffectsAO); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Affects Smoothness", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.affectsSmoothness.isOn; - toggle.RegisterValueChangedCallback(ChangeAffectsSmoothness); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Affects Emission", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.affectsEmission.isOn; - toggle.RegisterValueChangedCallback(ChangeAffectsEmission); - }); - }); - - Add(ps); - Add(GetShaderGUIOverridePropertySheet()); - } - - void ChangeAffectsAlbedo(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Affects Albedo Change"); - ToggleData td = m_Node.affectsAlbedo; - td.isOn = evt.newValue; - m_Node.affectsAlbedo = td; - } - - void ChangeAffectsNormal(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Affects Normal Change"); - ToggleData td = m_Node.affectsNormal; - td.isOn = evt.newValue; - m_Node.affectsNormal = td; - } - - void ChangeAffectsMetal(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Affects Metal Change"); - ToggleData td = m_Node.affectsMetal; - td.isOn = evt.newValue; - m_Node.affectsMetal = td; - } - - void ChangeAffectsAO(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Affects AO Change"); - ToggleData td = m_Node.affectsAO; - td.isOn = evt.newValue; - m_Node.affectsAO = td; - } - - void ChangeAffectsSmoothness(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Affects Smoothness Change"); - ToggleData td = m_Node.affectsSmoothness; - td.isOn = evt.newValue; - m_Node.affectsSmoothness = td; - } - - void ChangeAffectsEmission(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Affects Emission Change"); - ToggleData td = m_Node.affectsEmission; - td.isOn = evt.newValue; - m_Node.affectsEmission = td; - } - - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.Migration.cs new file mode 100644 index 00000000000..b7699a48739 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.Migration.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + sealed partial class DecalSubTarget : HDSubTarget, ILegacyTarget, IRequiresData + { + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is DecalMasterNode1 decalMasterNode)) + return false; + + // Set data + systemData.surfaceType = (SurfaceType)decalMasterNode.m_SurfaceType; + systemData.dotsInstancing = decalMasterNode.m_DOTSInstancing; + decalData.affectsMetal = decalMasterNode.m_AffectsMetal; + decalData.affectsAO = decalMasterNode.m_AffectsAO; + decalData.affectsSmoothness = decalMasterNode.m_AffectsSmoothness; + decalData.affectsAlbedo = decalMasterNode.m_AffectsAlbedo; + decalData.affectsNormal = decalMasterNode.m_AffectsNormal; + decalData.affectsEmission = decalMasterNode.m_AffectsEmission; + decalData.drawOrder = decalMasterNode.m_DrawOrder; + target.customEditorGUI = decalMasterNode.m_OverrideEnabled ? decalMasterNode.m_ShaderGUIOverride : ""; + + // Convert SlotMask to BlockMap entries + var blockMapLookup = new Dictionary() + { + { DecalMasterNode1.SlotMask.Position, BlockFields.VertexDescription.Position }, + { DecalMasterNode1.SlotMask.VertexNormal, BlockFields.VertexDescription.Normal }, + { DecalMasterNode1.SlotMask.VertexTangent, BlockFields.VertexDescription.Tangent }, + { DecalMasterNode1.SlotMask.Albedo, BlockFields.SurfaceDescription.BaseColor }, + { DecalMasterNode1.SlotMask.AlphaAlbedo, BlockFields.SurfaceDescription.Alpha }, + { DecalMasterNode1.SlotMask.Normal, BlockFields.SurfaceDescription.NormalTS }, + { DecalMasterNode1.SlotMask.AlphaNormal, HDBlockFields.SurfaceDescription.NormalAlpha }, + { DecalMasterNode1.SlotMask.Metallic, BlockFields.SurfaceDescription.Metallic }, + { DecalMasterNode1.SlotMask.Occlusion, BlockFields.SurfaceDescription.Occlusion }, + { DecalMasterNode1.SlotMask.Smoothness, BlockFields.SurfaceDescription.Smoothness }, + { DecalMasterNode1.SlotMask.AlphaMAOS, HDBlockFields.SurfaceDescription.MAOSAlpha }, + { DecalMasterNode1.SlotMask.Emission, BlockFields.SurfaceDescription.Emission }, + }; + + // Set blockmap + blockMap = new Dictionary(); + foreach(DecalMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(DecalMasterNode1.SlotMask))) + { + if(decalMasterNode.MaterialTypeUsesSlotMask(slotMask)) + { + if(!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) + continue; + + var slotId = Mathf.Log((int)slotMask, 2); + blockMap.Add(blockFieldDescriptor, (int)slotId); + } + } + + return true; + } + } +} \ No newline at end of file diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSettingsView.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.Migration.cs.meta similarity index 83% rename from com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSettingsView.cs.meta rename to com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.Migration.cs.meta index 717d7ea547c..aa12b350414 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSettingsView.cs.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.Migration.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: a16e0965efec43748ab4d96982eebc60 +guid: f1fccb4c5ef1c0c41a8c38dc63bdf983 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/HDDecalSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.cs similarity index 76% rename from com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/HDDecalSubTarget.cs rename to com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.cs index 51967091da5..7f1d3e043e0 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/HDDecalSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.cs @@ -1,23 +1,108 @@ -using UnityEngine.Rendering.HighDefinition; +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { - sealed class HDDecalSubTarget : SubTarget + sealed partial class DecalSubTarget : HDSubTarget, ILegacyTarget, IRequiresData { - const string kAssetGuid = "3ec927dfcb5d60e4883b2c224857b6c2"; static string passTemplatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/Decal/ShaderGraph/DecalPass.template"; - public HDDecalSubTarget() + public DecalSubTarget() => displayName = "Decal"; + + protected override string subTargetAssetGuid => "3ec927dfcb5d60e4883b2c224857b6c2"; + protected override string customInspector => "Rendering.HighDefinition.DecalGUI"; + protected override string renderType => HDRenderTypeTags.Opaque.ToString(); + protected override string renderQueue => HDRenderQueue.GetShaderTagValue(HDRenderQueue.ChangeType(HDRenderQueue.RenderQueueType.Opaque, decalData.drawOrder, false)); + + // Material Data + DecalData m_DecalData; + + // Interface Properties + DecalData IRequiresData.data + { + get => m_DecalData; + set => m_DecalData = value; + } + + // Public properties + public DecalData decalData { - displayName = "Decal"; + get => m_DecalData; + set => m_DecalData = value; } - public override void Setup(ref TargetSetupContext context) + protected override IEnumerable EnumerateSubShaders() + { + yield return SubShaders.Decal; + } + + public override void GetFields(ref TargetFieldContext context) + { + // Decal properties + context.AddField(HDFields.AffectsAlbedo, decalData.affectsAlbedo); + context.AddField(HDFields.AffectsNormal, decalData.affectsNormal); + context.AddField(HDFields.AffectsEmission, decalData.affectsEmission); + context.AddField(HDFields.AffectsMetal, decalData.affectsMetal); + context.AddField(HDFields.AffectsAO, decalData.affectsAO); + context.AddField(HDFields.AffectsSmoothness, decalData.affectsSmoothness); + context.AddField(HDFields.AffectsMaskMap, decalData.affectsSmoothness || decalData.affectsMetal || decalData.affectsAO); + context.AddField(HDFields.DecalDefault, decalData.affectsAlbedo || decalData.affectsNormal || decalData.affectsMetal || + decalData.affectsAO || decalData.affectsSmoothness ); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + // Vertex + context.AddBlock(BlockFields.VertexDescription.Position); + context.AddBlock(BlockFields.VertexDescription.Normal); + context.AddBlock(BlockFields.VertexDescription.Tangent); + + // Decal + context.AddBlock(BlockFields.SurfaceDescription.BaseColor); + context.AddBlock(BlockFields.SurfaceDescription.Alpha); + context.AddBlock(BlockFields.SurfaceDescription.NormalTS); + context.AddBlock(HDBlockFields.SurfaceDescription.NormalAlpha); + context.AddBlock(BlockFields.SurfaceDescription.Metallic); + context.AddBlock(BlockFields.SurfaceDescription.Occlusion); + context.AddBlock(BlockFields.SurfaceDescription.Smoothness); + context.AddBlock(HDBlockFields.SurfaceDescription.MAOSAlpha); + context.AddBlock(BlockFields.SurfaceDescription.Emission); + } + + protected override void AddInspectorPropertyBlocks(SubTargetPropertiesGUI blockList) + { + blockList.AddPropertyBlock(new DecalPropertyBlock(decalData)); + } + + protected override ShaderID shaderID => HDShaderUtils.ShaderID.SG_Lit; + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) { - context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); - context.SetDefaultShaderGUI("Rendering.HighDefinition.DecalGUI"); - context.AddSubShader(SubShaders.Decal); + Vector1ShaderProperty drawOrder = new Vector1ShaderProperty(); + drawOrder.overrideReferenceName = "_DrawOrder"; + drawOrder.displayName = "Draw Order"; + drawOrder.floatType = FloatType.Integer; + drawOrder.hidden = true; + drawOrder.value = 0; + collector.AddShaderProperty(drawOrder); + + Vector1ShaderProperty decalMeshDepthBias = new Vector1ShaderProperty(); + decalMeshDepthBias.overrideReferenceName = "_DecalMeshDepthBias"; + decalMeshDepthBias.displayName = "DecalMesh DepthBias"; + decalMeshDepthBias.hidden = true; + decalMeshDepthBias.floatType = FloatType.Default; + decalMeshDepthBias.value = 0; + collector.AddShaderProperty(decalMeshDepthBias); } #region SubShaders @@ -59,7 +144,7 @@ public static class DecalPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port mask - pixelPorts = DecalPortMasks.FragmentDefault, + validPixelBlocks = DecalBlockMasks.FragmentDefault, //Fields structs = CoreStructCollections.Default, @@ -83,7 +168,7 @@ public static class DecalPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port mask - pixelPorts = DecalPortMasks.FragmentDefault, + validPixelBlocks = DecalBlockMasks.FragmentDefault, //Fields structs = CoreStructCollections.Default, @@ -109,7 +194,7 @@ public static class DecalPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port mask - pixelPorts = DecalPortMasks.FragmentEmissive, + validPixelBlocks = DecalBlockMasks.FragmentEmissive, //Fields structs = CoreStructCollections.Default, @@ -134,7 +219,7 @@ public static class DecalPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port mask - pixelPorts = DecalPortMasks.FragmentDefault, + validPixelBlocks = DecalBlockMasks.FragmentDefault, //Fields structs = CoreStructCollections.Default, @@ -161,7 +246,7 @@ public static class DecalPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port mask - pixelPorts = DecalPortMasks.FragmentDefault, + validPixelBlocks = DecalBlockMasks.FragmentDefault, //Fields structs = CoreStructCollections.Default, @@ -188,7 +273,7 @@ public static class DecalPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port mask - pixelPorts = DecalPortMasks.FragmentMeshEmissive, + validPixelBlocks = DecalBlockMasks.FragmentMeshEmissive, //Fields structs = CoreStructCollections.Default, @@ -214,7 +299,7 @@ public static class DecalPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port mask - pixelPorts = DecalPortMasks.FragmentMeshEmissive, + validPixelBlocks = DecalBlockMasks.FragmentMeshEmissive, //Fields structs = CoreStructCollections.Default, @@ -229,37 +314,37 @@ public static class DecalPasses } #endregion -#region PortMasks - static class DecalPortMasks +#region BlockMasks + static class DecalBlockMasks { - public static int[] FragmentDefault = new int[] + public static BlockFieldDescriptor[] FragmentDefault = new BlockFieldDescriptor[] { - DecalMasterNode.AlbedoSlotId, - DecalMasterNode.BaseColorOpacitySlotId, - DecalMasterNode.NormalSlotId, - DecalMasterNode.NormaOpacitySlotId, - DecalMasterNode.MetallicSlotId, - DecalMasterNode.AmbientOcclusionSlotId, - DecalMasterNode.SmoothnessSlotId, - DecalMasterNode.MAOSOpacitySlotId, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.NormalAlpha, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Smoothness, + HDBlockFields.SurfaceDescription.MAOSAlpha, }; - public static int[] FragmentEmissive = new int[] + public static BlockFieldDescriptor[] FragmentEmissive = new BlockFieldDescriptor[] { - DecalMasterNode.EmissionSlotId + BlockFields.SurfaceDescription.Emission, }; - public static int[] FragmentMeshEmissive = new int[] + public static BlockFieldDescriptor[] FragmentMeshEmissive = new BlockFieldDescriptor[] { - DecalMasterNode.AlbedoSlotId, - DecalMasterNode.BaseColorOpacitySlotId, - DecalMasterNode.NormalSlotId, - DecalMasterNode.NormaOpacitySlotId, - DecalMasterNode.MetallicSlotId, - DecalMasterNode.AmbientOcclusionSlotId, - DecalMasterNode.SmoothnessSlotId, - DecalMasterNode.MAOSOpacitySlotId, - DecalMasterNode.EmissionSlotId, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.NormalAlpha, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Smoothness, + HDBlockFields.SurfaceDescription.MAOSAlpha, + BlockFields.SurfaceDescription.Emission, }; } #endregion diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/HDDecalSubTarget.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.cs.meta similarity index 100% rename from com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/HDDecalSubTarget.cs.meta rename to com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs index 2a8794ad40a..91f5a923888 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs @@ -1,13 +1,34 @@ +using System; using UnityEditor.ShaderGraph; -namespace UnityEditor.Rendering.HighDefinition +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { static class CreateEyeShaderGraph { - [MenuItem("Assets/Create/Shader/HDRP/Eye Graph (Experimental)", false, 208)] - public static void CreateMaterialGraph() + [MenuItem("Assets/Create/Shader/HDRP/Eye Shader Graph (Experimental)", false, 208)] + public static void CreateEyeGraph() { - GraphUtil.CreateNewGraph(new EyeMasterNode()); + var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); + target.TrySetActiveSubTarget(typeof(EyeSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.IrisNormal, + HDBlockFields.SurfaceDescription.BentNormal, + BlockFields.SurfaceDescription.Smoothness, + HDBlockFields.SurfaceDescription.IOR, + BlockFields.SurfaceDescription.Occlusion, + HDBlockFields.SurfaceDescription.Mask, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs.meta index ea5232a74da..83be86afc29 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 1c420b007c865ea46acf39ca5a4a0044 +guid: db108348de4127f4f9c40888d9b494c1 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeData.cs new file mode 100644 index 00000000000..3ffb915a28b --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeData.cs @@ -0,0 +1,23 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class EyeData : HDTargetData + { + public enum MaterialType + { + Eye, + EyeCinematic + } + + [SerializeField] + MaterialType m_MaterialType; + public MaterialType materialType + { + get => m_MaterialType; + set => m_MaterialType = value; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSettingsView.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeData.cs.meta similarity index 83% rename from com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSettingsView.cs.meta rename to com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeData.cs.meta index 2966f8d6023..6b1aa711def 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSettingsView.cs.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeData.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 0f478c54cb669c743a23580d825341fe +guid: 945baf95fa6df374cb4a014b8fcb5c18 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeMasterNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeMasterNode.cs deleted file mode 100644 index 1edd17c94c1..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeMasterNode.cs +++ /dev/null @@ -1,903 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEditor.ShaderGraph.Internal; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEngine.Rendering.HighDefinition; -using UnityEngine.Rendering; -using UnityEditor.Rendering.HighDefinition.Drawing; -using UnityEditor.Rendering.HighDefinition.ShaderGraph; - -// Include material common properties names -using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; - -namespace UnityEditor.Rendering.HighDefinition -{ - [Serializable] - [Title("Master", "Eye (HDRP)(Preview)")] - class EyeMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string PositionSlotName = "Vertex Position"; - public const string PositionSlotDisplayName = "Vertex Position"; - public const int PositionSlotId = 0; - - public const string AlbedoSlotName = "Albedo"; - public const string AlbedoDisplaySlotName = "BaseColor"; - public const int AlbedoSlotId = 1; - - public const string SpecularOcclusionSlotName = "SpecularOcclusion"; - public const int SpecularOcclusionSlotId = 2; - - public const string NormalSlotName = "Normal"; - public const int NormalSlotId = 3; - - public const string IrisNormalSlotName = "IrisNormal"; - public const int IrisNormalSlotId = 4; - - public const string SmoothnessSlotName = "Smoothness"; - public const int SmoothnessSlotId = 5; - - public const string IORSlotName = "IOR"; - public const int IORSlotId = 6; - - public const string AmbientOcclusionSlotName = "Occlusion"; - public const string AmbientOcclusionDisplaySlotName = "AmbientOcclusion"; - public const int AmbientOcclusionSlotId = 7; - - public const string MaskSlotName = "Mask"; - public const int MaskSlotId = 8; - - public const string DiffusionProfileHashSlotName = "DiffusionProfileHash"; - public const string DiffusionProfileHashSlotDisplayName = "Diffusion Profile"; - public const int DiffusionProfileHashSlotId = 9; - - public const string SubsurfaceMaskSlotName = "SubsurfaceMask"; - public const int SubsurfaceMaskSlotId = 10; - - public const string EmissionSlotName = "Emission"; - public const int EmissionSlotId = 11; - - public const string AlphaSlotName = "Alpha"; - public const int AlphaSlotId = 12; - - public const string AlphaClipThresholdSlotName = "AlphaClipThreshold"; - public const int AlphaClipThresholdSlotId = 13; - - public const string BentNormalSlotName = "BentNormal"; - public const int BentNormalSlotId = 14; - - public const int LightingSlotId = 15; - public const string BakedGISlotName = "BakedGI"; - - public const int BackLightingSlotId = 16; - public const string BakedBackGISlotName = "BakedBackGI"; - - public const int DepthOffsetSlotId = 17; - public const string DepthOffsetSlotName = "DepthOffset"; - - public const string VertexNormalSlotName = "Vertex Normal"; - public const int VertexNormalSlotID = 18; - - public const string VertexTangentSlotName = "Vertex Tangent"; - public const int VertexTangentSlotID = 19; - - public enum MaterialType - { - Eye, - EyeCinematic - } - - // Don't support Multiply - public enum AlphaModeEye - { - Alpha, - Premultiply, - Additive, - } - - // Just for convenience of doing simple masks. We could run out of bits of course. - [Flags] - enum SlotMask - { - None = 0, - Position = 1 << PositionSlotId, - VertexNormal = 1 << VertexNormalSlotID, - VertexTangent = 1 << VertexTangentSlotID, - Albedo = 1 << AlbedoSlotId, - SpecularOcclusion = 1 << SpecularOcclusionSlotId, - Normal = 1 << NormalSlotId, - IrisNormal = 1 << IrisNormalSlotId, - Smoothness = 1 << SmoothnessSlotId, - IOR = 1 << IORSlotId, - Occlusion = 1 << AmbientOcclusionSlotId, - Mask = 1 << MaskSlotId, - DiffusionProfile = 1 << DiffusionProfileHashSlotId, - SubsurfaceMask = 1 << SubsurfaceMaskSlotId, - Emission = 1 << EmissionSlotId, - Alpha = 1 << AlphaSlotId, - AlphaClipThreshold = 1 << AlphaClipThresholdSlotId, - BentNormal = 1 << BentNormalSlotId, - BakedGI = 1 << LightingSlotId, - BakedBackGI = 1 << BackLightingSlotId, - DepthOffset = 1 << DepthOffsetSlotId, - } - - const SlotMask EyeSlotMask = SlotMask.Position | SlotMask.VertexNormal | SlotMask.VertexTangent | SlotMask.Albedo | SlotMask.SpecularOcclusion | SlotMask.Normal | SlotMask.IrisNormal | SlotMask.Smoothness | SlotMask.IOR | SlotMask.Occlusion | SlotMask.Mask | SlotMask.DiffusionProfile | SlotMask.SubsurfaceMask | SlotMask.Emission | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.BentNormal | SlotMask.BakedGI | SlotMask.DepthOffset; - const SlotMask EyeCinematicSlotMask = EyeSlotMask; - - // This could also be a simple array. For now, catch any mismatched data. - SlotMask GetActiveSlotMask() - { - switch (materialType) - { - case MaterialType.Eye: - return EyeSlotMask; - - case MaterialType.EyeCinematic: - return EyeCinematicSlotMask; - - default: - return SlotMask.None; - } - } - - bool MaterialTypeUsesSlotMask(SlotMask mask) - { - SlotMask activeMask = GetActiveSlotMask(); - return (activeMask & mask) != 0; - } - - [SerializeField] - SurfaceType m_SurfaceType; - - public SurfaceType surfaceType - { - get { return m_SurfaceType; } - set - { - if (m_SurfaceType == value) - return; - - m_SurfaceType = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - AlphaMode m_AlphaMode; - - public AlphaMode alphaMode - { - get { return m_AlphaMode; } - set - { - if (m_AlphaMode == value) - return; - - m_AlphaMode = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_BlendPreserveSpecular = true; - - public ToggleData blendPreserveSpecular - { - get { return new ToggleData(m_BlendPreserveSpecular); } - set - { - if (m_BlendPreserveSpecular == value.isOn) - return; - m_BlendPreserveSpecular = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_TransparencyFog = true; - - public ToggleData transparencyFog - { - get { return new ToggleData(m_TransparencyFog); } - set - { - if (m_TransparencyFog == value.isOn) - return; - m_TransparencyFog = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaTest; - - public ToggleData alphaTest - { - get { return new ToggleData(m_AlphaTest); } - set - { - if (m_AlphaTest == value.isOn) - return; - m_AlphaTest = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaToMask = false; - - public ToggleData alphaToMask - { - get { return new ToggleData(m_AlphaToMask); } - set - { - if (m_AlphaToMask == value.isOn) - return; - m_AlphaToMask = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaTestDepthPrepass; - - public ToggleData alphaTestDepthPrepass - { - get { return new ToggleData(m_AlphaTestDepthPrepass); } - set - { - if (m_AlphaTestDepthPrepass == value.isOn) - return; - m_AlphaTestDepthPrepass = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaTestDepthPostpass; - - public ToggleData alphaTestDepthPostpass - { - get { return new ToggleData(m_AlphaTestDepthPostpass); } - set - { - if (m_AlphaTestDepthPostpass == value.isOn) - return; - m_AlphaTestDepthPostpass = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - int m_SortPriority; - - public int sortPriority - { - get { return m_SortPriority; } - set - { - if (m_SortPriority == value) - return; - m_SortPriority = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - DoubleSidedMode m_DoubleSidedMode; - - public DoubleSidedMode doubleSidedMode - { - get { return m_DoubleSidedMode; } - set - { - if (m_DoubleSidedMode == value) - return; - - m_DoubleSidedMode = value; - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - MaterialType m_MaterialType; - - public MaterialType materialType - { - get { return m_MaterialType; } - set - { - if (m_MaterialType == value) - return; - - m_MaterialType = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_ReceiveDecals = true; - - public ToggleData receiveDecals - { - get { return new ToggleData(m_ReceiveDecals); } - set - { - if (m_ReceiveDecals == value.isOn) - return; - m_ReceiveDecals = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_ReceivesSSR = true; - public ToggleData receiveSSR - { - get { return new ToggleData(m_ReceivesSSR); } - set - { - if (m_ReceivesSSR == value.isOn) - return; - m_ReceivesSSR = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AddPrecomputedVelocity = false; - - public ToggleData addPrecomputedVelocity - { - get { return new ToggleData(m_AddPrecomputedVelocity); } - set - { - if (m_AddPrecomputedVelocity == value.isOn) - return; - m_AddPrecomputedVelocity = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_SubsurfaceScattering = false; - - public ToggleData subsurfaceScattering - { - get { return new ToggleData(m_SubsurfaceScattering); } - set - { - if (m_SubsurfaceScattering == value.isOn) - return; - m_SubsurfaceScattering = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - SpecularOcclusionMode m_SpecularOcclusionMode; - - public SpecularOcclusionMode specularOcclusionMode - { - get { return m_SpecularOcclusionMode; } - set - { - if (m_SpecularOcclusionMode == value) - return; - - m_SpecularOcclusionMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_overrideBakedGI; - - public ToggleData overrideBakedGI - { - get { return new ToggleData(m_overrideBakedGI); } - set - { - if (m_overrideBakedGI == value.isOn) - return; - m_overrideBakedGI = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_depthOffset; - - public ToggleData depthOffset - { - get { return new ToggleData(m_depthOffset); } - set - { - if (m_depthOffset == value.isOn) - return; - m_depthOffset = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_ZWrite; - - public ToggleData zWrite - { - get { return new ToggleData(m_ZWrite); } - set - { - if (m_ZWrite == value.isOn) - return; - m_ZWrite = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - TransparentCullMode m_transparentCullMode = TransparentCullMode.Back; - public TransparentCullMode transparentCullMode - { - get => m_transparentCullMode; - set - { - if (m_transparentCullMode == value) - return; - - m_transparentCullMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - CompareFunction m_ZTest = CompareFunction.LessEqual; - public CompareFunction zTest - { - get => m_ZTest; - set - { - if (m_ZTest == value) - return; - - m_ZTest = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_SupportLodCrossFade; - - public ToggleData supportLodCrossFade - { - get { return new ToggleData(m_SupportLodCrossFade); } - set - { - if (m_SupportLodCrossFade == value.isOn) - return; - m_SupportLodCrossFade = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Node); - } - } - - [SerializeField] - bool m_DOTSInstancing = false; - - public ToggleData dotsInstancing - { - get { return new ToggleData(m_DOTSInstancing); } - set - { - if (m_DOTSInstancing == value.isOn) - return; - - m_DOTSInstancing = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - int m_MaterialNeedsUpdateHash = 0; - - int ComputeMaterialNeedsUpdateHash() - { - int hash = 0; - - hash |= (alphaTest.isOn ? 0 : 1) << 0; - hash |= (receiveSSR.isOn ? 0 : 1) << 1; - hash |= (RequiresSplitLighting() ? 0 : 1) << 2; - - return hash; - } - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public EyeMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - public override string documentationURL - { - get { return null; } - } - - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "Eye Master"; - - List validSlots = new List(); - - // Position - if (MaterialTypeUsesSlotMask(SlotMask.Position)) - { - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionSlotDisplayName, PositionSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(PositionSlotId); - } - - //Normal in Vertex - if (MaterialTypeUsesSlotMask(SlotMask.VertexNormal)) - { - AddSlot(new NormalMaterialSlot(VertexNormalSlotID, VertexNormalSlotName, VertexNormalSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexNormalSlotID); - } - - //Tangent in Vertex - if (MaterialTypeUsesSlotMask(SlotMask.VertexTangent)) - { - AddSlot(new TangentMaterialSlot(VertexTangentSlotID, VertexTangentSlotName, VertexTangentSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexTangentSlotID); - } - - // Albedo - if (MaterialTypeUsesSlotMask(SlotMask.Albedo)) - { - AddSlot(new ColorRGBMaterialSlot(AlbedoSlotId, AlbedoDisplaySlotName, AlbedoSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(AlbedoSlotId); - } - - // Specular Occlusion - if (MaterialTypeUsesSlotMask(SlotMask.SpecularOcclusion) && specularOcclusionMode == SpecularOcclusionMode.Custom) - { - AddSlot(new Vector1MaterialSlot(SpecularOcclusionSlotId, SpecularOcclusionSlotName, SpecularOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularOcclusionSlotId); - } - - // Normal - if (MaterialTypeUsesSlotMask(SlotMask.Normal)) - { - AddSlot(new NormalMaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(NormalSlotId); - } - - // IrisNormal - if (MaterialTypeUsesSlotMask(SlotMask.IrisNormal)) - { - AddSlot(new NormalMaterialSlot(IrisNormalSlotId, IrisNormalSlotName, IrisNormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(IrisNormalSlotId); - } - - // BentNormal - if (MaterialTypeUsesSlotMask(SlotMask.BentNormal)) - { - AddSlot(new NormalMaterialSlot(BentNormalSlotId, BentNormalSlotName, BentNormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(BentNormalSlotId); - } - - // Smoothness - if (MaterialTypeUsesSlotMask(SlotMask.Smoothness)) - { - AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.9f, ShaderStageCapability.Fragment)); - validSlots.Add(SmoothnessSlotId); - } - - // IOR - if (MaterialTypeUsesSlotMask(SlotMask.IOR)) - { - AddSlot(new Vector1MaterialSlot(IORSlotId, IORSlotName, IORSlotName, SlotType.Input, 1.4f, ShaderStageCapability.Fragment)); - validSlots.Add(IORSlotId); - } - - // Ambient Occlusion - if (MaterialTypeUsesSlotMask(SlotMask.Occlusion)) - { - AddSlot(new Vector1MaterialSlot(AmbientOcclusionSlotId, AmbientOcclusionDisplaySlotName, AmbientOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AmbientOcclusionSlotId); - } - - // Mask - if (MaterialTypeUsesSlotMask(SlotMask.Mask)) - { - AddSlot(new Vector2MaterialSlot(MaskSlotId, MaskSlotName, MaskSlotName, SlotType.Input, new Vector2(1.0f, 0.0f), ShaderStageCapability.Fragment)); - validSlots.Add(MaskSlotId); - } - - // Diffusion Profile - if (MaterialTypeUsesSlotMask(SlotMask.DiffusionProfile) && subsurfaceScattering.isOn) - { - AddSlot(new DiffusionProfileInputMaterialSlot(DiffusionProfileHashSlotId, DiffusionProfileHashSlotDisplayName, DiffusionProfileHashSlotName, ShaderStageCapability.Fragment)); - validSlots.Add(DiffusionProfileHashSlotId); - } - - // Subsurface mask - if (MaterialTypeUsesSlotMask(SlotMask.SubsurfaceMask) && subsurfaceScattering.isOn) - { - AddSlot(new Vector1MaterialSlot(SubsurfaceMaskSlotId, SubsurfaceMaskSlotName, SubsurfaceMaskSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SubsurfaceMaskSlotId); - } - - // Emission Normal - if (MaterialTypeUsesSlotMask(SlotMask.Emission)) - { - AddSlot(new ColorRGBMaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Color.black, ColorMode.HDR, ShaderStageCapability.Fragment)); - validSlots.Add(EmissionSlotId); - } - - // Alpha - if (MaterialTypeUsesSlotMask(SlotMask.Alpha)) - { - AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaSlotId); - } - - // Alpha threshold - if (MaterialTypeUsesSlotMask(SlotMask.AlphaClipThreshold) && alphaTest.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaClipThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaClipThresholdSlotId); - } - - if (MaterialTypeUsesSlotMask(SlotMask.BakedGI) && overrideBakedGI.isOn) - { - AddSlot(new DefaultMaterialSlot(LightingSlotId, BakedGISlotName, BakedGISlotName, ShaderStageCapability.Fragment)); - validSlots.Add(LightingSlotId); - AddSlot(new DefaultMaterialSlot(BackLightingSlotId, BakedBackGISlotName, BakedBackGISlotName, ShaderStageCapability.Fragment)); - validSlots.Add(BackLightingSlotId); - } - - if (depthOffset.isOn) - { - AddSlot(new Vector1MaterialSlot(DepthOffsetSlotId, DepthOffsetSlotName, DepthOffsetSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(DepthOffsetSlotId); - } - - RemoveSlotsNameNotMatching(validSlots, true); - } - - public VisualElement CreateSettingsElement() - { - return new EyeSettingsView(this); - } - - public string renderQueueTag - { - get - { - var renderingPass = surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; - int queue = HDRenderQueue.ChangeType(renderingPass, sortPriority, alphaTest.isOn); - return HDRenderQueue.GetShaderTagValue(queue); - } - } - - public string renderTypeTag => "HDLitShader"; - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - var ambientOcclusionSlot = FindSlot(AmbientOcclusionSlotId); - - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PositionSlotId) || - IsSlotConnected(VertexNormalSlotID) || - IsSlotConnected(VertexTangentSlotID)), - new ConditionalField(Fields.GraphPixel, true), - new ConditionalField(Fields.LodCrossFade, supportLodCrossFade.isOn), - - // Surface Type - new ConditionalField(Fields.SurfaceOpaque, surfaceType == SurfaceType.Opaque), - new ConditionalField(Fields.SurfaceTransparent, surfaceType != SurfaceType.Opaque), - - // Structs - new ConditionalField(HDStructFields.FragInputs.IsFrontFace,doubleSidedMode != DoubleSidedMode.Disabled && - !pass.Equals(HDEyeSubTarget.EyePasses.MotionVectors)), - - // Material - new ConditionalField(HDFields.Eye, materialType == MaterialType.Eye), - new ConditionalField(HDFields.EyeCinematic, materialType == MaterialType.EyeCinematic), - new ConditionalField(HDFields.SubsurfaceScattering, subsurfaceScattering.isOn && surfaceType != SurfaceType.Transparent), - - // Specular Occlusion - new ConditionalField(HDFields.SpecularOcclusionFromAO, specularOcclusionMode == SpecularOcclusionMode.FromAO), - new ConditionalField(HDFields.SpecularOcclusionFromAOBentNormal, specularOcclusionMode == SpecularOcclusionMode.FromAOAndBentNormal), - new ConditionalField(HDFields.SpecularOcclusionCustom, specularOcclusionMode == SpecularOcclusionMode.Custom), - - // Misc - new ConditionalField(Fields.AlphaTest, alphaTest.isOn && pass.pixelPorts.Contains(AlphaClipThresholdSlotId)), - new ConditionalField(HDFields.DoAlphaTest, alphaTest.isOn && pass.pixelPorts.Contains(AlphaClipThresholdSlotId)), - new ConditionalField(Fields.AlphaToMask, alphaTest.isOn && pass.pixelPorts.Contains(AlphaClipThresholdSlotId) && alphaToMask.isOn), - new ConditionalField(HDFields.AlphaFog, surfaceType != SurfaceType.Opaque && transparencyFog.isOn), - new ConditionalField(HDFields.BlendPreserveSpecular, surfaceType != SurfaceType.Opaque && blendPreserveSpecular.isOn), - new ConditionalField(HDFields.DisableDecals, !receiveDecals.isOn), - new ConditionalField(HDFields.DisableSSR, !receiveSSR.isOn), - new ConditionalField(Fields.VelocityPrecomputed, addPrecomputedVelocity.isOn), - new ConditionalField(HDFields.BentNormal, IsSlotConnected(BentNormalSlotId) && - pass.pixelPorts.Contains(BentNormalSlotId)), - new ConditionalField(HDFields.AmbientOcclusion, pass.pixelPorts.Contains(AmbientOcclusionSlotId) && - (IsSlotConnected(AmbientOcclusionSlotId) || - ambientOcclusionSlot.value != ambientOcclusionSlot.defaultValue)), - new ConditionalField(HDFields.LightingGI, IsSlotConnected(LightingSlotId) && - pass.pixelPorts.Contains(LightingSlotId)), - new ConditionalField(HDFields.BackLightingGI, IsSlotConnected(BackLightingSlotId) && - pass.pixelPorts.Contains(BackLightingSlotId)), - new ConditionalField(HDFields.DepthOffset, depthOffset.isOn && pass.pixelPorts.Contains(DepthOffsetSlotId)), - }; - } - - public void ProcessPreviewMaterial(Material material) - { - // Fixup the material settings: - material.SetFloat(kSurfaceType, (int)(SurfaceType)surfaceType); - material.SetFloat(kDoubleSidedNormalMode, (int)doubleSidedMode); - material.SetFloat(kDoubleSidedEnable, doubleSidedMode != DoubleSidedMode.Disabled ? 1.0f : 0.0f); - material.SetFloat(kAlphaCutoffEnabled, alphaTest.isOn ? 1 : 0); - material.SetFloat(kBlendMode, (int)HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode)); - material.SetFloat(kEnableFogOnTransparent, transparencyFog.isOn ? 1.0f : 0.0f); - material.SetFloat(kZTestTransparent, (int)zTest); - material.SetFloat(kTransparentCullMode, (int)transparentCullMode); - material.SetFloat(kZWrite, zWrite.isOn ? 1.0f : 0.0f); - // No sorting priority for shader graph preview - var renderingPass = surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; - material.renderQueue = (int)HDRenderQueue.ChangeType(renderingPass, offset: 0, alphaTest: alphaTest.isOn); - - EyeGUI.SetupMaterialKeywordsAndPass(material); - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public bool RequiresSplitLighting() - { - return subsurfaceScattering.isOn; - } - public override object saveContext - { - get - { - int hash = ComputeMaterialNeedsUpdateHash(); - - bool needsUpdate = hash != m_MaterialNeedsUpdateHash; - - if (needsUpdate) - m_MaterialNeedsUpdateHash = hash; - - return new HDSaveContext{ updateMaterials = needsUpdate }; - } - } - - public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) - { - // Trunk currently relies on checking material property "_EmissionColor" to allow emissive GI. If it doesn't find that property, or it is black, GI is forced off. - // ShaderGraph doesn't use this property, so currently it inserts a dummy color (white). This dummy color may be removed entirely once the following PR has been merged in trunk: Pull request #74105 - // The user will then need to explicitly disable emissive GI if it is not needed. - // To be able to automatically disable emission based on the ShaderGraph config when emission is black, - // we will need a more general way to communicate this to the engine (not directly tied to a material property). - collector.AddShaderProperty(new ColorShaderProperty() - { - overrideReferenceName = "_EmissionColor", - hidden = true, - value = new Color(1.0f, 1.0f, 1.0f, 1.0f) - }); - - //See SG-ADDITIONALVELOCITY-NOTE - if (addPrecomputedVelocity.isOn) - { - collector.AddShaderProperty(new BooleanShaderProperty - { - value = true, - hidden = true, - overrideReferenceName = kAddPrecomputedVelocity, - }); - } - - // Add all shader properties required by the inspector - HDSubShaderUtilities.AddStencilShaderProperties(collector, RequiresSplitLighting(), receiveSSR.isOn, receiveSSR.isOn, false); - HDSubShaderUtilities.AddBlendingStatesShaderProperties( - collector, - surfaceType, - HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode), - sortPriority, - alphaToMask.isOn, - zWrite.isOn, - transparentCullMode, - zTest, - false, - transparencyFog.isOn - ); - HDSubShaderUtilities.AddAlphaCutoffShaderProperties(collector, alphaTest.isOn, false); - HDSubShaderUtilities.AddDoubleSidedProperty(collector, doubleSidedMode); - HDSubShaderUtilities.AddPrePostPassProperties(collector, alphaTestDepthPrepass.isOn, alphaTestDepthPostpass.isOn); - - base.CollectShaderProperties(collector, generationMode); - } - - public bool supportsVirtualTexturing => true; - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyePass.template b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyePass.template index ac790f4bc41..fb462570346 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyePass.template +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyePass.template @@ -152,7 +152,7 @@ Pass surfaceData.specularOcclusion = 1.0; // copy across graph values, if defined - $SurfaceDescription.Albedo: surfaceData.baseColor = surfaceDescription.Albedo; + $SurfaceDescription.BaseColor: surfaceData.baseColor = surfaceDescription.BaseColor; $SurfaceDescription.SpecularOcclusion: surfaceData.specularOcclusion = surfaceDescription.SpecularOcclusion; $SurfaceDescription.Smoothness: surfaceData.perceptualSmoothness = surfaceDescription.Smoothness; $SurfaceDescription.Occlusion: surfaceData.ambientOcclusion = surfaceDescription.Occlusion; @@ -184,7 +184,7 @@ Pass // tangent-space normal float3 normalTS = float3(0.0f, 0.0f, 1.0f); - $SurfaceDescription.Normal: normalTS = surfaceDescription.Normal; + $SurfaceDescription.NormalTS: normalTS = surfaceDescription.NormalTS; // compute world space normal GetNormalWS(fragInputs, normalTS, surfaceData.normalWS, doubleSidedConstants); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSettingsView.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSettingsView.cs deleted file mode 100644 index f4834dc03dc..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSettingsView.cs +++ /dev/null @@ -1,478 +0,0 @@ -using System; -using UnityEditor.UIElements; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEditor.Graphing.Util; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEngine.Rendering.HighDefinition; -using UnityEngine.Rendering; - -namespace UnityEditor.Rendering.HighDefinition.Drawing -{ - class EyeSettingsView : MasterNodeSettingsView - { - EyeMasterNode m_Node; - - IntegerField m_SortPiorityField; - - Label CreateLabel(string text, int indentLevel) - { - string label = ""; - for (var i = 0; i < indentLevel; i++) - { - label += " "; - } - return new Label(label + text); - } - - public EyeSettingsView(EyeMasterNode node) : base(node) - { - m_Node = node; - PropertySheet ps = new PropertySheet(); - - int indentLevel = 0; - ps.Add(new PropertyRow(CreateLabel("Surface Type", indentLevel)), (row) => - { - row.Add(new EnumField(SurfaceType.Opaque), (field) => - { - field.value = m_Node.surfaceType; - field.RegisterValueChangedCallback(ChangeSurfaceType); - }); - }); - - if (m_Node.surfaceType == SurfaceType.Transparent) - { - ++indentLevel; - - ps.Add(new PropertyRow(CreateLabel("Blend Preserves Specular", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.blendPreserveSpecular.isOn; - toggle.OnToggleChanged(ChangeBlendPreserveSpecular); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Fog", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.transparencyFog.isOn; - toggle.OnToggleChanged(ChangeTransparencyFog); - }); - }); - - m_SortPiorityField = new IntegerField(); - ps.Add(new PropertyRow(CreateLabel("Sort Priority", indentLevel)), (row) => - { - row.Add(m_SortPiorityField, (field) => - { - field.value = m_Node.sortPriority; - field.RegisterValueChangedCallback(ChangeSortPriority); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Depth Write", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.zWrite.isOn; - toggle.OnToggleChanged(ChangeZWrite); - }); - }); - - if (m_Node.doubleSidedMode == DoubleSidedMode.Disabled) - { - ps.Add(new PropertyRow(CreateLabel("Cull Mode", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.transparentCullMode), (e) => - { - e.value = m_Node.transparentCullMode; - e.RegisterValueChangedCallback(ChangeTransparentCullMode); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Depth Test", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.zTest), (e) => - { - e.value = m_Node.zTest; - e.RegisterValueChangedCallback(ChangeZTest); - }); - }); - - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Alpha Clipping", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTest.isOn; - toggle.OnToggleChanged(ChangeAlphaTest); - }); - }); - - if (m_Node.alphaTest.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Alpha to Mask", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaToMask.isOn; - toggle.OnToggleChanged(ChangeAlphaToMask); - }); - }); - - if (m_Node.surfaceType == SurfaceType.Transparent) - { - ps.Add(new PropertyRow(CreateLabel("Alpha Cutoff Depth Prepass", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestDepthPrepass.isOn; - toggle.OnToggleChanged(ChangeAlphaTestPrepass); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Alpha Cutoff Depth Postpass", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestDepthPostpass.isOn; - toggle.OnToggleChanged(ChangeAlphaTestPostpass); - }); - }); - } - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Double-Sided", indentLevel)), (row) => - { - row.Add(new EnumField(DoubleSidedMode.Disabled), (field) => - { - field.value = m_Node.doubleSidedMode; - field.RegisterValueChangedCallback(ChangeDoubleSidedMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Material Type", indentLevel)), (row) => - { - row.Add(new EnumField(EyeMasterNode.MaterialType.Eye), (field) => - { - field.value = m_Node.materialType; - field.RegisterValueChangedCallback(ChangeMaterialType); - }); - }); - - if (m_Node.surfaceType != SurfaceType.Transparent) - { - ps.Add(new PropertyRow(CreateLabel("Subsurface Scattering", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.subsurfaceScattering.isOn; - toggle.OnToggleChanged(ChangeSubsurfaceScattering); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Receive Decals", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.receiveDecals.isOn; - toggle.OnToggleChanged(ChangeDecal); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Receive SSR", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.receiveSSR.isOn; - toggle.OnToggleChanged(ChangeSSR); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Add Precomputed Velocity", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.addPrecomputedVelocity.isOn; - toggle.OnToggleChanged(ChangeAddPrecomputedVelocity); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion Mode", indentLevel)), (row) => - { - row.Add(new EnumField(SpecularOcclusionMode.Off), (field) => - { - field.value = m_Node.specularOcclusionMode; - field.RegisterValueChangedCallback(ChangeSpecularOcclusionMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Override Baked GI", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.overrideBakedGI.isOn; - toggle.OnToggleChanged(ChangeoverrideBakedGI); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Depth Offset", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.depthOffset.isOn; - toggle.OnToggleChanged(ChangeDepthOffset); - }); - }); - - - ps.Add(new PropertyRow(CreateLabel("Support LOD CrossFade", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.supportLodCrossFade.isOn; - toggle.OnToggleChanged(ChangeSupportLODCrossFade); - }); - }); - - Add(ps); - Add(GetShaderGUIOverridePropertySheet()); - } - - void ChangeSurfaceType(ChangeEvent evt) - { - if (Equals(m_Node.surfaceType, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Surface Type Change"); - m_Node.surfaceType = (SurfaceType)evt.newValue; - } - - void ChangeDoubleSidedMode(ChangeEvent evt) - { - if (Equals(m_Node.doubleSidedMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Double-Sided Mode Change"); - m_Node.doubleSidedMode = (DoubleSidedMode)evt.newValue; - } - - void ChangeMaterialType(ChangeEvent evt) - { - if (Equals(m_Node.materialType, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Material Type Change"); - m_Node.materialType = (EyeMasterNode.MaterialType)evt.newValue; - } - - void ChangeSubsurfaceScattering(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SSS Change"); - ToggleData td = m_Node.subsurfaceScattering; - td.isOn = evt.newValue; - m_Node.subsurfaceScattering = td; - } - - void ChangeBlendMode(ChangeEvent evt) - { - // Make sure the mapping is correct by handling each case. - AlphaMode alphaMode = GetAlphaMode((EyeMasterNode.AlphaModeEye)evt.newValue); - - if (Equals(m_Node.alphaMode, alphaMode)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Mode Change"); - m_Node.alphaMode = alphaMode; - } - - void ChangeBlendPreserveSpecular(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Blend Preserve Specular Change"); - ToggleData td = m_Node.blendPreserveSpecular; - td.isOn = evt.newValue; - m_Node.blendPreserveSpecular = td; - } - - void ChangeTransparencyFog(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparency Fog Change"); - ToggleData td = m_Node.transparencyFog; - td.isOn = evt.newValue; - m_Node.transparencyFog = td; - } - - void ChangeSortPriority(ChangeEvent evt) - { - m_Node.sortPriority = HDRenderQueue.ClampsTransparentRangePriority(evt.newValue); - // Force the text to match. - m_SortPiorityField.value = m_Node.sortPriority; - if (Equals(m_Node.sortPriority, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Sort Priority Change"); - } - - void ChangeZWrite(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("ZWrite Change"); - ToggleData td = m_Node.zWrite; - td.isOn = evt.newValue; - m_Node.zWrite = td; - } - - void ChangeAlphaTest(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Change"); - ToggleData td = m_Node.alphaTest; - td.isOn = evt.newValue; - m_Node.alphaTest = td; - } - - void ChangeAlphaToMask(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha to Mask Change"); - ToggleData td = m_Node.alphaToMask; - td.isOn = evt.newValue; - m_Node.alphaToMask = td; - } - - void ChangeAlphaTestPrepass(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Prepass Change"); - ToggleData td = m_Node.alphaTestDepthPrepass; - td.isOn = evt.newValue; - m_Node.alphaTestDepthPrepass = td; - } - - void ChangeAlphaTestPostpass(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Postpass Change"); - ToggleData td = m_Node.alphaTestDepthPostpass; - td.isOn = evt.newValue; - m_Node.alphaTestDepthPostpass = td; - } - - void ChangeDecal(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Decal Change"); - ToggleData td = m_Node.receiveDecals; - td.isOn = evt.newValue; - m_Node.receiveDecals = td; - } - - void ChangeSSR(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SSR Change"); - ToggleData td = m_Node.receiveSSR; - td.isOn = evt.newValue; - m_Node.receiveSSR = td; - } - - void ChangeAddPrecomputedVelocity(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Add Precomputed Velocity"); - ToggleData td = m_Node.addPrecomputedVelocity; - td.isOn = evt.newValue; - m_Node.addPrecomputedVelocity = td; - } - - void ChangeSpecularOcclusionMode(ChangeEvent evt) - { - if (Equals(m_Node.specularOcclusionMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Specular Occlusion Mode Change"); - m_Node.specularOcclusionMode = (SpecularOcclusionMode)evt.newValue; - } - - void ChangeoverrideBakedGI(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("overrideBakedGI Change"); - ToggleData td = m_Node.overrideBakedGI; - td.isOn = evt.newValue; - m_Node.overrideBakedGI = td; - } - - void ChangeDepthOffset(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("DepthOffset Change"); - ToggleData td = m_Node.depthOffset; - td.isOn = evt.newValue; - m_Node.depthOffset = td; - } - - void ChangeTransparentCullMode(ChangeEvent evt) - { - if (Equals(m_Node.transparentCullMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparent Cull Mode Change"); - m_Node.transparentCullMode = (TransparentCullMode)evt.newValue; - } - - void ChangeZTest(ChangeEvent evt) - { - if (Equals(m_Node.zTest, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("ZTest Change"); - m_Node.zTest = (CompareFunction)evt.newValue; - } - - void ChangeSupportLODCrossFade(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Support LOD CrossFade Change"); - ToggleData td = m_Node.supportLodCrossFade; - td.isOn = evt.newValue; - m_Node.supportLodCrossFade = td; - } - - public AlphaMode GetAlphaMode(EyeMasterNode.AlphaModeEye alphaModeLit) - { - switch (alphaModeLit) - { - case EyeMasterNode.AlphaModeEye.Alpha: - return AlphaMode.Alpha; - case EyeMasterNode.AlphaModeEye.Premultiply: - return AlphaMode.Premultiply; - case EyeMasterNode.AlphaModeEye.Additive: - return AlphaMode.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaModeLit); - return AlphaMode.Alpha; - } - - } - } - - public EyeMasterNode.AlphaModeEye GetAlphaModeLit(AlphaMode alphaMode) - { - switch (alphaMode) - { - case AlphaMode.Alpha: - return EyeMasterNode.AlphaModeEye.Alpha; - case AlphaMode.Premultiply: - return EyeMasterNode.AlphaModeEye.Premultiply; - case AlphaMode.Additive: - return EyeMasterNode.AlphaModeEye.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaMode); - return EyeMasterNode.AlphaModeEye.Alpha; - } - } - } - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.Migration.cs new file mode 100644 index 00000000000..948f9d206d1 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.Migration.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + sealed partial class EyeSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData + { + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is EyeMasterNode1 eyeMasterNode)) + return false; + + // Set data + systemData.surfaceType = (SurfaceType)eyeMasterNode.m_SurfaceType; + systemData.blendMode = HDSubShaderUtilities.UpgradeLegacyAlphaModeToBlendMode((int)eyeMasterNode.m_AlphaMode); + // Previous master node wasn't having any renderingPass. Assign it correctly now. + systemData.renderingPass = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; + systemData.alphaTest = eyeMasterNode.m_AlphaTest; + systemData.alphaTestDepthPrepass = eyeMasterNode.m_AlphaTestDepthPrepass; + systemData.alphaTestDepthPostpass = eyeMasterNode.m_AlphaTestDepthPostpass; + systemData.sortPriority = eyeMasterNode.m_SortPriority; + systemData.doubleSidedMode = eyeMasterNode.m_DoubleSidedMode; + systemData.zWrite = eyeMasterNode.m_ZWrite; + systemData.transparentCullMode = eyeMasterNode.m_transparentCullMode; + systemData.zTest = eyeMasterNode.m_ZTest; + systemData.supportLodCrossFade = eyeMasterNode.m_SupportLodCrossFade; + systemData.dotsInstancing = eyeMasterNode.m_DOTSInstancing; + systemData.materialNeedsUpdateHash = eyeMasterNode.m_MaterialNeedsUpdateHash; + + builtinData.transparencyFog = eyeMasterNode.m_TransparencyFog; + builtinData.addPrecomputedVelocity = eyeMasterNode.m_AddPrecomputedVelocity; + builtinData.depthOffset = eyeMasterNode.m_depthOffset; + builtinData.alphaToMask = eyeMasterNode.m_AlphaToMask; + + lightingData.blendPreserveSpecular = eyeMasterNode.m_BlendPreserveSpecular; + lightingData.receiveDecals = eyeMasterNode.m_ReceiveDecals; + lightingData.receiveSSR = eyeMasterNode.m_ReceivesSSR; + lightingData.receiveSSRTransparent = eyeMasterNode.m_ReceivesSSRTransparent; + lightingData.specularOcclusionMode = eyeMasterNode.m_SpecularOcclusionMode; + lightingData.overrideBakedGI = eyeMasterNode.m_overrideBakedGI; + lightingData.subsurfaceScattering = eyeMasterNode.m_SubsurfaceScattering; + + eyeData.materialType = (EyeData.MaterialType)eyeMasterNode.m_MaterialType; + target.customEditorGUI = eyeMasterNode.m_OverrideEnabled ? eyeMasterNode.m_ShaderGUIOverride : ""; + + // Convert SlotMask to BlockMap entries + var blockMapLookup = new Dictionary() + { + { EyeMasterNode1.SlotMask.Position, BlockFields.VertexDescription.Position }, + { EyeMasterNode1.SlotMask.VertexNormal, BlockFields.VertexDescription.Normal }, + { EyeMasterNode1.SlotMask.VertexTangent, BlockFields.VertexDescription.Tangent }, + { EyeMasterNode1.SlotMask.Albedo, BlockFields.SurfaceDescription.BaseColor }, + { EyeMasterNode1.SlotMask.SpecularOcclusion, HDBlockFields.SurfaceDescription.SpecularOcclusion }, + { EyeMasterNode1.SlotMask.Normal, BlockFields.SurfaceDescription.NormalTS }, + { EyeMasterNode1.SlotMask.IrisNormal, HDBlockFields.SurfaceDescription.IrisNormal }, + { EyeMasterNode1.SlotMask.BentNormal, HDBlockFields.SurfaceDescription.BentNormal }, + { EyeMasterNode1.SlotMask.Smoothness, BlockFields.SurfaceDescription.Smoothness }, + { EyeMasterNode1.SlotMask.IOR, HDBlockFields.SurfaceDescription.IOR }, + { EyeMasterNode1.SlotMask.Occlusion, BlockFields.SurfaceDescription.Occlusion }, + { EyeMasterNode1.SlotMask.Mask, HDBlockFields.SurfaceDescription.Mask }, + { EyeMasterNode1.SlotMask.DiffusionProfile, HDBlockFields.SurfaceDescription.DiffusionProfileHash }, + { EyeMasterNode1.SlotMask.SubsurfaceMask, HDBlockFields.SurfaceDescription.SubsurfaceMask }, + { EyeMasterNode1.SlotMask.Emission, BlockFields.SurfaceDescription.Emission }, + { EyeMasterNode1.SlotMask.Alpha, BlockFields.SurfaceDescription.Alpha }, + { EyeMasterNode1.SlotMask.AlphaClipThreshold, BlockFields.SurfaceDescription.AlphaClipThreshold }, + }; + + // Legacy master node slots have additional slot conditions, test them here + bool AdditionalSlotMaskTests(EyeMasterNode1.SlotMask slotMask) + { + switch(slotMask) + { + case EyeMasterNode1.SlotMask.SpecularOcclusion: + return lightingData.specularOcclusionMode == SpecularOcclusionMode.Custom; + case EyeMasterNode1.SlotMask.DiffusionProfile: + return lightingData.subsurfaceScattering; + case EyeMasterNode1.SlotMask.SubsurfaceMask: + return lightingData.subsurfaceScattering; + case EyeMasterNode1.SlotMask.AlphaClipThreshold: + return systemData.alphaTest; + default: + return true; + } + } + + // Set blockmap + blockMap = new Dictionary(); + foreach(EyeMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(EyeMasterNode1.SlotMask))) + { + if(eyeMasterNode.MaterialTypeUsesSlotMask(slotMask)) + { + if(!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) + continue; + + if(!AdditionalSlotMaskTests(slotMask)) + continue; + + var slotId = Mathf.Log((int)slotMask, 2); + blockMap.Add(blockFieldDescriptor, (int)slotId); + } + } + + // Override Baked GI + if(lightingData.overrideBakedGI) + { + blockMap.Add(HDBlockFields.SurfaceDescription.BakedGI, EyeMasterNode1.LightingSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.BakedBackGI, EyeMasterNode1.BackLightingSlotId); + } + + // Depth Offset + if(builtinData.depthOffset) + { + blockMap.Add(HDBlockFields.SurfaceDescription.DepthOffset, EyeMasterNode1.DepthOffsetSlotId); + } + + return true; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.Migration.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.Migration.cs.meta new file mode 100644 index 00000000000..b49e04e9f1d --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.Migration.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c43943c04106ed4418f28341b8bc7388 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/HDEyeSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.cs similarity index 57% rename from com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/HDEyeSubTarget.cs rename to com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.cs index 56fbb0a4a68..5c70bd5e45d 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/HDEyeSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.cs @@ -1,23 +1,76 @@ -using UnityEngine.Rendering.HighDefinition; +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { - sealed class HDEyeSubTarget : SubTarget + sealed partial class EyeSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData { - const string kAssetGuid = "864e4e09d6293cf4d98457f740bb3301"; static string passTemplatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/Eye/ShaderGraph/EyePass.template"; + protected override string customInspector => "Rendering.HighDefinition.EyeGUI"; + protected override string subTargetAssetGuid => "864e4e09d6293cf4d98457f740bb3301"; + protected override ShaderID shaderID => HDShaderUtils.ShaderID.SG_Eye; - public HDEyeSubTarget() + public EyeSubTarget() => displayName = "Eye"; + + EyeData m_EyeData; + + EyeData IRequiresData.data + { + get => m_EyeData; + set => m_EyeData = value; + } + + public EyeData eyeData { - displayName = "Eye"; + get => m_EyeData; + set => m_EyeData = value; } - public override void Setup(ref TargetSetupContext context) + protected override IEnumerable EnumerateSubShaders() { - context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); - context.SetDefaultShaderGUI("Rendering.HighDefinition.EyeGUI"); - context.AddSubShader(SubShaders.Eye); + yield return SubShaders.Eye; + } + + public override void GetFields(ref TargetFieldContext context) + { + base.GetFields(ref context); + + // Eye specific properties + context.AddField(HDStructFields.FragInputs.IsFrontFace, systemData.doubleSidedMode != DoubleSidedMode.Disabled && !context.pass.Equals(EyeSubTarget.EyePasses.MotionVectors)); + context.AddField(HDFields.Eye, eyeData.materialType == EyeData.MaterialType.Eye); + context.AddField(HDFields.EyeCinematic, eyeData.materialType == EyeData.MaterialType.EyeCinematic); + context.AddField(HDFields.SubsurfaceScattering, lightingData.subsurfaceScattering && systemData.surfaceType != SurfaceType.Transparent); + context.AddField(HDFields.DoAlphaTest, systemData.alphaTest && context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.AlphaClipThreshold)); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + base.GetActiveBlocks(ref context); + + // Eye specific blocks + context.AddBlock(BlockFields.SurfaceDescription.NormalTS); + context.AddBlock(HDBlockFields.SurfaceDescription.IrisNormal); + context.AddBlock(HDBlockFields.SurfaceDescription.BentNormal); + context.AddBlock(HDBlockFields.SurfaceDescription.IOR); + context.AddBlock(HDBlockFields.SurfaceDescription.Mask); + context.AddBlock(HDBlockFields.SurfaceDescription.DiffusionProfileHash, lightingData.subsurfaceScattering); + context.AddBlock(HDBlockFields.SurfaceDescription.SubsurfaceMask, lightingData.subsurfaceScattering); + } + + protected override void AddInspectorPropertyBlocks(SubTargetPropertiesGUI blockList) + { + blockList.AddPropertyBlock(new EyeSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features.Lit, eyeData)); + blockList.AddPropertyBlock(new AdvancedOptionsPropertyBlock()); } #region SubShaders @@ -56,7 +109,7 @@ public static class EyePasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - pixelPorts = EyePortMasks.FragmentMETA, + validPixelBlocks = EyeBlockMasks.FragmentMETA, // Collections structs = CoreStructCollections.Default, @@ -81,8 +134,8 @@ public static class EyePasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = EyePortMasks.Vertex, - pixelPorts = EyePortMasks.FragmentAlphaDepth, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = EyeBlockMasks.FragmentAlphaDepth, // Collections structs = CoreStructCollections.Default, @@ -106,8 +159,8 @@ public static class EyePasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = EyePortMasks.Vertex, - pixelPorts = EyePortMasks.FragmentAlphaDepth, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = EyeBlockMasks.FragmentAlphaDepth, // Collections structs = CoreStructCollections.Default, @@ -132,8 +185,8 @@ public static class EyePasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = EyePortMasks.Vertex, - pixelPorts = EyePortMasks.FragmentDepthMotionVectors, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = EyeBlockMasks.FragmentDepthMotionVectors, // Collections structs = CoreStructCollections.Default, @@ -159,8 +212,8 @@ public static class EyePasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = EyePortMasks.Vertex, - pixelPorts = EyePortMasks.FragmentDepthMotionVectors, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = EyeBlockMasks.FragmentDepthMotionVectors, // Collections structs = CoreStructCollections.Default, @@ -186,8 +239,8 @@ public static class EyePasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = EyePortMasks.Vertex, - pixelPorts = EyePortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = EyeBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -202,67 +255,60 @@ public static class EyePasses } #endregion -#region PortMasks - static class EyePortMasks +#region BlockMasks + static class EyeBlockMasks { - public static int[] Vertex = new int[] - { - EyeMasterNode.PositionSlotId, - EyeMasterNode.VertexNormalSlotID, - EyeMasterNode.VertexTangentSlotID, - }; - - public static int[] FragmentMETA = new int[] + public static BlockFieldDescriptor[] FragmentMETA = new BlockFieldDescriptor[] { - EyeMasterNode.AlbedoSlotId, - EyeMasterNode.SpecularOcclusionSlotId, - EyeMasterNode.NormalSlotId, - EyeMasterNode.IrisNormalSlotId, - EyeMasterNode.SmoothnessSlotId, - EyeMasterNode.IORSlotId, - EyeMasterNode.AmbientOcclusionSlotId, - EyeMasterNode.MaskSlotId, - EyeMasterNode.DiffusionProfileHashSlotId, - EyeMasterNode.SubsurfaceMaskSlotId, - EyeMasterNode.EmissionSlotId, - EyeMasterNode.AlphaSlotId, - EyeMasterNode.AlphaClipThresholdSlotId, + BlockFields.SurfaceDescription.BaseColor, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.IrisNormal, + BlockFields.SurfaceDescription.Smoothness, + HDBlockFields.SurfaceDescription.IOR, + BlockFields.SurfaceDescription.Occlusion, + HDBlockFields.SurfaceDescription.Mask, + HDBlockFields.SurfaceDescription.DiffusionProfileHash, + HDBlockFields.SurfaceDescription.SubsurfaceMask, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, }; - public static int[] FragmentAlphaDepth = new int[] + public static BlockFieldDescriptor[] FragmentAlphaDepth = new BlockFieldDescriptor[] { - EyeMasterNode.AlphaSlotId, - EyeMasterNode.AlphaClipThresholdSlotId, - EyeMasterNode.DepthOffsetSlotId, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, }; - public static int[] FragmentDepthMotionVectors = new int[] + public static BlockFieldDescriptor[] FragmentDepthMotionVectors = new BlockFieldDescriptor[] { - EyeMasterNode.NormalSlotId, - EyeMasterNode.SmoothnessSlotId, - EyeMasterNode.AlphaSlotId, - EyeMasterNode.AlphaClipThresholdSlotId, - EyeMasterNode.DepthOffsetSlotId, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, }; - public static int[] FragmentForward = new int[] + public static BlockFieldDescriptor[] FragmentForward = new BlockFieldDescriptor[] { - EyeMasterNode.AlbedoSlotId, - EyeMasterNode.SpecularOcclusionSlotId, - EyeMasterNode.NormalSlotId, - EyeMasterNode.IrisNormalSlotId, - EyeMasterNode.SmoothnessSlotId, - EyeMasterNode.IORSlotId, - EyeMasterNode.AmbientOcclusionSlotId, - EyeMasterNode.MaskSlotId, - EyeMasterNode.DiffusionProfileHashSlotId, - EyeMasterNode.SubsurfaceMaskSlotId, - EyeMasterNode.EmissionSlotId, - EyeMasterNode.AlphaSlotId, - EyeMasterNode.AlphaClipThresholdSlotId, - EyeMasterNode.LightingSlotId, - EyeMasterNode.BackLightingSlotId, - EyeMasterNode.DepthOffsetSlotId, + BlockFields.SurfaceDescription.BaseColor, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.IrisNormal, + BlockFields.SurfaceDescription.Smoothness, + HDBlockFields.SurfaceDescription.IOR, + BlockFields.SurfaceDescription.Occlusion, + HDBlockFields.SurfaceDescription.Mask, + HDBlockFields.SurfaceDescription.DiffusionProfileHash, + HDBlockFields.SurfaceDescription.SubsurfaceMask, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.BakedGI, + HDBlockFields.SurfaceDescription.BakedBackGI, + HDBlockFields.SurfaceDescription.DepthOffset, }; } #endregion diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/HDEyeSubTarget.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.cs.meta similarity index 100% rename from com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/HDEyeSubTarget.cs.meta rename to com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSurfaceOptionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSurfaceOptionPropertyBlock.cs new file mode 100644 index 00000000000..2e23349ff3f --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSurfaceOptionPropertyBlock.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.LitSurfaceInputsUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.SurfaceOptionUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.RefractionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class EyeSurfaceOptionPropertyBlock : SurfaceOptionPropertyBlock + { + class Styles + { + public static GUIContent materialType = new GUIContent("Material Type", "TODO"); + } + + EyeData eyeData; + + public EyeSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features features, EyeData eyeData) : base(features) + => this.eyeData = eyeData; + + protected override void CreatePropertyGUI() + { + AddProperty(Styles.materialType, () => eyeData.materialType, (newValue) => eyeData.materialType = newValue); + + base.CreatePropertyGUI(); + + // Eye specific properties: + AddProperty(subsurfaceEnableText, () => lightingData.subsurfaceScattering, (newValue) => lightingData.subsurfaceScattering = newValue); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSurfaceOptionPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSurfaceOptionPropertyBlock.cs.meta new file mode 100644 index 00000000000..93aa4315e03 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSurfaceOptionPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8457a6f490f4bd24cb340713da4c499c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs index c9623bc80ea..d7425d7c14a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs @@ -1,13 +1,32 @@ +using System; using UnityEditor.ShaderGraph; -namespace UnityEditor.Rendering.HighDefinition +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { static class CreateFabricShaderGraph { - [MenuItem("Assets/Create/Shader/HDRP/Fabric Graph", false, 208)] - public static void CreateMaterialGraph() + [MenuItem("Assets/Create/Shader/HDRP/Fabric Shader Graph", false, 208)] + public static void CreateFabricGraph() { - GraphUtil.CreateNewGraph(new FabricMasterNode()); + var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); + target.TrySetActiveSubTarget(typeof(FabricSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.BentNormal, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Specular, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs.meta index 03b644fbc59..ff8390dbadf 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 55a9196e05a8afc468cef4634dfa4ef7 +guid: e39e89b8b5ef7b8448a07c1f5c36da5f MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricData.cs new file mode 100644 index 00000000000..1cd2953ef3c --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricData.cs @@ -0,0 +1,39 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class FabricData : HDTargetData + { + public enum MaterialType + { + CottonWool, + Silk + } + + [SerializeField] + MaterialType m_MaterialType; + public MaterialType materialType + { + get => m_MaterialType; + set => m_MaterialType = value; + } + + [SerializeField] + bool m_EnergyConservingSpecular = true; + public bool energyConservingSpecular + { + get => m_EnergyConservingSpecular; + set => m_EnergyConservingSpecular = value; + } + + [SerializeField] + bool m_Transmission = false; + public bool transmission + { + get => m_Transmission; + set => m_Transmission = value; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricData.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricData.cs.meta new file mode 100644 index 00000000000..167fac05771 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 68c571ff13c4d2641b2e3c7ba6c53971 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricMasterNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricMasterNode.cs deleted file mode 100644 index c95c1714506..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricMasterNode.cs +++ /dev/null @@ -1,965 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEngine.Rendering.HighDefinition; -using UnityEngine.Rendering; -using UnityEditor.Rendering.HighDefinition.Drawing; -using UnityEditor.ShaderGraph.Internal; -using UnityEditor.Rendering.HighDefinition.ShaderGraph; - -// Include material common properties names -using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; - -namespace UnityEditor.Rendering.HighDefinition -{ - [Serializable] - [Title("Master", "Fabric (HDRP)")] - [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.FabricMasterNode")] - [FormerName("UnityEditor.ShaderGraph.FabricMasterNode")] - class FabricMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string PositionSlotName = "Vertex Position"; - public const string PositionSlotDisplayName = "Vertex Position"; - public const int PositionSlotId = 0; - - public const string AlbedoSlotName = "Albedo"; - public const string AlbedoDisplaySlotName = "BaseColor"; - public const int AlbedoSlotId = 1; - - public const string SpecularOcclusionSlotName = "SpecularOcclusion"; - public const int SpecularOcclusionSlotId = 2; - - public const string NormalSlotName = "Normal"; - public const int NormalSlotId = 3; - - public const string SmoothnessSlotName = "Smoothness"; - public const int SmoothnessSlotId = 4; - - public const string AmbientOcclusionSlotName = "Occlusion"; - public const string AmbientOcclusionDisplaySlotName = "AmbientOcclusion"; - public const int AmbientOcclusionSlotId = 5; - - public const string SpecularColorSlotName = "Specular"; - public const string SpecularColorDisplaySlotName = "SpecularColor"; - public const int SpecularColorSlotId = 6; - - public const string DiffusionProfileHashSlotName = "DiffusionProfileHash"; - public const string DiffusionProfileHashSlotDisplayName = "Diffusion Profile"; - public const int DiffusionProfileHashSlotId = 7; - - public const string SubsurfaceMaskSlotName = "SubsurfaceMask"; - public const int SubsurfaceMaskSlotId = 8; - - public const string ThicknessSlotName = "Thickness"; - public const int ThicknessSlotId = 9; - - public const string TangentSlotName = "Tangent"; - public const int TangentSlotId = 10; - - public const string AnisotropySlotName = "Anisotropy"; - public const int AnisotropySlotId = 11; - - public const string EmissionSlotName = "Emission"; - public const int EmissionSlotId = 12; - - public const string AlphaSlotName = "Alpha"; - public const int AlphaSlotId = 13; - - public const string AlphaClipThresholdSlotName = "AlphaClipThreshold"; - public const int AlphaClipThresholdSlotId = 14; - - public const string BentNormalSlotName = "BentNormal"; - public const int BentNormalSlotId = 15; - - public const int LightingSlotId = 16; - public const string BakedGISlotName = "BakedGI"; - - public const int BackLightingSlotId = 17; - public const string BakedBackGISlotName = "BakedBackGI"; - - public const int DepthOffsetSlotId = 18; - public const string DepthOffsetSlotName = "DepthOffset"; - public const int VertexNormalSlotId = 19; - public const string VertexNormalSlotName = "Vertex Normal"; - public const int VertexTangentSlotId = 20; - public const string VertexTangentSlotName = "Vertex Tangent"; - - public enum MaterialType - { - CottonWool, - Silk - } - - // Don't support Multiply - public enum AlphaModeFabric - { - Alpha, - Premultiply, - Additive, - } - - // Just for convenience of doing simple masks. We could run out of bits of course. - [Flags] - enum SlotMask - { - None = 0, - Position = 1 << PositionSlotId, - Albedo = 1 << AlbedoSlotId, - SpecularOcclusion = 1 << SpecularOcclusionSlotId, - Normal = 1 << NormalSlotId, - Smoothness = 1 << SmoothnessSlotId, - Occlusion = 1 << AmbientOcclusionSlotId, - Specular = 1 << SpecularColorSlotId, - DiffusionProfile = 1 << DiffusionProfileHashSlotId, - SubsurfaceMask = 1 << SubsurfaceMaskSlotId, - Thickness = 1 << ThicknessSlotId, - Tangent = 1 << TangentSlotId, - Anisotropy = 1 << AnisotropySlotId, - Emission = 1 << EmissionSlotId, - Alpha = 1 << AlphaSlotId, - AlphaClipThreshold = 1 << AlphaClipThresholdSlotId, - BentNormal = 1 << BentNormalSlotId, - BakedGI = 1 << LightingSlotId, - BakedBackGI = 1 << BackLightingSlotId, - DepthOffset = 1 << DepthOffsetSlotId, - VertexNormal = 1 << VertexNormalSlotId, - VertexTangent = 1 << VertexTangentSlotId, - } - - const SlotMask CottonWoolSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.SpecularOcclusion | SlotMask.Normal | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.Specular | SlotMask.DiffusionProfile | SlotMask.SubsurfaceMask | SlotMask.Thickness | SlotMask.Emission | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.BentNormal | SlotMask.BakedGI | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; - const SlotMask SilkSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.SpecularOcclusion | SlotMask.Normal | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.Specular | SlotMask.DiffusionProfile | SlotMask.SubsurfaceMask | SlotMask.Thickness | SlotMask.Tangent | SlotMask.Anisotropy | SlotMask.Emission | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.BentNormal | SlotMask.BakedGI | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; - - // This could also be a simple array. For now, catch any mismatched data. - SlotMask GetActiveSlotMask() - { - switch (materialType) - { - case MaterialType.CottonWool: - return CottonWoolSlotMask; - - case MaterialType.Silk: - return SilkSlotMask; - - default: - return SlotMask.None; - } - } - - bool MaterialTypeUsesSlotMask(SlotMask mask) - { - SlotMask activeMask = GetActiveSlotMask(); - return (activeMask & mask) != 0; - } - - [SerializeField] - SurfaceType m_SurfaceType; - - public SurfaceType surfaceType - { - get { return m_SurfaceType; } - set - { - if (m_SurfaceType == value) - return; - - m_SurfaceType = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - AlphaMode m_AlphaMode; - - public AlphaMode alphaMode - { - get { return m_AlphaMode; } - set - { - if (m_AlphaMode == value) - return; - - m_AlphaMode = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_BlendPreserveSpecular = true; - - public ToggleData blendPreserveSpecular - { - get { return new ToggleData(m_BlendPreserveSpecular); } - set - { - if (m_BlendPreserveSpecular == value.isOn) - return; - m_BlendPreserveSpecular = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_TransparencyFog = true; - - public ToggleData transparencyFog - { - get { return new ToggleData(m_TransparencyFog); } - set - { - if (m_TransparencyFog == value.isOn) - return; - m_TransparencyFog = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaTest; - - public ToggleData alphaTest - { - get { return new ToggleData(m_AlphaTest); } - set - { - if (m_AlphaTest == value.isOn) - return; - m_AlphaTest = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaToMask = false; - - public ToggleData alphaToMask - { - get { return new ToggleData(m_AlphaToMask); } - set - { - if (m_AlphaToMask == value.isOn) - return; - m_AlphaToMask = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaTestDepthPrepass; - - public ToggleData alphaTestDepthPrepass - { - get { return new ToggleData(m_AlphaTestDepthPrepass); } - set - { - if (m_AlphaTestDepthPrepass == value.isOn) - return; - m_AlphaTestDepthPrepass = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaTestDepthPostpass; - - public ToggleData alphaTestDepthPostpass - { - get { return new ToggleData(m_AlphaTestDepthPostpass); } - set - { - if (m_AlphaTestDepthPostpass == value.isOn) - return; - m_AlphaTestDepthPostpass = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - int m_SortPriority; - - public int sortPriority - { - get { return m_SortPriority; } - set - { - if (m_SortPriority == value) - return; - m_SortPriority = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - DoubleSidedMode m_DoubleSidedMode; - - public DoubleSidedMode doubleSidedMode - { - get { return m_DoubleSidedMode; } - set - { - if (m_DoubleSidedMode == value) - return; - - m_DoubleSidedMode = value; - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - MaterialType m_MaterialType; - - public MaterialType materialType - { - get { return m_MaterialType; } - set - { - if (m_MaterialType == value) - return; - - m_MaterialType = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_ReceiveDecals = true; - - public ToggleData receiveDecals - { - get { return new ToggleData(m_ReceiveDecals); } - set - { - if (m_ReceiveDecals == value.isOn) - return; - m_ReceiveDecals = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_ReceivesSSR = true; - public ToggleData receiveSSR - { - get { return new ToggleData(m_ReceivesSSR); } - set - { - if (m_ReceivesSSR == value.isOn) - return; - m_ReceivesSSR = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_ReceivesSSRTransparent = false; - public ToggleData receiveSSRTransparent - { - get { return new ToggleData(m_ReceivesSSRTransparent); } - set - { - if (m_ReceivesSSR == value.isOn) - return; - m_ReceivesSSR = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AddPrecomputedVelocity = false; - - public ToggleData addPrecomputedVelocity - { - get { return new ToggleData(m_AddPrecomputedVelocity); } - set - { - if (m_AddPrecomputedVelocity == value.isOn) - return; - m_AddPrecomputedVelocity = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_EnergyConservingSpecular = true; - - public ToggleData energyConservingSpecular - { - get { return new ToggleData(m_EnergyConservingSpecular); } - set - { - if (m_EnergyConservingSpecular == value.isOn) - return; - m_EnergyConservingSpecular = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_Transmission = false; - - public ToggleData transmission - { - get { return new ToggleData(m_Transmission); } - set - { - if (m_Transmission == value.isOn) - return; - m_Transmission = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_SubsurfaceScattering = false; - - public ToggleData subsurfaceScattering - { - get { return new ToggleData(m_SubsurfaceScattering); } - set - { - if (m_SubsurfaceScattering == value.isOn) - return; - m_SubsurfaceScattering = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - SpecularOcclusionMode m_SpecularOcclusionMode; - - public SpecularOcclusionMode specularOcclusionMode - { - get { return m_SpecularOcclusionMode; } - set - { - if (m_SpecularOcclusionMode == value) - return; - - m_SpecularOcclusionMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_overrideBakedGI; - - public ToggleData overrideBakedGI - { - get { return new ToggleData(m_overrideBakedGI); } - set - { - if (m_overrideBakedGI == value.isOn) - return; - m_overrideBakedGI = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_depthOffset; - - public ToggleData depthOffset - { - get { return new ToggleData(m_depthOffset); } - set - { - if (m_depthOffset == value.isOn) - return; - m_depthOffset = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_ZWrite; - - public ToggleData zWrite - { - get { return new ToggleData(m_ZWrite); } - set - { - if (m_ZWrite == value.isOn) - return; - m_ZWrite = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - TransparentCullMode m_transparentCullMode = TransparentCullMode.Back; - public TransparentCullMode transparentCullMode - { - get => m_transparentCullMode; - set - { - if (m_transparentCullMode == value) - return; - - m_transparentCullMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - CompareFunction m_ZTest = CompareFunction.LessEqual; - public CompareFunction zTest - { - get => m_ZTest; - set - { - if (m_ZTest == value) - return; - - m_ZTest = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_SupportLodCrossFade; - - public ToggleData supportLodCrossFade - { - get { return new ToggleData(m_SupportLodCrossFade); } - set - { - if (m_SupportLodCrossFade == value.isOn) - return; - m_SupportLodCrossFade = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Node); - } - } - - [SerializeField] - bool m_DOTSInstancing = false; - - public ToggleData dotsInstancing - { - get { return new ToggleData(m_DOTSInstancing); } - set - { - if (m_DOTSInstancing == value.isOn) - return; - - m_DOTSInstancing = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - int m_MaterialNeedsUpdateHash = 0; - - int ComputeMaterialNeedsUpdateHash() - { - int hash = 0; - - hash |= (alphaTest.isOn ? 0 : 1) << 0; - hash |= (receiveSSR.isOn ? 0 : 1) << 1; - hash |= (RequiresSplitLighting() ? 0 : 1) << 2; - - return hash; - } - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public FabricMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - public override string documentationURL - { - get { return null; } - } - - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "Fabric Master"; - - List validSlots = new List(); - - // Position - if (MaterialTypeUsesSlotMask(SlotMask.Position)) - { - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionSlotDisplayName, PositionSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(PositionSlotId); - } - - // Normal in Vertex - if (MaterialTypeUsesSlotMask(SlotMask.VertexNormal)) - { - AddSlot(new NormalMaterialSlot(VertexNormalSlotId, VertexNormalSlotName, VertexNormalSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexNormalSlotId); - } - - // tangent in Vertex - if (MaterialTypeUsesSlotMask(SlotMask.VertexTangent)) - { - AddSlot(new TangentMaterialSlot(VertexTangentSlotId, VertexTangentSlotName, VertexTangentSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexTangentSlotId); - } - - // Albedo - if (MaterialTypeUsesSlotMask(SlotMask.Albedo)) - { - AddSlot(new ColorRGBMaterialSlot(AlbedoSlotId, AlbedoDisplaySlotName, AlbedoSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(AlbedoSlotId); - } - - // Specular Occlusion - if (MaterialTypeUsesSlotMask(SlotMask.SpecularOcclusion) && specularOcclusionMode == SpecularOcclusionMode.Custom) - { - AddSlot(new Vector1MaterialSlot(SpecularOcclusionSlotId, SpecularOcclusionSlotName, SpecularOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularOcclusionSlotId); - } - - // Normal - if (MaterialTypeUsesSlotMask(SlotMask.Normal)) - { - AddSlot(new NormalMaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(NormalSlotId); - } - - // BentNormal - if (MaterialTypeUsesSlotMask(SlotMask.BentNormal)) - { - AddSlot(new NormalMaterialSlot(BentNormalSlotId, BentNormalSlotName, BentNormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(BentNormalSlotId); - } - - // Smoothness - if (MaterialTypeUsesSlotMask(SlotMask.Smoothness)) - { - AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(SmoothnessSlotId); - } - - // Ambient Occlusion - if (MaterialTypeUsesSlotMask(SlotMask.Occlusion)) - { - AddSlot(new Vector1MaterialSlot(AmbientOcclusionSlotId, AmbientOcclusionDisplaySlotName, AmbientOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AmbientOcclusionSlotId); - } - - // Specular Color - if (MaterialTypeUsesSlotMask(SlotMask.Specular)) - { - AddSlot(new ColorRGBMaterialSlot(SpecularColorSlotId, SpecularColorDisplaySlotName, SpecularColorSlotName, SlotType.Input, new Color(0.2f,0.2f,0.2f,1.0f), ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularColorSlotId); - } - - // Diffusion Profile - if (MaterialTypeUsesSlotMask(SlotMask.DiffusionProfile) && (subsurfaceScattering.isOn || transmission.isOn)) - { - AddSlot(new DiffusionProfileInputMaterialSlot(DiffusionProfileHashSlotId, DiffusionProfileHashSlotDisplayName, DiffusionProfileHashSlotName, ShaderStageCapability.Fragment)); - validSlots.Add(DiffusionProfileHashSlotId); - } - - // Subsurface mask - if (MaterialTypeUsesSlotMask(SlotMask.SubsurfaceMask) && subsurfaceScattering.isOn) - { - AddSlot(new Vector1MaterialSlot(SubsurfaceMaskSlotId, SubsurfaceMaskSlotName, SubsurfaceMaskSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SubsurfaceMaskSlotId); - } - - // Thickness - if (MaterialTypeUsesSlotMask(SlotMask.Thickness) && transmission.isOn) - { - AddSlot(new Vector1MaterialSlot(ThicknessSlotId, ThicknessSlotName, ThicknessSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(ThicknessSlotId); - } - - // Tangent - if (MaterialTypeUsesSlotMask(SlotMask.Tangent)) - { - AddSlot(new TangentMaterialSlot(TangentSlotId, TangentSlotName, TangentSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(TangentSlotId); - } - - // Anisotropy - if (MaterialTypeUsesSlotMask(SlotMask.Anisotropy)) - { - AddSlot(new Vector1MaterialSlot(AnisotropySlotId, AnisotropySlotName, AnisotropySlotName, SlotType.Input, 0.8f, ShaderStageCapability.Fragment)); - validSlots.Add(AnisotropySlotId); - } - - // Emission Normal - if (MaterialTypeUsesSlotMask(SlotMask.Emission)) - { - AddSlot(new ColorRGBMaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Color.black, ColorMode.HDR, ShaderStageCapability.Fragment)); - validSlots.Add(EmissionSlotId); - } - - // Alpha - if (MaterialTypeUsesSlotMask(SlotMask.Alpha)) - { - AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaSlotId); - } - - // Alpha threshold - if (MaterialTypeUsesSlotMask(SlotMask.AlphaClipThreshold) && alphaTest.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaClipThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaClipThresholdSlotId); - } - - if (MaterialTypeUsesSlotMask(SlotMask.BakedGI) && overrideBakedGI.isOn) - { - AddSlot(new DefaultMaterialSlot(LightingSlotId, BakedGISlotName, BakedGISlotName, ShaderStageCapability.Fragment)); - validSlots.Add(LightingSlotId); - AddSlot(new DefaultMaterialSlot(BackLightingSlotId, BakedBackGISlotName, BakedBackGISlotName, ShaderStageCapability.Fragment)); - validSlots.Add(BackLightingSlotId); - } - - if (depthOffset.isOn) - { - AddSlot(new Vector1MaterialSlot(DepthOffsetSlotId, DepthOffsetSlotName, DepthOffsetSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(DepthOffsetSlotId); - } - - RemoveSlotsNameNotMatching(validSlots, true); - } - - public VisualElement CreateSettingsElement() - { - return new FabricSettingsView(this); - } - - public string renderQueueTag - { - get - { - var renderingPass = surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; - int queue = HDRenderQueue.ChangeType(renderingPass, sortPriority, alphaTest.isOn); - return HDRenderQueue.GetShaderTagValue(queue); - } - } - - public string renderTypeTag => HDRenderTypeTags.HDLitShader.ToString(); - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - var ambientOcclusionSlot = FindSlot(AmbientOcclusionSlotId); - - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PositionSlotId) || - IsSlotConnected(VertexNormalSlotId) || - IsSlotConnected(VertexTangentSlotId)), - new ConditionalField(Fields.GraphPixel, true), - new ConditionalField(Fields.LodCrossFade, supportLodCrossFade.isOn), - - // Surface Type - new ConditionalField(Fields.SurfaceOpaque, surfaceType == SurfaceType.Opaque), - new ConditionalField(Fields.SurfaceTransparent, surfaceType != SurfaceType.Opaque), - - // Structs - new ConditionalField(HDStructFields.FragInputs.IsFrontFace,doubleSidedMode != DoubleSidedMode.Disabled && - !pass.Equals(HDFabricSubTarget.FabricPasses.MotionVectors)), - // Material - new ConditionalField(HDFields.CottonWool, materialType == MaterialType.CottonWool), - new ConditionalField(HDFields.Silk, materialType == MaterialType.Silk), - new ConditionalField(HDFields.SubsurfaceScattering, subsurfaceScattering.isOn && surfaceType != SurfaceType.Transparent), - new ConditionalField(HDFields.Transmission, transmission.isOn), - - // Specular Occlusion - new ConditionalField(HDFields.SpecularOcclusionFromAO, specularOcclusionMode == SpecularOcclusionMode.FromAO), - new ConditionalField(HDFields.SpecularOcclusionFromAOBentNormal, specularOcclusionMode == SpecularOcclusionMode.FromAOAndBentNormal), - new ConditionalField(HDFields.SpecularOcclusionCustom, specularOcclusionMode == SpecularOcclusionMode.Custom), - - // Misc - new ConditionalField(Fields.AlphaTest, alphaTest.isOn && pass.pixelPorts.Contains(AlphaClipThresholdSlotId)), - new ConditionalField(HDFields.DoAlphaTest, alphaTest.isOn && pass.pixelPorts.Contains(AlphaClipThresholdSlotId)), - new ConditionalField(Fields.AlphaToMask, alphaTest.isOn && pass.pixelPorts.Contains(AlphaClipThresholdSlotId) && alphaToMask.isOn), - new ConditionalField(HDFields.AlphaFog, surfaceType != SurfaceType.Opaque && transparencyFog.isOn), - new ConditionalField(HDFields.BlendPreserveSpecular, surfaceType != SurfaceType.Opaque && blendPreserveSpecular.isOn), - new ConditionalField(HDFields.DisableDecals, !receiveDecals.isOn), - new ConditionalField(HDFields.DisableSSR, !receiveSSR.isOn), - new ConditionalField(HDFields.DisableSSRTransparent, !receiveSSRTransparent.isOn), - new ConditionalField(Fields.VelocityPrecomputed, addPrecomputedVelocity.isOn), - new ConditionalField(HDFields.BentNormal, IsSlotConnected(BentNormalSlotId) && - pass.pixelPorts.Contains(BentNormalSlotId)), - new ConditionalField(HDFields.AmbientOcclusion, pass.pixelPorts.Contains(AmbientOcclusionSlotId) && - (IsSlotConnected(AmbientOcclusionSlotId) || - ambientOcclusionSlot.value != ambientOcclusionSlot.defaultValue)), - new ConditionalField(HDFields.Tangent, IsSlotConnected(TangentSlotId) && - pass.pixelPorts.Contains(TangentSlotId)), - new ConditionalField(HDFields.LightingGI, IsSlotConnected(LightingSlotId) && - pass.pixelPorts.Contains(LightingSlotId)), - new ConditionalField(HDFields.BackLightingGI, IsSlotConnected(BackLightingSlotId) && - pass.pixelPorts.Contains(BackLightingSlotId)), - new ConditionalField(HDFields.DepthOffset, depthOffset.isOn && pass.pixelPorts.Contains(DepthOffsetSlotId)), - new ConditionalField(HDFields.EnergyConservingSpecular, energyConservingSpecular.isOn), - - }; - } - - public void ProcessPreviewMaterial(Material material) - { - // Fixup the material settings: - material.SetFloat(kSurfaceType, (int)(SurfaceType)surfaceType); - material.SetFloat(kDoubleSidedNormalMode, (int)doubleSidedMode); - material.SetFloat(kDoubleSidedEnable, doubleSidedMode != DoubleSidedMode.Disabled ? 1.0f : 0.0f); - material.SetFloat(kAlphaCutoffEnabled, alphaTest.isOn ? 1 : 0); - material.SetFloat(kBlendMode, (int)HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode)); - material.SetFloat(kEnableFogOnTransparent, transparencyFog.isOn ? 1.0f : 0.0f); - material.SetFloat(kZTestTransparent, (int)zTest); - material.SetFloat(kTransparentCullMode, (int)transparentCullMode); - material.SetFloat(kZWrite, zWrite.isOn ? 1.0f : 0.0f); - // No sorting priority for shader graph preview - var renderingPass = surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; - material.renderQueue = (int)HDRenderQueue.ChangeType(renderingPass, offset: 0, alphaTest: alphaTest.isOn); - - FabricGUI.SetupMaterialKeywordsAndPass(material); - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public bool RequiresSplitLighting() - { - return subsurfaceScattering.isOn; - } - public override object saveContext - { - get - { - int hash = ComputeMaterialNeedsUpdateHash(); - - bool needsUpdate = hash != m_MaterialNeedsUpdateHash; - - if (needsUpdate) - m_MaterialNeedsUpdateHash = hash; - - return new HDSaveContext{ updateMaterials = needsUpdate }; - } - } - - public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) - { - // Trunk currently relies on checking material property "_EmissionColor" to allow emissive GI. If it doesn't find that property, or it is black, GI is forced off. - // ShaderGraph doesn't use this property, so currently it inserts a dummy color (white). This dummy color may be removed entirely once the following PR has been merged in trunk: Pull request #74105 - // The user will then need to explicitly disable emissive GI if it is not needed. - // To be able to automatically disable emission based on the ShaderGraph config when emission is black, - // we will need a more general way to communicate this to the engine (not directly tied to a material property). - collector.AddShaderProperty(new ColorShaderProperty() - { - overrideReferenceName = "_EmissionColor", - hidden = true, - value = new Color(1.0f, 1.0f, 1.0f, 1.0f) - }); - - //See SG-ADDITIONALVELOCITY-NOTE - if (addPrecomputedVelocity.isOn) - { - collector.AddShaderProperty(new BooleanShaderProperty - { - value = true, - hidden = true, - overrideReferenceName = kAddPrecomputedVelocity, - }); - } - - // Add all shader properties required by the inspector - HDSubShaderUtilities.AddStencilShaderProperties(collector, RequiresSplitLighting(), surfaceType == SurfaceType.Opaque ? receiveSSR.isOn : receiveSSRTransparent.isOn, receiveSSR.isOn, receiveSSRTransparent.isOn); - HDSubShaderUtilities.AddBlendingStatesShaderProperties( - collector, - surfaceType, - HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode), - sortPriority, - alphaToMask.isOn, - zWrite.isOn, - transparentCullMode, - zTest, - false, - transparencyFog.isOn - ); - HDSubShaderUtilities.AddAlphaCutoffShaderProperties(collector, alphaTest.isOn, false); - HDSubShaderUtilities.AddDoubleSidedProperty(collector, doubleSidedMode); - HDSubShaderUtilities.AddPrePostPassProperties(collector, false, false); - - base.CollectShaderProperties(collector, generationMode); - } - - public bool supportsVirtualTexturing => true; - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricMasterNode.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricMasterNode.cs.meta deleted file mode 100644 index 980563bb4ec..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricMasterNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ac92c898af204d34ba48573dca72063f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricPass.template b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricPass.template index 3b3474a544d..d9b8648834b 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricPass.template +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricPass.template @@ -156,7 +156,7 @@ Pass surfaceData.specularOcclusion = 1.0; // copy across graph values, if defined - $SurfaceDescription.Albedo: surfaceData.baseColor = surfaceDescription.Albedo; + $SurfaceDescription.BaseColor: surfaceData.baseColor = surfaceDescription.BaseColor; $SurfaceDescription.SpecularOcclusion: surfaceData.specularOcclusion = surfaceDescription.SpecularOcclusion; $SurfaceDescription.Smoothness: surfaceData.perceptualSmoothness = surfaceDescription.Smoothness; $SurfaceDescription.Occlusion: surfaceData.ambientOcclusion = surfaceDescription.Occlusion; @@ -197,7 +197,7 @@ Pass // tangent-space normal float3 normalTS = float3(0.0f, 0.0f, 1.0f); - $SurfaceDescription.Normal: normalTS = surfaceDescription.Normal; + $SurfaceDescription.NormalTS: normalTS = surfaceDescription.NormalTS; // compute world space normal GetNormalWS(fragInputs, normalTS, surfaceData.normalWS, doubleSidedConstants); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSettingsView.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSettingsView.cs deleted file mode 100644 index c579c950974..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSettingsView.cs +++ /dev/null @@ -1,524 +0,0 @@ -using System; -using UnityEditor.UIElements; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEditor.Graphing.Util; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEngine.Rendering.HighDefinition; -using UnityEngine.Rendering; - -namespace UnityEditor.Rendering.HighDefinition.Drawing -{ - class FabricSettingsView : MasterNodeSettingsView - { - FabricMasterNode m_Node; - - IntegerField m_SortPiorityField; - - Label CreateLabel(string text, int indentLevel) - { - string label = ""; - for (var i = 0; i < indentLevel; i++) - { - label += " "; - } - return new Label(label + text); - } - - public FabricSettingsView(FabricMasterNode node) : base(node) - { - m_Node = node; - PropertySheet ps = new PropertySheet(); - - int indentLevel = 0; - ps.Add(new PropertyRow(CreateLabel("Surface Type", indentLevel)), (row) => - { - row.Add(new EnumField(SurfaceType.Opaque), (field) => - { - field.value = m_Node.surfaceType; - field.RegisterValueChangedCallback(ChangeSurfaceType); - }); - }); - - if (m_Node.surfaceType == SurfaceType.Transparent) - { - ++indentLevel; - - ps.Add(new PropertyRow(CreateLabel("Blend Preserves Specular", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.blendPreserveSpecular.isOn; - toggle.OnToggleChanged(ChangeBlendPreserveSpecular); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Fog", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.transparencyFog.isOn; - toggle.OnToggleChanged(ChangeTransparencyFog); - }); - }); - - m_SortPiorityField = new IntegerField(); - ps.Add(new PropertyRow(CreateLabel("Sort Priority", indentLevel)), (row) => - { - row.Add(m_SortPiorityField, (field) => - { - field.value = m_Node.sortPriority; - field.RegisterValueChangedCallback(ChangeSortPriority); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Transparent Depth Prepass", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestDepthPrepass.isOn; - toggle.OnToggleChanged(ChangeAlphaTestPrepass); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Transparent Depth Postpass", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestDepthPostpass.isOn; - toggle.OnToggleChanged(ChangeAlphaTestPostpass); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Depth Write", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.zWrite.isOn; - toggle.OnToggleChanged(ChangeZWrite); - }); - }); - - if (m_Node.doubleSidedMode == DoubleSidedMode.Disabled) - { - ps.Add(new PropertyRow(CreateLabel("Cull Mode", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.transparentCullMode), (e) => - { - e.value = m_Node.transparentCullMode; - e.RegisterValueChangedCallback(ChangeTransparentCullMode); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Depth Test", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.zTest), (e) => - { - e.value = m_Node.zTest; - e.RegisterValueChangedCallback(ChangeZTest); - }); - }); - - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Alpha Clipping", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTest.isOn; - toggle.OnToggleChanged(ChangeAlphaTest); - }); - }); - - if (m_Node.alphaTest.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Alpha to Mask", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaToMask.isOn; - toggle.OnToggleChanged(ChangeAlphaToMask); - }); - }); - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Double-Sided", indentLevel)), (row) => - { - row.Add(new EnumField(DoubleSidedMode.Disabled), (field) => - { - field.value = m_Node.doubleSidedMode; - field.RegisterValueChangedCallback(ChangeDoubleSidedMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Energy Conserving Specular", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.energyConservingSpecular.isOn; - toggle.OnToggleChanged(ChangeEnergyConservingSpecular); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Material Type", indentLevel)), (row) => - { - row.Add(new EnumField(FabricMasterNode.MaterialType.CottonWool), (field) => - { - field.value = m_Node.materialType; - field.RegisterValueChangedCallback(ChangeMaterialType); - }); - }); - - if (m_Node.surfaceType != SurfaceType.Transparent) - { - ps.Add(new PropertyRow(CreateLabel("Subsurface Scattering", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.subsurfaceScattering.isOn; - toggle.OnToggleChanged(ChangeSubsurfaceScattering); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Transmission", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.transmission.isOn; - toggle.OnToggleChanged(ChangeTransmission); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Receive Decals", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.receiveDecals.isOn; - toggle.OnToggleChanged(ChangeDecal); - }); - }); - - ps.Add(new PropertyRow(CreateLabel((m_Node.surfaceType == SurfaceType.Transparent) ? "Receive SSR Transparent" : "Receive SSR", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - if (m_Node.surfaceType == SurfaceType.Transparent) - { - toggle.value = m_Node.receiveSSRTransparent.isOn; - toggle.OnToggleChanged(ChangeSSRTransparent); - } - else - { - toggle.value = m_Node.receiveSSR.isOn; - toggle.OnToggleChanged(ChangeSSR); - } - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Add Precomputed Velocity", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.addPrecomputedVelocity.isOn; - toggle.OnToggleChanged(ChangeAddPrecomputedVelocity); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion Mode", indentLevel)), (row) => - { - row.Add(new EnumField(SpecularOcclusionMode.Off), (field) => - { - field.value = m_Node.specularOcclusionMode; - field.RegisterValueChangedCallback(ChangeSpecularOcclusionMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Override Baked GI", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.overrideBakedGI.isOn; - toggle.OnToggleChanged(ChangeoverrideBakedGI); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Depth Offset", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.depthOffset.isOn; - toggle.OnToggleChanged(ChangeDepthOffset); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Support LOD CrossFade", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.supportLodCrossFade.isOn; - toggle.OnToggleChanged(ChangeSupportLODCrossFade); - }); - }); - - Add(ps); - Add(GetShaderGUIOverridePropertySheet()); - } - - void ChangeSurfaceType(ChangeEvent evt) - { - if (Equals(m_Node.surfaceType, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Surface Type Change"); - m_Node.surfaceType = (SurfaceType)evt.newValue; - } - - void ChangeDoubleSidedMode(ChangeEvent evt) - { - if (Equals(m_Node.doubleSidedMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Double-Sided Mode Change"); - m_Node.doubleSidedMode = (DoubleSidedMode)evt.newValue; - } - - void ChangeMaterialType(ChangeEvent evt) - { - if (Equals(m_Node.materialType, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Material Type Change"); - m_Node.materialType = (FabricMasterNode.MaterialType)evt.newValue; - } - - void ChangeTransmission(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Transmission Change"); - ToggleData td = m_Node.transmission; - td.isOn = evt.newValue; - m_Node.transmission = td; - } - - void ChangeSubsurfaceScattering(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SSS Change"); - ToggleData td = m_Node.subsurfaceScattering; - td.isOn = evt.newValue; - m_Node.subsurfaceScattering = td; - } - - void ChangeBlendMode(ChangeEvent evt) - { - // Make sure the mapping is correct by handling each case. - AlphaMode alphaMode = GetAlphaMode((FabricMasterNode.AlphaModeFabric)evt.newValue); - - if (Equals(m_Node.alphaMode, alphaMode)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Mode Change"); - m_Node.alphaMode = alphaMode; - } - - void ChangeBlendPreserveSpecular(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Blend Preserve Specular Change"); - ToggleData td = m_Node.blendPreserveSpecular; - td.isOn = evt.newValue; - m_Node.blendPreserveSpecular = td; - } - - void ChangeTransparencyFog(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparency Fog Change"); - ToggleData td = m_Node.transparencyFog; - td.isOn = evt.newValue; - m_Node.transparencyFog = td; - } - - void ChangeSortPriority(ChangeEvent evt) - { - m_Node.sortPriority = HDRenderQueue.ClampsTransparentRangePriority(evt.newValue); - // Force the text to match. - m_SortPiorityField.value = m_Node.sortPriority; - if (Equals(m_Node.sortPriority, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Sort Priority Change"); - } - - void ChangeZWrite(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("ZWrite Change"); - ToggleData td = m_Node.zWrite; - td.isOn = evt.newValue; - m_Node.zWrite = td; - } - - void ChangeAlphaTest(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Change"); - ToggleData td = m_Node.alphaTest; - td.isOn = evt.newValue; - m_Node.alphaTest = td; - } - - void ChangeAlphaTestPrepass(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Prepass Change"); - ToggleData td = m_Node.alphaTestDepthPrepass; - td.isOn = evt.newValue; - m_Node.alphaTestDepthPrepass = td; - } - - void ChangeAlphaTestPostpass(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Postpass Change"); - ToggleData td = m_Node.alphaTestDepthPostpass; - td.isOn = evt.newValue; - m_Node.alphaTestDepthPostpass = td; - } - - void ChangeAlphaToMask(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha to Mask Change"); - ToggleData td = m_Node.alphaToMask; - td.isOn = evt.newValue; - m_Node.alphaToMask = td; - } - - void ChangeDecal(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Decal Change"); - ToggleData td = m_Node.receiveDecals; - td.isOn = evt.newValue; - m_Node.receiveDecals = td; - } - - void ChangeSSR(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SSR Change"); - ToggleData td = m_Node.receiveSSR; - td.isOn = evt.newValue; - m_Node.receiveSSR = td; - } - - void ChangeSSRTransparent(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SSR Transparent Change"); - ToggleData td = m_Node.receiveSSRTransparent; - td.isOn = evt.newValue; - m_Node.receiveSSR = td; - } - - void ChangeAddPrecomputedVelocity(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Add Precomputed Velocity"); - ToggleData td = m_Node.addPrecomputedVelocity; - td.isOn = evt.newValue; - m_Node.addPrecomputedVelocity = td; - } - - void ChangeEnergyConservingSpecular(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Energy Conserving Specular Change"); - ToggleData td = m_Node.energyConservingSpecular; - td.isOn = evt.newValue; - m_Node.energyConservingSpecular = td; - } - - void ChangeSpecularOcclusionMode(ChangeEvent evt) - { - if (Equals(m_Node.specularOcclusionMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Specular Occlusion Mode Change"); - m_Node.specularOcclusionMode = (SpecularOcclusionMode)evt.newValue; - } - - void ChangeoverrideBakedGI(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("overrideBakedGI Change"); - ToggleData td = m_Node.overrideBakedGI; - td.isOn = evt.newValue; - m_Node.overrideBakedGI = td; - } - - void ChangeDepthOffset(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("DepthOffset Change"); - ToggleData td = m_Node.depthOffset; - td.isOn = evt.newValue; - m_Node.depthOffset = td; - } - - void ChangeTransparentCullMode(ChangeEvent evt) - { - if (Equals(m_Node.transparentCullMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparent Cull Mode Change"); - m_Node.transparentCullMode = (TransparentCullMode)evt.newValue; - } - - void ChangeZTest(ChangeEvent evt) - { - if (Equals(m_Node.zTest, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("ZTest Change"); - m_Node.zTest = (CompareFunction)evt.newValue; - } - - void ChangeSupportLODCrossFade(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Support LOD CrossFade Change"); - ToggleData td = m_Node.supportLodCrossFade; - td.isOn = evt.newValue; - m_Node.supportLodCrossFade = td; - } - - public AlphaMode GetAlphaMode(FabricMasterNode.AlphaModeFabric alphaModeLit) - { - switch (alphaModeLit) - { - case FabricMasterNode.AlphaModeFabric.Alpha: - return AlphaMode.Alpha; - case FabricMasterNode.AlphaModeFabric.Premultiply: - return AlphaMode.Premultiply; - case FabricMasterNode.AlphaModeFabric.Additive: - return AlphaMode.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaModeLit); - return AlphaMode.Alpha; - } - - } - } - - public FabricMasterNode.AlphaModeFabric GetAlphaModeLit(AlphaMode alphaMode) - { - switch (alphaMode) - { - case AlphaMode.Alpha: - return FabricMasterNode.AlphaModeFabric.Alpha; - case AlphaMode.Premultiply: - return FabricMasterNode.AlphaModeFabric.Premultiply; - case AlphaMode.Additive: - return FabricMasterNode.AlphaModeFabric.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaMode); - return FabricMasterNode.AlphaModeFabric.Alpha; - } - } - } - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSettingsView.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSettingsView.cs.meta deleted file mode 100644 index 33bf72a5e24..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSettingsView.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: dbe8d40ff0e92474a8f400bfad8310bc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.Migration.cs new file mode 100644 index 00000000000..2fd7d88dfb2 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.Migration.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + sealed partial class FabricSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData + { + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is FabricMasterNode1 fabricMasterNode)) + return false; + + // Set data + systemData.surfaceType = (SurfaceType)fabricMasterNode.m_SurfaceType; + systemData.blendMode = HDSubShaderUtilities.UpgradeLegacyAlphaModeToBlendMode((int)fabricMasterNode.m_AlphaMode); + // Previous master node wasn't having any renderingPass. Assign it correctly now. + systemData.renderingPass = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; + systemData.alphaTest = fabricMasterNode.m_AlphaTest; + systemData.sortPriority = fabricMasterNode.m_SortPriority; + systemData.doubleSidedMode = fabricMasterNode.m_DoubleSidedMode; + systemData.zWrite = fabricMasterNode.m_ZWrite; + systemData.transparentCullMode = fabricMasterNode.m_transparentCullMode; + systemData.zTest = fabricMasterNode.m_ZTest; + systemData.supportLodCrossFade = fabricMasterNode.m_SupportLodCrossFade; + systemData.dotsInstancing = fabricMasterNode.m_DOTSInstancing; + systemData.materialNeedsUpdateHash = fabricMasterNode.m_MaterialNeedsUpdateHash; + + builtinData.transparencyFog = fabricMasterNode.m_TransparencyFog; + builtinData.addPrecomputedVelocity = fabricMasterNode.m_AddPrecomputedVelocity; + builtinData.depthOffset = fabricMasterNode.m_depthOffset; + builtinData.alphaToMask = fabricMasterNode.m_AlphaToMask; + + lightingData.blendPreserveSpecular = fabricMasterNode.m_BlendPreserveSpecular; + lightingData.receiveDecals = fabricMasterNode.m_ReceiveDecals; + lightingData.receiveSSR = fabricMasterNode.m_ReceivesSSR; + lightingData.receiveSSRTransparent = fabricMasterNode.m_ReceivesSSRTransparent; + lightingData.specularOcclusionMode = fabricMasterNode.m_SpecularOcclusionMode; + lightingData.overrideBakedGI = fabricMasterNode.m_overrideBakedGI; + lightingData.subsurfaceScattering = fabricMasterNode.m_SubsurfaceScattering; + + fabricData.transmission = fabricMasterNode.m_Transmission; + fabricData.energyConservingSpecular = fabricMasterNode.m_EnergyConservingSpecular; + fabricData.materialType = (FabricData.MaterialType)fabricMasterNode.m_MaterialType; + target.customEditorGUI = fabricMasterNode.m_OverrideEnabled ? fabricMasterNode.m_ShaderGUIOverride : ""; + + // Convert SlotMask to BlockMap entries + var blockMapLookup = new Dictionary() + { + { FabricMasterNode1.SlotMask.Position, BlockFields.VertexDescription.Position }, + { FabricMasterNode1.SlotMask.VertexNormal, BlockFields.VertexDescription.Normal }, + { FabricMasterNode1.SlotMask.VertexTangent, BlockFields.VertexDescription.Tangent }, + { FabricMasterNode1.SlotMask.Albedo, BlockFields.SurfaceDescription.BaseColor }, + { FabricMasterNode1.SlotMask.SpecularOcclusion, HDBlockFields.SurfaceDescription.SpecularOcclusion }, + { FabricMasterNode1.SlotMask.Normal, BlockFields.SurfaceDescription.NormalTS }, + { FabricMasterNode1.SlotMask.BentNormal, HDBlockFields.SurfaceDescription.BentNormal }, + { FabricMasterNode1.SlotMask.Smoothness, BlockFields.SurfaceDescription.Smoothness }, + { FabricMasterNode1.SlotMask.Occlusion, BlockFields.SurfaceDescription.Occlusion }, + { FabricMasterNode1.SlotMask.Specular, BlockFields.SurfaceDescription.Specular }, + { FabricMasterNode1.SlotMask.DiffusionProfile, HDBlockFields.SurfaceDescription.DiffusionProfileHash }, + { FabricMasterNode1.SlotMask.SubsurfaceMask, HDBlockFields.SurfaceDescription.SubsurfaceMask }, + { FabricMasterNode1.SlotMask.Thickness, HDBlockFields.SurfaceDescription.Thickness }, + { FabricMasterNode1.SlotMask.Tangent, HDBlockFields.SurfaceDescription.Tangent }, + { FabricMasterNode1.SlotMask.Anisotropy, HDBlockFields.SurfaceDescription.Anisotropy }, + { FabricMasterNode1.SlotMask.Emission, BlockFields.SurfaceDescription.Emission }, + { FabricMasterNode1.SlotMask.Alpha, BlockFields.SurfaceDescription.Alpha }, + { FabricMasterNode1.SlotMask.AlphaClipThreshold, BlockFields.SurfaceDescription.AlphaClipThreshold }, + }; + + // Legacy master node slots have additional slot conditions, test them here + bool AdditionalSlotMaskTests(FabricMasterNode1.SlotMask slotMask) + { + switch(slotMask) + { + case FabricMasterNode1.SlotMask.SpecularOcclusion: + return lightingData.specularOcclusionMode == SpecularOcclusionMode.Custom; + case FabricMasterNode1.SlotMask.DiffusionProfile: + return lightingData.subsurfaceScattering || fabricData.transmission; + case FabricMasterNode1.SlotMask.SubsurfaceMask: + return lightingData.subsurfaceScattering; + case FabricMasterNode1.SlotMask.Thickness: + return fabricData.transmission; + case FabricMasterNode1.SlotMask.AlphaClipThreshold: + return systemData.alphaTest; + default: + return true; + } + } + + // Set blockmap + blockMap = new Dictionary(); + foreach(FabricMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(FabricMasterNode1.SlotMask))) + { + if(fabricMasterNode.MaterialTypeUsesSlotMask(slotMask)) + { + if(!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) + continue; + + if(!AdditionalSlotMaskTests(slotMask)) + continue; + + var slotId = Mathf.Log((int)slotMask, 2); + blockMap.Add(blockFieldDescriptor, (int)slotId); + } + } + + // Override Baked GI + if(lightingData.overrideBakedGI) + { + blockMap.Add(HDBlockFields.SurfaceDescription.BakedGI, FabricMasterNode1.LightingSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.BakedBackGI, FabricMasterNode1.BackLightingSlotId); + } + + // Depth Offset + if(builtinData.depthOffset) + { + blockMap.Add(HDBlockFields.SurfaceDescription.DepthOffset, FabricMasterNode1.DepthOffsetSlotId); + } + + return true; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.Migration.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.Migration.cs.meta new file mode 100644 index 00000000000..6d38ba71c47 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.Migration.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3cf12c31390c5ca4aa5be1436b34f4d1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/HDFabricSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.cs similarity index 67% rename from com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/HDFabricSubTarget.cs rename to com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.cs index 2921a85139c..6c46879b8ce 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/HDFabricSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.cs @@ -1,24 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; using UnityEngine.Rendering.HighDefinition; using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { - sealed class HDFabricSubTarget : SubTarget + sealed partial class FabricSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData { - const string kAssetGuid = "74f1a4749bab90d429ac01d094be0aeb"; static string passTemplatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/Fabric/ShaderGraph/FabricPass.template"; - public HDFabricSubTarget() + public FabricSubTarget() => displayName = "Fabric"; + + protected override string subTargetAssetGuid => "74f1a4749bab90d429ac01d094be0aeb"; // FabricSubTarget.cs + protected override string customInspector => "Rendering.HighDefinition.FabricGUI"; + protected override ShaderID shaderID => HDShaderUtils.ShaderID.SG_Fabric; + + FabricData m_FabricData; + + FabricData IRequiresData.data + { + get => m_FabricData; + set => m_FabricData = value; + } + + public FabricData fabricData + { + get => m_FabricData; + set => m_FabricData = value; + } + + protected override IEnumerable EnumerateSubShaders() + { + yield return SubShaders.Fabric; + yield return SubShaders.FabricRaytracing; + } + + public override void GetFields(ref TargetFieldContext context) { - displayName = "Fabric"; + base.GetFields(ref context); + + // Fabric specific properties + context.AddField(HDStructFields.FragInputs.IsFrontFace, systemData.doubleSidedMode != DoubleSidedMode.Disabled && !context.pass.Equals(FabricSubTarget.FabricPasses.MotionVectors)); + context.AddField(HDFields.CottonWool, fabricData.materialType == FabricData.MaterialType.CottonWool); + context.AddField(HDFields.Silk, fabricData.materialType == FabricData.MaterialType.Silk); + context.AddField(HDFields.SubsurfaceScattering, lightingData.subsurfaceScattering && systemData.surfaceType != SurfaceType.Transparent); + context.AddField(HDFields.Transmission, fabricData.transmission); + context.AddField(HDFields.DoAlphaTest, systemData.alphaTest && context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.AlphaClipThreshold)); + context.AddField(HDFields.EnergyConservingSpecular, fabricData.energyConservingSpecular); } - public override void Setup(ref TargetSetupContext context) + public override void GetActiveBlocks(ref TargetActiveBlockContext context) { - context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); - context.SetDefaultShaderGUI("Rendering.HighDefinition.FabricGUI"); - context.AddSubShader(SubShaders.Fabric); - context.AddSubShader(SubShaders.FabricRaytracing); + base.GetActiveBlocks(ref context); + + // Fabric specific blocks + context.AddBlock(HDBlockFields.SurfaceDescription.BentNormal); + context.AddBlock(BlockFields.SurfaceDescription.Specular); + context.AddBlock(HDBlockFields.SurfaceDescription.DiffusionProfileHash, lightingData.subsurfaceScattering || fabricData.transmission); + context.AddBlock(HDBlockFields.SurfaceDescription.SubsurfaceMask, lightingData.subsurfaceScattering); + context.AddBlock(HDBlockFields.SurfaceDescription.Thickness, fabricData.transmission); + + // Fabric Silk + if(fabricData.materialType == FabricData.MaterialType.Silk) + { + context.AddBlock(HDBlockFields.SurfaceDescription.Tangent); + context.AddBlock(HDBlockFields.SurfaceDescription.Anisotropy); + } + } + + protected override void AddInspectorPropertyBlocks(SubTargetPropertiesGUI blockList) + { + blockList.AddPropertyBlock(new FabricSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features.Lit, fabricData)); + blockList.AddPropertyBlock(new AdvancedOptionsPropertyBlock()); } #region SubShaders @@ -81,7 +142,7 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - pixelPorts = FabricPortMasks.FragmentMETA, + validPixelBlocks = FabricBlockMasks.FragmentMETA, // Collections structs = CoreStructCollections.Default, @@ -106,8 +167,8 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentAlphaDepth, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentAlphaDepth, // Collections structs = CoreStructCollections.Default, @@ -131,8 +192,8 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentAlphaDepth, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentAlphaDepth, // Collections structs = CoreStructCollections.Default, @@ -157,8 +218,8 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentDepthMotionVectors, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentDepthMotionVectors, // Collections structs = CoreStructCollections.Default, @@ -184,8 +245,8 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentDepthMotionVectors, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentDepthMotionVectors, // Collections structs = CoreStructCollections.Default, @@ -211,13 +272,14 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentTransparentDepthPrepass, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentTransparentDepthPrepass, // Collections structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.LitFull, fieldDependencies = CoreFieldDependencies.Default, - renderStates = FabricRenderStates.TransparentDepthPrePass, + renderStates = CoreRenderStates.TransparentDepthPrePass, pragmas = CorePragmas.DotsInstancedInV2Only, defines = CoreDefines.TransparentDepthPrepass, keywords = CoreKeywords.HDBase, @@ -237,8 +299,8 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -264,13 +326,13 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentTransparentDepthPostpass, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentTransparentDepthPostpass, // Collections structs = CoreStructCollections.Default, fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.TransparentDepthPrePostPass, + renderStates = CoreRenderStates.TransparentDepthPostPass, pragmas = CorePragmas.DotsInstancedInV2Only, defines = CoreDefines.ShaderGraphRaytracingHigh, keywords = CoreKeywords.HDBase, @@ -290,8 +352,8 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -316,8 +378,8 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -342,8 +404,8 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -368,8 +430,8 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -394,8 +456,8 @@ public static class FabricPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, //Port mask - vertexPorts = FabricPortMasks.Vertex, - pixelPorts = FabricPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = FabricBlockMasks.FragmentForward, //Collections structs = CoreStructCollections.Default, @@ -409,105 +471,87 @@ public static class FabricPasses } #endregion -#region PortMasks - static class FabricPortMasks +#region BlockMasks + static class FabricBlockMasks { - public static int[] Vertex = new int[] - { - FabricMasterNode.PositionSlotId, - FabricMasterNode.VertexNormalSlotId, - FabricMasterNode.VertexTangentSlotId, - }; - - public static int[] FragmentMETA = new int[] - { - FabricMasterNode.AlbedoSlotId, - FabricMasterNode.SpecularOcclusionSlotId, - FabricMasterNode.NormalSlotId, - FabricMasterNode.SmoothnessSlotId, - FabricMasterNode.AmbientOcclusionSlotId, - FabricMasterNode.SpecularColorSlotId, - FabricMasterNode.DiffusionProfileHashSlotId, - FabricMasterNode.SubsurfaceMaskSlotId, - FabricMasterNode.ThicknessSlotId, - FabricMasterNode.TangentSlotId, - FabricMasterNode.AnisotropySlotId, - FabricMasterNode.EmissionSlotId, - FabricMasterNode.AlphaSlotId, - FabricMasterNode.AlphaClipThresholdSlotId, - }; - - public static int[] FragmentAlphaDepth = new int[] - { - FabricMasterNode.AlphaSlotId, - FabricMasterNode.AlphaClipThresholdSlotId, - FabricMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentDepthMotionVectors = new int[] - { - FabricMasterNode.NormalSlotId, - FabricMasterNode.SmoothnessSlotId, - FabricMasterNode.AlphaSlotId, - FabricMasterNode.AlphaClipThresholdSlotId, - FabricMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentTransparentDepthPrepass = new int[] - { - FabricMasterNode.AlphaSlotId, - FabricMasterNode.AlphaClipThresholdSlotId, - FabricMasterNode.DepthOffsetSlotId, - FabricMasterNode.NormalSlotId, - FabricMasterNode.SmoothnessSlotId, - }; - - public static int[] FragmentForward = new int[] - { - FabricMasterNode.AlbedoSlotId, - FabricMasterNode.SpecularOcclusionSlotId, - FabricMasterNode.NormalSlotId, - FabricMasterNode.BentNormalSlotId, - FabricMasterNode.SmoothnessSlotId, - FabricMasterNode.AmbientOcclusionSlotId, - FabricMasterNode.SpecularColorSlotId, - FabricMasterNode.DiffusionProfileHashSlotId, - FabricMasterNode.SubsurfaceMaskSlotId, - FabricMasterNode.ThicknessSlotId, - FabricMasterNode.TangentSlotId, - FabricMasterNode.AnisotropySlotId, - FabricMasterNode.EmissionSlotId, - FabricMasterNode.AlphaSlotId, - FabricMasterNode.AlphaClipThresholdSlotId, - FabricMasterNode.LightingSlotId, - FabricMasterNode.BackLightingSlotId, - FabricMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentTransparentDepthPostpass = new int[] - { - FabricMasterNode.AlphaSlotId, - FabricMasterNode.AlphaClipThresholdSlotId, - FabricMasterNode.DepthOffsetSlotId, - }; - } -#endregion - -#region RenderStates - static class FabricRenderStates - { - public static RenderStateCollection TransparentDepthPrePass = new RenderStateCollection - { - { RenderState.Blend(Blend.One, Blend.Zero) }, - { RenderState.Cull(CoreRenderStates.Uniforms.cullMode) }, - { RenderState.ZWrite(ZWrite.On) }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = CoreRenderStates.Uniforms.stencilWriteMaskDepth, - Ref = CoreRenderStates.Uniforms.stencilRefDepth, - Comp = "Always", - Pass = "Replace", - }) }, + public static BlockFieldDescriptor[] FragmentMETA = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Specular, + HDBlockFields.SurfaceDescription.DiffusionProfileHash, + HDBlockFields.SurfaceDescription.SubsurfaceMask, + HDBlockFields.SurfaceDescription.Thickness, + HDBlockFields.SurfaceDescription.Tangent, + HDBlockFields.SurfaceDescription.Anisotropy, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + }; + + public static BlockFieldDescriptor[] FragmentAlphaDepth = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentDepthMotionVectors = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentTransparentDepthPrepass = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass, + HDBlockFields.SurfaceDescription.DepthOffset, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.Smoothness, + }; + + public static BlockFieldDescriptor[] FragmentForward = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + HDBlockFields.SurfaceDescription.BentNormal, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Specular, + HDBlockFields.SurfaceDescription.DiffusionProfileHash, + HDBlockFields.SurfaceDescription.SubsurfaceMask, + HDBlockFields.SurfaceDescription.Thickness, + HDBlockFields.SurfaceDescription.Tangent, + HDBlockFields.SurfaceDescription.Anisotropy, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.BakedGI, + HDBlockFields.SurfaceDescription.BakedBackGI, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentTransparentDepthPostpass = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass, + HDBlockFields.SurfaceDescription.DepthOffset, }; } #endregion diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/HDFabricSubTarget.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.cs.meta similarity index 100% rename from com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/HDFabricSubTarget.cs.meta rename to com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSurfaceOptionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSurfaceOptionPropertyBlock.cs new file mode 100644 index 00000000000..6702e6a50fa --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSurfaceOptionPropertyBlock.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.LitSurfaceInputsUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.SurfaceOptionUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.RefractionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class FabricSurfaceOptionPropertyBlock : SurfaceOptionPropertyBlock + { + class Styles + { + public static GUIContent materialType = new GUIContent("Material Type", "TODO"); + } + + FabricData fabricData; + + public FabricSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features features, FabricData fabricData) : base(features) + => this.fabricData = fabricData; + + protected override void CreatePropertyGUI() + { + AddProperty(Styles.materialType, () => fabricData.materialType, (newValue) => fabricData.materialType = newValue); + + base.CreatePropertyGUI(); + + // Fabric specific properties: + AddProperty(energyConservingSpecularColorText, () => fabricData.energyConservingSpecular, (newValue) => fabricData.energyConservingSpecular = newValue); + AddProperty(subsurfaceEnableText, () => lightingData.subsurfaceScattering, (newValue) => lightingData.subsurfaceScattering = newValue); + AddProperty(transmissionEnableText, () => fabricData.transmission, (newValue) => fabricData.transmission = newValue); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSurfaceOptionPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSurfaceOptionPropertyBlock.cs.meta new file mode 100644 index 00000000000..17e924ca6d6 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSurfaceOptionPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0ecbbfd0c8f45b046bd39742548eb207 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs index 6e02ecf93c8..0f0e2541035 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs @@ -1,13 +1,38 @@ +using System; using UnityEditor.ShaderGraph; -namespace UnityEditor.Rendering.HighDefinition +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { static class CreateHairShaderGraph { - [MenuItem("Assets/Create/Shader/HDRP/Hair Graph", false, 208)] - public static void CreateMaterialGraph() + [MenuItem("Assets/Create/Shader/HDRP/Hair Shader Graph", false, 208)] + public static void CreateHairGraph() { - GraphUtil.CreateNewGraph(new HairMasterNode()); + var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); + target.TrySetActiveSubTarget(typeof(HairSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.HairStrandDirection, + HDBlockFields.SurfaceDescription.Transmittance, + HDBlockFields.SurfaceDescription.RimTransmissionIntensity, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.SpecularTint, + HDBlockFields.SurfaceDescription.SpecularShift, + HDBlockFields.SurfaceDescription.SecondarySpecularTint, + HDBlockFields.SurfaceDescription.SecondarySmoothness, + HDBlockFields.SurfaceDescription.SecondarySpecularShift, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs.meta index 4a9701cdc83..18e11971ad0 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: f8cd1630249e23445be1ed78d1b524dd +guid: 7f59b1b67bb3c724a8cded306b6a036a MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairAdvancedOptionsPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairAdvancedOptionsPropertyBlock.cs new file mode 100644 index 00000000000..126c5e7bcc0 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairAdvancedOptionsPropertyBlock.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.AdvancedOptionsUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.SurfaceOptionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class HairAdvancedOptionsPropertyBlock : AdvancedOptionsPropertyBlock + { + class Styles + { + public static GUIContent useLightFacingNormal = new GUIContent("Use Light Facing Normal", "TODO"); + } + + HairData hairData; + + public HairAdvancedOptionsPropertyBlock(HairData hairData) => this.hairData = hairData; + + protected override void CreatePropertyGUI() + { + base.CreatePropertyGUI(); + + // Hair specific properties GUI + AddProperty(Styles.useLightFacingNormal, () => hairData.useLightFacingNormal, (newValue) => hairData.useLightFacingNormal = newValue); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairAdvancedOptionsPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairAdvancedOptionsPropertyBlock.cs.meta new file mode 100644 index 00000000000..429e4eda893 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairAdvancedOptionsPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7d7c6ea35025a26458a0d9af3098f7b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairData.cs new file mode 100644 index 00000000000..7c102b59832 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairData.cs @@ -0,0 +1,30 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class HairData : HDTargetData + { + public enum MaterialType + { + KajiyaKay + } + + [SerializeField] + MaterialType m_MaterialType; + public MaterialType materialType + { + get => m_MaterialType; + set => m_MaterialType = value; + } + + [SerializeField] + bool m_UseLightFacingNormal = false; + public bool useLightFacingNormal + { + get => m_UseLightFacingNormal; + set => m_UseLightFacingNormal = value; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairData.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairData.cs.meta new file mode 100644 index 00000000000..671d0ecc6ef --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5f4a5a7dba99a1848b4029424cdd31f4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairMasterNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairMasterNode.cs deleted file mode 100644 index d7d22721524..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairMasterNode.cs +++ /dev/null @@ -1,1056 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEngine.Rendering.HighDefinition; -using UnityEngine.Rendering; -using UnityEditor.Rendering.HighDefinition.Drawing; -using UnityEditor.ShaderGraph.Internal; -using UnityEditor.Rendering.HighDefinition.ShaderGraph; - -// Include material common properties names -using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; - -namespace UnityEditor.Rendering.HighDefinition -{ - [Serializable] - [Title("Master", "Hair (HDRP)")] - [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.HairMasterNode")] - class HairMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string PositionSlotName = "Vertex Position"; - public const string PositionSlotDisplayName = "Vertex Position"; - public const int PositionSlotId = 0; - - public const string AlbedoSlotName = "Albedo"; - public const string AlbedoDisplaySlotName = "DiffuseColor"; - public const int AlbedoSlotId = 1; - - public const string NormalSlotName = "Normal"; - public const int NormalSlotId = 2; - - public const string SpecularOcclusionSlotName = "SpecularOcclusion"; - public const int SpecularOcclusionSlotId = 3; - - public const string BentNormalSlotName = "BentNormal"; - public const int BentNormalSlotId = 4; - - public const string HairStrandDirectionSlotName = "HairStrandDirection"; - public const int HairStrandDirectionSlotId = 5; - - public const int UnusedSlot6 = 6; - - public const string TransmittanceSlotName = "Transmittance"; - public const int TransmittanceSlotId = 7; - - public const string RimTransmissionIntensitySlotName = "RimTransmissionIntensity"; - public const int RimTransmissionIntensitySlotId = 8; - - public const string SmoothnessSlotName = "Smoothness"; - public const int SmoothnessSlotId = 9; - - public const string AmbientOcclusionSlotName = "Occlusion"; - public const string AmbientOcclusionDisplaySlotName = "AmbientOcclusion"; - public const int AmbientOcclusionSlotId = 10; - - public const string EmissionSlotName = "Emission"; - public const int EmissionSlotId = 11; - - public const string AlphaSlotName = "Alpha"; - public const int AlphaSlotId = 12; - - public const string AlphaClipThresholdSlotName = "AlphaClipThreshold"; - public const int AlphaClipThresholdSlotId = 13; - - public const string AlphaClipThresholdDepthPrepassSlotName = "AlphaClipThresholdDepthPrepass"; - public const int AlphaClipThresholdDepthPrepassSlotId = 14; - - public const string AlphaClipThresholdDepthPostpassSlotName = "AlphaClipThresholdDepthPostpass"; - public const int AlphaClipThresholdDepthPostpassSlotId = 15; - - public const string SpecularAAScreenSpaceVarianceSlotName = "SpecularAAScreenSpaceVariance"; - public const int SpecularAAScreenSpaceVarianceSlotId = 16; - - public const string SpecularAAThresholdSlotName = "SpecularAAThreshold"; - public const int SpecularAAThresholdSlotId = 17; - - //Hair Specific - public const string SpecularTintSlotName = "SpecularTint"; - public const int SpecularTintSlotId = 18; - - public const string SpecularShiftSlotName = "SpecularShift"; - public const int SpecularShiftSlotId = 19; - - public const string SecondarySpecularTintSlotName = "SecondarySpecularTint"; - public const int SecondarySpecularTintSlotId = 20; - - public const string SecondarySmoothnessSlotName = "SecondarySmoothness"; - public const int SecondarySmoothnessSlotId = 21; - - public const string SecondarySpecularShiftSlotName = "SecondarySpecularShift"; - public const int SecondarySpecularShiftSlotId = 22; - - public const string AlphaClipThresholdShadowSlotName = "AlphaClipThresholdShadow"; - public const int AlphaClipThresholdShadowSlotId = 23; - - public const string BakedGISlotName = "BakedGI"; - public const int LightingSlotId = 24; - - public const string BakedBackGISlotName = "BakedBackGI"; - public const int BackLightingSlotId = 25; - - public const string DepthOffsetSlotName = "DepthOffset"; - public const int DepthOffsetSlotId = 26; - - public const int VertexNormalSlotId = 27; - public const string VertexNormalSlotName = "Vertex Normal"; - - public const int VertexTangentSlotId = 28; - public const string VertexTangentSlotName = "Vertex Tangent"; - - public enum MaterialType - { - KajiyaKay - } - - // Don't support Multiply - public enum AlphaModeLit - { - Alpha, - Premultiply, - Additive, - } - - // Just for convenience of doing simple masks. We could run out of bits of course. - [Flags] - enum SlotMask - { - None = 0, - Position = 1 << PositionSlotId, - Albedo = 1 << AlbedoSlotId, - Normal = 1 << NormalSlotId, - SpecularOcclusion = 1 << SpecularOcclusionSlotId, - BentNormal = 1 << BentNormalSlotId, - HairStrandDirection = 1 << HairStrandDirectionSlotId, - Slot6 = 1 << UnusedSlot6, - Transmittance = 1 << TransmittanceSlotId, - RimTransmissionIntensity = 1 << RimTransmissionIntensitySlotId, - Smoothness = 1 << SmoothnessSlotId, - Occlusion = 1 << AmbientOcclusionSlotId, - Emission = 1 << EmissionSlotId, - Alpha = 1 << AlphaSlotId, - AlphaClipThreshold = 1 << AlphaClipThresholdSlotId, - AlphaClipThresholdDepthPrepass = 1 << AlphaClipThresholdDepthPrepassSlotId, - AlphaClipThresholdDepthPostpass = 1 << AlphaClipThresholdDepthPostpassSlotId, - SpecularTint = 1 << SpecularTintSlotId, - SpecularShift = 1 << SpecularShiftSlotId, - SecondarySpecularTint = 1 << SecondarySpecularTintSlotId, - SecondarySmoothness = 1 << SecondarySmoothnessSlotId, - SecondarySpecularShift = 1 << SecondarySpecularShiftSlotId, - AlphaClipThresholdShadow = 1 << AlphaClipThresholdShadowSlotId, - BakedGI = 1 << LightingSlotId, - BakedBackGI = 1 << BackLightingSlotId, - DepthOffset = 1 << DepthOffsetSlotId, - VertexNormal = 1 << VertexNormalSlotId, - VertexTangent = 1 << VertexTangentSlotId, - } - - const SlotMask KajiyaKaySlotMask = SlotMask.Position | SlotMask.VertexNormal | SlotMask.VertexTangent | SlotMask.Albedo | SlotMask.Normal | SlotMask.SpecularOcclusion | SlotMask.BentNormal | SlotMask.HairStrandDirection | SlotMask.Slot6 - | SlotMask.Transmittance | SlotMask.RimTransmissionIntensity | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.AlphaClipThresholdDepthPrepass - | SlotMask.AlphaClipThresholdDepthPostpass | SlotMask.SpecularTint | SlotMask.SpecularShift | SlotMask.SecondarySpecularTint | SlotMask.SecondarySmoothness | SlotMask.SecondarySpecularShift | SlotMask.AlphaClipThresholdShadow | SlotMask.BakedGI | SlotMask.DepthOffset; - - // This could also be a simple array. For now, catch any mismatched data. - SlotMask GetActiveSlotMask() - { - switch (materialType) - { - case MaterialType.KajiyaKay: - return KajiyaKaySlotMask; - default: - return KajiyaKaySlotMask; - } - } - - bool MaterialTypeUsesSlotMask(SlotMask mask) - { - SlotMask activeMask = GetActiveSlotMask(); - return (activeMask & mask) != 0; - } - - [SerializeField] - SurfaceType m_SurfaceType; - - public SurfaceType surfaceType - { - get { return m_SurfaceType; } - set - { - if (m_SurfaceType == value) - return; - - m_SurfaceType = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - AlphaMode m_AlphaMode; - - public AlphaMode alphaMode - { - get { return m_AlphaMode; } - set - { - if (m_AlphaMode == value) - return; - - m_AlphaMode = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_BlendPreserveSpecular = true; - - public ToggleData blendPreserveSpecular - { - get { return new ToggleData(m_BlendPreserveSpecular); } - set - { - if (m_BlendPreserveSpecular == value.isOn) - return; - m_BlendPreserveSpecular = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_TransparencyFog = true; - - public ToggleData transparencyFog - { - get { return new ToggleData(m_TransparencyFog); } - set - { - if (m_TransparencyFog == value.isOn) - return; - m_TransparencyFog = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaTest; - - public ToggleData alphaTest - { - get { return new ToggleData(m_AlphaTest); } - set - { - if (m_AlphaTest == value.isOn) - return; - m_AlphaTest = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaToMask = false; - - public ToggleData alphaToMask - { - get { return new ToggleData(m_AlphaToMask); } - set - { - if (m_AlphaToMask == value.isOn) - return; - m_AlphaToMask = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaTestDepthPrepass; - - public ToggleData alphaTestDepthPrepass - { - get { return new ToggleData(m_AlphaTestDepthPrepass); } - set - { - if (m_AlphaTestDepthPrepass == value.isOn) - return; - m_AlphaTestDepthPrepass = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaTestDepthPostpass; - - public ToggleData alphaTestDepthPostpass - { - get { return new ToggleData(m_AlphaTestDepthPostpass); } - set - { - if (m_AlphaTestDepthPostpass == value.isOn) - return; - m_AlphaTestDepthPostpass = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_TransparentWritesMotionVec; - - public ToggleData transparentWritesMotionVec - { - get { return new ToggleData(m_TransparentWritesMotionVec); } - set - { - if (m_TransparentWritesMotionVec == value.isOn) - return; - m_TransparentWritesMotionVec = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaTestShadow; - - public ToggleData alphaTestShadow - { - get { return new ToggleData(m_AlphaTestShadow); } - set - { - if (m_AlphaTestShadow == value.isOn) - return; - m_AlphaTestShadow = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_BackThenFrontRendering; - - public ToggleData backThenFrontRendering - { - get { return new ToggleData(m_BackThenFrontRendering); } - set - { - if (m_BackThenFrontRendering == value.isOn) - return; - m_BackThenFrontRendering = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - int m_SortPriority; - - public int sortPriority - { - get { return m_SortPriority; } - set - { - if (m_SortPriority == value) - return; - m_SortPriority = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - DoubleSidedMode m_DoubleSidedMode; - - public DoubleSidedMode doubleSidedMode - { - get { return m_DoubleSidedMode; } - set - { - if (m_DoubleSidedMode == value) - return; - - m_DoubleSidedMode = value; - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - MaterialType m_MaterialType; - - public MaterialType materialType - { - get { return m_MaterialType; } - set - { - if (m_MaterialType == value) - return; - - m_MaterialType = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_ReceiveDecals = true; - - public ToggleData receiveDecals - { - get { return new ToggleData(m_ReceiveDecals); } - set - { - if (m_ReceiveDecals == value.isOn) - return; - m_ReceiveDecals = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_ReceivesSSR = true; - public ToggleData receiveSSR - { - get { return new ToggleData(m_ReceivesSSR); } - set - { - if (m_ReceivesSSR == value.isOn) - return; - m_ReceivesSSR = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_ReceivesSSRTransparent = false; - public ToggleData receiveSSRTransparent - { - get { return new ToggleData(m_ReceivesSSRTransparent); } - set - { - if (m_ReceivesSSRTransparent == value.isOn) - return; - m_ReceivesSSRTransparent = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AddPrecomputedVelocity = false; - - public ToggleData addPrecomputedVelocity - { - get { return new ToggleData(m_AddPrecomputedVelocity); } - set - { - if (m_AddPrecomputedVelocity == value.isOn) - return; - m_AddPrecomputedVelocity = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - - - [SerializeField] - bool m_UseLightFacingNormal = false; - public ToggleData useLightFacingNormal - { - get { return new ToggleData(m_UseLightFacingNormal); } - set - { - if (m_UseLightFacingNormal == value.isOn) - return; - m_UseLightFacingNormal = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_SpecularAA; - - public ToggleData specularAA - { - get { return new ToggleData(m_SpecularAA); } - set - { - if (m_SpecularAA == value.isOn) - return; - m_SpecularAA = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - float m_SpecularAAScreenSpaceVariance; - - public float specularAAScreenSpaceVariance - { - get { return m_SpecularAAScreenSpaceVariance; } - set - { - if (m_SpecularAAScreenSpaceVariance == value) - return; - m_SpecularAAScreenSpaceVariance = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - float m_SpecularAAThreshold; - - public float specularAAThreshold - { - get { return m_SpecularAAThreshold; } - set - { - if (m_SpecularAAThreshold == value) - return; - m_SpecularAAThreshold = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - SpecularOcclusionMode m_SpecularOcclusionMode; - - public SpecularOcclusionMode specularOcclusionMode - { - get { return m_SpecularOcclusionMode; } - set - { - if (m_SpecularOcclusionMode == value) - return; - - m_SpecularOcclusionMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_overrideBakedGI; - - public ToggleData overrideBakedGI - { - get { return new ToggleData(m_overrideBakedGI); } - set - { - if (m_overrideBakedGI == value.isOn) - return; - m_overrideBakedGI = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_depthOffset; - - public ToggleData depthOffset - { - get { return new ToggleData(m_depthOffset); } - set - { - if (m_depthOffset == value.isOn) - return; - m_depthOffset = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_ZWrite; - - public ToggleData zWrite - { - get { return new ToggleData(m_ZWrite); } - set - { - if (m_ZWrite == value.isOn) - return; - m_ZWrite = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - TransparentCullMode m_transparentCullMode = TransparentCullMode.Back; - public TransparentCullMode transparentCullMode - { - get => m_transparentCullMode; - set - { - if (m_transparentCullMode == value) - return; - - m_transparentCullMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - CompareFunction m_ZTest = CompareFunction.LessEqual; - public CompareFunction zTest - { - get => m_ZTest; - set - { - if (m_ZTest == value) - return; - - m_ZTest = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_SupportLodCrossFade; - - public ToggleData supportLodCrossFade - { - get { return new ToggleData(m_SupportLodCrossFade); } - set - { - if (m_SupportLodCrossFade == value.isOn) - return; - m_SupportLodCrossFade = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Node); - } - } - - [SerializeField] - bool m_DOTSInstancing = false; - - public ToggleData dotsInstancing - { - get { return new ToggleData(m_DOTSInstancing); } - set - { - if (m_DOTSInstancing == value.isOn) - return; - - m_DOTSInstancing = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - int m_MaterialNeedsUpdateHash = 0; - - int ComputeMaterialNeedsUpdateHash() - { - int hash = 0; - - hash |= (alphaTest.isOn ? 0 : 1) << 0; - hash |= (alphaTestShadow.isOn ? 0 : 1) << 1; - hash |= (receiveSSR.isOn ? 0 : 1) << 2; - - return hash; - } - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public HairMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - public override string documentationURL => Documentation.GetPageLink("Master-Node-Hair"); - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "Hair Master"; - - List validSlots = new List(); - - if (MaterialTypeUsesSlotMask(SlotMask.Position)) - { - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionSlotDisplayName, PositionSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(PositionSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.VertexNormal)) - { - AddSlot(new NormalMaterialSlot(VertexNormalSlotId, VertexNormalSlotName, VertexNormalSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexNormalSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.VertexTangent)) - { - AddSlot(new TangentMaterialSlot(VertexTangentSlotId, VertexTangentSlotName, VertexTangentSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexTangentSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Albedo)) - { - AddSlot(new ColorRGBMaterialSlot(AlbedoSlotId, AlbedoDisplaySlotName, AlbedoSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(AlbedoSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.SpecularOcclusion) && specularOcclusionMode == SpecularOcclusionMode.Custom) - { - AddSlot(new Vector1MaterialSlot(SpecularOcclusionSlotId, SpecularOcclusionSlotName, SpecularOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularOcclusionSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Normal)) - { - AddSlot(new NormalMaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(NormalSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.BentNormal)) - { - AddSlot(new NormalMaterialSlot(BentNormalSlotId, BentNormalSlotName, BentNormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(BentNormalSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Smoothness)) - { - AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(SmoothnessSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Occlusion)) - { - AddSlot(new Vector1MaterialSlot(AmbientOcclusionSlotId, AmbientOcclusionDisplaySlotName, AmbientOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AmbientOcclusionSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Transmittance)) - { - AddSlot(new Vector3MaterialSlot(TransmittanceSlotId, TransmittanceSlotName, TransmittanceSlotName, SlotType.Input, 0.3f * new Vector3(1.0f, 0.65f, 0.3f), ShaderStageCapability.Fragment)); - validSlots.Add(TransmittanceSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.RimTransmissionIntensity)) - { - AddSlot(new Vector1MaterialSlot(RimTransmissionIntensitySlotId, RimTransmissionIntensitySlotName, RimTransmissionIntensitySlotName, SlotType.Input, 0.2f, ShaderStageCapability.Fragment)); - validSlots.Add(RimTransmissionIntensitySlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.HairStrandDirection)) - { - AddSlot(new Vector3MaterialSlot(HairStrandDirectionSlotId, HairStrandDirectionSlotName, HairStrandDirectionSlotName, SlotType.Input, new Vector3(0, -1, 0), ShaderStageCapability.Fragment)); - validSlots.Add(HairStrandDirectionSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Emission)) - { - AddSlot(new ColorRGBMaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Color.black, ColorMode.HDR, ShaderStageCapability.Fragment)); - validSlots.Add(EmissionSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Alpha)) - { - AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.AlphaClipThreshold) && alphaTest.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaClipThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaClipThresholdSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.AlphaClipThresholdDepthPrepass) && surfaceType == SurfaceType.Transparent && alphaTest.isOn && alphaTestDepthPrepass.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaClipThresholdDepthPrepassSlotId, AlphaClipThresholdDepthPrepassSlotName, AlphaClipThresholdDepthPrepassSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaClipThresholdDepthPrepassSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.AlphaClipThresholdDepthPostpass) && surfaceType == SurfaceType.Transparent && alphaTest.isOn && alphaTestDepthPostpass.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaClipThresholdDepthPostpassSlotId, AlphaClipThresholdDepthPostpassSlotName, AlphaClipThresholdDepthPostpassSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaClipThresholdDepthPostpassSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.AlphaClipThresholdShadow) && alphaTest.isOn && alphaTestShadow.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaClipThresholdShadowSlotId, AlphaClipThresholdShadowSlotName, AlphaClipThresholdShadowSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaClipThresholdShadowSlotId); - } - if (specularAA.isOn) - { - AddSlot(new Vector1MaterialSlot(SpecularAAScreenSpaceVarianceSlotId, SpecularAAScreenSpaceVarianceSlotName, SpecularAAScreenSpaceVarianceSlotName, SlotType.Input, 0.1f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularAAScreenSpaceVarianceSlotId); - - AddSlot(new Vector1MaterialSlot(SpecularAAThresholdSlotId, SpecularAAThresholdSlotName, SpecularAAThresholdSlotName, SlotType.Input, 0.2f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularAAThresholdSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.SpecularTint)) - { - AddSlot(new ColorRGBMaterialSlot(SpecularTintSlotId, SpecularTintSlotName, SpecularTintSlotName, SlotType.Input, Color.white, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularTintSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.SpecularShift)) - { - AddSlot(new Vector1MaterialSlot(SpecularShiftSlotId, SpecularShiftSlotName, SpecularShiftSlotName, SlotType.Input, 0.1f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularShiftSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.SecondarySpecularTint)) - { - AddSlot(new ColorRGBMaterialSlot(SecondarySpecularTintSlotId, SecondarySpecularTintSlotName, SecondarySpecularTintSlotName, SlotType.Input, Color.grey, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(SecondarySpecularTintSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.SecondarySmoothness)) - { - AddSlot(new Vector1MaterialSlot(SecondarySmoothnessSlotId, SecondarySmoothnessSlotName, SecondarySmoothnessSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(SecondarySmoothnessSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.SecondarySpecularShift)) - { - AddSlot(new Vector1MaterialSlot(SecondarySpecularShiftSlotId, SecondarySpecularShiftSlotName, SecondarySpecularShiftSlotName, SlotType.Input, -0.1f, ShaderStageCapability.Fragment)); - validSlots.Add(SecondarySpecularShiftSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.BakedGI) && overrideBakedGI.isOn) - { - AddSlot(new DefaultMaterialSlot(LightingSlotId, BakedGISlotName, BakedGISlotName, ShaderStageCapability.Fragment)); - validSlots.Add(LightingSlotId); - AddSlot(new DefaultMaterialSlot(BackLightingSlotId, BakedBackGISlotName, BakedBackGISlotName, ShaderStageCapability.Fragment)); - validSlots.Add(BackLightingSlotId); - } - if (depthOffset.isOn) - { - AddSlot(new Vector1MaterialSlot(DepthOffsetSlotId, DepthOffsetSlotName, DepthOffsetSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(DepthOffsetSlotId); - } - - RemoveSlotsNameNotMatching(validSlots, true); - } - - public VisualElement CreateSettingsElement() - { - return new HairSettingsView(this); - } - - public string renderQueueTag - { - get - { - var renderingPass = surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; - int queue = HDRenderQueue.ChangeType(renderingPass, sortPriority, alphaTest.isOn); - return HDRenderQueue.GetShaderTagValue(queue); - } - } - - public string renderTypeTag => HDRenderTypeTags.HDLitShader.ToString(); - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - var ambientOcclusionSlot = FindSlot(AmbientOcclusionSlotId); - - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PositionSlotId) || - IsSlotConnected(VertexNormalSlotId) || - IsSlotConnected(VertexTangentSlotId)), - new ConditionalField(Fields.GraphPixel, true), - new ConditionalField(Fields.LodCrossFade, supportLodCrossFade.isOn), - - // Surface Type - new ConditionalField(Fields.SurfaceOpaque, surfaceType == SurfaceType.Opaque), - new ConditionalField(Fields.SurfaceTransparent, surfaceType != SurfaceType.Opaque), - - // Structs - new ConditionalField(HDStructFields.FragInputs.IsFrontFace,doubleSidedMode != DoubleSidedMode.Disabled && - !pass.Equals(HDHairSubTarget.HairPasses.MotionVectors)), - // Material - new ConditionalField(HDFields.KajiyaKay, materialType == MaterialType.KajiyaKay), - - // Specular Occlusion - new ConditionalField(HDFields.SpecularOcclusionFromAO, specularOcclusionMode == SpecularOcclusionMode.FromAO), - new ConditionalField(HDFields.SpecularOcclusionFromAOBentNormal, specularOcclusionMode == SpecularOcclusionMode.FromAOAndBentNormal), - new ConditionalField(HDFields.SpecularOcclusionCustom, specularOcclusionMode == SpecularOcclusionMode.Custom), - - // Misc - // We always generate the keyword ALPHATEST_ON - new ConditionalField(Fields.AlphaTest, alphaTest.isOn && (pass.pixelPorts.Contains(AlphaClipThresholdSlotId) || pass.pixelPorts.Contains(AlphaClipThresholdShadowSlotId) || - pass.pixelPorts.Contains(AlphaClipThresholdDepthPrepassSlotId) || pass.pixelPorts.Contains(AlphaClipThresholdDepthPostpassSlotId))), - // All the DoAlphaXXX field drive the generation of which code to use for alpha test in the template - // Do alpha test only if we aren't using the TestShadow one - new ConditionalField(HDFields.DoAlphaTest, alphaTest.isOn && (pass.pixelPorts.Contains(AlphaClipThresholdSlotId) && - !(alphaTestShadow.isOn && pass.pixelPorts.Contains(AlphaClipThresholdShadowSlotId)))), - new ConditionalField(HDFields.DoAlphaTestShadow, alphaTest.isOn && alphaTestShadow.isOn && pass.pixelPorts.Contains(AlphaClipThresholdShadowSlotId)), - new ConditionalField(HDFields.DoAlphaTestPrepass, alphaTest.isOn && alphaTestDepthPrepass.isOn && pass.pixelPorts.Contains(AlphaClipThresholdDepthPrepassSlotId)), - new ConditionalField(HDFields.DoAlphaTestPostpass, alphaTest.isOn && alphaTestDepthPostpass.isOn && pass.pixelPorts.Contains(AlphaClipThresholdDepthPostpassSlotId)), - new ConditionalField(Fields.AlphaToMask, alphaTest.isOn && pass.pixelPorts.Contains(AlphaClipThresholdSlotId) && alphaToMask.isOn), - new ConditionalField(HDFields.AlphaFog, surfaceType != SurfaceType.Opaque && transparencyFog.isOn), - new ConditionalField(HDFields.BlendPreserveSpecular, surfaceType != SurfaceType.Opaque && blendPreserveSpecular.isOn), - new ConditionalField(HDFields.TransparentWritesMotionVec, surfaceType != SurfaceType.Opaque && transparentWritesMotionVec.isOn), - new ConditionalField(HDFields.DisableDecals, !receiveDecals.isOn), - new ConditionalField(HDFields.DisableSSR, !receiveSSR.isOn), - new ConditionalField(HDFields.DisableSSRTransparent, !receiveSSRTransparent.isOn), - new ConditionalField(Fields.VelocityPrecomputed, addPrecomputedVelocity.isOn), - new ConditionalField(HDFields.BentNormal, IsSlotConnected(BentNormalSlotId) && - pass.pixelPorts.Contains(BentNormalSlotId)), - new ConditionalField(HDFields.AmbientOcclusion, pass.pixelPorts.Contains(AmbientOcclusionSlotId) && - (IsSlotConnected(AmbientOcclusionSlotId) || - ambientOcclusionSlot.value != ambientOcclusionSlot.defaultValue)), - new ConditionalField(HDFields.LightingGI, IsSlotConnected(LightingSlotId) && - pass.pixelPorts.Contains(LightingSlotId)), - new ConditionalField(HDFields.BackLightingGI, IsSlotConnected(BackLightingSlotId) && - pass.pixelPorts.Contains(BackLightingSlotId)), - new ConditionalField(HDFields.DepthOffset, depthOffset.isOn && pass.pixelPorts.Contains(DepthOffsetSlotId)), - new ConditionalField(HDFields.SpecularAA, specularAA.isOn && - pass.pixelPorts.Contains(SpecularAAThresholdSlotId) && - pass.pixelPorts.Contains(SpecularAAScreenSpaceVarianceSlotId)), - - new ConditionalField(HDFields.HairStrandDirection, IsSlotConnected(HairStrandDirectionSlotId) && - pass.pixelPorts.Contains(HairStrandDirectionSlotId)), - new ConditionalField(HDFields.Transmittance, IsSlotConnected(TransmittanceSlotId) && - pass.pixelPorts.Contains(TransmittanceSlotId)), - new ConditionalField(HDFields.RimTransmissionIntensity, IsSlotConnected(RimTransmissionIntensitySlotId) && - pass.pixelPorts.Contains(RimTransmissionIntensitySlotId)), - new ConditionalField(HDFields.UseLightFacingNormal, useLightFacingNormal.isOn), - new ConditionalField(HDFields.TransparentBackFace, surfaceType != SurfaceType.Opaque && backThenFrontRendering.isOn), - new ConditionalField(HDFields.TransparentDepthPrePass, surfaceType != SurfaceType.Opaque && alphaTestDepthPrepass.isOn), - new ConditionalField(HDFields.TransparentDepthPostPass, surfaceType != SurfaceType.Opaque && alphaTestDepthPrepass.isOn), - }; - } - - public void ProcessPreviewMaterial(Material material) - { - // Fixup the material settings: - material.SetFloat(kSurfaceType, (int)(SurfaceType)surfaceType); - material.SetFloat(kDoubleSidedNormalMode, (int)doubleSidedMode); - material.SetFloat(kDoubleSidedEnable, doubleSidedMode != DoubleSidedMode.Disabled ? 1.0f : 0.0f); - material.SetFloat(kAlphaCutoffEnabled, alphaTest.isOn ? 1 : 0); - material.SetFloat(kBlendMode, (int)HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode)); - material.SetFloat(kEnableFogOnTransparent, transparencyFog.isOn ? 1.0f : 0.0f); - material.SetFloat(kZTestTransparent, (int)zTest); - material.SetFloat(kTransparentCullMode, (int)transparentCullMode); - material.SetFloat(kZWrite, zWrite.isOn ? 1.0f : 0.0f); - // No sorting priority for shader graph preview - var renderingPass = surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; - material.renderQueue = (int)HDRenderQueue.ChangeType(renderingPass, offset: 0, alphaTest: alphaTest.isOn); - - HairGUI.SetupMaterialKeywordsAndPass(material); - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public override object saveContext - { - get - { - int hash = ComputeMaterialNeedsUpdateHash(); - - bool needsUpdate = hash != m_MaterialNeedsUpdateHash; - - if (needsUpdate) - m_MaterialNeedsUpdateHash = hash; - - return new HDSaveContext{ updateMaterials = needsUpdate }; - } - } - - public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) - { - // Trunk currently relies on checking material property "_EmissionColor" to allow emissive GI. If it doesn't find that property, or it is black, GI is forced off. - // ShaderGraph doesn't use this property, so currently it inserts a dummy color (white). This dummy color may be removed entirely once the following PR has been merged in trunk: Pull request #74105 - // The user will then need to explicitly disable emissive GI if it is not needed. - // To be able to automatically disable emission based on the ShaderGraph config when emission is black, - // we will need a more general way to communicate this to the engine (not directly tied to a material property). - collector.AddShaderProperty(new ColorShaderProperty() - { - overrideReferenceName = "_EmissionColor", - hidden = true, - value = new Color(1.0f, 1.0f, 1.0f, 1.0f) - }); - - //See SG-ADDITIONALVELOCITY-NOTE - if (addPrecomputedVelocity.isOn) - { - collector.AddShaderProperty(new BooleanShaderProperty - { - value = true, - hidden = true, - overrideReferenceName = kAddPrecomputedVelocity, - }); - } - - // Add all shader properties required by the inspector - HDSubShaderUtilities.AddStencilShaderProperties(collector, false, surfaceType == SurfaceType.Opaque ? receiveSSR.isOn : receiveSSRTransparent.isOn, receiveSSR.isOn, receiveSSRTransparent.isOn); - HDSubShaderUtilities.AddBlendingStatesShaderProperties( - collector, - surfaceType, - HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode), - sortPriority, - alphaToMask.isOn, - zWrite.isOn, - transparentCullMode, - zTest, - backThenFrontRendering.isOn, - transparencyFog.isOn - ); - HDSubShaderUtilities.AddAlphaCutoffShaderProperties(collector, alphaTest.isOn, alphaTestShadow.isOn); - HDSubShaderUtilities.AddDoubleSidedProperty(collector, doubleSidedMode); - HDSubShaderUtilities.AddPrePostPassProperties(collector, alphaTestDepthPrepass.isOn, alphaTestDepthPostpass.isOn); - - base.CollectShaderProperties(collector, generationMode); - } - - public bool supportsVirtualTexturing => true; - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairMasterNode.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairMasterNode.cs.meta deleted file mode 100644 index 78a2253dc90..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairMasterNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1004adfa507edb84eb29d34ccc7c7d9a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairPass.template b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairPass.template index d939ca09457..01dccf50d14 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairPass.template +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairPass.template @@ -155,7 +155,7 @@ Pass surfaceData.specularOcclusion = 1.0; // copy across graph values, if defined - $SurfaceDescription.Albedo: surfaceData.diffuseColor = surfaceDescription.Albedo; + $SurfaceDescription.BaseColor: surfaceData.diffuseColor = surfaceDescription.BaseColor; $SurfaceDescription.SpecularOcclusion: surfaceData.specularOcclusion = surfaceDescription.SpecularOcclusion; $SurfaceDescription.Smoothness: surfaceData.perceptualSmoothness = surfaceDescription.Smoothness; $SurfaceDescription.Occlusion: surfaceData.ambientOcclusion = surfaceDescription.Occlusion; @@ -221,7 +221,7 @@ Pass // tangent-space normal float3 normalTS = float3(0.0f, 0.0f, 1.0f); - $SurfaceDescription.Normal: normalTS = surfaceDescription.Normal; + $SurfaceDescription.NormalTS: normalTS = surfaceDescription.NormalTS; // compute world space (user-provided) normal GetNormalWS(fragInputs, normalTS, surfaceData.normalWS, doubleSidedConstants); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSettingsView.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSettingsView.cs deleted file mode 100644 index ddaf37ece35..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSettingsView.cs +++ /dev/null @@ -1,537 +0,0 @@ -using System; -using UnityEditor.UIElements; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEditor.Graphing.Util; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEngine.Rendering.HighDefinition; -using UnityEngine.Rendering; - -namespace UnityEditor.Rendering.HighDefinition.Drawing -{ - class HairSettingsView : MasterNodeSettingsView - { - HairMasterNode m_Node; - - IntegerField m_SortPriorityField; - - Label CreateLabel(string text, int indentLevel) - { - string label = ""; - for (var i = 0; i < indentLevel; i++) - { - label += " "; - } - return new Label(label + text); - } - - public HairSettingsView(HairMasterNode node) : base(node) - { - m_Node = node; - PropertySheet ps = new PropertySheet(); - - int indentLevel = 0; - ps.Add(new PropertyRow(CreateLabel("Surface Type", indentLevel)), (row) => - { - row.Add(new EnumField(SurfaceType.Opaque), (field) => - { - field.value = m_Node.surfaceType; - field.RegisterValueChangedCallback(ChangeSurfaceType); - }); - }); - - if (m_Node.surfaceType == SurfaceType.Transparent) - { - ++indentLevel; - - ps.Add(new PropertyRow(CreateLabel("Preserve Specular Lighting", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.blendPreserveSpecular.isOn; - toggle.OnToggleChanged(ChangeBlendPreserveSpecular); - }); - }); - - m_SortPriorityField = new IntegerField(); - ps.Add(new PropertyRow(CreateLabel("Sorting Priority", indentLevel)), (row) => - { - row.Add(m_SortPriorityField, (field) => - { - field.value = m_Node.sortPriority; - field.RegisterValueChangedCallback(ChangeSortPriority); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Receive Fog", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.transparencyFog.isOn; - toggle.OnToggleChanged(ChangeTransparencyFog); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Back Then Front Rendering", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.backThenFrontRendering.isOn; - toggle.OnToggleChanged(ChangeBackThenFrontRendering); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Transparent Depth Prepass", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestDepthPrepass.isOn; - toggle.OnToggleChanged(ChangeAlphaTestPrepass); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Transparent Depth Postpass", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestDepthPostpass.isOn; - toggle.OnToggleChanged(ChangeAlphaTestPostpass); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Transparent Writes Motion Vector", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.transparentWritesMotionVec.isOn; - toggle.OnToggleChanged(ChangeTransparentWritesMotionVec); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Depth Write", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.zWrite.isOn; - toggle.OnToggleChanged(ChangeZWrite); - }); - }); - - if (m_Node.doubleSidedMode == DoubleSidedMode.Disabled) - { - ps.Add(new PropertyRow(CreateLabel("Cull Mode", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.transparentCullMode), (e) => - { - e.value = m_Node.transparentCullMode; - e.RegisterValueChangedCallback(ChangeTransparentCullMode); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Depth Test", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.zTest), (e) => - { - e.value = m_Node.zTest; - e.RegisterValueChangedCallback(ChangeZTest); - }); - }); - - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Double-Sided", indentLevel)), (row) => - { - row.Add(new EnumField(DoubleSidedMode.Disabled), (field) => - { - field.value = m_Node.doubleSidedMode; - field.RegisterValueChangedCallback(ChangeDoubleSidedMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Alpha Clipping", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTest.isOn; - toggle.OnToggleChanged(ChangeAlphaTest); - }); - }); - - if (m_Node.alphaTest.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Use Shadow Threshold", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestShadow.isOn; - toggle.OnToggleChanged(ChangeAlphaTestShadow); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Alpha to Mask", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaToMask.isOn; - toggle.OnToggleChanged(ChangeAlphaToMask); - }); - }); - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Receive Decals", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.receiveDecals.isOn; - toggle.OnToggleChanged(ChangeDecal); - }); - }); - - ps.Add(new PropertyRow(CreateLabel((m_Node.surfaceType == SurfaceType.Transparent) ? "Receive SSR Transparent" : "Receive SSR", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - if (m_Node.surfaceType == SurfaceType.Transparent) - { - toggle.value = m_Node.receiveSSRTransparent.isOn; - toggle.OnToggleChanged(ChangeSSRTransparent); - } - else - { - toggle.value = m_Node.receiveSSR.isOn; - toggle.OnToggleChanged(ChangeSSR); - } - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Add Precomputed Velocity", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.addPrecomputedVelocity.isOn; - toggle.OnToggleChanged(ChangeAddPrecomputedVelocity); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Geometric Specular AA", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.specularAA.isOn; - toggle.OnToggleChanged(ChangeSpecularAA); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion Mode", indentLevel)), (row) => - { - row.Add(new EnumField(SpecularOcclusionMode.Off), (field) => - { - field.value = m_Node.specularOcclusionMode; - field.RegisterValueChangedCallback(ChangeSpecularOcclusionMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Override Baked GI", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.overrideBakedGI.isOn; - toggle.OnToggleChanged(ChangeoverrideBakedGI); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Depth Offset", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.depthOffset.isOn; - toggle.OnToggleChanged(ChangeDepthOffset); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Use Light Facing Normal", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.useLightFacingNormal.isOn; - toggle.OnToggleChanged(ChangeUseLightFacingNormal); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Support LOD CrossFade", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.supportLodCrossFade.isOn; - toggle.OnToggleChanged(ChangeSupportLODCrossFade); - }); - }); - - Add(ps); - Add(GetShaderGUIOverridePropertySheet()); - } - - void ChangeSurfaceType(ChangeEvent evt) - { - if (Equals(m_Node.surfaceType, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Surface Type Change"); - m_Node.surfaceType = (SurfaceType)evt.newValue; - } - - void ChangeDoubleSidedMode(ChangeEvent evt) - { - if (Equals(m_Node.doubleSidedMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Double-Sided Mode Change"); - m_Node.doubleSidedMode = (DoubleSidedMode)evt.newValue; - } - - void ChangeBlendMode(ChangeEvent evt) - { - // Make sure the mapping is correct by handling each case. - AlphaMode alphaMode = GetAlphaMode((HairMasterNode.AlphaModeLit)evt.newValue); - - if (Equals(m_Node.alphaMode, alphaMode)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Mode Change"); - m_Node.alphaMode = alphaMode; - } - - void ChangeBlendPreserveSpecular(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Blend Preserve Specular Change"); - ToggleData td = m_Node.blendPreserveSpecular; - td.isOn = evt.newValue; - m_Node.blendPreserveSpecular = td; - } - - void ChangeTransparencyFog(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparency Fog Change"); - ToggleData td = m_Node.transparencyFog; - td.isOn = evt.newValue; - m_Node.transparencyFog = td; - } - - void ChangeBackThenFrontRendering(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Back Then Front Rendering Change"); - ToggleData td = m_Node.backThenFrontRendering; - td.isOn = evt.newValue; - m_Node.backThenFrontRendering = td; - } - - void ChangeSortPriority(ChangeEvent evt) - { - m_Node.sortPriority = HDRenderQueue.ClampsTransparentRangePriority(evt.newValue); - // Force the text to match. - m_SortPriorityField.value = m_Node.sortPriority; - if (Equals(m_Node.sortPriority, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Sort Priority Change"); - } - - void ChangeAlphaTest(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Change"); - ToggleData td = m_Node.alphaTest; - td.isOn = evt.newValue; - m_Node.alphaTest = td; - } - - void ChangeAlphaToMask(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha to Mask Change"); - ToggleData td = m_Node.alphaToMask; - td.isOn = evt.newValue; - m_Node.alphaToMask = td; - } - - void ChangeAlphaTestPrepass(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Prepass Change"); - ToggleData td = m_Node.alphaTestDepthPrepass; - td.isOn = evt.newValue; - m_Node.alphaTestDepthPrepass = td; - } - - void ChangeAlphaTestPostpass(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Postpass Change"); - ToggleData td = m_Node.alphaTestDepthPostpass; - td.isOn = evt.newValue; - m_Node.alphaTestDepthPostpass = td; - } - - void ChangeTransparentWritesMotionVec(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparent Writes Motion Vector Change"); - ToggleData td = m_Node.transparentWritesMotionVec; - td.isOn = evt.newValue; - m_Node.transparentWritesMotionVec = td; - } - - void ChangeAlphaTestShadow(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Shadow Change"); - ToggleData td = m_Node.alphaTestShadow; - td.isOn = evt.newValue; - m_Node.alphaTestShadow = td; - } - - void ChangeDecal(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Decal Change"); - ToggleData td = m_Node.receiveDecals; - td.isOn = evt.newValue; - m_Node.receiveDecals = td; - } - - void ChangeSSR(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SSR Change"); - ToggleData td = m_Node.receiveSSR; - td.isOn = evt.newValue; - m_Node.receiveSSR = td; - } - - void ChangeSSRTransparent(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SSR Transparent Change"); - ToggleData td = m_Node.receiveSSRTransparent; - td.isOn = evt.newValue; - m_Node.receiveSSR = td; - } - - void ChangeAddPrecomputedVelocity(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Add Precomputed Velocity"); - ToggleData td = m_Node.addPrecomputedVelocity; - td.isOn = evt.newValue; - m_Node.addPrecomputedVelocity = td; - } - - void ChangeUseLightFacingNormal(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Use Light Facing Normal Change"); - ToggleData td = m_Node.useLightFacingNormal; - td.isOn = evt.newValue; - m_Node.useLightFacingNormal = td; - } - - void ChangeSpecularAA(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Specular AA Change"); - ToggleData td = m_Node.specularAA; - td.isOn = evt.newValue; - m_Node.specularAA = td; - } - - void ChangeSpecularOcclusionMode(ChangeEvent evt) - { - if (Equals(m_Node.specularOcclusionMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Specular Occlusion Mode Change"); - m_Node.specularOcclusionMode = (SpecularOcclusionMode)evt.newValue; - } - - void ChangeoverrideBakedGI(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("overrideBakedGI Change"); - ToggleData td = m_Node.overrideBakedGI; - td.isOn = evt.newValue; - m_Node.overrideBakedGI = td; - } - - void ChangeDepthOffset(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("DepthOffset Change"); - ToggleData td = m_Node.depthOffset; - td.isOn = evt.newValue; - m_Node.depthOffset = td; - } - - void ChangeZWrite(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("ZWrite Change"); - ToggleData td = m_Node.zWrite; - td.isOn = evt.newValue; - m_Node.zWrite = td; - } - - void ChangeTransparentCullMode(ChangeEvent evt) - { - if (Equals(m_Node.transparentCullMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparent Cull Mode Change"); - m_Node.transparentCullMode = (TransparentCullMode)evt.newValue; - } - - void ChangeZTest(ChangeEvent evt) - { - if (Equals(m_Node.zTest, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("ZTest Change"); - m_Node.zTest = (CompareFunction)evt.newValue; - } - - void ChangeSupportLODCrossFade(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Support LOD CrossFade Change"); - ToggleData td = m_Node.supportLodCrossFade; - td.isOn = evt.newValue; - m_Node.supportLodCrossFade = td; - } - - public AlphaMode GetAlphaMode(HairMasterNode.AlphaModeLit alphaModeLit) - { - switch (alphaModeLit) - { - case HairMasterNode.AlphaModeLit.Alpha: - return AlphaMode.Alpha; - case HairMasterNode.AlphaModeLit.Premultiply: - return AlphaMode.Premultiply; - case HairMasterNode.AlphaModeLit.Additive: - return AlphaMode.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaModeLit); - return AlphaMode.Alpha; - } - - } - } - - public HairMasterNode.AlphaModeLit GetAlphaModeLit(AlphaMode alphaMode) - { - switch (alphaMode) - { - case AlphaMode.Alpha: - return HairMasterNode.AlphaModeLit.Alpha; - case AlphaMode.Premultiply: - return HairMasterNode.AlphaModeLit.Premultiply; - case AlphaMode.Additive: - return HairMasterNode.AlphaModeLit.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaMode); - return HairMasterNode.AlphaModeLit.Alpha; - } - } - } - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSettingsView.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSettingsView.cs.meta deleted file mode 100644 index ab0b1913ab8..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSettingsView.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 32e16a9129dd75443a57732b47cfde94 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.Migration.cs new file mode 100644 index 00000000000..c2ee7c09669 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.Migration.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + sealed partial class HairSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData + { + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is HairMasterNode1 hairMasterNode)) + return false; + + // Set data + systemData.surfaceType = (SurfaceType)hairMasterNode.m_SurfaceType; + systemData.blendMode = HDSubShaderUtilities.UpgradeLegacyAlphaModeToBlendMode((int)hairMasterNode.m_AlphaMode); + // Previous master node wasn't having any renderingPass. Assign it correctly now. + systemData.renderingPass = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; + systemData.alphaTest = hairMasterNode.m_AlphaTest; + systemData.alphaTestDepthPrepass = hairMasterNode.m_AlphaTestDepthPrepass; + systemData.alphaTestDepthPostpass = hairMasterNode.m_AlphaTestDepthPostpass; + systemData.sortPriority = hairMasterNode.m_SortPriority; + systemData.doubleSidedMode = hairMasterNode.m_DoubleSidedMode; + systemData.zWrite = hairMasterNode.m_ZWrite; + systemData.transparentCullMode = hairMasterNode.m_transparentCullMode; + systemData.zTest = hairMasterNode.m_ZTest; + systemData.supportLodCrossFade = hairMasterNode.m_SupportLodCrossFade; + systemData.dotsInstancing = hairMasterNode.m_DOTSInstancing; + systemData.materialNeedsUpdateHash = hairMasterNode.m_MaterialNeedsUpdateHash; + + builtinData.transparencyFog = hairMasterNode.m_TransparencyFog; + builtinData.transparentWritesMotionVec = hairMasterNode.m_TransparentWritesMotionVec; + builtinData.addPrecomputedVelocity = hairMasterNode.m_AddPrecomputedVelocity; + builtinData.depthOffset = hairMasterNode.m_depthOffset; + builtinData.alphaToMask = hairMasterNode.m_AlphaToMask; + + builtinData.alphaTestShadow = hairMasterNode.m_AlphaTestShadow; + builtinData.backThenFrontRendering = hairMasterNode.m_BackThenFrontRendering; + lightingData.blendPreserveSpecular = hairMasterNode.m_BlendPreserveSpecular; + lightingData.receiveDecals = hairMasterNode.m_ReceiveDecals; + lightingData.receiveSSR = hairMasterNode.m_ReceivesSSR; + lightingData.receiveSSRTransparent = hairMasterNode.m_ReceivesSSRTransparent; + lightingData.specularAA = hairMasterNode.m_SpecularAA; + lightingData.specularOcclusionMode = hairMasterNode.m_SpecularOcclusionMode; + lightingData.overrideBakedGI = hairMasterNode.m_overrideBakedGI; + + hairData.materialType = (HairData.MaterialType)hairMasterNode.m_MaterialType; + hairData.useLightFacingNormal = hairMasterNode.m_UseLightFacingNormal; + target.customEditorGUI = hairMasterNode.m_OverrideEnabled ? hairMasterNode.m_ShaderGUIOverride : ""; + + // Convert SlotMask to BlockMap entries + var blockMapLookup = new Dictionary() + { + { HairMasterNode1.SlotMask.Position, BlockFields.VertexDescription.Position }, + { HairMasterNode1.SlotMask.VertexNormal, BlockFields.VertexDescription.Normal }, + { HairMasterNode1.SlotMask.VertexTangent, BlockFields.VertexDescription.Tangent }, + { HairMasterNode1.SlotMask.Albedo, BlockFields.SurfaceDescription.BaseColor }, + { HairMasterNode1.SlotMask.SpecularOcclusion, HDBlockFields.SurfaceDescription.SpecularOcclusion }, + { HairMasterNode1.SlotMask.Normal, BlockFields.SurfaceDescription.NormalTS }, + { HairMasterNode1.SlotMask.BentNormal, HDBlockFields.SurfaceDescription.BentNormal }, + { HairMasterNode1.SlotMask.Smoothness, BlockFields.SurfaceDescription.Smoothness }, + { HairMasterNode1.SlotMask.Occlusion, BlockFields.SurfaceDescription.Occlusion }, + { HairMasterNode1.SlotMask.Transmittance, HDBlockFields.SurfaceDescription.Transmittance }, + { HairMasterNode1.SlotMask.RimTransmissionIntensity, HDBlockFields.SurfaceDescription.RimTransmissionIntensity }, + { HairMasterNode1.SlotMask.HairStrandDirection, HDBlockFields.SurfaceDescription.HairStrandDirection }, + { HairMasterNode1.SlotMask.Emission, BlockFields.SurfaceDescription.Emission }, + { HairMasterNode1.SlotMask.Alpha, BlockFields.SurfaceDescription.Alpha }, + { HairMasterNode1.SlotMask.AlphaClipThreshold, BlockFields.SurfaceDescription.AlphaClipThreshold }, + { HairMasterNode1.SlotMask.AlphaClipThresholdDepthPrepass, HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass }, + { HairMasterNode1.SlotMask.AlphaClipThresholdDepthPostpass, HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass }, + { HairMasterNode1.SlotMask.AlphaClipThresholdShadow, HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow }, + { HairMasterNode1.SlotMask.SpecularTint, HDBlockFields.SurfaceDescription.SpecularTint }, + { HairMasterNode1.SlotMask.SpecularShift, HDBlockFields.SurfaceDescription.SpecularShift }, + { HairMasterNode1.SlotMask.SecondarySpecularTint, HDBlockFields.SurfaceDescription.SecondarySpecularTint }, + { HairMasterNode1.SlotMask.SecondarySmoothness, HDBlockFields.SurfaceDescription.SecondarySmoothness }, + { HairMasterNode1.SlotMask.SecondarySpecularShift, HDBlockFields.SurfaceDescription.SecondarySpecularShift }, + }; + + // Legacy master node slots have additional slot conditions, test them here + bool AdditionalSlotMaskTests(HairMasterNode1.SlotMask slotMask) + { + switch(slotMask) + { + case HairMasterNode1.SlotMask.SpecularOcclusion: + return lightingData.specularOcclusionMode == SpecularOcclusionMode.Custom; + case HairMasterNode1.SlotMask.AlphaClipThreshold: + return systemData.alphaTest; + case HairMasterNode1.SlotMask.AlphaClipThresholdDepthPrepass: + return systemData.surfaceType == SurfaceType.Transparent && systemData.alphaTest && systemData.alphaTestDepthPrepass; + case HairMasterNode1.SlotMask.AlphaClipThresholdDepthPostpass: + return systemData.surfaceType == SurfaceType.Transparent && systemData.alphaTest && systemData.alphaTestDepthPostpass; + case HairMasterNode1.SlotMask.AlphaClipThresholdShadow: + return systemData.alphaTest && builtinData.alphaTestShadow; + default: + return true; + } + } + + // Set blockmap + blockMap = new Dictionary(); + foreach(HairMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(HairMasterNode1.SlotMask))) + { + if(hairMasterNode.MaterialTypeUsesSlotMask(slotMask)) + { + if(!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) + continue; + + if(!AdditionalSlotMaskTests(slotMask)) + continue; + + var slotId = Mathf.Log((int)slotMask, 2); + blockMap.Add(blockFieldDescriptor, (int)slotId); + } + } + + // Specular AA + if(lightingData.specularAA) + { + blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, HairMasterNode1.SpecularAAScreenSpaceVarianceSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAThreshold, HairMasterNode1.SpecularAAThresholdSlotId); + } + + // Override Baked GI + if(lightingData.overrideBakedGI) + { + blockMap.Add(HDBlockFields.SurfaceDescription.BakedGI, HairMasterNode1.LightingSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.BakedBackGI, HairMasterNode1.BackLightingSlotId); + } + + // Depth Offset + if(builtinData.depthOffset) + { + blockMap.Add(HDBlockFields.SurfaceDescription.DepthOffset, HairMasterNode1.DepthOffsetSlotId); + } + + return true; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.Migration.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.Migration.cs.meta new file mode 100644 index 00000000000..5f7c9779bbd --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.Migration.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 50ca841de81d7c148973ed8862e90b2e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HDHairSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.cs similarity index 59% rename from com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HDHairSubTarget.cs rename to com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.cs index 374b8e4512b..175c403b896 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HDHairSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.cs @@ -1,24 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; using UnityEngine.Rendering.HighDefinition; using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { - sealed class HDHairSubTarget : SubTarget + sealed partial class HairSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData { - const string kAssetGuid = "7e681cc79dd8e6c46ba1e8412d519e26"; static string passTemplatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/Hair/ShaderGraph/HairPass.template"; + protected override string customInspector => "Rendering.HighDefinition.HairGUI"; + protected override string subTargetAssetGuid => "7e681cc79dd8e6c46ba1e8412d519e26"; // HairSubTarget.cs + protected override ShaderID shaderID => HDShaderUtils.ShaderID.SG_Hair; - public HDHairSubTarget() + public HairSubTarget() => displayName = "Hair"; + + HairData m_HairData; + + HairData IRequiresData.data + { + get => m_HairData; + set => m_HairData = value; + } + + public HairData hairData + { + get => m_HairData; + set => m_HairData = value; + } + + protected override IEnumerable EnumerateSubShaders() + { + yield return SubShaders.Hair; + yield return SubShaders.HairRaytracing; + } + + public override void GetFields(ref TargetFieldContext context) { - displayName = "Hair"; + // TODO: move this elsewhere: + // Make sure that we don't end up in an unsupported configuration + lightingData.subsurfaceScattering = false; + + base.GetFields(ref context); + + var descs = context.blocks.Select(x => x.descriptor); + // Hair specific properties: + context.AddField(HDStructFields.FragInputs.IsFrontFace, systemData.doubleSidedMode != DoubleSidedMode.Disabled && !context.pass.Equals(HairSubTarget.HairPasses.MotionVectors)); + context.AddField(HDFields.KajiyaKay, hairData.materialType == HairData.MaterialType.KajiyaKay); + context.AddField(HDFields.HairStrandDirection, descs.Contains(HDBlockFields.SurfaceDescription.HairStrandDirection) && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.HairStrandDirection)); + context.AddField(HDFields.RimTransmissionIntensity, descs.Contains(HDBlockFields.SurfaceDescription.RimTransmissionIntensity) && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.RimTransmissionIntensity)); + context.AddField(HDFields.UseLightFacingNormal, hairData.useLightFacingNormal); + context.AddField(HDFields.Transmittance, descs.Contains(HDBlockFields.SurfaceDescription.Transmittance) && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.Transmittance)); + + // All the DoAlphaXXX field drive the generation of which code to use for alpha test in the template + // Do alpha test only if we aren't using the TestShadow one + context.AddField(HDFields.DoAlphaTest, systemData.alphaTest && (context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.AlphaClipThreshold) && + !(builtinData.alphaTestShadow && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow)))); + + // Misc + context.AddField(HDFields.SpecularAA, lightingData.specularAA && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance)); } - public override void Setup(ref TargetSetupContext context) + public override void GetActiveBlocks(ref TargetActiveBlockContext context) { - context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); - context.SetDefaultShaderGUI("Rendering.HighDefinition.HairGUI"); - context.AddSubShader(SubShaders.Hair); - context.AddSubShader(SubShaders.HairRaytracing); + base.GetActiveBlocks(ref context); + + // Hair specific blocks + context.AddBlock(HDBlockFields.SurfaceDescription.BentNormal); + context.AddBlock(HDBlockFields.SurfaceDescription.Transmittance); + context.AddBlock(HDBlockFields.SurfaceDescription.RimTransmissionIntensity); + context.AddBlock(HDBlockFields.SurfaceDescription.HairStrandDirection); + context.AddBlock(HDBlockFields.SurfaceDescription.SpecularTint); + context.AddBlock(HDBlockFields.SurfaceDescription.SpecularShift); + context.AddBlock(HDBlockFields.SurfaceDescription.SecondarySpecularTint); + context.AddBlock(HDBlockFields.SurfaceDescription.SecondarySmoothness); + context.AddBlock(HDBlockFields.SurfaceDescription.SecondarySpecularShift); + } + + protected override void AddInspectorPropertyBlocks(SubTargetPropertiesGUI blockList) + { + blockList.AddPropertyBlock(new SurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features.Lit)); + blockList.AddPropertyBlock(new HairAdvancedOptionsPropertyBlock(hairData)); } #region SubShaders @@ -35,14 +106,14 @@ static class SubShaders { HairPasses.SceneSelection }, { HairPasses.DepthForwardOnly }, { HairPasses.MotionVectors }, - { HairPasses.TransparentBackface, new FieldCondition(HDFields.TransparentBackFace, true) }, - { HairPasses.TransparentDepthPrepass, new FieldCondition[]{ + { HairPasses.TransparentBackface, new FieldCondition(HDFields.TransparentBackFace, true) }, + { HairPasses.TransparentDepthPrepass, new FieldCondition[]{ new FieldCondition(HDFields.TransparentDepthPrePass, true), new FieldCondition(HDFields.DisableSSRTransparent, true) }}, - { HairPasses.TransparentDepthPrepass, new FieldCondition[]{ + { HairPasses.TransparentDepthPrepass, new FieldCondition[]{ new FieldCondition(HDFields.TransparentDepthPrePass, true), new FieldCondition(HDFields.DisableSSRTransparent, false) }}, - { HairPasses.TransparentDepthPrepass, new FieldCondition[]{ + { HairPasses.TransparentDepthPrepass, new FieldCondition[]{ new FieldCondition(HDFields.TransparentDepthPrePass, false), new FieldCondition(HDFields.DisableSSRTransparent, false) }}, { HairPasses.ForwardOnly }, @@ -82,7 +153,7 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - pixelPorts = HairPortMasks.FragmentMETA, + validPixelBlocks = HairBlockMasks.FragmentMETA, // Collections structs = CoreStructCollections.Default, @@ -107,8 +178,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentShadowCaster, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentShadowCaster, // Collections structs = CoreStructCollections.Default, @@ -132,8 +203,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentAlphaDepth, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentAlphaDepth, // Collections structs = CoreStructCollections.Default, @@ -158,8 +229,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentDepthMotionVectors, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentDepthMotionVectors, // Collections structs = CoreStructCollections.Default, @@ -185,8 +256,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentDepthMotionVectors, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentDepthMotionVectors, // Collections structs = CoreStructCollections.Default, @@ -212,13 +283,14 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentTransparentDepthPrepass, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentTransparentDepthPrepass, // Collections structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.LitFull, fieldDependencies = CoreFieldDependencies.Default, - renderStates = HairRenderStates.TransparentDepthPrePass, + renderStates = CoreRenderStates.TransparentDepthPrePass, pragmas = CorePragmas.DotsInstancedInV2Only, defines = CoreDefines.TransparentDepthPrepass, keywords = CoreKeywords.HDBase, @@ -238,8 +310,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentTransparentBackface, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentTransparentBackface, // Collections structs = CoreStructCollections.Default, @@ -265,8 +337,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -292,13 +364,13 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentTransparentDepthPostpass, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentTransparentDepthPostpass, // Collections structs = CoreStructCollections.Default, fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.TransparentDepthPrePostPass, + renderStates = CoreRenderStates.TransparentDepthPostPass, pragmas = CorePragmas.DotsInstancedInV2Only, defines = CoreDefines.ShaderGraphRaytracingHigh, keywords = CoreKeywords.HDBase, @@ -318,8 +390,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -344,8 +416,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -370,8 +442,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -396,8 +468,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -422,8 +494,8 @@ public static class HairPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = HairPortMasks.Vertex, - pixelPorts = HairPortMasks.FragmentForward, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = HairBlockMasks.FragmentForward, //Collections structs = CoreStructCollections.Default, @@ -437,127 +509,130 @@ public static class HairPasses } #endregion -#region PortMasks - static class HairPortMasks +#region BlockMasks + static class HairBlockMasks { - public static int[] Vertex = new int[] - { - HairMasterNode.PositionSlotId, - HairMasterNode.VertexNormalSlotId, - HairMasterNode.VertexTangentSlotId, - }; - - public static int[] FragmentMETA = new int[] - { - HairMasterNode.AlbedoSlotId, - HairMasterNode.NormalSlotId, - HairMasterNode.SpecularOcclusionSlotId, - HairMasterNode.BentNormalSlotId, - HairMasterNode.HairStrandDirectionSlotId, - HairMasterNode.TransmittanceSlotId, - HairMasterNode.RimTransmissionIntensitySlotId, - HairMasterNode.SmoothnessSlotId, - HairMasterNode.AmbientOcclusionSlotId, - HairMasterNode.EmissionSlotId, - HairMasterNode.AlphaSlotId, - HairMasterNode.AlphaClipThresholdSlotId, - HairMasterNode.SpecularAAScreenSpaceVarianceSlotId, - HairMasterNode.SpecularAAThresholdSlotId, - HairMasterNode.SpecularTintSlotId, - HairMasterNode.SpecularShiftSlotId, - HairMasterNode.SecondarySpecularTintSlotId, - HairMasterNode.SecondarySmoothnessSlotId, - HairMasterNode.SecondarySpecularShiftSlotId, - }; - - public static int[] FragmentShadowCaster = new int[] - { - HairMasterNode.AlphaSlotId, - HairMasterNode.AlphaClipThresholdSlotId, - HairMasterNode.AlphaClipThresholdShadowSlotId, - HairMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentAlphaDepth = new int[] - { - HairMasterNode.AlphaSlotId, - HairMasterNode.AlphaClipThresholdSlotId, - HairMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentDepthMotionVectors = new int[] - { - HairMasterNode.NormalSlotId, - HairMasterNode.SmoothnessSlotId, - HairMasterNode.AlphaSlotId, - HairMasterNode.AlphaClipThresholdSlotId, - HairMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentTransparentDepthPrepass = new int[] - { - HairMasterNode.AlphaSlotId, - HairMasterNode.AlphaClipThresholdDepthPrepassSlotId, - HairMasterNode.DepthOffsetSlotId, - HairMasterNode.NormalSlotId, - HairMasterNode.SmoothnessSlotId, - }; - - public static int[] FragmentTransparentBackface = new int[] - { - HairMasterNode.AlbedoSlotId, - HairMasterNode.NormalSlotId, - HairMasterNode.SpecularOcclusionSlotId, - HairMasterNode.BentNormalSlotId, - HairMasterNode.HairStrandDirectionSlotId, - HairMasterNode.TransmittanceSlotId, - HairMasterNode.RimTransmissionIntensitySlotId, - HairMasterNode.SmoothnessSlotId, - HairMasterNode.AmbientOcclusionSlotId, - HairMasterNode.EmissionSlotId, - HairMasterNode.AlphaSlotId, - HairMasterNode.AlphaClipThresholdSlotId, - HairMasterNode.SpecularAAScreenSpaceVarianceSlotId, - HairMasterNode.SpecularAAThresholdSlotId, - HairMasterNode.SpecularTintSlotId, - HairMasterNode.SpecularShiftSlotId, - HairMasterNode.SecondarySpecularTintSlotId, - HairMasterNode.SecondarySmoothnessSlotId, - HairMasterNode.SecondarySpecularShiftSlotId, - HairMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentForward = new int[] - { - HairMasterNode.AlbedoSlotId, - HairMasterNode.NormalSlotId, - HairMasterNode.SpecularOcclusionSlotId, - HairMasterNode.BentNormalSlotId, - HairMasterNode.HairStrandDirectionSlotId, - HairMasterNode.TransmittanceSlotId, - HairMasterNode.RimTransmissionIntensitySlotId, - HairMasterNode.SmoothnessSlotId, - HairMasterNode.AmbientOcclusionSlotId, - HairMasterNode.EmissionSlotId, - HairMasterNode.AlphaSlotId, - HairMasterNode.AlphaClipThresholdSlotId, - HairMasterNode.SpecularAAScreenSpaceVarianceSlotId, - HairMasterNode.SpecularAAThresholdSlotId, - HairMasterNode.SpecularTintSlotId, - HairMasterNode.SpecularShiftSlotId, - HairMasterNode.SecondarySpecularTintSlotId, - HairMasterNode.SecondarySmoothnessSlotId, - HairMasterNode.SecondarySpecularShiftSlotId, - HairMasterNode.LightingSlotId, - HairMasterNode.BackLightingSlotId, - HairMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentTransparentDepthPostpass = new int[] - { - HairMasterNode.AlphaSlotId, - HairMasterNode.AlphaClipThresholdDepthPostpassSlotId, - HairMasterNode.DepthOffsetSlotId, + public static BlockFieldDescriptor[] FragmentMETA = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.HairStrandDirection, + HDBlockFields.SurfaceDescription.Transmittance, + HDBlockFields.SurfaceDescription.RimTransmissionIntensity, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, + HDBlockFields.SurfaceDescription.SpecularAAThreshold, + HDBlockFields.SurfaceDescription.SpecularTint, + HDBlockFields.SurfaceDescription.SpecularShift, + HDBlockFields.SurfaceDescription.SecondarySpecularTint, + HDBlockFields.SurfaceDescription.SecondarySmoothness, + HDBlockFields.SurfaceDescription.SecondarySpecularShift, + }; + + public static BlockFieldDescriptor[] FragmentShadowCaster = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentAlphaDepth = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentDepthMotionVectors = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentTransparentDepthPrepass = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass, + HDBlockFields.SurfaceDescription.DepthOffset, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.Smoothness, + }; + + public static BlockFieldDescriptor[] FragmentTransparentBackface = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.HairStrandDirection, + HDBlockFields.SurfaceDescription.Transmittance, + HDBlockFields.SurfaceDescription.RimTransmissionIntensity, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, + HDBlockFields.SurfaceDescription.SpecularAAThreshold, + HDBlockFields.SurfaceDescription.SpecularTint, + HDBlockFields.SurfaceDescription.SpecularShift, + HDBlockFields.SurfaceDescription.SecondarySpecularTint, + HDBlockFields.SurfaceDescription.SecondarySmoothness, + HDBlockFields.SurfaceDescription.SecondarySpecularShift, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentForward = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.HairStrandDirection, + HDBlockFields.SurfaceDescription.Transmittance, + HDBlockFields.SurfaceDescription.RimTransmissionIntensity, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, + HDBlockFields.SurfaceDescription.SpecularAAThreshold, + HDBlockFields.SurfaceDescription.SpecularTint, + HDBlockFields.SurfaceDescription.SpecularShift, + HDBlockFields.SurfaceDescription.SecondarySpecularTint, + HDBlockFields.SurfaceDescription.SecondarySmoothness, + HDBlockFields.SurfaceDescription.SecondarySpecularShift, + HDBlockFields.SurfaceDescription.BakedGI, + HDBlockFields.SurfaceDescription.BakedBackGI, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentTransparentDepthPostpass = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass, + HDBlockFields.SurfaceDescription.DepthOffset, }; } #endregion @@ -576,20 +651,6 @@ static class HairRenderStates Pass = "Replace", }) }, }; - - public static RenderStateCollection TransparentDepthPrePass = new RenderStateCollection - { - { RenderState.Blend(Blend.One, Blend.Zero) }, - { RenderState.Cull(CoreRenderStates.Uniforms.cullMode) }, - { RenderState.ZWrite(ZWrite.On) }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = CoreRenderStates.Uniforms.stencilWriteMaskDepth, - Ref = CoreRenderStates.Uniforms.stencilRefDepth, - Comp = "Always", - Pass = "Replace", - }) }, - }; } #endregion diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HDHairSubTarget.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.cs.meta similarity index 100% rename from com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HDHairSubTarget.cs.meta rename to com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitShaderPreprocessor.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitShaderPreprocessor.cs index 11e21446424..d418df51f72 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitShaderPreprocessor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitShaderPreprocessor.cs @@ -3,6 +3,7 @@ using UnityEngine; using UnityEngine.Rendering.HighDefinition; using UnityEditor.ShaderGraph; +using UnityEditor.Rendering.HighDefinition.ShaderGraph; namespace UnityEditor.Rendering.HighDefinition { @@ -26,17 +27,13 @@ protected override bool DoShadersStripper(HDRenderPipelineAsset hdrpAsset, Shade // Cache Shader Graph lookup data so we don't continually keep reloading graphs from disk. // TODO: Should really be able to answer the questions "is shader graph" and "uses HDLitMasterNode" without // hitting disk on every invoke. - if (!m_ShaderGraphMasterNodeType.TryGetValue(shader, out var shaderGraphMasterNodeType)) + if (shader.IsShaderGraph()) { - if (shader.IsShaderGraph()) + if(shader.TryGetMetadataOfType(out var obj)) { - string shaderPath = AssetDatabase.GetAssetPath(shader); - shaderGraphMasterNodeType = GraphUtil.GetOutputNodeType(shaderPath); + isBuiltInLit |= obj.shaderID == HDShaderUtils.ShaderID.SG_Lit; } - - m_ShaderGraphMasterNodeType[shader] = shaderGraphMasterNodeType; } - isBuiltInLit |= shaderGraphMasterNodeType == typeof(HDLitMasterNode); // Caution: Currently only HDRP/TerrainLit is using keyword _ALPHATEST_ON with multi compile, we shouldn't test any other built in shader if (isBuiltInTerrainLit) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs index 60693a3005a..7bf1d6ab9e4 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs @@ -1,13 +1,33 @@ +using System; using UnityEditor.ShaderGraph; -namespace UnityEditor.Rendering.HighDefinition +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { - static class CreateHDLitShaderGraph + static class CreateLitShaderGraph { - [MenuItem("Assets/Create/Shader/HDRP/Lit Graph", false, 208)] - public static void CreateMaterialGraph() + [MenuItem("Assets/Create/Shader/HDRP/Lit Shader Graph", false, 208)] + public static void CreateHDLitGraph() { - GraphUtil.CreateNewGraph(new HDLitMasterNode()); + var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); + target.TrySetActiveSubTarget(typeof(HDLitSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.CoatMask, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Alpha, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs.meta index 529aec842a3..a10eea99fb8 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: bbd40829fa8125b46b0759b6834cfff2 +guid: 103646262e4572e4aa892b422dca66d1 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitData.cs new file mode 100644 index 00000000000..798de0ea7f8 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitData.cs @@ -0,0 +1,78 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class HDLitData : HDTargetData + { + public enum MaterialType + { + Standard, + SubsurfaceScattering, + Anisotropy, + Iridescence, + SpecularColor, + Translucent + } + + [SerializeField] + bool m_RayTracing; + public bool rayTracing + { + get => m_RayTracing; + set => m_RayTracing = value; + } + + [SerializeField] + MaterialType m_MaterialType; + public MaterialType materialType + { + get => m_MaterialType; + set => m_MaterialType = value; + } + + [SerializeField] + ScreenSpaceRefraction.RefractionModel m_RefractionModel; + public ScreenSpaceRefraction.RefractionModel refractionModel + { + get => m_RefractionModel; + set => m_RefractionModel = value; + } + + // TODO: Can this use m_Transmission from HDLightingData? + // TODO: These have different defaults + [SerializeField] + bool m_SSSTransmission = true; + public bool sssTransmission + { + get => m_SSSTransmission; + set => m_SSSTransmission = value; + } + + // TODO: This seems to have been replaced by a Port? + // [SerializeField] + // int m_DiffusionProfile; + // public int diffusionProfile + // { + // get => m_DiffusionProfile; + // set => m_DiffusionProfile = value; + // } + + [SerializeField] + bool m_EnergyConservingSpecular = true; + public bool energyConservingSpecular + { + get => m_EnergyConservingSpecular; + set => m_EnergyConservingSpecular = value; + } + + [SerializeField] + bool m_ClearCoat = false; + public bool clearCoat + { + get => m_ClearCoat; + set => m_ClearCoat = value; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitData.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitData.cs.meta new file mode 100644 index 00000000000..557336664c6 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 58230676215f8ca4f8f1cf839699dbd1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitMasterNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitMasterNode.cs deleted file mode 100644 index f48dc6ba65b..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitMasterNode.cs +++ /dev/null @@ -1,1387 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEngine.Rendering.HighDefinition; -using UnityEngine.Rendering; -using UnityEditor.Rendering.HighDefinition.Drawing; -using UnityEditor.ShaderGraph.Internal; -using UnityEditor.Rendering.HighDefinition.ShaderGraph; - -// Include material common properties names -using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; - -namespace UnityEditor.Rendering.HighDefinition -{ - [Serializable] - [Title("Master", "Lit (HDRP)")] - [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.HDLitMasterNode")] - [FormerName("UnityEditor.ShaderGraph.HDLitMasterNode")] - class HDLitMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string AlbedoSlotName = "Albedo"; - public const string AlbedoDisplaySlotName = "BaseColor"; - public const string NormalSlotName = "Normal"; - public const string BentNormalSlotName = "BentNormal"; - public const string TangentSlotName = "Tangent"; - public const string SubsurfaceMaskSlotName = "SubsurfaceMask"; - public const string ThicknessSlotName = "Thickness"; - public const string DiffusionProfileHashSlotName = "DiffusionProfileHash"; - public const string DiffusionProfileHashSlotDisplayName = "Diffusion Profile"; - public const string IridescenceMaskSlotName = "IridescenceMask"; - public const string IridescenceThicknessSlotName = "IridescenceThickness"; - public const string IridescenceThicknessSlotDisplayName = "Iridescence Layer Thickness"; - public const string SpecularColorSlotName = "Specular"; - public const string SpecularColorDisplaySlotName = "SpecularColor"; - public const string CoatMaskSlotName = "CoatMask"; - public const string EmissionSlotName = "Emission"; - public const string MetallicSlotName = "Metallic"; - public const string SmoothnessSlotName = "Smoothness"; - public const string AmbientOcclusionSlotName = "Occlusion"; - public const string AmbientOcclusionDisplaySlotName = "AmbientOcclusion"; - public const string AlphaSlotName = "Alpha"; - public const string AlphaClipThresholdSlotName = "AlphaClipThreshold"; - public const string AlphaClipThresholdDepthPrepassSlotName = "AlphaClipThresholdDepthPrepass"; - public const string AlphaClipThresholdDepthPostpassSlotName = "AlphaClipThresholdDepthPostpass"; - public const string AnisotropySlotName = "Anisotropy"; - public const string PositionSlotName = "Vertex Position"; - public const string PositionSlotDisplayName = "Vertex Position"; - public const string VertexNormalSlotName = "Vertex Normal"; - public const string VertexTangentSlotName = "Vertex Tangent"; - public const string SpecularAAScreenSpaceVarianceSlotName = "SpecularAAScreenSpaceVariance"; - public const string SpecularAAThresholdSlotName = "SpecularAAThreshold"; - public const string RefractionIndexSlotName = "RefractionIndex"; - public const string RefractionColorSlotName = "RefractionColor"; - public const string RefractionColorSlotDisplayName = "Transmittance Color"; - public const string RefractionDistanceSlotName = "RefractionDistance"; - public const string RefractionDistanceSlotDisplayName = "Transmittance Absorption Distance"; - public const string DistortionSlotName = "Distortion"; - public const string DistortionSlotDisplayName = "Distortion Vector"; - public const string DistortionBlurSlotName = "DistortionBlur"; - public const string SpecularOcclusionSlotName = "SpecularOcclusion"; - public const string AlphaClipThresholdShadowSlotName = "AlphaClipThresholdShadow"; - public const string BakedGISlotName = "Baked GI"; - public const string BakedBackGISlotName = "Baked Back GI"; - public const string DepthOffsetSlotName = "DepthOffset"; - - public const int PositionSlotId = 0; - public const int AlbedoSlotId = 1; - public const int NormalSlotId = 2; - public const int BentNormalSlotId = 3; - public const int TangentSlotId = 4; - public const int SubsurfaceMaskSlotId = 5; - public const int ThicknessSlotId = 6; - public const int DiffusionProfileHashSlotId = 7; - public const int IridescenceMaskSlotId = 8; - public const int IridescenceThicknessSlotId = 9; - public const int SpecularColorSlotId = 10; - public const int CoatMaskSlotId = 11; - public const int MetallicSlotId = 12; - public const int EmissionSlotId = 13; - public const int SmoothnessSlotId = 14; - public const int AmbientOcclusionSlotId = 15; - public const int AlphaSlotId = 16; - public const int AlphaThresholdSlotId = 17; - public const int AlphaThresholdDepthPrepassSlotId = 18; - public const int AlphaThresholdDepthPostpassSlotId = 19; - public const int AnisotropySlotId = 20; - public const int SpecularAAScreenSpaceVarianceSlotId = 21; - public const int SpecularAAThresholdSlotId = 22; - public const int RefractionIndexSlotId = 23; - public const int RefractionColorSlotId = 24; - public const int RefractionDistanceSlotId = 25; - public const int DistortionSlotId = 26; - public const int DistortionBlurSlotId = 27; - public const int SpecularOcclusionSlotId = 28; - public const int AlphaThresholdShadowSlotId = 29; - public const int LightingSlotId = 30; - public const int BackLightingSlotId = 31; - public const int DepthOffsetSlotId = 32; - public const int VertexNormalSlotID = 33; - public const int VertexTangentSlotID = 34; - - public enum MaterialType - { - Standard, - SubsurfaceScattering, - Anisotropy, - Iridescence, - SpecularColor, - Translucent - } - - // Don't support Multiply - public enum AlphaModeLit - { - Alpha, - Premultiply, - Additive, - } - - // Just for convenience of doing simple masks. We could run out of bits of course. - [Flags] - enum SlotMask - { - None = 0, - Position = 1 << PositionSlotId, - Albedo = 1 << AlbedoSlotId, - Normal = 1 << NormalSlotId, - BentNormal = 1 << BentNormalSlotId, - Tangent = 1 << TangentSlotId, - SubsurfaceMask = 1 << SubsurfaceMaskSlotId, - Thickness = 1 << ThicknessSlotId, - DiffusionProfile = 1 << DiffusionProfileHashSlotId, - IridescenceMask = 1 << IridescenceMaskSlotId, - IridescenceLayerThickness = 1 << IridescenceThicknessSlotId, - Specular = 1 << SpecularColorSlotId, - CoatMask = 1 << CoatMaskSlotId, - Metallic = 1 << MetallicSlotId, - Emission = 1 << EmissionSlotId, - Smoothness = 1 << SmoothnessSlotId, - Occlusion = 1 << AmbientOcclusionSlotId, - Alpha = 1 << AlphaSlotId, - AlphaThreshold = 1 << AlphaThresholdSlotId, - AlphaThresholdDepthPrepass = 1 << AlphaThresholdDepthPrepassSlotId, - AlphaThresholdDepthPostpass = 1 << AlphaThresholdDepthPostpassSlotId, - Anisotropy = 1 << AnisotropySlotId, - SpecularOcclusion = 1 << SpecularOcclusionSlotId, - AlphaThresholdShadow = 1 << AlphaThresholdShadowSlotId, - Lighting = 1 << LightingSlotId, - BackLighting = 1 << BackLightingSlotId, - DepthOffset = 1 << DepthOffsetSlotId, - VertexNormal = 1 << VertexNormalSlotID, - VertexTangent = 1 << VertexTangentSlotID - } - - const SlotMask StandardSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Metallic | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; - const SlotMask SubsurfaceScatteringSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.SubsurfaceMask | SlotMask.Thickness | SlotMask.DiffusionProfile | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; - const SlotMask AnisotropySlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.Tangent | SlotMask.Anisotropy | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Metallic | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; - const SlotMask IridescenceSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.IridescenceMask | SlotMask.IridescenceLayerThickness | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Metallic | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; - const SlotMask SpecularColorSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.Specular | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; - const SlotMask TranslucentSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.Thickness | SlotMask.DiffusionProfile | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; - - // This could also be a simple array. For now, catch any mismatched data. - SlotMask GetActiveSlotMask() - { - switch (materialType) - { - case MaterialType.Standard: - return StandardSlotMask; - - case MaterialType.SubsurfaceScattering: - return SubsurfaceScatteringSlotMask; - - case MaterialType.Anisotropy: - return AnisotropySlotMask; - - case MaterialType.Iridescence: - return IridescenceSlotMask; - - case MaterialType.SpecularColor: - return SpecularColorSlotMask; - - case MaterialType.Translucent: - return TranslucentSlotMask; - - default: - return SlotMask.None; - } - } - - bool MaterialTypeUsesSlotMask(SlotMask mask) - { - SlotMask activeMask = GetActiveSlotMask(); - return (activeMask & mask) != 0; - } - - [SerializeField] - bool m_RayTracing; - - public ToggleData rayTracing - { - get { return new ToggleData(m_RayTracing); } - set - { - if (m_RayTracing == value.isOn) - return; - - m_RayTracing = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - SurfaceType m_SurfaceType; - - public SurfaceType surfaceType - { - get { return m_SurfaceType; } - set - { - if (m_SurfaceType == value) - return; - - m_SurfaceType = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - AlphaMode m_AlphaMode; - - public AlphaMode alphaMode - { - get { return m_AlphaMode; } - set - { - if (m_AlphaMode == value) - return; - - m_AlphaMode = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - HDRenderQueue.RenderQueueType m_RenderingPass = HDRenderQueue.RenderQueueType.Opaque; - - public HDRenderQueue.RenderQueueType renderingPass - { - get { return m_RenderingPass; } - set - { - if (m_RenderingPass == value) - return; - - m_RenderingPass = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_BlendPreserveSpecular = true; - - public ToggleData blendPreserveSpecular - { - get { return new ToggleData(m_BlendPreserveSpecular); } - set - { - if (m_BlendPreserveSpecular == value.isOn) - return; - m_BlendPreserveSpecular = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_TransparencyFog = true; - - public ToggleData transparencyFog - { - get { return new ToggleData(m_TransparencyFog); } - set - { - if (m_TransparencyFog == value.isOn) - return; - m_TransparencyFog = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField, Obsolete("Kept for data migration")] - internal bool m_DrawBeforeRefraction; - - [SerializeField] - ScreenSpaceRefraction.RefractionModel m_RefractionModel; - - public ScreenSpaceRefraction.RefractionModel refractionModel - { - get { return m_RefractionModel; } - set - { - if (m_RefractionModel == value) - return; - - m_RefractionModel = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_Distortion; - - public ToggleData distortion - { - get { return new ToggleData(m_Distortion); } - set - { - if (m_Distortion == value.isOn) - return; - m_Distortion = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - DistortionMode m_DistortionMode; - - public DistortionMode distortionMode - { - get { return m_DistortionMode; } - set - { - if (m_DistortionMode == value) - return; - - m_DistortionMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_DistortionDepthTest = true; - - public ToggleData distortionDepthTest - { - get { return new ToggleData(m_DistortionDepthTest); } - set - { - if (m_DistortionDepthTest == value.isOn) - return; - m_DistortionDepthTest = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaTest; - - public ToggleData alphaTest - { - get { return new ToggleData(m_AlphaTest); } - set - { - if (m_AlphaTest == value.isOn) - return; - m_AlphaTest = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaTestDepthPrepass; - - public ToggleData alphaTestDepthPrepass - { - get { return new ToggleData(m_AlphaTestDepthPrepass); } - set - { - if (m_AlphaTestDepthPrepass == value.isOn) - return; - m_AlphaTestDepthPrepass = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaTestDepthPostpass; - - public ToggleData alphaTestDepthPostpass - { - get { return new ToggleData(m_AlphaTestDepthPostpass); } - set - { - if (m_AlphaTestDepthPostpass == value.isOn) - return; - m_AlphaTestDepthPostpass = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_TransparentWritesMotionVec; - - public ToggleData transparentWritesMotionVec - { - get { return new ToggleData(m_TransparentWritesMotionVec); } - set - { - if (m_TransparentWritesMotionVec == value.isOn) - return; - m_TransparentWritesMotionVec = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaTestShadow; - - public ToggleData alphaTestShadow - { - get { return new ToggleData(m_AlphaTestShadow); } - set - { - if (m_AlphaTestShadow == value.isOn) - return; - m_AlphaTestShadow = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_BackThenFrontRendering; - - public ToggleData backThenFrontRendering - { - get { return new ToggleData(m_BackThenFrontRendering); } - set - { - if (m_BackThenFrontRendering == value.isOn) - return; - m_BackThenFrontRendering = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - int m_SortPriority; - - public int sortPriority - { - get { return m_SortPriority; } - set - { - if (m_SortPriority == value) - return; - m_SortPriority = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - DoubleSidedMode m_DoubleSidedMode; - - public DoubleSidedMode doubleSidedMode - { - get { return m_DoubleSidedMode; } - set - { - if (m_DoubleSidedMode == value) - return; - - m_DoubleSidedMode = value; - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - NormalDropOffSpace m_NormalDropOffSpace; - public NormalDropOffSpace normalDropOffSpace - { - get { return m_NormalDropOffSpace; } - set - { - if (m_NormalDropOffSpace == value) - return; - - m_NormalDropOffSpace = value; - if (!IsSlotConnected(NormalSlotId)) - updateNormalSlot = true; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - bool updateNormalSlot; - - - [SerializeField] - MaterialType m_MaterialType; - - public MaterialType materialType - { - get { return m_MaterialType; } - set - { - if (m_MaterialType == value) - return; - - m_MaterialType = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_SSSTransmission = true; - - public ToggleData sssTransmission - { - get { return new ToggleData(m_SSSTransmission); } - set - { - m_SSSTransmission = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_ReceiveDecals = true; - - public ToggleData receiveDecals - { - get { return new ToggleData(m_ReceiveDecals); } - set - { - if (m_ReceiveDecals == value.isOn) - return; - m_ReceiveDecals = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_ReceivesSSR = true; - public ToggleData receiveSSR - { - get { return new ToggleData(m_ReceivesSSR); } - set - { - if (m_ReceivesSSR == value.isOn) - return; - m_ReceivesSSR = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_ReceivesSSRTransparent = false; - public ToggleData receiveSSRTransparent - { - get { return new ToggleData(m_ReceivesSSRTransparent); } - set - { - if (m_ReceivesSSRTransparent == value.isOn) - return; - m_ReceivesSSRTransparent = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AddPrecomputedVelocity = false; - - public ToggleData addPrecomputedVelocity - { - get { return new ToggleData(m_AddPrecomputedVelocity); } - set - { - if (m_AddPrecomputedVelocity == value.isOn) - return; - m_AddPrecomputedVelocity = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_EnergyConservingSpecular = true; - - public ToggleData energyConservingSpecular - { - get { return new ToggleData(m_EnergyConservingSpecular); } - set - { - if (m_EnergyConservingSpecular == value.isOn) - return; - m_EnergyConservingSpecular = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_SpecularAA; - - public ToggleData specularAA - { - get { return new ToggleData(m_SpecularAA); } - set - { - if (m_SpecularAA == value.isOn) - return; - m_SpecularAA = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - float m_SpecularAAScreenSpaceVariance; - - public float specularAAScreenSpaceVariance - { - get { return m_SpecularAAScreenSpaceVariance; } - set - { - if (m_SpecularAAScreenSpaceVariance == value) - return; - m_SpecularAAScreenSpaceVariance = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - float m_SpecularAAThreshold; - - public float specularAAThreshold - { - get { return m_SpecularAAThreshold; } - set - { - if (m_SpecularAAThreshold == value) - return; - m_SpecularAAThreshold = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - SpecularOcclusionMode m_SpecularOcclusionMode; - - public SpecularOcclusionMode specularOcclusionMode - { - get { return m_SpecularOcclusionMode; } - set - { - if (m_SpecularOcclusionMode == value) - return; - - m_SpecularOcclusionMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - int m_DiffusionProfile; - - public int diffusionProfile - { - get { return m_DiffusionProfile; } - set - { - if (m_DiffusionProfile == value) - return; - - m_DiffusionProfile = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_overrideBakedGI; - - public ToggleData overrideBakedGI - { - get { return new ToggleData(m_overrideBakedGI); } - set - { - if (m_overrideBakedGI == value.isOn) - return; - m_overrideBakedGI = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_depthOffset; - - public ToggleData depthOffset - { - get { return new ToggleData(m_depthOffset); } - set - { - if (m_depthOffset == value.isOn) - return; - m_depthOffset = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_ZWrite = false; - public ToggleData zWrite - { - get { return new ToggleData(m_ZWrite); } - set - { - if (m_ZWrite == value.isOn) - return; - - m_ZWrite = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - TransparentCullMode m_transparentCullMode = TransparentCullMode.Back; - public TransparentCullMode transparentCullMode - { - get => m_transparentCullMode; - set - { - if (m_transparentCullMode == value) - return; - - m_transparentCullMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - CompareFunction m_ZTest = CompareFunction.LessEqual; - public CompareFunction zTest - { - get => m_ZTest; - set - { - if (m_ZTest == value) - return; - - m_ZTest = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_SupportLodCrossFade; - - public ToggleData supportLodCrossFade - { - get { return new ToggleData(m_SupportLodCrossFade); } - set - { - if (m_SupportLodCrossFade == value.isOn) - return; - m_SupportLodCrossFade = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Node); - } - } - - [SerializeField] - bool m_DOTSInstancing = false; - - public ToggleData dotsInstancing - { - get { return new ToggleData(m_DOTSInstancing); } - set - { - if (m_DOTSInstancing == value.isOn) - return; - - m_DOTSInstancing = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaToMask = false; - - public ToggleData alphaToMask - { - get { return new ToggleData(m_AlphaToMask); } - set - { - if (m_AlphaToMask == value.isOn) - return; - - m_AlphaToMask = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - - - [SerializeField] - int m_MaterialNeedsUpdateHash = 0; - - int ComputeMaterialNeedsUpdateHash() - { - int hash = 0; - - hash |= (alphaTest.isOn ? 0 : 1) << 0; - hash |= (alphaTestShadow.isOn ? 0 : 1) << 1; - hash |= (receiveSSR.isOn ? 0 : 1) << 2; - hash |= (receiveSSRTransparent.isOn ? 0 : 1) << 3; - hash |= (RequiresSplitLighting() ? 0 : 1) << 4; - - return hash; - } - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public HDLitMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - public override string documentationURL - { - get { return null; } - } - - public bool HasRefraction() - { - return (surfaceType == SurfaceType.Transparent && renderingPass != HDRenderQueue.RenderQueueType.PreRefraction && refractionModel != ScreenSpaceRefraction.RefractionModel.None); - } - - public bool HasDistortion() - { - return (surfaceType == SurfaceType.Transparent && distortion.isOn); - } - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "Lit Master"; - - List validSlots = new List(); - if (MaterialTypeUsesSlotMask(SlotMask.Position)) - { - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionSlotDisplayName, PositionSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(PositionSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.VertexNormal)) - { - AddSlot(new NormalMaterialSlot(VertexNormalSlotID, VertexNormalSlotName, VertexNormalSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexNormalSlotID); - } - if (MaterialTypeUsesSlotMask(SlotMask.VertexTangent)) - { - AddSlot(new TangentMaterialSlot(VertexTangentSlotID, VertexTangentSlotName, VertexTangentSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexTangentSlotID); - } - if (MaterialTypeUsesSlotMask(SlotMask.Albedo)) - { - AddSlot(new ColorRGBMaterialSlot(AlbedoSlotId, AlbedoDisplaySlotName, AlbedoSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(AlbedoSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Normal)) - { - var coordSpace = CoordinateSpace.Tangent; - if (updateNormalSlot) - { - RemoveSlot(NormalSlotId); - switch (m_NormalDropOffSpace) - { - case NormalDropOffSpace.Tangent: - coordSpace = CoordinateSpace.Tangent; - break; - case NormalDropOffSpace.World: - coordSpace = CoordinateSpace.World; - break; - case NormalDropOffSpace.Object: - coordSpace = CoordinateSpace.Object; - break; - } - updateNormalSlot = false; - } - AddSlot(new NormalMaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, coordSpace, ShaderStageCapability.Fragment)); - validSlots.Add(NormalSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.BentNormal)) - { - AddSlot(new NormalMaterialSlot(BentNormalSlotId, BentNormalSlotName, BentNormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(BentNormalSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Tangent)) - { - AddSlot(new TangentMaterialSlot(TangentSlotId, TangentSlotName, TangentSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(TangentSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Anisotropy)) - { - AddSlot(new Vector1MaterialSlot(AnisotropySlotId, AnisotropySlotName, AnisotropySlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AnisotropySlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.SubsurfaceMask)) - { - AddSlot(new Vector1MaterialSlot(SubsurfaceMaskSlotId, SubsurfaceMaskSlotName, SubsurfaceMaskSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SubsurfaceMaskSlotId); - } - if ((MaterialTypeUsesSlotMask(SlotMask.Thickness) && (sssTransmission.isOn || materialType == MaterialType.Translucent)) || HasRefraction()) - { - AddSlot(new Vector1MaterialSlot(ThicknessSlotId, ThicknessSlotName, ThicknessSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(ThicknessSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.DiffusionProfile)) - { - AddSlot(new DiffusionProfileInputMaterialSlot(DiffusionProfileHashSlotId, DiffusionProfileHashSlotDisplayName, DiffusionProfileHashSlotName, ShaderStageCapability.Fragment)); - validSlots.Add(DiffusionProfileHashSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.IridescenceMask)) - { - AddSlot(new Vector1MaterialSlot(IridescenceMaskSlotId, IridescenceMaskSlotName, IridescenceMaskSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(IridescenceMaskSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.IridescenceLayerThickness)) - { - AddSlot(new Vector1MaterialSlot(IridescenceThicknessSlotId, IridescenceThicknessSlotDisplayName, IridescenceThicknessSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(IridescenceThicknessSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Specular)) - { - AddSlot(new ColorRGBMaterialSlot(SpecularColorSlotId, SpecularColorDisplaySlotName, SpecularColorSlotName, SlotType.Input, Color.white, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularColorSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.CoatMask)) - { - AddSlot(new Vector1MaterialSlot(CoatMaskSlotId, CoatMaskSlotName, CoatMaskSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(CoatMaskSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Metallic)) - { - AddSlot(new Vector1MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(MetallicSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Smoothness)) - { - AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(SmoothnessSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Occlusion)) - { - AddSlot(new Vector1MaterialSlot(AmbientOcclusionSlotId, AmbientOcclusionDisplaySlotName, AmbientOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AmbientOcclusionSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.SpecularOcclusion) && specularOcclusionMode == SpecularOcclusionMode.Custom) - { - AddSlot(new Vector1MaterialSlot(SpecularOcclusionSlotId, SpecularOcclusionSlotName, SpecularOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularOcclusionSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Emission)) - { - AddSlot(new ColorRGBMaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Color.black, ColorMode.HDR, ShaderStageCapability.Fragment)); - validSlots.Add(EmissionSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Alpha)) - { - AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.AlphaThreshold) && alphaTest.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaThresholdSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.AlphaThresholdDepthPrepass) && surfaceType == SurfaceType.Transparent && alphaTest.isOn && alphaTestDepthPrepass.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaThresholdDepthPrepassSlotId, AlphaClipThresholdDepthPrepassSlotName, AlphaClipThresholdDepthPrepassSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaThresholdDepthPrepassSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.AlphaThresholdDepthPostpass) && surfaceType == SurfaceType.Transparent && alphaTest.isOn && alphaTestDepthPostpass.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaThresholdDepthPostpassSlotId, AlphaClipThresholdDepthPostpassSlotName, AlphaClipThresholdDepthPostpassSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaThresholdDepthPostpassSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.AlphaThresholdShadow) && alphaTest.isOn && alphaTestShadow.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaThresholdShadowSlotId, AlphaClipThresholdShadowSlotName, AlphaClipThresholdShadowSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaThresholdShadowSlotId); - } - if (specularAA.isOn) - { - AddSlot(new Vector1MaterialSlot(SpecularAAScreenSpaceVarianceSlotId, SpecularAAScreenSpaceVarianceSlotName, SpecularAAScreenSpaceVarianceSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularAAScreenSpaceVarianceSlotId); - - AddSlot(new Vector1MaterialSlot(SpecularAAThresholdSlotId, SpecularAAThresholdSlotName, SpecularAAThresholdSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularAAThresholdSlotId); - } - if (HasRefraction()) - { - AddSlot(new Vector1MaterialSlot(RefractionIndexSlotId, RefractionIndexSlotName, RefractionIndexSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(RefractionIndexSlotId); - - AddSlot(new ColorRGBMaterialSlot(RefractionColorSlotId, RefractionColorSlotDisplayName, RefractionColorSlotName, SlotType.Input, Color.white, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(RefractionColorSlotId); - - AddSlot(new Vector1MaterialSlot(RefractionDistanceSlotId, RefractionDistanceSlotDisplayName, RefractionDistanceSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(RefractionDistanceSlotId); - } - if (HasDistortion()) - { - AddSlot(new Vector2MaterialSlot(DistortionSlotId, DistortionSlotDisplayName, DistortionSlotName, SlotType.Input, new Vector2(2.0f, -1.0f), ShaderStageCapability.Fragment)); - validSlots.Add(DistortionSlotId); - - AddSlot(new Vector1MaterialSlot(DistortionBlurSlotId, DistortionBlurSlotName, DistortionBlurSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(DistortionBlurSlotId); - } - if (MaterialTypeUsesSlotMask(SlotMask.Lighting) && overrideBakedGI.isOn) - { - AddSlot(new DefaultMaterialSlot(LightingSlotId, BakedGISlotName, BakedGISlotName, ShaderStageCapability.Fragment)); - validSlots.Add(LightingSlotId); - AddSlot(new DefaultMaterialSlot(BackLightingSlotId, BakedBackGISlotName, BakedBackGISlotName, ShaderStageCapability.Fragment)); - validSlots.Add(BackLightingSlotId); - } - if (depthOffset.isOn) - { - AddSlot(new Vector1MaterialSlot(DepthOffsetSlotId, DepthOffsetSlotName, DepthOffsetSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(DepthOffsetSlotId); - } - - RemoveSlotsNameNotMatching(validSlots, true); - } - - public VisualElement CreateSettingsElement() - { - return new HDLitSettingsView(this); - } - - public string renderQueueTag - { - get - { - if(renderingPass == HDRenderQueue.RenderQueueType.Unknown) - { - switch(surfaceType) - { - case SurfaceType.Opaque: - renderingPass = HDRenderQueue.RenderQueueType.Opaque; - break; - case SurfaceType.Transparent: - #pragma warning disable CS0618 // Type or member is obsolete - if (m_DrawBeforeRefraction) - { - m_DrawBeforeRefraction = false; - #pragma warning restore CS0618 // Type or member is obsolete - renderingPass = HDRenderQueue.RenderQueueType.PreRefraction; - } - else - { - renderingPass = HDRenderQueue.RenderQueueType.Transparent; - } - break; - } - } - int queue = HDRenderQueue.ChangeType(renderingPass, sortPriority, alphaTest.isOn); - return HDRenderQueue.GetShaderTagValue(queue); - } - } - - public string renderTypeTag => HDRenderTypeTags.HDLitShader.ToString(); - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - var ambientOcclusionSlot = FindSlot(AmbientOcclusionSlotId); - var coatMaskSlot = FindSlot(CoatMaskSlotId); - - // We need this to know if there are any Dots properties active - // Ideally we do this another way but HDLit needs this for conditional pragmas - var shaderProperties = new PropertyCollector(); - owner.CollectShaderProperties(shaderProperties, GenerationMode.ForReals); - bool hasDotsProperties = shaderProperties.DotsInstancingProperties(GenerationMode.ForReals).Any(); - - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PositionSlotId) || - IsSlotConnected(VertexNormalSlotID) || - IsSlotConnected(VertexTangentSlotID)), - new ConditionalField(Fields.GraphPixel, true), - new ConditionalField(Fields.LodCrossFade, supportLodCrossFade.isOn), - - // Structs - new ConditionalField(HDStructFields.FragInputs.IsFrontFace,doubleSidedMode != DoubleSidedMode.Disabled && - !pass.Equals(HDLitSubTarget.LitPasses.MotionVectors)), - - // Dots - new ConditionalField(HDFields.DotsInstancing, dotsInstancing.isOn), - new ConditionalField(HDFields.DotsProperties, hasDotsProperties), - - // Material - new ConditionalField(HDFields.Anisotropy, materialType == MaterialType.Anisotropy), - new ConditionalField(HDFields.Iridescence, materialType == MaterialType.Iridescence), - new ConditionalField(HDFields.SpecularColor, materialType == MaterialType.SpecularColor), - new ConditionalField(HDFields.Standard, materialType == MaterialType.Standard), - new ConditionalField(HDFields.SubsurfaceScattering, materialType == MaterialType.SubsurfaceScattering && - surfaceType != SurfaceType.Transparent), - new ConditionalField(HDFields.Transmission, (materialType == MaterialType.SubsurfaceScattering && sssTransmission.isOn) || - (materialType == MaterialType.Translucent)), - new ConditionalField(HDFields.Translucent, materialType == MaterialType.Translucent), - - // Surface Type - new ConditionalField(Fields.SurfaceOpaque, surfaceType == SurfaceType.Opaque), - new ConditionalField(Fields.SurfaceTransparent, surfaceType != SurfaceType.Opaque), - - // Blend Mode - new ConditionalField(Fields.BlendAdd, surfaceType != SurfaceType.Opaque && alphaMode == AlphaMode.Additive), - new ConditionalField(Fields.BlendAlpha, surfaceType != SurfaceType.Opaque && alphaMode == AlphaMode.Alpha), - new ConditionalField(Fields.BlendMultiply, surfaceType != SurfaceType.Opaque && alphaMode == AlphaMode.Multiply), - new ConditionalField(Fields.BlendPremultiply, surfaceType != SurfaceType.Opaque && alphaMode == AlphaMode.Premultiply), - - // Double Sided - new ConditionalField(HDFields.DoubleSided, doubleSidedMode != DoubleSidedMode.Disabled), - new ConditionalField(HDFields.DoubleSidedFlip, doubleSidedMode == DoubleSidedMode.FlippedNormals && - !pass.Equals(HDLitSubTarget.LitPasses.MotionVectors)), - new ConditionalField(HDFields.DoubleSidedMirror, doubleSidedMode == DoubleSidedMode.MirroredNormals && - !pass.Equals(HDLitSubTarget.LitPasses.MotionVectors)), - - // Specular Occlusion - new ConditionalField(HDFields.SpecularOcclusionFromAO, specularOcclusionMode == SpecularOcclusionMode.FromAO), - new ConditionalField(HDFields.SpecularOcclusionFromAOBentNormal, specularOcclusionMode == SpecularOcclusionMode.FromAOAndBentNormal), - new ConditionalField(HDFields.SpecularOcclusionCustom, specularOcclusionMode == SpecularOcclusionMode.Custom), - - //Distortion - new ConditionalField(HDFields.DistortionDepthTest, distortionDepthTest.isOn), - new ConditionalField(HDFields.DistortionAdd, distortionMode == DistortionMode.Add), - new ConditionalField(HDFields.DistortionMultiply, distortionMode == DistortionMode.Multiply), - new ConditionalField(HDFields.DistortionReplace, distortionMode == DistortionMode.Replace), - new ConditionalField(HDFields.TransparentDistortion, surfaceType != SurfaceType.Opaque && distortion.isOn), - - // Refraction - new ConditionalField(HDFields.Refraction, HasRefraction()), - new ConditionalField(HDFields.RefractionBox, HasRefraction() && refractionModel == ScreenSpaceRefraction.RefractionModel.Box), - new ConditionalField(HDFields.RefractionSphere, HasRefraction() && refractionModel == ScreenSpaceRefraction.RefractionModel.Sphere), - new ConditionalField(HDFields.RefractionThin, HasRefraction() && refractionModel == ScreenSpaceRefraction.RefractionModel.Thin), - - //Normal Drop Off Space - new ConditionalField(Fields.NormalDropOffOS, normalDropOffSpace == NormalDropOffSpace.Object), - new ConditionalField(Fields.NormalDropOffTS, normalDropOffSpace == NormalDropOffSpace.Tangent), - new ConditionalField(Fields.NormalDropOffWS, normalDropOffSpace == NormalDropOffSpace.World), - - // Misc - // We always generate the keyword ALPHATEST_ON - new ConditionalField(Fields.AlphaTest, alphaTest.isOn && (pass.pixelPorts.Contains(AlphaThresholdSlotId) || pass.pixelPorts.Contains(AlphaThresholdShadowSlotId) || - pass.pixelPorts.Contains(AlphaThresholdDepthPrepassSlotId) || pass.pixelPorts.Contains(AlphaThresholdDepthPostpassSlotId))), - // All the DoAlphaXXX field drive the generation of which code to use for alpha test in the template - // Do alpha test only if we aren't using the TestShadow one - // Note: we always generate the code for DoAlphaTestXXX as it is then the keyword _ALPHATEST_ON that will define if it is enabled or not - new ConditionalField(HDFields.DoAlphaTest, alphaTest.isOn && (pass.pixelPorts.Contains(AlphaThresholdSlotId) && - !(alphaTestShadow.isOn && pass.pixelPorts.Contains(AlphaThresholdShadowSlotId)))), - new ConditionalField(HDFields.DoAlphaTestShadow, alphaTest.isOn && alphaTestShadow.isOn && pass.pixelPorts.Contains(AlphaThresholdShadowSlotId)), - new ConditionalField(HDFields.DoAlphaTestPrepass, alphaTest.isOn && alphaTestDepthPrepass.isOn && pass.pixelPorts.Contains(AlphaThresholdDepthPrepassSlotId)), - new ConditionalField(HDFields.DoAlphaTestPostpass, alphaTest.isOn && alphaTestDepthPostpass.isOn && pass.pixelPorts.Contains(AlphaThresholdDepthPostpassSlotId)), - new ConditionalField(Fields.AlphaToMask, alphaTest.isOn && pass.pixelPorts.Contains(AlphaThresholdSlotId) && alphaToMask.isOn), - new ConditionalField(HDFields.AlphaFog, surfaceType != SurfaceType.Opaque && transparencyFog.isOn), - new ConditionalField(HDFields.BlendPreserveSpecular, surfaceType != SurfaceType.Opaque && blendPreserveSpecular.isOn), - new ConditionalField(HDFields.TransparentWritesMotionVec, surfaceType != SurfaceType.Opaque && transparentWritesMotionVec.isOn), - new ConditionalField(HDFields.DisableDecals, !receiveDecals.isOn), - new ConditionalField(HDFields.DisableSSR, !receiveSSR.isOn), - new ConditionalField(HDFields.DisableSSRTransparent, !receiveSSRTransparent.isOn), - new ConditionalField(Fields.VelocityPrecomputed, addPrecomputedVelocity.isOn), - new ConditionalField(HDFields.SpecularAA, specularAA.isOn && - pass.pixelPorts.Contains(SpecularAAThresholdSlotId) && - pass.pixelPorts.Contains(SpecularAAScreenSpaceVarianceSlotId)), - new ConditionalField(HDFields.EnergyConservingSpecular, energyConservingSpecular.isOn), - new ConditionalField(HDFields.BentNormal, IsSlotConnected(BentNormalSlotId) && - pass.pixelPorts.Contains(BentNormalSlotId)), - new ConditionalField(HDFields.AmbientOcclusion, pass.pixelPorts.Contains(AmbientOcclusionSlotId) && - (IsSlotConnected(AmbientOcclusionSlotId) || - ambientOcclusionSlot.value != ambientOcclusionSlot.defaultValue)), - new ConditionalField(HDFields.CoatMask, pass.pixelPorts.Contains(CoatMaskSlotId) && - (IsSlotConnected(CoatMaskSlotId) || coatMaskSlot.value > 0.0f)), - new ConditionalField(HDFields.Tangent, IsSlotConnected(TangentSlotId) && - pass.pixelPorts.Contains(TangentSlotId)), - new ConditionalField(HDFields.LightingGI, IsSlotConnected(LightingSlotId) && - pass.pixelPorts.Contains(LightingSlotId)), - new ConditionalField(HDFields.BackLightingGI, IsSlotConnected(BackLightingSlotId) && - pass.pixelPorts.Contains(BackLightingSlotId)), - new ConditionalField(HDFields.DepthOffset, depthOffset.isOn && pass.pixelPorts.Contains(DepthOffsetSlotId)), - new ConditionalField(HDFields.TransparentBackFace, surfaceType != SurfaceType.Opaque && backThenFrontRendering.isOn), - new ConditionalField(HDFields.TransparentDepthPrePass, surfaceType != SurfaceType.Opaque && alphaTestDepthPrepass.isOn), - new ConditionalField(HDFields.TransparentDepthPostPass, surfaceType != SurfaceType.Opaque && alphaTestDepthPostpass.isOn), - new ConditionalField(HDFields.RayTracing, rayTracing.isOn), - }; - } - - public void ProcessPreviewMaterial(Material material) - { - // Fixup the material settings: - material.SetFloat(kSurfaceType, (int)(SurfaceType)surfaceType); - material.SetFloat(kDoubleSidedNormalMode, (int)doubleSidedMode); - material.SetFloat(kAlphaCutoffEnabled, alphaTest.isOn ? 1 : 0); - material.SetFloat(kBlendMode, (int)HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode)); - material.SetFloat(kEnableFogOnTransparent, transparencyFog.isOn ? 1.0f : 0.0f); - material.SetFloat(kZTestTransparent, (int)zTest); - material.SetFloat(kTransparentCullMode, (int)transparentCullMode); - material.SetFloat(kZWrite, zWrite.isOn ? 1.0f : 0.0f); - // No sorting priority for shader graph preview - material.renderQueue = (int)HDRenderQueue.ChangeType(renderingPass, offset: 0, alphaTest: alphaTest.isOn); - - HDLitGUI.SetupMaterialKeywordsAndPass(material); - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public bool RequiresSplitLighting() - { - return materialType == HDLitMasterNode.MaterialType.SubsurfaceScattering; - } - public override object saveContext - { - get - { - int hash = ComputeMaterialNeedsUpdateHash(); - - bool needsUpdate = hash != m_MaterialNeedsUpdateHash; - - if (needsUpdate) - m_MaterialNeedsUpdateHash = hash; - - return new HDSaveContext{ updateMaterials = needsUpdate }; - } - } - - public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) - { - // Trunk currently relies on checking material property "_EmissionColor" to allow emissive GI. If it doesn't find that property, or it is black, GI is forced off. - // ShaderGraph doesn't use this property, so currently it inserts a dummy color (white). This dummy color may be removed entirely once the following PR has been merged in trunk: Pull request #74105 - // The user will then need to explicitly disable emissive GI if it is not needed. - // To be able to automatically disable emission based on the ShaderGraph config when emission is black, - // we will need a more general way to communicate this to the engine (not directly tied to a material property). - collector.AddShaderProperty(new ColorShaderProperty() - { - overrideReferenceName = "_EmissionColor", - hidden = true, - value = new Color(1.0f, 1.0f, 1.0f, 1.0f) - }); - // ShaderGraph only property used to send the RenderQueueType to the material - collector.AddShaderProperty(new Vector1ShaderProperty - { - overrideReferenceName = "_RenderQueueType", - hidden = true, - value = (int)renderingPass, - }); - - //See SG-ADDITIONALVELOCITY-NOTE - if (addPrecomputedVelocity.isOn) - { - collector.AddShaderProperty(new BooleanShaderProperty - { - value = true, - hidden = true, - overrideReferenceName = kAddPrecomputedVelocity, - }); - } - - // Add all shader properties required by the inspector - HDSubShaderUtilities.AddStencilShaderProperties(collector, RequiresSplitLighting(), surfaceType == SurfaceType.Opaque ? receiveSSR.isOn : receiveSSRTransparent.isOn, receiveSSR.isOn, receiveSSRTransparent.isOn); - HDSubShaderUtilities.AddBlendingStatesShaderProperties( - collector, - surfaceType, - HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode), - sortPriority, - alphaToMask.isOn, - zWrite.isOn, - transparentCullMode, - zTest, - backThenFrontRendering.isOn, - transparencyFog.isOn - ); - HDSubShaderUtilities.AddAlphaCutoffShaderProperties(collector, alphaTest.isOn, alphaTestShadow.isOn); - HDSubShaderUtilities.AddDoubleSidedProperty(collector, doubleSidedMode); - HDSubShaderUtilities.AddRayTracingProperty(collector, rayTracing.isOn); - HDSubShaderUtilities.AddPrePostPassProperties(collector, alphaTestDepthPrepass.isOn, alphaTestDepthPostpass.isOn); - - base.CollectShaderProperties(collector, generationMode); - } - - public override void Setup() - { - base.Setup(); - var hdPipelineAsset = HDRenderPipeline.currentAsset; - - if (hdPipelineAsset == null) - return; - - var diffusionProfileSlot = FindSlot(DiffusionProfileHashSlotId); - - if (diffusionProfileSlot == null) - return; - - if ((diffusionProfileSlot.diffusionProfile) != null && !hdPipelineAsset.diffusionProfileSettingsList.Any(d => d == diffusionProfileSlot.diffusionProfile)) - { - //owner.AddSetupError(tempId, $"Diffusion profile '{diffusionProfileSlot.diffusionProfile.name}' is not referenced in the current HDRP asset", ShaderCompilerMessageSeverity.Warning); - } - - } - - public bool supportsVirtualTexturing => true; - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitMasterNode.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitMasterNode.cs.meta deleted file mode 100644 index f24111be7a7..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitMasterNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: dcb07bfb82b753e43bba3637f7e723a7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSettingsView.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSettingsView.cs deleted file mode 100644 index 8b1b24412c9..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSettingsView.cs +++ /dev/null @@ -1,791 +0,0 @@ -using System; -using UnityEditor.UIElements; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEditor.Graphing.Util; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Internal; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEngine.Rendering.HighDefinition; -using UnityEngine.Rendering; - -namespace UnityEditor.Rendering.HighDefinition.Drawing -{ - class HDLitSettingsView : MasterNodeSettingsView - { - HDLitMasterNode m_Node; - - IntegerField m_SortPriorityField; - - Label CreateLabel(string text, int indentLevel) - { - string label = ""; - for (var i = 0; i < indentLevel; i++) - { - label += " "; - } - return new Label(label + text); - } - - public HDLitSettingsView(HDLitMasterNode node) : base(node) - { - m_Node = node; - PropertySheet ps = new PropertySheet(); - - int indentLevel = 0; - - ps.Add(new PropertyRow(CreateLabel("Ray Tracing (Preview)", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.rayTracing.isOn; - toggle.RegisterValueChangedCallback(ChangeRayTracingFlag); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Surface Type", indentLevel)), (row) => - { - row.Add(new EnumField(SurfaceType.Opaque), (field) => - { - field.value = m_Node.surfaceType; - field.RegisterValueChangedCallback(ChangeSurfaceType); - }); - }); - - ++indentLevel; - switch (m_Node.surfaceType) - { - case SurfaceType.Opaque: - ps.Add(new PropertyRow(CreateLabel("Rendering Pass", indentLevel)), (row) => - { - var valueList = HDSubShaderUtilities.GetRenderingPassList(true, false); - - row.Add(new PopupField(valueList, HDRenderQueue.RenderQueueType.Opaque, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName), (field) => - { - field.value = HDRenderQueue.GetOpaqueEquivalent(m_Node.renderingPass); - field.RegisterValueChangedCallback(ChangeRenderingPass); - }); - }); - break; - case SurfaceType.Transparent: - ps.Add(new PropertyRow(CreateLabel("Rendering Pass", indentLevel)), (row) => - { - Enum defaultValue; - switch (m_Node.renderingPass) // Migration - { - default: //when deserializing without issue, we still need to init the default to something even if not used. - case HDRenderQueue.RenderQueueType.Transparent: - defaultValue = HDRenderQueue.TransparentRenderQueue.Default; - break; - case HDRenderQueue.RenderQueueType.PreRefraction: - defaultValue = HDRenderQueue.TransparentRenderQueue.BeforeRefraction; - break; - } - - var valueList = HDSubShaderUtilities.GetRenderingPassList(false, false); - - row.Add(new PopupField(valueList, HDRenderQueue.RenderQueueType.Transparent, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName), (field) => - { - field.value = HDRenderQueue.GetTransparentEquivalent(m_Node.renderingPass); - field.RegisterValueChangedCallback(ChangeRenderingPass); - }); - }); - break; - default: - throw new ArgumentException("Unknown SurfaceType"); - } - --indentLevel; - - if (m_Node.surfaceType == SurfaceType.Transparent) - { - ++indentLevel; - - if (!m_Node.HasRefraction()) - { - ps.Add(new PropertyRow(CreateLabel("Blending Mode", indentLevel)), (row) => - { - row.Add(new EnumField(HDLitMasterNode.AlphaModeLit.Additive), (field) => - { - field.value = GetAlphaModeLit(m_Node.alphaMode); - field.RegisterValueChangedCallback(ChangeBlendMode); - }); - }); - - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Preserve Specular Lighting", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.blendPreserveSpecular.isOn; - toggle.OnToggleChanged(ChangeBlendPreserveSpecular); - }); - }); - --indentLevel; - } - - m_SortPriorityField = new IntegerField(); - ps.Add(new PropertyRow(CreateLabel("Sorting Priority", indentLevel)), (row) => - { - row.Add(m_SortPriorityField, (field) => - { - field.value = m_Node.sortPriority; - field.RegisterValueChangedCallback(ChangeSortPriority); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Receive Fog", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.transparencyFog.isOn; - toggle.OnToggleChanged(ChangeTransparencyFog); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Back Then Front Rendering", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.backThenFrontRendering.isOn; - toggle.OnToggleChanged(ChangeBackThenFrontRendering); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Transparent Depth Prepass", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestDepthPrepass.isOn; - toggle.OnToggleChanged(ChangeAlphaTestPrepass); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Transparent Depth Postpass", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestDepthPostpass.isOn; - toggle.OnToggleChanged(ChangeAlphaTestPostpass); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Transparent Writes Motion Vector", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.transparentWritesMotionVec.isOn; - toggle.OnToggleChanged(ChangeTransparentWritesMotionVec); - }); - }); - - if (m_Node.renderingPass != HDRenderQueue.RenderQueueType.PreRefraction) - { - ps.Add(new PropertyRow(CreateLabel("Refraction Model", indentLevel)), (row) => - { - row.Add(new EnumField(ScreenSpaceRefraction.RefractionModel.None), (field) => - { - field.value = m_Node.refractionModel; - field.RegisterValueChangedCallback(ChangeRefractionModel); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Distortion", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.distortion.isOn; - toggle.OnToggleChanged(ChangeDistortion); - }); - }); - - if (m_Node.distortion.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Distortion Blend Mode", indentLevel)), (row) => - { - row.Add(new EnumField(DistortionMode.Add), (field) => - { - field.value = m_Node.distortionMode; - field.RegisterValueChangedCallback(ChangeDistortionMode); - }); - }); - ps.Add(new PropertyRow(CreateLabel("Distortion Depth Test", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.distortionDepthTest.isOn; - toggle.OnToggleChanged(ChangeDistortionDepthTest); - }); - }); - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Depth Write", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.zWrite.isOn; - toggle.OnToggleChanged(ChangeZWrite); - }); - }); - - if (m_Node.doubleSidedMode == DoubleSidedMode.Disabled) - { - ps.Add(new PropertyRow(CreateLabel("Cull Mode", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.transparentCullMode), (e) => - { - e.value = m_Node.transparentCullMode; - e.RegisterValueChangedCallback(ChangeTransparentCullMode); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Depth Test", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.zTest), (e) => - { - e.value = m_Node.zTest; - e.RegisterValueChangedCallback(ChangeZTest); - }); - }); - - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Double-Sided", indentLevel)), (row) => - { - row.Add(new EnumField(DoubleSidedMode.Disabled), (field) => - { - field.value = m_Node.doubleSidedMode; - field.RegisterValueChangedCallback(ChangeDoubleSidedMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Fragment Normal Space", indentLevel)), (row) => - { - row.Add(new EnumField(NormalDropOffSpace.Tangent), (field) => - { - field.value = m_Node.normalDropOffSpace; - field.RegisterValueChangedCallback(ChangeSpaceOfNormalDropOffMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Alpha Clipping", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTest.isOn; - toggle.OnToggleChanged(ChangeAlphaTest); - }); - }); - - if (m_Node.alphaTest.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Use Shadow Threshold", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestShadow.isOn; - toggle.OnToggleChanged(ChangeAlphaTestShadow); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Alpha to Mask", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaToMask.isOn; - toggle.OnToggleChanged(ChangeAlphaToMask); - }); - }); - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Material Type", indentLevel)), (row) => - { - row.Add(new EnumField(HDLitMasterNode.MaterialType.Standard), (field) => - { - field.value = m_Node.materialType; - field.RegisterValueChangedCallback(ChangeMaterialType); - }); - }); - - ++indentLevel; - if (m_Node.materialType == HDLitMasterNode.MaterialType.SubsurfaceScattering) - { - ps.Add(new PropertyRow(CreateLabel("Transmission", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.sssTransmission.isOn; - toggle.OnToggleChanged(ChangeSSSTransmission); - }); - }); - } - - if (m_Node.materialType == HDLitMasterNode.MaterialType.SpecularColor) - { - ps.Add(new PropertyRow(CreateLabel("Energy Conserving Specular", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.energyConservingSpecular.isOn; - toggle.OnToggleChanged(ChangeEnergyConservingSpecular); - }); - }); - } - --indentLevel; - - ps.Add(new PropertyRow(CreateLabel("Receive Decals", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.receiveDecals.isOn; - toggle.OnToggleChanged(ChangeDecal); - }); - }); - - ps.Add(new PropertyRow(CreateLabel((m_Node.surfaceType == SurfaceType.Transparent) ? "Receive SSR Transparent" : "Receive SSR", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - if (m_Node.surfaceType == SurfaceType.Transparent) - { - toggle.value = m_Node.receiveSSRTransparent.isOn; - toggle.OnToggleChanged(ChangeSSRTransparent); - } - else - { - toggle.value = m_Node.receiveSSR.isOn; - toggle.OnToggleChanged(ChangeSSR); - } - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Add Precomputed Velocity", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.addPrecomputedVelocity.isOn; - toggle.OnToggleChanged(ChangeAddPrecomputedVelocity); - }); - }); - - - ps.Add(new PropertyRow(CreateLabel("Geometric Specular AA", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.specularAA.isOn; - toggle.OnToggleChanged(ChangeSpecularAA); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion Mode", indentLevel)), (row) => - { - row.Add(new EnumField(SpecularOcclusionMode.Off), (field) => - { - field.value = m_Node.specularOcclusionMode; - field.RegisterValueChangedCallback(ChangeSpecularOcclusionMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Override Baked GI", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.overrideBakedGI.isOn; - toggle.OnToggleChanged(ChangeoverrideBakedGI); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Depth Offset", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.depthOffset.isOn; - toggle.OnToggleChanged(ChangeDepthOffset); - }); - }); - ps.Add(new PropertyRow(CreateLabel("Support LOD CrossFade", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.supportLodCrossFade.isOn; - toggle.OnToggleChanged(ChangeSupportLODCrossFade); - }); - }); - - Add(ps); - Add(GetShaderGUIOverridePropertySheet()); - } - - void ChangeRayTracingFlag(ChangeEvent evt) - { - if (Equals(m_Node.rayTracing, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Ray Tracing Flag Change"); - ToggleData rt = m_Node.rayTracing; - rt.isOn = evt.newValue; - m_Node.rayTracing = rt; - } - - void ChangeSurfaceType(ChangeEvent evt) - { - if (Equals(m_Node.surfaceType, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Surface Type Change"); - m_Node.surfaceType = (SurfaceType)evt.newValue; - - UpdateRenderingPassValue(m_Node.renderingPass); - } - - void ChangeDoubleSidedMode(ChangeEvent evt) - { - if (Equals(m_Node.doubleSidedMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Double-Sided Mode Change"); - m_Node.doubleSidedMode = (DoubleSidedMode)evt.newValue; - } - - void ChangeSpaceOfNormalDropOffMode(ChangeEvent evt) - { - if (Equals(m_Node.normalDropOffSpace, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Normal Space Drop-Off Mode Change"); - m_Node.normalDropOffSpace = (NormalDropOffSpace)evt.newValue; - } - - void ChangeMaterialType(ChangeEvent evt) - { - if (Equals(m_Node.materialType, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Material Type Change"); - m_Node.materialType = (HDLitMasterNode.MaterialType)evt.newValue; - } - - void ChangeSSSTransmission(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SSS Transmission Change"); - ToggleData td = m_Node.sssTransmission; - td.isOn = evt.newValue; - m_Node.sssTransmission = td; - } - - void ChangeBlendMode(ChangeEvent evt) - { - // Make sure the mapping is correct by handling each case. - - AlphaMode alphaMode = GetAlphaMode((HDLitMasterNode.AlphaModeLit)evt.newValue); - - if (Equals(m_Node.alphaMode, alphaMode)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Mode Change"); - m_Node.alphaMode = alphaMode; - } - - void ChangeRenderingPass(ChangeEvent evt) - { - switch (evt.newValue) - { - case HDRenderQueue.RenderQueueType.Overlay: - case HDRenderQueue.RenderQueueType.Unknown: - case HDRenderQueue.RenderQueueType.Background: - throw new ArgumentException("Unexpected kind of RenderQueue, was " + evt.newValue); - default: - break; - }; - UpdateRenderingPassValue(evt.newValue); - } - - void UpdateRenderingPassValue(HDRenderQueue.RenderQueueType newValue) - { - HDRenderQueue.RenderQueueType renderingPass; - switch (m_Node.surfaceType) - { - case SurfaceType.Opaque: - renderingPass = HDRenderQueue.GetOpaqueEquivalent(newValue); - break; - case SurfaceType.Transparent: - renderingPass = HDRenderQueue.GetTransparentEquivalent(newValue); - break; - default: - throw new ArgumentException("Unknown SurfaceType"); - } - - if (Equals(m_Node.renderingPass, renderingPass)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Rendering Pass Change"); - m_Node.renderingPass = renderingPass; - } - - void ChangeBlendPreserveSpecular(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Blend Preserve Specular Change"); - ToggleData td = m_Node.blendPreserveSpecular; - td.isOn = evt.newValue; - m_Node.blendPreserveSpecular = td; - } - - void ChangeTransparencyFog(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparency Fog Change"); - ToggleData td = m_Node.transparencyFog; - td.isOn = evt.newValue; - m_Node.transparencyFog = td; - } - - void ChangeRefractionModel(ChangeEvent evt) - { - if (Equals(m_Node.refractionModel, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Refraction Model Change"); - m_Node.refractionModel = (ScreenSpaceRefraction.RefractionModel)evt.newValue; - } - - void ChangeDistortion(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Change"); - ToggleData td = m_Node.distortion; - td.isOn = evt.newValue; - m_Node.distortion = td; - } - - void ChangeDistortionMode(ChangeEvent evt) - { - if (Equals(m_Node.distortionMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Mode Change"); - m_Node.distortionMode = (DistortionMode)evt.newValue; - } - - void ChangeDistortionDepthTest(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Depth Test Change"); - ToggleData td = m_Node.distortionDepthTest; - td.isOn = evt.newValue; - m_Node.distortionDepthTest = td; - } - - void ChangeBackThenFrontRendering(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Back Then Front Rendering Change"); - ToggleData td = m_Node.backThenFrontRendering; - td.isOn = evt.newValue; - m_Node.backThenFrontRendering = td; - } - - void ChangeSortPriority(ChangeEvent evt) - { - m_Node.sortPriority = HDRenderQueue.ClampsTransparentRangePriority(evt.newValue); - // Force the text to match. - m_SortPriorityField.value = m_Node.sortPriority; - if (Equals(m_Node.sortPriority, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Sort Priority Change"); - } - - void ChangeAlphaTest(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Change"); - ToggleData td = m_Node.alphaTest; - td.isOn = evt.newValue; - m_Node.alphaTest = td; - } - - void ChangeAlphaTestPrepass(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Prepass Change"); - ToggleData td = m_Node.alphaTestDepthPrepass; - td.isOn = evt.newValue; - m_Node.alphaTestDepthPrepass = td; - } - - void ChangeAlphaTestPostpass(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Postpass Change"); - ToggleData td = m_Node.alphaTestDepthPostpass; - td.isOn = evt.newValue; - m_Node.alphaTestDepthPostpass = td; - } - void ChangeTransparentWritesMotionVec(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparent Writes Motion Vector Change"); - ToggleData td = m_Node.transparentWritesMotionVec; - td.isOn = evt.newValue; - m_Node.transparentWritesMotionVec = td; - } - void ChangeAlphaTestShadow(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Shadow Change"); - ToggleData td = m_Node.alphaTestShadow; - td.isOn = evt.newValue; - m_Node.alphaTestShadow = td; - } - - void ChangeDecal(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Decal Change"); - ToggleData td = m_Node.receiveDecals; - td.isOn = evt.newValue; - m_Node.receiveDecals = td; - } - - void ChangeSSR(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SSR Change"); - ToggleData td = m_Node.receiveSSR; - td.isOn = evt.newValue; - m_Node.receiveSSR = td; - } - - void ChangeSSRTransparent(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SSR Change"); - ToggleData td = m_Node.receiveSSRTransparent; - td.isOn = evt.newValue; - m_Node.receiveSSRTransparent = td; - } - - void ChangeAddPrecomputedVelocity(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Add Precomputed Velocity"); - ToggleData td = m_Node.addPrecomputedVelocity; - td.isOn = evt.newValue; - m_Node.addPrecomputedVelocity = td; - } - - void ChangeSpecularAA(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Specular AA Change"); - ToggleData td = m_Node.specularAA; - td.isOn = evt.newValue; - m_Node.specularAA = td; - } - - void ChangeEnergyConservingSpecular(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Energy Conserving Specular Change"); - ToggleData td = m_Node.energyConservingSpecular; - td.isOn = evt.newValue; - m_Node.energyConservingSpecular = td; - } - - void ChangeSpecularOcclusionMode(ChangeEvent evt) - { - if (Equals(m_Node.specularOcclusionMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Specular Occlusion Mode Change"); - m_Node.specularOcclusionMode = (SpecularOcclusionMode)evt.newValue; - } - - void ChangeoverrideBakedGI(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("overrideBakedGI Change"); - ToggleData td = m_Node.overrideBakedGI; - td.isOn = evt.newValue; - m_Node.overrideBakedGI = td; - } - - void ChangeDepthOffset(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("DepthOffset Change"); - ToggleData td = m_Node.depthOffset; - td.isOn = evt.newValue; - m_Node.depthOffset = td; - } - - void ChangeSupportLODCrossFade(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Support LOD CrossFade Change"); - ToggleData td = m_Node.supportLodCrossFade; - td.isOn = evt.newValue; - m_Node.supportLodCrossFade = td; - } - - void ChangeAlphaToMask(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha to Mask Change"); - ToggleData td = m_Node.alphaToMask; - td.isOn = evt.newValue; - m_Node.alphaToMask = td; - } - - void ChangeZWrite(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("ZWrite Change"); - ToggleData td = m_Node.zWrite; - td.isOn = evt.newValue; - m_Node.zWrite = td; - } - - void ChangeTransparentCullMode(ChangeEvent evt) - { - if (Equals(m_Node.transparentCullMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparent Cull Mode Change"); - m_Node.transparentCullMode = (TransparentCullMode)evt.newValue; - } - - void ChangeZTest(ChangeEvent evt) - { - if (Equals(m_Node.zTest, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("ZTest Change"); - m_Node.zTest = (CompareFunction)evt.newValue; - } - - public AlphaMode GetAlphaMode(HDLitMasterNode.AlphaModeLit alphaModeLit) - { - switch (alphaModeLit) - { - case HDLitMasterNode.AlphaModeLit.Alpha: - return AlphaMode.Alpha; - case HDLitMasterNode.AlphaModeLit.Premultiply: - return AlphaMode.Premultiply; - case HDLitMasterNode.AlphaModeLit.Additive: - return AlphaMode.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaModeLit); - return AlphaMode.Alpha; - } - } - } - - public HDLitMasterNode.AlphaModeLit GetAlphaModeLit(AlphaMode alphaMode) - { - switch (alphaMode) - { - case AlphaMode.Alpha: - return HDLitMasterNode.AlphaModeLit.Alpha; - case AlphaMode.Premultiply: - return HDLitMasterNode.AlphaModeLit.Premultiply; - case AlphaMode.Additive: - return HDLitMasterNode.AlphaModeLit.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaMode); - return HDLitMasterNode.AlphaModeLit.Alpha; - } - } - } - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSettingsView.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSettingsView.cs.meta deleted file mode 100644 index e24452b95f8..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSettingsView.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 00b9f1cdcb0d93f40b3703a12d4c146f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.Migration.cs new file mode 100644 index 00000000000..63881ad6511 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.Migration.cs @@ -0,0 +1,299 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + sealed partial class HDLitSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData + { + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + switch(masterNode) + { + case PBRMasterNode1 pbrMasterNode: + UpgradePBRMasterNode(pbrMasterNode, out blockMap); + return true; + case HDLitMasterNode1 hdLitMasterNode: + UpgradeHDLitMasterNode(hdLitMasterNode, out blockMap); + return true; + default: + return false; + } + } + + void UpgradePBRMasterNode(PBRMasterNode1 pbrMasterNode, out Dictionary blockMap) + { + m_MigrateFromOldCrossPipelineSG = true; + + // Set data + systemData.surfaceType = (SurfaceType)pbrMasterNode.m_SurfaceType; + systemData.blendMode = HDSubShaderUtilities.UpgradeLegacyAlphaModeToBlendMode((int)pbrMasterNode.m_AlphaMode); + systemData.doubleSidedMode = pbrMasterNode.m_TwoSided ? DoubleSidedMode.Enabled : DoubleSidedMode.Disabled; + // Previous master node wasn't having any renderingPass. Assign it correctly now. + systemData.renderingPass = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; + systemData.alphaTest = HDSubShaderUtilities.UpgradeLegacyAlphaClip(pbrMasterNode); + systemData.dotsInstancing = false; + builtinData.addPrecomputedVelocity = false; + lightingData.blendPreserveSpecular = false; + lightingData.normalDropOffSpace = pbrMasterNode.m_NormalDropOffSpace; + lightingData.receiveDecals = false; + lightingData.receiveSSR = true; + lightingData.receiveSSRTransparent = false; + litData.materialType = pbrMasterNode.m_Model == PBRMasterNode1.Model.Specular ? HDLitData.MaterialType.SpecularColor : HDLitData.MaterialType.Standard; + litData.energyConservingSpecular = false; + litData.clearCoat = false; + target.customEditorGUI = pbrMasterNode.m_OverrideEnabled ? pbrMasterNode.m_ShaderGUIOverride : ""; + // Handle mapping of Normal block specifically + BlockFieldDescriptor normalBlock; + switch(lightingData.normalDropOffSpace) + { + case NormalDropOffSpace.Object: + normalBlock = BlockFields.SurfaceDescription.NormalOS; + break; + case NormalDropOffSpace.World: + normalBlock = BlockFields.SurfaceDescription.NormalWS; + break; + default: + normalBlock = BlockFields.SurfaceDescription.NormalTS; + break; + } + + // PBRMasterNode adds/removes Metallic/Specular based on settings + BlockFieldDescriptor specularMetallicBlock; + int specularMetallicId; + if(litData.materialType == HDLitData.MaterialType.SpecularColor) + { + specularMetallicBlock = BlockFields.SurfaceDescription.Specular; + specularMetallicId = 3; + } + else + { + specularMetallicBlock = BlockFields.SurfaceDescription.Metallic; + specularMetallicId = 2; + } + + // Set blockmap + blockMap = new Dictionary() + { + { BlockFields.VertexDescription.Position, 9 }, + { BlockFields.VertexDescription.Normal, 10 }, + { BlockFields.VertexDescription.Tangent, 11 }, + { BlockFields.SurfaceDescription.BaseColor, 0 }, + { normalBlock, 1 }, + { specularMetallicBlock, specularMetallicId }, + { BlockFields.SurfaceDescription.Emission, 4 }, + { BlockFields.SurfaceDescription.Smoothness, 5 }, + { BlockFields.SurfaceDescription.Occlusion, 6 }, + { BlockFields.SurfaceDescription.Alpha, 7 }, + { BlockFields.SurfaceDescription.AlphaClipThreshold, 8 }, + }; + } + + void UpgradeHDLitMasterNode(HDLitMasterNode1 hdLitMasterNode, out Dictionary blockMap) + { + // Set data + systemData.surfaceType = (SurfaceType)hdLitMasterNode.m_SurfaceType; + systemData.blendMode = HDSubShaderUtilities.UpgradeLegacyAlphaModeToBlendMode((int)hdLitMasterNode.m_AlphaMode); + systemData.renderingPass = hdLitMasterNode.m_RenderingPass; + // Patch rendering pass in case the master node had an old configuration + if (systemData.renderingPass == HDRenderQueue.RenderQueueType.Background) + systemData.renderingPass = HDRenderQueue.RenderQueueType.Opaque; + systemData.alphaTest = hdLitMasterNode.m_AlphaTest; + systemData.alphaTestDepthPrepass = hdLitMasterNode.m_AlphaTestDepthPrepass; + systemData.alphaTestDepthPostpass = hdLitMasterNode.m_AlphaTestDepthPostpass; + systemData.sortPriority = hdLitMasterNode.m_SortPriority; + systemData.doubleSidedMode = hdLitMasterNode.m_DoubleSidedMode; + systemData.zWrite = hdLitMasterNode.m_ZWrite; + systemData.transparentCullMode = hdLitMasterNode.m_transparentCullMode; + systemData.zTest = hdLitMasterNode.m_ZTest; + systemData.supportLodCrossFade = hdLitMasterNode.m_SupportLodCrossFade; + systemData.dotsInstancing = hdLitMasterNode.m_DOTSInstancing; + systemData.materialNeedsUpdateHash = hdLitMasterNode.m_MaterialNeedsUpdateHash; + + builtinData.transparencyFog = hdLitMasterNode.m_TransparencyFog; + builtinData.distortion = hdLitMasterNode.m_Distortion; + builtinData.distortionMode = hdLitMasterNode.m_DistortionMode; + builtinData.distortionDepthTest = hdLitMasterNode.m_DistortionDepthTest; + builtinData.transparentWritesMotionVec = hdLitMasterNode.m_TransparentWritesMotionVec; + builtinData.addPrecomputedVelocity = hdLitMasterNode.m_AddPrecomputedVelocity; + builtinData.depthOffset = hdLitMasterNode.m_depthOffset; + builtinData.alphaToMask = hdLitMasterNode.m_AlphaToMask; + + builtinData.alphaTestShadow = hdLitMasterNode.m_AlphaTestShadow; + builtinData.backThenFrontRendering = hdLitMasterNode.m_BackThenFrontRendering; + lightingData.normalDropOffSpace = hdLitMasterNode.m_NormalDropOffSpace; + lightingData.blendPreserveSpecular = hdLitMasterNode.m_BlendPreserveSpecular; + lightingData.receiveDecals = hdLitMasterNode.m_ReceiveDecals; + lightingData.receiveSSR = hdLitMasterNode.m_ReceivesSSR; + lightingData.receiveSSRTransparent = hdLitMasterNode.m_ReceivesSSRTransparent; + lightingData.specularAA = hdLitMasterNode.m_SpecularAA; + lightingData.specularOcclusionMode = hdLitMasterNode.m_SpecularOcclusionMode; + lightingData.overrideBakedGI = hdLitMasterNode.m_overrideBakedGI; + HDLitData.MaterialType materialType = (HDLitData.MaterialType)hdLitMasterNode.m_MaterialType; + lightingData.subsurfaceScattering = materialType == HDLitData.MaterialType.SubsurfaceScattering; + + litData.clearCoat = UpgradeCoatMask(hdLitMasterNode); + litData.energyConservingSpecular = hdLitMasterNode.m_EnergyConservingSpecular; + litData.rayTracing = hdLitMasterNode.m_RayTracing; + litData.refractionModel = hdLitMasterNode.m_RefractionModel; + litData.materialType = materialType; + litData.sssTransmission = hdLitMasterNode.m_SSSTransmission; + + target.customEditorGUI = hdLitMasterNode.m_OverrideEnabled ? hdLitMasterNode.m_ShaderGUIOverride : ""; + + // Handle mapping of Normal block specifically + BlockFieldDescriptor normalBlock; + switch(lightingData.normalDropOffSpace) + { + case NormalDropOffSpace.Object: + normalBlock = BlockFields.SurfaceDescription.NormalOS; + break; + case NormalDropOffSpace.World: + normalBlock = BlockFields.SurfaceDescription.NormalWS; + break; + default: + normalBlock = BlockFields.SurfaceDescription.NormalTS; + break; + } + + // Convert SlotMask to BlockMap entries + var blockMapLookup = new Dictionary() + { + { HDLitMasterNode1.SlotMask.Albedo, BlockFields.SurfaceDescription.BaseColor }, + { HDLitMasterNode1.SlotMask.Normal, normalBlock }, + { HDLitMasterNode1.SlotMask.BentNormal, HDBlockFields.SurfaceDescription.BentNormal }, + { HDLitMasterNode1.SlotMask.Tangent, HDBlockFields.SurfaceDescription.Tangent }, + { HDLitMasterNode1.SlotMask.Anisotropy, HDBlockFields.SurfaceDescription.Anisotropy }, + { HDLitMasterNode1.SlotMask.SubsurfaceMask, HDBlockFields.SurfaceDescription.SubsurfaceMask }, + { HDLitMasterNode1.SlotMask.Thickness, HDBlockFields.SurfaceDescription.Thickness }, + { HDLitMasterNode1.SlotMask.DiffusionProfile, HDBlockFields.SurfaceDescription.DiffusionProfileHash }, + { HDLitMasterNode1.SlotMask.IridescenceMask, HDBlockFields.SurfaceDescription.IridescenceMask }, + { HDLitMasterNode1.SlotMask.IridescenceLayerThickness, HDBlockFields.SurfaceDescription.IridescenceThickness }, + { HDLitMasterNode1.SlotMask.Specular, BlockFields.SurfaceDescription.Specular }, + { HDLitMasterNode1.SlotMask.CoatMask, HDBlockFields.SurfaceDescription.CoatMask }, + { HDLitMasterNode1.SlotMask.Metallic, BlockFields.SurfaceDescription.Metallic }, + { HDLitMasterNode1.SlotMask.Smoothness, BlockFields.SurfaceDescription.Smoothness }, + { HDLitMasterNode1.SlotMask.Occlusion, BlockFields.SurfaceDescription.Occlusion }, + { HDLitMasterNode1.SlotMask.SpecularOcclusion, HDBlockFields.SurfaceDescription.SpecularOcclusion }, + { HDLitMasterNode1.SlotMask.Emission, BlockFields.SurfaceDescription.Emission }, + { HDLitMasterNode1.SlotMask.Alpha, BlockFields.SurfaceDescription.Alpha }, + { HDLitMasterNode1.SlotMask.AlphaThreshold, BlockFields.SurfaceDescription.AlphaClipThreshold }, + { HDLitMasterNode1.SlotMask.AlphaThresholdDepthPrepass, HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass }, + { HDLitMasterNode1.SlotMask.AlphaThresholdDepthPostpass, HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass }, + { HDLitMasterNode1.SlotMask.AlphaThresholdShadow, HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow }, + }; + + // Legacy master node slots have additional slot conditions, test them here + bool AdditionalSlotMaskTests(HDLitMasterNode1.SlotMask slotMask) + { + switch(slotMask) + { + case HDLitMasterNode1.SlotMask.Thickness: + return litData.sssTransmission || litData.materialType == HDLitData.MaterialType.Translucent; + case HDLitMasterNode1.SlotMask.SpecularOcclusion: + return lightingData.specularOcclusionMode == SpecularOcclusionMode.Custom; + case HDLitMasterNode1.SlotMask.AlphaThreshold: + return systemData.alphaTest; + case HDLitMasterNode1.SlotMask.AlphaThresholdDepthPrepass: + return systemData.surfaceType == SurfaceType.Transparent && systemData.alphaTest && systemData.alphaTestDepthPrepass; + case HDLitMasterNode1.SlotMask.AlphaThresholdDepthPostpass: + return systemData.surfaceType == SurfaceType.Transparent && systemData.alphaTest && systemData.alphaTestDepthPostpass; + case HDLitMasterNode1.SlotMask.AlphaThresholdShadow: + return systemData.alphaTest && builtinData.alphaTestShadow; + default: + return true; + } + } + + bool UpgradeCoatMask(HDLitMasterNode1 masterNode) + { + var coatMaskSlotId = HDLitMasterNode1.CoatMaskSlotId; + + var node = masterNode as AbstractMaterialNode; + var coatMaskSlot = node.FindSlot(coatMaskSlotId); + if(coatMaskSlot == null) + return false; + + coatMaskSlot.owner = node; + return (coatMaskSlot.isConnected || coatMaskSlot.value > 0.0f); + } + + // Set blockmap + blockMap = new Dictionary(); + + // First handle vertex blocks. We ran out of SlotMask bits for VertexNormal and VertexTangent + // so do all Vertex blocks here to maintain correct block order (Position is not in blockMapLookup) + blockMap.Add(BlockFields.VertexDescription.Position, HDLitMasterNode1.PositionSlotId); + blockMap.Add(BlockFields.VertexDescription.Normal, HDLitMasterNode1.VertexNormalSlotID); + blockMap.Add(BlockFields.VertexDescription.Tangent, HDLitMasterNode1.VertexTangentSlotID); + + // Now handle the SlotMask cases + foreach(HDLitMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(HDLitMasterNode1.SlotMask))) + { + if(hdLitMasterNode.MaterialTypeUsesSlotMask(slotMask)) + { + if(!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) + continue; + + if(!AdditionalSlotMaskTests(slotMask)) + continue; + + var slotId = Mathf.Log((int)slotMask, 2); + blockMap.Add(blockFieldDescriptor, (int)slotId); + } + } + + // Specular AA + if(lightingData.specularAA) + { + blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, HDLitMasterNode1.SpecularAAScreenSpaceVarianceSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAThreshold, HDLitMasterNode1.SpecularAAThresholdSlotId); + } + + // Refraction + bool hasRefraction = (systemData.surfaceType == SurfaceType.Transparent && systemData.renderingPass != HDRenderQueue.RenderQueueType.PreRefraction && litData.refractionModel != ScreenSpaceRefraction.RefractionModel.None); + if(hasRefraction) + { + if(!blockMap.TryGetValue(HDBlockFields.SurfaceDescription.Thickness, out _)) + { + blockMap.Add(HDBlockFields.SurfaceDescription.Thickness, HDLitMasterNode1.ThicknessSlotId); + } + + blockMap.Add(HDBlockFields.SurfaceDescription.RefractionIndex, HDLitMasterNode1.RefractionIndexSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.RefractionColor, HDLitMasterNode1.RefractionColorSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.RefractionDistance, HDLitMasterNode1.RefractionDistanceSlotId); + } + + // Distortion + bool hasDistortion = (systemData.surfaceType == SurfaceType.Transparent && builtinData.distortion); + if(hasDistortion) + { + blockMap.Add(HDBlockFields.SurfaceDescription.Distortion, HDLitMasterNode1.DistortionSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.DistortionBlur, HDLitMasterNode1.DistortionBlurSlotId); + } + + // Override Baked GI + if(lightingData.overrideBakedGI) + { + blockMap.Add(HDBlockFields.SurfaceDescription.BakedGI, HDLitMasterNode1.LightingSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.BakedBackGI, HDLitMasterNode1.BackLightingSlotId); + } + + // Depth Offset (Removed from SlotMask because of missing bits) + if(builtinData.depthOffset) + { + blockMap.Add(HDBlockFields.SurfaceDescription.DepthOffset, HDLitMasterNode1.DepthOffsetSlotId); + } + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.Migration.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.Migration.cs.meta new file mode 100644 index 00000000000..075b8762b92 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.Migration.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0bb123874ee52c147a73bc9d779f600e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.cs index d2a7a3dc640..73f56d47de8 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.cs @@ -1,24 +1,154 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; using UnityEngine.Rendering.HighDefinition; using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { - sealed class HDLitSubTarget : SubTarget + sealed partial class HDLitSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData { - const string kAssetGuid = "caab952c840878340810cca27417971c"; static string passTemplatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/Lit/ShaderGraph/LitPass.template"; - public HDLitSubTarget() + public HDLitSubTarget() => displayName = "Lit"; + + protected override string customInspector => "Rendering.HighDefinition.HDLitGUI"; + protected override string subTargetAssetGuid => "caab952c840878340810cca27417971c"; // HDLitSubTarget.cs + protected override ShaderID shaderID => HDShaderUtils.ShaderID.SG_Lit; + + HDLitData m_LitData; + + HDLitData IRequiresData.data + { + get => m_LitData; + set => m_LitData = value; + } + + public HDLitData litData + { + get => m_LitData; + set => m_LitData = value; + } + + // Iterate over the sub passes available in the shader + protected override IEnumerable EnumerateSubShaders() + { + yield return SubShaders.Lit; + yield return SubShaders.LitRaytracing; + } + + public override void GetFields(ref TargetFieldContext context) { - displayName = "Lit"; + base.GetFields(ref context); + AddDistortionFields(ref context); + var descs = context.blocks.Select(x => x.descriptor); + + bool hasRefraction = (systemData.surfaceType == SurfaceType.Transparent && systemData.renderingPass != HDRenderQueue.RenderQueueType.PreRefraction && litData.refractionModel != ScreenSpaceRefraction.RefractionModel.None); + + // Lit specific properties + context.AddField(HDStructFields.FragInputs.IsFrontFace, systemData.doubleSidedMode != DoubleSidedMode.Disabled && !context.pass.Equals(HDLitSubTarget.LitPasses.MotionVectors)); + + context.AddField(HDFields.DotsProperties, context.hasDotsProperties); + + // Material + context.AddField(HDFields.Anisotropy, litData.materialType == HDLitData.MaterialType.Anisotropy); + context.AddField(HDFields.Iridescence, litData.materialType == HDLitData.MaterialType.Iridescence); + context.AddField(HDFields.SpecularColor, litData.materialType == HDLitData.MaterialType.SpecularColor); + context.AddField(HDFields.Standard, litData.materialType == HDLitData.MaterialType.Standard); + context.AddField(HDFields.SubsurfaceScattering, litData.materialType == HDLitData.MaterialType.SubsurfaceScattering && systemData.surfaceType != SurfaceType.Transparent); + context.AddField(HDFields.Transmission, (litData.materialType == HDLitData.MaterialType.SubsurfaceScattering && litData.sssTransmission) || + (litData.materialType == HDLitData.MaterialType.Translucent)); + context.AddField(HDFields.Translucent, litData.materialType == HDLitData.MaterialType.Translucent); + + context.AddField(HDFields.DoubleSidedFlip, systemData.doubleSidedMode == DoubleSidedMode.FlippedNormals && !context.pass.Equals(HDLitSubTarget.LitPasses.MotionVectors)); + context.AddField(HDFields.DoubleSidedMirror, systemData.doubleSidedMode == DoubleSidedMode.MirroredNormals && !context.pass.Equals(HDLitSubTarget.LitPasses.MotionVectors)); + + // Refraction + context.AddField(HDFields.Refraction, hasRefraction); + context.AddField(HDFields.RefractionBox, hasRefraction && litData.refractionModel == ScreenSpaceRefraction.RefractionModel.Box); + context.AddField(HDFields.RefractionSphere, hasRefraction && litData.refractionModel == ScreenSpaceRefraction.RefractionModel.Sphere); + context.AddField(HDFields.RefractionThin, hasRefraction && litData.refractionModel == ScreenSpaceRefraction.RefractionModel.Thin); + + // AlphaTest + // All the DoAlphaXXX field drive the generation of which code to use for alpha test in the template + // Do alpha test only if we aren't using the TestShadow one + context.AddField(HDFields.DoAlphaTest, systemData.alphaTest && (context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.AlphaClipThreshold) && + !(builtinData.alphaTestShadow && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow)))); + + // Misc + + context.AddField(HDFields.EnergyConservingSpecular, litData.energyConservingSpecular); + context.AddField(HDFields.CoatMask, descs.Contains(HDBlockFields.SurfaceDescription.CoatMask) && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.CoatMask) && litData.clearCoat); + context.AddField(HDFields.ClearCoat, litData.clearCoat); // Enable clear coat material feature + context.AddField(HDFields.Tangent, descs.Contains(HDBlockFields.SurfaceDescription.Tangent) && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.Tangent)); + context.AddField(HDFields.RayTracing, litData.rayTracing); } - public override void Setup(ref TargetSetupContext context) + public override void GetActiveBlocks(ref TargetActiveBlockContext context) { - context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); - context.SetDefaultShaderGUI("Rendering.HighDefinition.HDLitGUI"); - context.AddSubShader(SubShaders.Lit); - context.AddSubShader(SubShaders.LitRaytracing); + bool hasRefraction = (systemData.surfaceType == SurfaceType.Transparent && systemData.renderingPass != HDRenderQueue.RenderQueueType.PreRefraction && litData.refractionModel != ScreenSpaceRefraction.RefractionModel.None); + bool hasDistortion = (systemData.surfaceType == SurfaceType.Transparent && builtinData.distortion); + + // Vertex + base.GetActiveBlocks(ref context); + AddDistortionBlocks(ref context); + + // Common + context.AddBlock(HDBlockFields.SurfaceDescription.CoatMask, litData.clearCoat); + + // Refraction + context.AddBlock(HDBlockFields.SurfaceDescription.RefractionIndex, hasRefraction); + context.AddBlock(HDBlockFields.SurfaceDescription.RefractionColor, hasRefraction); + context.AddBlock(HDBlockFields.SurfaceDescription.RefractionDistance, hasRefraction); + + // Material + context.AddBlock(HDBlockFields.SurfaceDescription.Tangent, litData.materialType == HDLitData.MaterialType.Anisotropy); + context.AddBlock(HDBlockFields.SurfaceDescription.Anisotropy, litData.materialType == HDLitData.MaterialType.Anisotropy); + context.AddBlock(HDBlockFields.SurfaceDescription.SubsurfaceMask, litData.materialType == HDLitData.MaterialType.SubsurfaceScattering); + context.AddBlock(HDBlockFields.SurfaceDescription.Thickness, ((litData.materialType == HDLitData.MaterialType.SubsurfaceScattering || litData.materialType == HDLitData.MaterialType.Translucent) && + (litData.sssTransmission || litData.materialType == HDLitData.MaterialType.Translucent)) || hasRefraction); + context.AddBlock(HDBlockFields.SurfaceDescription.DiffusionProfileHash, litData.materialType == HDLitData.MaterialType.SubsurfaceScattering || litData.materialType == HDLitData.MaterialType.Translucent); + context.AddBlock(HDBlockFields.SurfaceDescription.IridescenceMask, litData.materialType == HDLitData.MaterialType.Iridescence); + context.AddBlock(HDBlockFields.SurfaceDescription.IridescenceThickness, litData.materialType == HDLitData.MaterialType.Iridescence); + context.AddBlock(BlockFields.SurfaceDescription.Specular, litData.materialType == HDLitData.MaterialType.SpecularColor); + context.AddBlock(BlockFields.SurfaceDescription.Metallic, litData.materialType == HDLitData.MaterialType.Standard || + litData.materialType == HDLitData.MaterialType.Anisotropy || + litData.materialType == HDLitData.MaterialType.Iridescence); + } + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) + { + base.CollectShaderProperties(collector, generationMode); + + HDSubShaderUtilities.AddRayTracingProperty(collector, litData.rayTracing); + } + + protected override void AddInspectorPropertyBlocks(SubTargetPropertiesGUI blockList) + { + blockList.AddPropertyBlock(new LitSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features.Lit, litData)); + if (systemData.surfaceType == SurfaceType.Transparent) + blockList.AddPropertyBlock(new DistortionPropertyBlock()); + blockList.AddPropertyBlock(new AdvancedOptionsPropertyBlock()); + } + + protected override int ComputeMaterialNeedsUpdateHash() + { + int hash = base.ComputeMaterialNeedsUpdateHash(); + + unchecked + { + bool subsurfaceScattering = litData.materialType == HDLitData.MaterialType.SubsurfaceScattering; + hash = hash * 23 + subsurfaceScattering.GetHashCode(); + } + + return hash; } #region SubShaders @@ -86,8 +216,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDefault, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -115,7 +245,7 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - pixelPorts = LitPortMasks.FragmentMeta, + validPixelBlocks = LitBlockMasks.FragmentMeta, // Collections structs = CoreStructCollections.Default, @@ -141,8 +271,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentShadowCaster, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentShadowCaster, // Collections structs = CoreStructCollections.Default, @@ -167,8 +297,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentSceneSelection, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentSceneSelection, // Collections structs = CoreStructCollections.Default, @@ -193,8 +323,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDepthMotionVectors, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDepthMotionVectors, // Collections structs = CoreStructCollections.Default, @@ -220,8 +350,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDepthMotionVectors, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDepthMotionVectors, // Collections structs = CoreStructCollections.Default, @@ -247,8 +377,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDistortion, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDistortion, // Collections structs = CoreStructCollections.Default, @@ -273,14 +403,14 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentTransparentDepthPrepass, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentTransparentDepthPrepass, // Collections structs = CoreStructCollections.Default, requiredFields = CoreRequiredFields.LitFull, fieldDependencies = CoreFieldDependencies.Default, - renderStates = LitRenderStates.TransparentDepthPrePostPass, + renderStates = CoreRenderStates.TransparentDepthPrePass, pragmas = CorePragmas.DotsInstancedInV1AndV2, defines = CoreDefines.TransparentDepthPrepass, keywords = CoreKeywords.HDBase, @@ -300,8 +430,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentTransparentBackface, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentTransparentBackface, // Collections structs = CoreStructCollections.Default, @@ -326,8 +456,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDefault, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -355,13 +485,13 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentTransparentDepthPostpass, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentTransparentDepthPostpass, // Collections structs = CoreStructCollections.Default, fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.TransparentDepthPrePostPass, + renderStates = CoreRenderStates.TransparentDepthPostPass, pragmas = CorePragmas.DotsInstancedInV1AndV2, defines = CoreDefines.ShaderGraphRaytracingHigh, keywords = CoreKeywords.HDBase, @@ -381,8 +511,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentRayTracingPrepass, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentRayTracingPrepass, // Collections structs = CoreStructCollections.Default, @@ -407,8 +537,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDefault, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -433,8 +563,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDefault, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -459,8 +589,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDefault, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -485,8 +615,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, // Port Mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDefault, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -511,8 +641,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, //Port mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDefault, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDefault, //Collections structs = CoreStructCollections.Default, @@ -537,8 +667,8 @@ public static class LitPasses sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, //Port mask - vertexPorts = LitPortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentDefault, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentDefault, //Collections structs = CoreStructCollections.Default, @@ -552,157 +682,160 @@ public static class LitPasses } #endregion -#region PortMasks - static class LitPortMasks +#region BlockMasks + static class LitBlockMasks { - public static int[] Vertex = new int[] - { - HDLitMasterNode.PositionSlotId, - HDLitMasterNode.VertexNormalSlotID, - HDLitMasterNode.VertexTangentSlotID, - }; - - public static int[] FragmentDefault = new int[] - { - HDLitMasterNode.AlbedoSlotId, - HDLitMasterNode.NormalSlotId, - HDLitMasterNode.BentNormalSlotId, - HDLitMasterNode.TangentSlotId, - HDLitMasterNode.SubsurfaceMaskSlotId, - HDLitMasterNode.ThicknessSlotId, - HDLitMasterNode.DiffusionProfileHashSlotId, - HDLitMasterNode.IridescenceMaskSlotId, - HDLitMasterNode.IridescenceThicknessSlotId, - HDLitMasterNode.SpecularColorSlotId, - HDLitMasterNode.CoatMaskSlotId, - HDLitMasterNode.MetallicSlotId, - HDLitMasterNode.EmissionSlotId, - HDLitMasterNode.SmoothnessSlotId, - HDLitMasterNode.AmbientOcclusionSlotId, - HDLitMasterNode.SpecularOcclusionSlotId, - HDLitMasterNode.AlphaSlotId, - HDLitMasterNode.AlphaThresholdSlotId, - HDLitMasterNode.AnisotropySlotId, - HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId, - HDLitMasterNode.SpecularAAThresholdSlotId, - HDLitMasterNode.RefractionIndexSlotId, - HDLitMasterNode.RefractionColorSlotId, - HDLitMasterNode.RefractionDistanceSlotId, - HDLitMasterNode.LightingSlotId, - HDLitMasterNode.BackLightingSlotId, - HDLitMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentMeta = new int[] - { - HDLitMasterNode.AlbedoSlotId, - HDLitMasterNode.NormalSlotId, - HDLitMasterNode.BentNormalSlotId, - HDLitMasterNode.TangentSlotId, - HDLitMasterNode.SubsurfaceMaskSlotId, - HDLitMasterNode.ThicknessSlotId, - HDLitMasterNode.DiffusionProfileHashSlotId, - HDLitMasterNode.IridescenceMaskSlotId, - HDLitMasterNode.IridescenceThicknessSlotId, - HDLitMasterNode.SpecularColorSlotId, - HDLitMasterNode.CoatMaskSlotId, - HDLitMasterNode.MetallicSlotId, - HDLitMasterNode.EmissionSlotId, - HDLitMasterNode.SmoothnessSlotId, - HDLitMasterNode.AmbientOcclusionSlotId, - HDLitMasterNode.SpecularOcclusionSlotId, - HDLitMasterNode.AlphaSlotId, - HDLitMasterNode.AlphaThresholdSlotId, - HDLitMasterNode.AnisotropySlotId, - HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId, - HDLitMasterNode.SpecularAAThresholdSlotId, - HDLitMasterNode.RefractionIndexSlotId, - HDLitMasterNode.RefractionColorSlotId, - HDLitMasterNode.RefractionDistanceSlotId, - }; - - public static int[] FragmentShadowCaster = new int[] - { - HDLitMasterNode.AlphaSlotId, - HDLitMasterNode.AlphaThresholdSlotId, - HDLitMasterNode.AlphaThresholdShadowSlotId, - HDLitMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentSceneSelection = new int[] - { - HDLitMasterNode.AlphaSlotId, - HDLitMasterNode.AlphaThresholdSlotId, - HDLitMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentDepthMotionVectors = new int[] - { - HDLitMasterNode.NormalSlotId, - HDLitMasterNode.SmoothnessSlotId, - HDLitMasterNode.AlphaSlotId, - HDLitMasterNode.AlphaThresholdSlotId, - HDLitMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentDistortion = new int[] - { - HDLitMasterNode.AlphaSlotId, - HDLitMasterNode.AlphaThresholdSlotId, - HDLitMasterNode.DistortionSlotId, - HDLitMasterNode.DistortionBlurSlotId, - }; - - public static int[] FragmentTransparentDepthPrepass = new int[] - { - HDLitMasterNode.AlphaSlotId, - HDLitMasterNode.AlphaThresholdDepthPrepassSlotId, - HDLitMasterNode.DepthOffsetSlotId, - HDLitMasterNode.NormalSlotId, - HDLitMasterNode.SmoothnessSlotId, - }; - - public static int[] FragmentTransparentBackface = new int[] - { - HDLitMasterNode.AlbedoSlotId, - HDLitMasterNode.NormalSlotId, - HDLitMasterNode.BentNormalSlotId, - HDLitMasterNode.TangentSlotId, - HDLitMasterNode.SubsurfaceMaskSlotId, - HDLitMasterNode.ThicknessSlotId, - HDLitMasterNode.DiffusionProfileHashSlotId, - HDLitMasterNode.IridescenceMaskSlotId, - HDLitMasterNode.IridescenceThicknessSlotId, - HDLitMasterNode.SpecularColorSlotId, - HDLitMasterNode.CoatMaskSlotId, - HDLitMasterNode.MetallicSlotId, - HDLitMasterNode.EmissionSlotId, - HDLitMasterNode.SmoothnessSlotId, - HDLitMasterNode.AmbientOcclusionSlotId, - HDLitMasterNode.SpecularOcclusionSlotId, - HDLitMasterNode.AlphaSlotId, - HDLitMasterNode.AlphaThresholdSlotId, - HDLitMasterNode.AnisotropySlotId, - HDLitMasterNode.SpecularAAScreenSpaceVarianceSlotId, - HDLitMasterNode.SpecularAAThresholdSlotId, - HDLitMasterNode.RefractionIndexSlotId, - HDLitMasterNode.RefractionColorSlotId, - HDLitMasterNode.RefractionDistanceSlotId, - HDLitMasterNode.DepthOffsetSlotId, + public static BlockFieldDescriptor[] FragmentDefault = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.Tangent, + HDBlockFields.SurfaceDescription.SubsurfaceMask, + HDBlockFields.SurfaceDescription.Thickness, + HDBlockFields.SurfaceDescription.DiffusionProfileHash, + HDBlockFields.SurfaceDescription.IridescenceMask, + HDBlockFields.SurfaceDescription.IridescenceThickness, + BlockFields.SurfaceDescription.Specular, + HDBlockFields.SurfaceDescription.CoatMask, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.Anisotropy, + HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, + HDBlockFields.SurfaceDescription.SpecularAAThreshold, + HDBlockFields.SurfaceDescription.RefractionIndex, + HDBlockFields.SurfaceDescription.RefractionColor, + HDBlockFields.SurfaceDescription.RefractionDistance, + HDBlockFields.SurfaceDescription.BakedGI, + HDBlockFields.SurfaceDescription.BakedBackGI, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentMeta = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.Tangent, + HDBlockFields.SurfaceDescription.SubsurfaceMask, + HDBlockFields.SurfaceDescription.Thickness, + HDBlockFields.SurfaceDescription.DiffusionProfileHash, + HDBlockFields.SurfaceDescription.IridescenceMask, + HDBlockFields.SurfaceDescription.IridescenceThickness, + BlockFields.SurfaceDescription.Specular, + HDBlockFields.SurfaceDescription.CoatMask, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.Anisotropy, + HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, + HDBlockFields.SurfaceDescription.SpecularAAThreshold, + HDBlockFields.SurfaceDescription.RefractionIndex, + HDBlockFields.SurfaceDescription.RefractionColor, + HDBlockFields.SurfaceDescription.RefractionDistance, + }; + + public static BlockFieldDescriptor[] FragmentShadowCaster = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentSceneSelection = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentDepthMotionVectors = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentDistortion = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.Distortion, + HDBlockFields.SurfaceDescription.DistortionBlur, + }; + + public static BlockFieldDescriptor[] FragmentTransparentDepthPrepass = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass, + HDBlockFields.SurfaceDescription.DepthOffset, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.Smoothness, }; - public static int[] FragmentTransparentDepthPostpass = new int[] - { - HDLitMasterNode.AlphaSlotId, - HDLitMasterNode.AlphaThresholdDepthPostpassSlotId, - HDLitMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentRayTracingPrepass = new int[] - { - HDLitMasterNode.AlphaSlotId, - HDLitMasterNode.AlphaThresholdSlotId, - HDLitMasterNode.DepthOffsetSlotId, + public static BlockFieldDescriptor[] FragmentTransparentBackface = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.Tangent, + HDBlockFields.SurfaceDescription.SubsurfaceMask, + HDBlockFields.SurfaceDescription.Thickness, + HDBlockFields.SurfaceDescription.DiffusionProfileHash, + HDBlockFields.SurfaceDescription.IridescenceMask, + HDBlockFields.SurfaceDescription.IridescenceThickness, + BlockFields.SurfaceDescription.Specular, + HDBlockFields.SurfaceDescription.CoatMask, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.Anisotropy, + HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, + HDBlockFields.SurfaceDescription.SpecularAAThreshold, + HDBlockFields.SurfaceDescription.RefractionIndex, + HDBlockFields.SurfaceDescription.RefractionColor, + HDBlockFields.SurfaceDescription.RefractionDistance, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentTransparentDepthPostpass = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentRayTracingPrepass = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, }; } #endregion @@ -741,20 +874,6 @@ static class LitRenderStates }) }, }; - public static RenderStateCollection TransparentDepthPrePostPass = new RenderStateCollection - { - { RenderState.Blend(Blend.One, Blend.Zero) }, - { RenderState.Cull(CoreRenderStates.Uniforms.cullMode) }, - { RenderState.ZWrite(ZWrite.On) }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = CoreRenderStates.Uniforms.stencilWriteMaskDepth, - Ref = CoreRenderStates.Uniforms.stencilRefDepth, - Comp = "Always", - Pass = "Replace", - }) }, - }; - public static RenderStateCollection RayTracingPrepass = new RenderStateCollection { { RenderState.Blend(Blend.One, Blend.Zero) }, diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitPass.template b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitPass.template index a5141f236fc..fd69ae98c17 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitPass.template +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitPass.template @@ -30,6 +30,7 @@ Pass $Material.Anisotropy: #define _MATERIAL_FEATURE_ANISOTROPY 1 $Material.Iridescence: #define _MATERIAL_FEATURE_IRIDESCENCE 1 $Material.SpecularColor: #define _MATERIAL_FEATURE_SPECULAR_COLOR 1 + $Material.ClearCoat: #define _MATERIAL_FEATURE_CLEAR_COAT $AmbientOcclusion: #define _AMBIENT_OCCLUSION 1 $SpecularOcclusionFromAO: #define _SPECULAR_OCCLUSION_FROM_AO 1 $SpecularOcclusionFromAOBentNormal: #define _SPECULAR_OCCLUSION_FROM_AO_BENT_NORMAL 1 @@ -146,7 +147,7 @@ Pass // however specularOcclusion can come from the graph, so need to be init here so it can be override. surfaceData.specularOcclusion = 1.0; - $SurfaceDescription.Albedo: surfaceData.baseColor = surfaceDescription.Albedo; + $SurfaceDescription.BaseColor: surfaceData.baseColor = surfaceDescription.BaseColor; $SurfaceDescription.Smoothness: surfaceData.perceptualSmoothness = surfaceDescription.Smoothness; $SurfaceDescription.Occlusion: surfaceData.ambientOcclusion = surfaceDescription.Occlusion; $SurfaceDescription.SpecularOcclusion: surfaceData.specularOcclusion = surfaceDescription.SpecularOcclusion; @@ -207,7 +208,9 @@ Pass surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR; #endif - $CoatMask: surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_LIT_CLEAR_COAT; + #ifdef _MATERIAL_FEATURE_CLEAR_COAT + surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_LIT_CLEAR_COAT; + #endif #if defined (_MATERIAL_FEATURE_SPECULAR_COLOR) && defined (_ENERGY_CONSERVING_SPECULAR) // Require to have setup baseColor @@ -223,7 +226,9 @@ Pass // normal delivered to master node float3 normalSrc = float3(0.0f, 0.0f, 1.0f); - $SurfaceDescription.Normal: normalSrc = surfaceDescription.Normal; + $SurfaceDescription.NormalOS: normalSrc = surfaceDescription.NormalOS; + $SurfaceDescription.NormalTS: normalSrc = surfaceDescription.NormalTS; + $SurfaceDescription.NormalWS: normalSrc = surfaceDescription.NormalWS; // compute world space normal #if _NORMAL_DROPOFF_TS @@ -242,8 +247,11 @@ Pass #if HAVE_DECALS if (_EnableDecals) { + float alpha = 1.0; + $SurfaceDescription.Alpha: alpha = surfaceDescription.Alpha; + // Both uses and modifies 'surfaceData.normalWS'. - DecalSurfaceData decalSurfaceData = GetDecalSurfaceData(posInput, surfaceDescription.Alpha); + DecalSurfaceData decalSurfaceData = GetDecalSurfaceData(posInput, alpha); ApplyDecalToSurfaceData(decalSurfaceData, surfaceData); } #endif diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitPropertyBlock.cs new file mode 100644 index 00000000000..8267f78039f --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitPropertyBlock.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.DistortionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class LitPropertyBlock : SubTargetPropertyBlock + { + protected override string title => "Lit Properties"; + protected override int foldoutIndex => 2; + + HDLitData litData; + + public LitPropertyBlock(HDLitData litData) + { + this.litData = litData; + } + + protected override void CreatePropertyGUI() + { + + } + } +} \ No newline at end of file diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitPropertyBlock.cs.meta new file mode 100644 index 00000000000..08db573feab --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c3d42a05c18dfbd47af8937648d6ec0d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitSurfaceOptionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitSurfaceOptionPropertyBlock.cs new file mode 100644 index 00000000000..02a5bee5051 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitSurfaceOptionPropertyBlock.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.SurfaceOptionUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.LitSurfaceInputsUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.RefractionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class LitSurfaceOptionPropertyBlock : SurfaceOptionPropertyBlock + { + HDLitData litData; + + class Styles + { + public static GUIContent enableClearCoat = new GUIContent("Clear Coat", "Enable Clear Coat"); + } + + public LitSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features features, HDLitData litData) : base(features) + => this.litData = litData; + + protected override void CreatePropertyGUI() + { + // Lit specific properties: + AddProperty(materialIDText, () => litData.materialType, (newValue) => + { + // Sync duplicated data in GUI + lightingData.subsurfaceScattering = litData.materialType == HDLitData.MaterialType.SubsurfaceScattering; + litData.materialType = newValue; + }); + AddProperty(rayTracingText, () => litData.rayTracing, (newValue) => litData.rayTracing = newValue); + + base.CreatePropertyGUI(); + + AddProperty(Styles.enableClearCoat, () => litData.clearCoat, (newValue) => litData.clearCoat = newValue); + AddProperty(transmissionEnableText, () => litData.sssTransmission, (newValue) => litData.sssTransmission = newValue); + AddProperty(refractionModelText, () => litData.refractionModel, (newValue) => litData.refractionModel = newValue); + AddProperty(energyConservingSpecularColorText, () => litData.energyConservingSpecular, (newValue) => litData.energyConservingSpecular = newValue); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitSurfaceOptionPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitSurfaceOptionPropertyBlock.cs.meta new file mode 100644 index 00000000000..232804fb6ad --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitSurfaceOptionPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 660abe0253750824dbda6e78a07ce510 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/HDPBRLit.cs b/com.unity.render-pipelines.high-definition/Editor/Material/PBR/HDPBRLit.cs deleted file mode 100644 index 5ebe1d51237..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/HDPBRLit.cs +++ /dev/null @@ -1,46 +0,0 @@ -using UnityEngine; -using UnityEngine.Rendering.HighDefinition; - -namespace UnityEditor.Rendering.HighDefinition -{ - class HDPBRLitGUI : ShaderGUI - { - public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) - { - materialEditor.PropertiesDefaultGUI(props); - - EmissionUIBlock.BakedEmissionEnabledProperty(materialEditor); - - // Make sure all selected materials are initialized. - string materialTag = "MotionVector"; - foreach (var obj in materialEditor.targets) - { - var material = (Material)obj; - string tag = material.GetTag(materialTag, false, "Nothing"); - if (tag == "Nothing") - { - material.SetShaderPassEnabled(HDShaderPassNames.s_MotionVectorsStr, false); - material.SetOverrideTag(materialTag, "User"); - } - } - - { - // If using multi-select, apply toggled material to all materials. - bool enabled = ((Material)materialEditor.target).GetShaderPassEnabled(HDShaderPassNames.s_MotionVectorsStr); - EditorGUI.BeginChangeCheck(); - enabled = EditorGUILayout.Toggle("Motion Vector For Vertex Animation", enabled); - if (EditorGUI.EndChangeCheck()) - { - foreach (var obj in materialEditor.targets) - { - var material = (Material)obj; - material.SetShaderPassEnabled(HDShaderPassNames.s_MotionVectorsStr, enabled); - } - } - } - - if (DiffusionProfileMaterialUI.IsSupported(materialEditor)) - DiffusionProfileMaterialUI.OnGUI(materialEditor, FindProperty("_DiffusionProfileAsset", props), FindProperty("_DiffusionProfileHash", props), 0); - } - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/HDPBRLit.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/PBR/HDPBRLit.cs.meta deleted file mode 100644 index 1881409fdc7..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/HDPBRLit.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bb22e3c1445c1a149a6f25193878c264 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRPass.template b/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRPass.template deleted file mode 100644 index d7d8c934ce7..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRPass.template +++ /dev/null @@ -1,218 +0,0 @@ -Pass -{ - $splice(PassName) - Tags - { - $splice(LightMode) - } - - // Render State - $splice(RenderState) - - // Debug - $splice(Debug) - - // -------------------------------------------------- - // Pass - - HLSLPROGRAM - - // Pragmas - $splice(PassPragmas) - - // Keywords - $splice(PassKeywords) - $splice(GraphKeywords) - - // Defines - $SpecularSetup: #define _MATERIAL_FEATURE_SPECULAR_COLOR 1 - $SurfaceType.Transparent: #define _SURFACE_TYPE_TRANSPARENT 1 - $BlendMode.Alpha: #define _BLENDMODE_ALPHA 1 - $BlendMode.Add: #define _BLENDMODE_ADD 1 - $BlendMode.Premultiply: #define _BLENDMODE_PRE_MULTIPLY 1 - $DoubleSided: #define _DOUBLESIDED_ON 1 - $DoubleSided: #define VARYINGS_NEED_CULLFACE - $NormalDropOffTS: #define _NORMAL_DROPOFF_TS 1 - $NormalDropOffOS: #define _NORMAL_DROPOFF_OS 1 - $NormalDropOffWS: #define _NORMAL_DROPOFF_WS 1 - $AttributesMesh.normalOS: #define ATTRIBUTES_NEED_NORMAL - $AttributesMesh.tangentOS: #define ATTRIBUTES_NEED_TANGENT - $AttributesMesh.uv0: #define ATTRIBUTES_NEED_TEXCOORD0 - $AttributesMesh.uv1: #define ATTRIBUTES_NEED_TEXCOORD1 - $AttributesMesh.uv2: #define ATTRIBUTES_NEED_TEXCOORD2 - $AttributesMesh.uv3: #define ATTRIBUTES_NEED_TEXCOORD3 - $AttributesMesh.color: #define ATTRIBUTES_NEED_COLOR - $VaryingsMeshToPS.positionRWS: #define VARYINGS_NEED_POSITION_WS - $VaryingsMeshToPS.normalWS: #define VARYINGS_NEED_TANGENT_TO_WORLD - $VaryingsMeshToPS.texCoord0: #define VARYINGS_NEED_TEXCOORD0 - $VaryingsMeshToPS.texCoord1: #define VARYINGS_NEED_TEXCOORD1 - $VaryingsMeshToPS.texCoord2: #define VARYINGS_NEED_TEXCOORD2 - $VaryingsMeshToPS.texCoord3: #define VARYINGS_NEED_TEXCOORD3 - $VaryingsMeshToPS.color: #define VARYINGS_NEED_COLOR - $VaryingsMeshToPS.cullFace: #define VARYINGS_NEED_CULLFACE - $features.graphVertex: #define HAVE_MESH_MODIFICATION - $splice(GraphDefines) - - #ifndef DEBUG_DISPLAY - // In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI) - // Don't do it with debug display mode as it is possible there is no depth prepass in this case - #if !defined(_SURFACE_TYPE_TRANSPARENT) && defined(_ALPHATEST) - #if SHADERPASS == SHADERPASS_FORWARD - #define SHADERPASS_FORWARD_BYPASS_ALPHA_TEST - #elif SHADERPASS == SHADERPASS_GBUFFER - #define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST - #endif - #endif - #endif - - $splice(HybridV1InjectedBuiltinProperties) - - // Includes - $splice(PreGraphIncludes) - - // Used by SceneSelectionPass - int _ObjectId; - int _PassValue; - - // -------------------------------------------------- - // Structs and Packing - - $splice(PassStructs) - - $splice(InterpolatorPack) - - - // -------------------------------------------------- - // Graph - - // Graph Properties - $splice(GraphProperties) - - // Graph Functions - $splice(GraphFunctions) - - // Graph Vertex - $splice(GraphVertex) - - // Graph Pixel - $splice(GraphPixel) - - // -------------------------------------------------- - // Build Graph Inputs - - $features.graphVertex: $include("VertexAnimation.template.hlsl") - $features.graphPixel: $include("SharedCode.template.hlsl") - - // -------------------------------------------------- - // Build Surface Data - - void BuildSurfaceData(FragInputs fragInputs, inout SurfaceDescription surfaceDescription, float3 V, PositionInputs posInput, out SurfaceData surfaceData) - { - ZERO_INITIALIZE(SurfaceData, surfaceData); - - surfaceData.ambientOcclusion = 1.0; - surfaceData.specularOcclusion = 1.0; // This need to be init here to quiet the compiler in case of decal, but can be override later. - - $SurfaceDescription.Albedo: surfaceData.baseColor = surfaceDescription.Albedo; - $SurfaceDescription.Smoothness: surfaceData.perceptualSmoothness = surfaceDescription.Smoothness; - $SurfaceDescription.Occlusion: surfaceData.ambientOcclusion = surfaceDescription.Occlusion; - $SurfaceDescription.Metallic: surfaceData.metallic = surfaceDescription.Metallic; - $SurfaceDescription.Specular: surfaceData.specularColor = surfaceDescription.Specular; - - // These static material feature allow compile time optimization - surfaceData.materialFeatures = MATERIALFEATUREFLAGS_LIT_STANDARD; - - #ifdef _MATERIAL_FEATURE_SPECULAR_COLOR - surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR; - #endif - - float3 doubleSidedConstants = float3(1.0, 1.0, 1.0); - $DoubleSided.Flip: doubleSidedConstants = float3(-1.0, -1.0, -1.0); - $DoubleSided.Mirror: doubleSidedConstants = float3( 1.0, 1.0, -1.0); - - // normal delivered to master node - float3 normalSrc = float3(0.0f, 0.0f, 1.0f); - $SurfaceDescription.Normal: normalSrc = surfaceDescription.Normal; - - // compute world space normal - #if _NORMAL_DROPOFF_TS - GetNormalWS(fragInputs, normalSrc, surfaceData.normalWS, doubleSidedConstants); - #elif _NORMAL_DROPOFF_OS - surfaceData.normalWS = TransformObjectToWorldNormal(normalSrc); - #elif _NORMAL_DROPOFF_WS - surfaceData.normalWS = normalSrc; - #endif - - surfaceData.geomNormalWS = fragInputs.tangentToWorld[2]; - surfaceData.tangentWS = normalize(fragInputs.tangentToWorld[0].xyz); // The tangent is not normalize in tangentToWorld for mikkt. TODO: Check if it expected that we normalize with Morten. Tag: SURFACE_GRADIENT - - #if HAVE_DECALS - if (_EnableDecals) - { - // Both uses and modifies 'surfaceData.normalWS'. - DecalSurfaceData decalSurfaceData = GetDecalSurfaceData(posInput, surfaceDescription.Alpha); - ApplyDecalToSurfaceData(decalSurfaceData, surfaceData); - } - #endif - - surfaceData.tangentWS = Orthonormalize(surfaceData.tangentWS, surfaceData.normalWS); - - #ifdef DEBUG_DISPLAY - if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE) - { - // TODO: need to update mip info - surfaceData.metallic = 0; - } - - // We need to call ApplyDebugToSurfaceData after filling the surfarcedata and before filling builtinData - // as it can modify attribute use for static lighting - ApplyDebugToSurfaceData(fragInputs.tangentToWorld, surfaceData); - #endif - - // By default we use the ambient occlusion with Tri-ace trick (apply outside) for specular occlusion as PBR master node don't have any option - surfaceData.specularOcclusion = GetSpecularOcclusionFromAmbientOcclusion(ClampNdotV(dot(surfaceData.normalWS, V)), surfaceData.ambientOcclusion, PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness)); - } - - void GetSurfaceAndBuiltinData(FragInputs fragInputs, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData) - { - #ifdef LOD_FADE_CROSSFADE // enable dithering LOD transition if user select CrossFade transition in LOD group - uint3 fadeMaskSeed = asuint((int3)(V * _ScreenSize.xyx)); // Quantize V to _ScreenSize values - LODDitheringTransition(fadeMaskSeed, unity_LODFade.x); - #endif - - float3 doubleSidedConstants = float3(1.0, 1.0, 1.0); - $DoubleSided.Flip: doubleSidedConstants = float3(-1.0, -1.0, -1.0); - $DoubleSided.Mirror: doubleSidedConstants = float3( 1.0, 1.0, -1.0); - - ApplyDoubleSidedFlipOrMirror(fragInputs, doubleSidedConstants); - - SurfaceDescriptionInputs surfaceDescriptionInputs = FragInputsToSurfaceDescriptionInputs(fragInputs, V); - SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs); - - // Perform alpha test very early to save performance (a killed pixel will not sample textures) - // TODO: split graph evaluation to grab just alpha dependencies first? tricky.. - $AlphaTest: DoAlphaTest(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold); - - BuildSurfaceData(fragInputs, surfaceDescription, V, posInput, surfaceData); - - // Builtin Data - // For back lighting we use the oposite vertex normal - InitBuiltinData(posInput, surfaceDescription.Alpha, surfaceData.normalWS, -fragInputs.tangentToWorld[2], fragInputs.texCoord1, fragInputs.texCoord2, builtinData); - - $SurfaceDescription.Emission: builtinData.emissiveColor = surfaceDescription.Emission; - - //Note this will not fully work on transparent surfaces (can check with _SURFACE_TYPE_TRANSPARENT define) - //We will always overwrite vt feeback with the nearest. So behind transparent surfaces vt will not be resolved - //This is a limitation of the current MRT approach. - $SurfaceDescription.VTPackedFeedback: builtinData.vtPackedFeedback = surfaceDescription.VTPackedFeedback; - - PostInitBuiltinData(V, posInput, surfaceData, builtinData); - } - - // -------------------------------------------------- - // Main - - $splice(PostGraphIncludes) - - ENDHLSL -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRPass.template.meta b/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRPass.template.meta deleted file mode 100644 index cf5f771deb1..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRPass.template.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: bd2f8fe2aa130e64683bab499b868eeb -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRSubTarget.cs deleted file mode 100644 index 191b84c1e14..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRSubTarget.cs +++ /dev/null @@ -1,470 +0,0 @@ -using UnityEngine.Rendering.HighDefinition; -using UnityEditor.ShaderGraph; - -namespace UnityEditor.Rendering.HighDefinition.ShaderGraph -{ - sealed class PBRSubTarget : SubTarget - { - const string kAssetGuid = "c01e45594b63bd8419839b581ee0f601"; - static string passTemplatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/PBR/ShaderGraph/PBRPass.template"; - - public PBRSubTarget() - { - displayName = "PBR"; - } - - public override void Setup(ref TargetSetupContext context) - { - context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); - context.SetDefaultShaderGUI("Rendering.HighDefinition.HDPBRLitGUI"); - context.AddSubShader(SubShaders.PBR); - } - -#region SubShaders - static class SubShaders - { - public static SubShaderDescriptor PBR = new SubShaderDescriptor() - { - pipelineTag = HDRenderPipeline.k_ShaderTagName, - renderTypeOverride = HDRenderTypeTags.HDLitShader.ToString(), - generatesPreview = true, - passes = new PassCollection - { - { PBRPasses.ShadowCaster }, - { PBRPasses.META }, - { PBRPasses.SceneSelection }, - { PBRPasses.DepthOnly, new FieldCondition(Fields.SurfaceOpaque, true) }, - { PBRPasses.GBuffer, new FieldCondition(Fields.SurfaceOpaque, true) }, - { PBRPasses.MotionVectors, new FieldCondition(Fields.SurfaceOpaque, true) }, - { PBRPasses.Forward }, - }, - }; - } -#endregion - -#region Passes - static class PBRPasses - { - public static PassDescriptor GBuffer = new PassDescriptor() - { - // Definition - displayName = "GBuffer", - referenceName = "SHADERPASS_GBUFFER", - lightMode = "GBuffer", - useInPreview = true, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = PBRPortMasks.Vertex, - pixelPorts = PBRPortMasks.FragmentDefault, - - // Collections - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.LitMinimal, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = PBRRenderStates.GBuffer, - pragmas = CorePragmas.DotsInstancedInV2Only, - keywords = PBRKeywords.GBuffer, - includes = PBRIncludes.GBuffer, - - virtualTextureFeedback = true, - }; - - public static PassDescriptor META = new PassDescriptor() - { - // Definition - displayName = "META", - referenceName = "SHADERPASS_LIGHT_TRANSPORT", - lightMode = "META", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - pixelPorts = PBRPortMasks.FragmentDefault, - - // Collections - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.Meta, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.Meta, - pragmas = CorePragmas.DotsInstancedInV2Only, - keywords = PBRKeywords.LodFadeCrossfade, - includes = PBRIncludes.Meta, - }; - - public static PassDescriptor ShadowCaster = new PassDescriptor() - { - // Definition - displayName = "ShadowCaster", - referenceName = "SHADERPASS_SHADOWS", - lightMode = "ShadowCaster", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = PBRPortMasks.Vertex, - pixelPorts = PBRPortMasks.FragmentOnlyAlpha, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = PBRRenderStates.ShadowCaster, - pragmas = CorePragmas.DotsInstancedInV2Only, - keywords = PBRKeywords.LodFadeCrossfade, - includes = PBRIncludes.DepthOnly, - }; - - public static PassDescriptor SceneSelection = new PassDescriptor() - { - // Definition - displayName = "SceneSelectionPass", - referenceName = "SHADERPASS_DEPTH_ONLY", - lightMode = "SceneSelectionPass", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = PBRPortMasks.Vertex, - pixelPorts = PBRPortMasks.FragmentOnlyAlpha, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = PBRRenderStates.SceneSelection, - pragmas = CorePragmas.DotsInstancedInV2OnlyEditorSync, - defines = CoreDefines.SceneSelection, - keywords = PBRKeywords.LodFadeCrossfade, - includes = PBRIncludes.DepthOnly, - }; - - public static PassDescriptor DepthOnly = new PassDescriptor() - { - // Definition - displayName = "DepthOnly", - referenceName = "SHADERPASS_DEPTH_ONLY", - lightMode = "DepthOnly", - useInPreview = true, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = PBRPortMasks.Vertex, - pixelPorts = PBRPortMasks.FragmentDepthMotionVectors, - - // Collections - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.LitFull, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = PBRRenderStates.DepthOnly, - pragmas = CorePragmas.DotsInstancedInV2Only, - defines = CoreDefines.ShaderGraphRaytracingHigh, - keywords = PBRKeywords.DepthMotionVectors, - includes = PBRIncludes.DepthOnly, - }; - - public static PassDescriptor MotionVectors = new PassDescriptor() - { - // Definition - displayName = "MotionVectors", - referenceName = "SHADERPASS_MOTION_VECTORS", - lightMode = "MotionVectors", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = PBRPortMasks.Vertex, - pixelPorts = PBRPortMasks.FragmentDepthMotionVectors, - - // Fields - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.PositionRWS, - fieldDependencies = CoreFieldDependencies.Default, - - // Conditional State - renderStates = PBRRenderStates.MotionVectors, - pragmas = CorePragmas.DotsInstancedInV2Only, - defines = CoreDefines.ShaderGraphRaytracingHigh, - keywords = PBRKeywords.DepthMotionVectors, - includes = PBRIncludes.MotionVectors, - }; - - public static PassDescriptor Forward = new PassDescriptor() - { - // Definition - displayName = "Forward", - referenceName = "SHADERPASS_FORWARD", - lightMode = "Forward", - useInPreview = true, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = PBRPortMasks.Vertex, - pixelPorts = PBRPortMasks.FragmentDefault, - - // Collections - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.LitMinimal, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = PBRRenderStates.Forward, - pragmas = CorePragmas.DotsInstancedInV2Only, - defines = CoreDefines.Forward, - keywords = PBRKeywords.Forward, - includes = PBRIncludes.Forward, - - virtualTextureFeedback = true, - }; - } -#endregion - -#region PortMasks - static class PBRPortMasks - { - public static int[] Vertex = new int[] - { - PBRMasterNode.PositionSlotId, - PBRMasterNode.VertNormalSlotId, - PBRMasterNode.VertTangentSlotId, - }; - - public static int[] FragmentDefault = new int[] - { - PBRMasterNode.AlbedoSlotId, - PBRMasterNode.NormalSlotId, - PBRMasterNode.MetallicSlotId, - PBRMasterNode.SpecularSlotId, - PBRMasterNode.EmissionSlotId, - PBRMasterNode.SmoothnessSlotId, - PBRMasterNode.OcclusionSlotId, - PBRMasterNode.AlphaSlotId, - PBRMasterNode.AlphaThresholdSlotId, - }; - - public static int[] FragmentOnlyAlpha = new int[] - { - PBRMasterNode.AlphaSlotId, - PBRMasterNode.AlphaThresholdSlotId, - }; - - public static int[] FragmentDepthMotionVectors = new int[] - { - PBRMasterNode.NormalSlotId, - PBRMasterNode.SmoothnessSlotId, - PBRMasterNode.AlphaSlotId, - PBRMasterNode.AlphaThresholdSlotId, - }; - } -#endregion - -#region RenderStates - static class PBRRenderStates - { - public static RenderStateCollection GBuffer = new RenderStateCollection - { - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.ZTest(ZTest.Equal), new FieldCondition(Fields.AlphaClip, true) }, - { RenderState.ZTest(ZTest.LEqual), new FieldCondition(Fields.AlphaClip, false) }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = $"{ 0 | (int)StencilUsage.RequiresDeferredLighting | (int)StencilUsage.SubsurfaceScattering | (int)StencilUsage.TraceReflectionRay}", - Ref = $"{0 | (int)StencilUsage.RequiresDeferredLighting | (int)StencilUsage.TraceReflectionRay}", - Comp = "Always", - Pass = "Replace", - }) }, - }; - - public static RenderStateCollection ShadowCaster = new RenderStateCollection - { - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.Blend(Blend.One, Blend.Zero) }, - { RenderState.ZWrite(ZWrite.On) }, - { RenderState.ColorMask("ColorMask 0") }, - }; - - public static RenderStateCollection SceneSelection = new RenderStateCollection - { - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.ZWrite(ZWrite.On), new FieldCondition(Fields.SurfaceOpaque, true) }, - { RenderState.ZWrite(ZWrite.Off), new FieldCondition(Fields.SurfaceTransparent, true) }, - { RenderState.ColorMask("ColorMask 0") }, - }; - - public static RenderStateCollection DepthOnly = new RenderStateCollection - { - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.ZWrite(ZWrite.On) }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = $"{ 0 | (int)StencilUsage.TraceReflectionRay}", - Ref = $"{0 | (int)StencilUsage.TraceReflectionRay}", - Comp = "Always", - Pass = "Replace", - }) }, - }; - - public static RenderStateCollection MotionVectors = new RenderStateCollection - { - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = $"{0 | (int)StencilUsage.TraceReflectionRay | (int)StencilUsage.ObjectMotionVector}", - Ref = $"{ 0 | (int)StencilUsage.TraceReflectionRay | (int)StencilUsage.ObjectMotionVector}", - Comp = "Always", - Pass = "Replace", - }) }, - }; - - public static RenderStateCollection Forward = new RenderStateCollection - { - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.Blend(Blend.One, Blend.Zero, Blend.One, Blend.Zero), new FieldCondition(Fields.SurfaceOpaque, true) }, - { RenderState.Blend(Blend.One, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha), new FieldCondition[] { - new FieldCondition(Fields.SurfaceTransparent, true), - new FieldCondition(Fields.BlendAlpha, true) } }, - { RenderState.Blend(Blend.One, Blend.One, Blend.One, Blend.One), new FieldCondition[] { - new FieldCondition(Fields.SurfaceTransparent, true), - new FieldCondition(Fields.BlendAdd, true) } }, - { RenderState.Blend(Blend.One, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha), new FieldCondition[] { - new FieldCondition(Fields.SurfaceTransparent, true), - new FieldCondition(Fields.BlendPremultiply, true) } }, - { RenderState.Blend(Blend.One, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha), new FieldCondition[] { - new FieldCondition(Fields.SurfaceTransparent, true), - new FieldCondition(Fields.BlendMultiply, true) } }, - - { RenderState.ZTest(ZTest.Equal), new FieldCondition[] { - new FieldCondition(Fields.SurfaceOpaque, true), - new FieldCondition(Fields.AlphaTest, true) } }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = $"{(int)StencilUsage.RequiresDeferredLighting | (int)StencilUsage.SubsurfaceScattering}", - Ref = $"{(int)StencilUsage.Clear}", - Comp = "Always", - Pass = "Replace", - }) }, - }; - } -#endregion - -#region Keywords - static class PBRKeywords - { - public static KeywordCollection GBuffer = new KeywordCollection - { - { CoreKeywordDescriptors.LodFadeCrossfade }, - { CoreKeywordDescriptors.DebugDisplay }, - { CoreKeywords.Lightmaps }, - { CoreKeywordDescriptors.ShadowsShadowmask }, - { CoreKeywordDescriptors.LightLayers }, - { CoreKeywordDescriptors.Decals }, - { CoreKeywordDescriptors.AlphaTest, new FieldCondition(Fields.AlphaTest, true) }, - }; - - public static KeywordCollection LodFadeCrossfade = new KeywordCollection - { - { CoreKeywordDescriptors.LodFadeCrossfade }, - { CoreKeywordDescriptors.AlphaTest, new FieldCondition(Fields.AlphaTest, true) }, - }; - - public static KeywordCollection DepthMotionVectors = new KeywordCollection - { - { CoreKeywordDescriptors.WriteMsaaDepth }, - { CoreKeywordDescriptors.WriteNormalBuffer }, - { CoreKeywordDescriptors.LodFadeCrossfade }, - { CoreKeywordDescriptors.AlphaTest, new FieldCondition(Fields.AlphaTest, true) }, - }; - - public static KeywordCollection Forward = new KeywordCollection - { - { CoreKeywordDescriptors.LodFadeCrossfade }, - { CoreKeywordDescriptors.DebugDisplay }, - { CoreKeywords.Lightmaps }, - { CoreKeywordDescriptors.ShadowsShadowmask }, - { CoreKeywordDescriptors.Decals }, - { CoreKeywordDescriptors.Shadow }, - { CoreKeywordDescriptors.LightList, new FieldCondition(Fields.SurfaceOpaque, true) }, - { CoreKeywordDescriptors.AlphaTest, new FieldCondition(Fields.AlphaTest, true) }, - }; - } -#endregion - -#region Includes - static class PBRIncludes - { - // These are duplicated from HDLitSubTarget - // We avoid moving these to CoreIncludes because this SubTarget will be removed with Stacks - - const string kLitDecalData = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitDecalData.hlsl"; - const string kPassGBuffer = "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassGBuffer.hlsl"; - - public static IncludeCollection Common = new IncludeCollection - { - { CoreIncludes.CorePregraph }, - { CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph }, - { CoreIncludes.kLit, IncludeLocation.Pregraph }, - { CoreIncludes.CoreUtility }, - { CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph }, - { kLitDecalData, IncludeLocation.Pregraph }, - { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph }, - }; - - public static IncludeCollection GBuffer = new IncludeCollection - { - { Common }, - { kPassGBuffer, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection Meta = new IncludeCollection - { - { Common }, - { CoreIncludes.kPassLightTransport, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection DepthOnly = new IncludeCollection - { - { Common }, - { CoreIncludes.kPassDepthOnly, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection MotionVectors = new IncludeCollection - { - { Common }, - { CoreIncludes.kPassMotionVectors, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection Forward = new IncludeCollection - { - { CoreIncludes.CorePregraph }, - { CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph }, - { CoreIncludes.kLighting, IncludeLocation.Pregraph }, - { CoreIncludes.kLightLoopDef, IncludeLocation.Pregraph }, - { CoreIncludes.kLit, IncludeLocation.Pregraph }, - { CoreIncludes.kLightLoop, IncludeLocation.Pregraph }, - { CoreIncludes.CoreUtility }, - { CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph }, - { kLitDecalData, IncludeLocation.Pregraph }, - { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph }, - { CoreIncludes.kPassForward, IncludeLocation.Postgraph }, - }; - } -#endregion - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRSubTarget.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRSubTarget.cs.meta deleted file mode 100644 index fad43c60d64..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph/PBRSubTarget.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c01e45594b63bd8419839b581ee0f601 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph.meta b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph.meta similarity index 77% rename from com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph.meta rename to com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph.meta index 4c77f33b1c5..c2f25ee81c6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/PBR/ShaderGraph.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 95471fcb52faf7d4993ea3e131aa9ff6 +guid: 036e4d56f2e59b34988045b68f3bf064 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/AdvancedOptionsPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/AdvancedOptionsPropertyBlock.cs new file mode 100644 index 00000000000..2706b9cec3f --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/AdvancedOptionsPropertyBlock.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.AdvancedOptionsUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.SurfaceOptionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class AdvancedOptionsPropertyBlock : SubTargetPropertyBlock + { + class Styles + { + public static GUIContent overrideBakedGI = new GUIContent("Override Baked GI", "TODO"); + public static GUIContent supportLodCrossFade = new GUIContent("Support LOD CrossFade", "TODO"); + } + + protected override string title => "Advanced Options"; + protected override int foldoutIndex => 3; + + protected override void CreatePropertyGUI() + { + if (lightingData != null) + { + AddProperty(specularOcclusionModeText, () => lightingData.specularOcclusionMode, (newValue) => lightingData.specularOcclusionMode = newValue); + AddProperty(Styles.overrideBakedGI, () => lightingData.overrideBakedGI, (newValue) => lightingData.overrideBakedGI = newValue); + } + AddProperty(Styles.supportLodCrossFade, () => systemData.supportLodCrossFade, (newValue) => systemData.supportLodCrossFade = newValue); + AddProperty(addPrecomputedVelocityText, () => builtinData.addPrecomputedVelocity, (newValue) => builtinData.addPrecomputedVelocity = newValue); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/AdvancedOptionsPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/AdvancedOptionsPropertyBlock.cs.meta new file mode 100644 index 00000000000..dd51756a261 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/AdvancedOptionsPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 27501b0b352a8d442a4f1e892d5d4887 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DistortionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DistortionPropertyBlock.cs new file mode 100644 index 00000000000..603e4d4da87 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DistortionPropertyBlock.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.DistortionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class DistortionPropertyBlock : SubTargetPropertyBlock + { + protected override string title => "Distortion"; + protected override int foldoutIndex => 1; + + protected override void CreatePropertyGUI() + { + AddProperty(distortionEnableText, () => builtinData.distortion, (newValue) => builtinData.distortion = newValue); + AddProperty(distortionBlendModeText, () => builtinData.distortionMode, (newValue) => builtinData.distortionMode = newValue); + AddProperty(distortionDepthTestText, () => builtinData.distortionDepthTest, (newValue) => builtinData.distortionDepthTest = newValue); + } + } +} \ No newline at end of file diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DistortionPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DistortionPropertyBlock.cs.meta new file mode 100644 index 00000000000..f5edddb757b --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DistortionPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e555db764fc0c4942b3b48e1c40affe9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDPropertiesHeader.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDPropertiesHeader.cs new file mode 100644 index 00000000000..559d224c165 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDPropertiesHeader.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class HDPropertiesHeader : Toggle + { + public HDPropertiesHeader(string label) : base(label) + { + + } + } +} \ No newline at end of file diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDPropertiesHeader.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDPropertiesHeader.cs.meta new file mode 100644 index 00000000000..6ce96986ece --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDPropertiesHeader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 31b8812c1cf3c284e92bf49333fa31e3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubTarget.cs new file mode 100644 index 00000000000..8b6096e3b13 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubTarget.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + abstract class HDSubTarget : SubTarget, IHasMetadata, + IRequiresData + { + SystemData m_SystemData; + protected bool m_MigrateFromOldCrossPipelineSG; // Use only for the migration to shader stack architecture + + // Interface Properties + SystemData IRequiresData.data + { + get => m_SystemData; + set => m_SystemData = value; + } + + // Public properties + public SystemData systemData + { + get => m_SystemData; + set => m_SystemData = value; + } + + protected virtual int ComputeMaterialNeedsUpdateHash() + { + // Alpha test is currently the only property in system data to trigger the material upgrade script. + int hash = systemData.alphaTest.GetHashCode(); + return hash; + } + + public override bool IsActive() => true; + + protected abstract ShaderID shaderID { get; } + protected abstract string customInspector { get; } + protected abstract string subTargetAssetGuid { get; } + protected abstract string renderType { get; } + protected abstract string renderQueue { get; } + + public virtual string identifier => GetType().Name; + + public virtual ScriptableObject GetMetadataObject() + { + var hdMetadata = ScriptableObject.CreateInstance(); + hdMetadata.shaderID = shaderID; + hdMetadata.migrateFromOldCrossPipelineSG = m_MigrateFromOldCrossPipelineSG; + return hdMetadata; + } + + public sealed override void Setup(ref TargetSetupContext context) + { + context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath("c09e6e9062cbd5a48900c48a0c2ed1c2")); // HDSubTarget.cs + context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(subTargetAssetGuid)); + context.SetDefaultShaderGUI(customInspector); + + foreach (var subShader in EnumerateSubShaders()) + { + // patch render type and render queue from pass declaration: + var patchedSubShader = subShader; + patchedSubShader.renderType = renderType; + patchedSubShader.renderQueue = renderQueue; + context.AddSubShader(patchedSubShader); + } + } + + public override void GetFields(ref TargetFieldContext context) + { + // Common properties between all HD master nodes + // Surface Type + context.AddField(Fields.SurfaceOpaque, systemData.surfaceType == SurfaceType.Opaque); + context.AddField(Fields.SurfaceTransparent, systemData.surfaceType != SurfaceType.Opaque); + + // Dots + context.AddField(HDFields.DotsInstancing, systemData.dotsInstancing); + } + + protected abstract IEnumerable EnumerateSubShaders(); + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + var gui = new SubTargetPropertiesGUI(context, onChange, registerUndo, systemData, null, null); + AddInspectorPropertyBlocks(gui); + context.Add(gui); + } + + protected abstract void AddInspectorPropertyBlocks(SubTargetPropertiesGUI blockList); + + public override object saveContext + { + get + { + int hash = ComputeMaterialNeedsUpdateHash(); + bool needsUpdate = hash != systemData.materialNeedsUpdateHash; + if (needsUpdate) + systemData.materialNeedsUpdateHash = hash; + + return new HDSaveContext{ updateMaterials = needsUpdate }; + } + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubTarget.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubTarget.cs.meta new file mode 100644 index 00000000000..a7ee8b9a74a --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c09e6e9062cbd5a48900c48a0c2ed1c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/LightingSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/LightingSubTarget.cs new file mode 100644 index 00000000000..95c9d89a3b9 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/LightingSubTarget.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + abstract class LightingSubTarget : SurfaceSubTarget, IRequiresData + { + LightingData m_LightingData; + + LightingData IRequiresData.data + { + get => m_LightingData; + set => m_LightingData = value; + } + + protected override string renderType => HDRenderTypeTags.HDLitShader.ToString(); + + public LightingData lightingData + { + get => m_LightingData; + set => m_LightingData = value; + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + var gui = new SubTargetPropertiesGUI(context, onChange, registerUndo, systemData, builtinData, lightingData); + AddInspectorPropertyBlocks(gui); + context.Add(gui); + } + + protected override int ComputeMaterialNeedsUpdateHash() + { + int hash = base.ComputeMaterialNeedsUpdateHash(); + + unchecked + { + hash = hash * 23 + builtinData.alphaTestShadow.GetHashCode(); + hash = hash * 23 + lightingData.receiveSSR.GetHashCode(); + hash = hash * 23 + lightingData.receiveSSRTransparent.GetHashCode(); + hash = hash * 23 + lightingData.subsurfaceScattering.GetHashCode(); + } + + return hash; + } + + public override void GetFields(ref TargetFieldContext context) + { + base.GetFields(ref context); + + // Common properties to all Lit master nodes + var descs = context.blocks.Select(x => x.descriptor); + + // Normal dropoff space + context.AddField(Fields.NormalDropOffOS, lightingData.normalDropOffSpace == NormalDropOffSpace.Object); + context.AddField(Fields.NormalDropOffTS, lightingData.normalDropOffSpace == NormalDropOffSpace.Tangent); + context.AddField(Fields.NormalDropOffWS, lightingData.normalDropOffSpace == NormalDropOffSpace.World); + + // Misc + context.AddField(HDFields.BlendPreserveSpecular, systemData.surfaceType != SurfaceType.Opaque && lightingData.blendPreserveSpecular); + context.AddField(HDFields.DisableDecals, !lightingData.receiveDecals); + context.AddField(HDFields.DisableSSR, !lightingData.receiveSSR); + context.AddField(HDFields.DisableSSRTransparent, !lightingData.receiveSSRTransparent); + context.AddField(HDFields.SpecularAA, lightingData.specularAA && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance)); + context.AddField(HDFields.LightingGI, descs.Contains(HDBlockFields.SurfaceDescription.BakedGI) && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.BakedGI)); + context.AddField(HDFields.BackLightingGI, descs.Contains(HDBlockFields.SurfaceDescription.BakedBackGI) && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.BakedBackGI)); + context.AddField(HDFields.BentNormal, descs.Contains(HDBlockFields.SurfaceDescription.BentNormal) && context.connectedBlocks.Contains(HDBlockFields.SurfaceDescription.BentNormal) && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.BentNormal)); + context.AddField(HDFields.AmbientOcclusion, context.blocks.Contains((BlockFields.SurfaceDescription.Occlusion, false)) && context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.Occlusion)); + + // Specular Occlusion Fields + context.AddField(HDFields.SpecularOcclusionFromAO, lightingData.specularOcclusionMode == SpecularOcclusionMode.FromAO); + context.AddField(HDFields.SpecularOcclusionFromAOBentNormal, lightingData.specularOcclusionMode == SpecularOcclusionMode.FromAOAndBentNormal); + context.AddField(HDFields.SpecularOcclusionCustom, lightingData.specularOcclusionMode == SpecularOcclusionMode.Custom); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + base.GetActiveBlocks(ref context); + + context.AddBlock(HDBlockFields.SurfaceDescription.BentNormal); + context.AddBlock(BlockFields.SurfaceDescription.Smoothness); + context.AddBlock(BlockFields.SurfaceDescription.Occlusion); + + // Specular AA + context.AddBlock(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, lightingData.specularAA); + context.AddBlock(HDBlockFields.SurfaceDescription.SpecularAAThreshold, lightingData.specularAA); + + // Baked GI + context.AddBlock(HDBlockFields.SurfaceDescription.BakedGI, lightingData.overrideBakedGI); + context.AddBlock(HDBlockFields.SurfaceDescription.BakedBackGI, lightingData.overrideBakedGI); + + // Misc + context.AddBlock(HDBlockFields.SurfaceDescription.SpecularOcclusion, lightingData.specularOcclusionMode == SpecularOcclusionMode.Custom); + + // Normal dropoff space + context.AddBlock(BlockFields.SurfaceDescription.NormalOS, lightingData.normalDropOffSpace == NormalDropOffSpace.Object); + context.AddBlock(BlockFields.SurfaceDescription.NormalTS, lightingData.normalDropOffSpace == NormalDropOffSpace.Tangent); + context.AddBlock(BlockFields.SurfaceDescription.NormalWS, lightingData.normalDropOffSpace == NormalDropOffSpace.World); + } + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) + { + base.CollectShaderProperties(collector, generationMode); + + // Add all shader properties required by the inspector + HDSubShaderUtilities.AddStencilShaderProperties(collector, systemData, lightingData); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/LightingSubTarget.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/LightingSubTarget.cs.meta new file mode 100644 index 00000000000..f151ef058fc --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/LightingSubTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aea3df556ea7e9b44855d1fff79fed53 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertiesGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertiesGUI.cs new file mode 100644 index 00000000000..8b224e2c236 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertiesGUI.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class SubTargetPropertiesGUI : VisualElement + { + TargetPropertyGUIContext context; + Action onChange; + Action registerUndo; + SystemData systemData; + BuiltinData builtinData; + LightingData lightingData; + + public List uiBlocks = new List(); + + public SubTargetPropertiesGUI(TargetPropertyGUIContext context, Action onChange, Action registerUndo, + SystemData systemData, BuiltinData builtinData, LightingData lightingData) + { + this.context = context; + this.onChange = onChange; + this.registerUndo = registerUndo; + this.systemData = systemData; + this.builtinData = builtinData; + this.lightingData = lightingData; + } + + public void AddPropertyBlock(SubTargetPropertyBlock block) + { + block.Initialize(context, onChange, registerUndo, systemData, builtinData, lightingData); + block.CreatePropertyGUIWithHeader(); + Add(block); + } + } +} \ No newline at end of file diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertiesGUI.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertiesGUI.cs.meta new file mode 100644 index 00000000000..6cf8ba90156 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertiesGUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1c8649774bb728c46a0eb3a2c6462b81 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertyBlock.cs new file mode 100644 index 00000000000..f264df1f5a3 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertyBlock.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; +using RenderQueueType = UnityEngine.Rendering.HighDefinition.HDRenderQueue.RenderQueueType; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + abstract class SubTargetPropertyBlock : VisualElement + { + // Null/Empty means no title + protected virtual string title => null; + + protected TargetPropertyGUIContext context; + protected Action onChange; + protected Action registerUndo; + protected SystemData systemData; + protected BuiltinData builtinData; + protected LightingData lightingData; + + internal void Initialize(TargetPropertyGUIContext context, Action onChange, Action registerUndo, + SystemData systemData, BuiltinData builtinData, LightingData lightingData) + { + this.context = context; + this.onChange = onChange; + this.registerUndo = registerUndo; + this.systemData = systemData; + this.builtinData = builtinData; + this.lightingData = lightingData; + } + + // Utility function to create UIElement fields: + protected void AddProperty(string displayName, Func getter, Action setter, int indentLevel = 0) + => AddProperty(new GUIContent(displayName), getter, setter, indentLevel); + + protected void AddProperty(GUIContent displayName, Func getter, Action setter, int indentLevel = 0) + { + // Create UIElement from type: + BaseField elem = null; + BaseField elemEnum = null; + + switch (getter()) + { + case bool b: elem = new Toggle { value = b, tooltip = displayName.tooltip } as BaseField; break; + case int i: elem = new IntegerField { value = i, tooltip = displayName.tooltip } as BaseField; break; + case float f: elem = new FloatField { value = f, tooltip = displayName.tooltip } as BaseField; break; + case SurfaceType e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case RenderQueueType e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case BlendMode e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case CompareFunction e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case TransparentCullMode e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case DoubleSidedMode e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case NormalDropOffSpace e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case HDLitData.MaterialType e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case DistortionMode e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case ScreenSpaceRefraction.RefractionModel e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case SpecularOcclusionMode e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case FabricData.MaterialType e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case EyeData.MaterialType e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case StackLit.BaseParametrization e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + case StackLit.DualSpecularLobeParametrization e: elemEnum = new EnumField(e) { value = e, tooltip = displayName.tooltip } as BaseField; break; + default: throw new Exception($"Can't create UI field for type {getter().GetType()}, please add it if it's relevant. If you can't consider using TargetPropertyGUIContext.AddProperty instead."); + } + + if (elem != null) + { + context.AddProperty(displayName.text, indentLevel, elem, (evt) => { + if (Equals(getter(), evt.newValue)) + return; + + registerUndo(displayName.text); + setter(evt.newValue); + onChange(); + }); + } + else + { + context.AddProperty(displayName.text, indentLevel, elemEnum, (evt) => { + if (Equals(getter(), evt.newValue)) + return; + + registerUndo(displayName.text); + setter((Data)(object)evt.newValue); + onChange(); + }); + } + } + + protected void AddFoldout(string text, Func getter, Action setter) + => AddFoldout(new GUIContent(text), getter, setter); + + protected void AddFoldout(GUIContent content, Func getter, Action setter) + { + var foldout = new Foldout() { + value = getter(), + text = content.text, + tooltip = content.tooltip + }; + + foldout.RegisterValueChangedCallback((evt) => { + setter(evt.newValue); + onChange(); + }); + + // Apply padding: + foldout.style.paddingLeft = context.globalIndentLevel * 15; + + context.Add(foldout); + } + + public void CreatePropertyGUIWithHeader() + { + if (!String.IsNullOrEmpty(title)) + { + int index = foldoutIndex; + AddFoldout(title, + () => (systemData.inspectorFoldoutMask & (1 << index)) != 0, + (value) => + { + systemData.inspectorFoldoutMask &= ~(1 << index); // Clear + systemData.inspectorFoldoutMask |= (value ? 1 : 0) << index; // Set + } + ); + context.globalIndentLevel++; + if ((systemData.inspectorFoldoutMask & (1 << index)) != 0) + CreatePropertyGUI(); + context.globalIndentLevel--; + } + else + CreatePropertyGUI(); + } + + protected abstract void CreatePropertyGUI(); + + /// Warning: this property must have a different value for each property block type! + protected abstract int foldoutIndex { get; } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertyBlock.cs.meta new file mode 100644 index 00000000000..976be52ab1d --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 75e8a39b82611424ea7f2a18003ab651 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceOptionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceOptionPropertyBlock.cs new file mode 100644 index 00000000000..440e0171e24 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceOptionPropertyBlock.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.SurfaceOptionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class SurfaceOptionPropertyBlock : SubTargetPropertyBlock + { + [Flags] + // TODO: remove ? + public enum Features + { + None = 0, + All = ~0, + + Unlit = All, + Lit = All, + } + + class Styles + { + public static GUIContent fragmentNormalSpace = new GUIContent("Fragment Normal Space", "TODO"); + public static GUIContent doubleSidedModeText = new GUIContent("Double Sided Mode", "TODO"); + } + + Features enabledFeatures; + + protected override string title => "Surface Option"; + protected override int foldoutIndex => 0; + + public SurfaceOptionPropertyBlock(Features features) => enabledFeatures = features; + + protected override void CreatePropertyGUI() + { + AddProperty(surfaceTypeText, () => systemData.surfaceType, (newValue) => { + systemData.surfaceType = newValue; + systemData.TryChangeRenderingPass(systemData.renderingPass); + }); + + var renderingPassList = HDSubShaderUtilities.GetRenderingPassList(systemData.surfaceType == SurfaceType.Opaque, false); + var renderingPassValue = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.GetOpaqueEquivalent(systemData.renderingPass) : HDRenderQueue.GetTransparentEquivalent(systemData.renderingPass); + var renderQueueType = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; + context.AddProperty(renderingPassText, new PopupField(renderingPassList, renderQueueType, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName) { value = renderingPassValue }, (evt) => + { + registerUndo(renderingPassText); + if(systemData.TryChangeRenderingPass(evt.newValue)) + onChange(); + }); + + if (systemData.surfaceType == SurfaceType.Transparent) + { + context.globalIndentLevel++; + AddProperty(blendModeText, () => systemData.blendMode, (newValue) => systemData.blendMode = newValue); + AddProperty(enableTransparentFogText, () => builtinData.transparencyFog, (newValue) => builtinData.transparencyFog = newValue); + AddProperty(transparentZTestText, () => systemData.zTest, (newValue) => systemData.zTest = newValue); + AddProperty(zWriteEnableText, () => systemData.zWrite, (newValue) => systemData.zWrite = newValue); + AddProperty(transparentCullModeText, () => systemData.transparentCullMode, (newValue) => systemData.transparentCullMode = newValue); + AddProperty(transparentSortPriorityText, () => systemData.sortPriority, (newValue) => systemData.sortPriority = HDRenderQueue.ClampsTransparentRangePriority(newValue)); + AddProperty(transparentBackfaceEnableText, () => builtinData.backThenFrontRendering, (newValue) => builtinData.backThenFrontRendering = newValue); + AddProperty(transparentDepthPrepassEnableText, () => systemData.alphaTestDepthPrepass, (newValue) => systemData.alphaTestDepthPrepass = newValue); + AddProperty(transparentDepthPostpassEnableText, () => systemData.alphaTestDepthPostpass, (newValue) => systemData.alphaTestDepthPostpass = newValue); + AddProperty(transparentWritingMotionVecText, () => builtinData.transparentWritesMotionVec, (newValue) => builtinData.transparentWritesMotionVec = newValue); + + if (lightingData != null) + AddProperty(enableBlendModePreserveSpecularLightingText, () => lightingData.blendPreserveSpecular, (newValue) => lightingData.blendPreserveSpecular = newValue); + context.globalIndentLevel--; + } + + // Alpha Test + // TODO: AlphaTest is in SystemData but Alpha to Mask is in BuiltinData? + AddProperty(alphaCutoffEnableText, () => systemData.alphaTest, (newValue) => systemData.alphaTest = newValue); + AddProperty(useShadowThresholdText, () => builtinData.alphaTestShadow, (newValue) => builtinData.alphaTestShadow = newValue); + AddProperty(alphaToMaskText, () => builtinData.alphaToMask, (newValue) => builtinData.alphaToMask = newValue); + + // Misc + AddProperty(Styles.doubleSidedModeText, () => systemData.doubleSidedMode, (newValue) => systemData.doubleSidedMode = newValue); + if (lightingData != null) + AddProperty(Styles.fragmentNormalSpace, () => lightingData.normalDropOffSpace, (newValue) => lightingData.normalDropOffSpace = newValue); + + // Misc Cont. + if (lightingData != null) + { + AddProperty(supportDecalsText, () => lightingData.receiveDecals, (newValue) => lightingData.receiveDecals = newValue); + + if (systemData.surfaceType == SurfaceType.Transparent) + AddProperty(receivesSSRTransparentText, () => lightingData.receiveSSRTransparent, (newValue) => lightingData.receiveSSRTransparent = newValue); + else + AddProperty(receivesSSRText, () => lightingData.receiveSSR, (newValue) => lightingData.receiveSSR = newValue); + + AddProperty(enableGeometricSpecularAAText, () => lightingData.specularAA, (newValue) => lightingData.specularAA = newValue); + } + AddProperty(depthOffsetEnableText, () => builtinData.depthOffset, (newValue) => builtinData.depthOffset = newValue); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceOptionPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceOptionPropertyBlock.cs.meta new file mode 100644 index 00000000000..cb3a746ffdf --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceOptionPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cc62914ce909bf94f8b31d46a1ad9778 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs new file mode 100644 index 00000000000..0a4c9f31bcd --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + abstract class SurfaceSubTarget : HDSubTarget, IRequiresData + { + BuiltinData m_BuiltinData; + + // Interface Properties + BuiltinData IRequiresData.data + { + get => m_BuiltinData; + set => m_BuiltinData = value; + } + + public BuiltinData builtinData + { + get => m_BuiltinData; + set => m_BuiltinData = value; + } + + protected override string renderQueue + { + get => HDRenderQueue.GetShaderTagValue(HDRenderQueue.ChangeType(systemData.renderingPass, systemData.sortPriority, systemData.alphaTest)); + } + + public override void GetFields(ref TargetFieldContext context) + { + base.GetFields(ref context); + + // Common properties between all "surface" master nodes (everything except decal right now) + + // Blend Mode + context.AddField(Fields.BlendAdd, systemData.surfaceType != SurfaceType.Opaque && systemData.blendMode == BlendMode.Additive); + context.AddField(Fields.BlendAlpha, systemData.surfaceType != SurfaceType.Opaque && systemData.blendMode == BlendMode.Alpha); + context.AddField(Fields.BlendPremultiply, systemData.surfaceType != SurfaceType.Opaque && systemData.blendMode == BlendMode.Premultiply); + + // We always generate the keyword ALPHATEST_ON + context.AddField(Fields.AlphaTest, systemData.alphaTest + && (context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.AlphaClipThreshold) + || context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow) + || context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass) + || context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass))); + + // Double Sided + context.AddField(HDFields.DoubleSided, systemData.doubleSidedMode != DoubleSidedMode.Disabled); + + context.AddField(HDFields.DoAlphaTestPrepass, systemData.alphaTest && systemData.alphaTestDepthPrepass && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass)); + context.AddField(HDFields.DoAlphaTestPostpass, systemData.alphaTest && systemData.alphaTestDepthPostpass && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass)); + context.AddField(HDFields.DoAlphaTestShadow, systemData.alphaTest && builtinData.alphaTestShadow && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow)); + + context.AddField(HDFields.TransparentDepthPrePass, systemData.surfaceType != SurfaceType.Opaque && systemData.alphaTestDepthPrepass); + context.AddField(HDFields.TransparentDepthPostPass, systemData.surfaceType != SurfaceType.Opaque && systemData.alphaTestDepthPostpass); + + // Features & Misc + context.AddField(Fields.LodCrossFade, systemData.supportLodCrossFade); + context.AddField(Fields.VelocityPrecomputed, builtinData.addPrecomputedVelocity); + context.AddField(HDFields.TransparentWritesMotionVec, systemData.surfaceType != SurfaceType.Opaque && builtinData.transparentWritesMotionVec); + context.AddField(Fields.AlphaToMask, systemData.alphaTest && context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.AlphaClipThreshold) && builtinData.alphaToMask); + context.AddField(HDFields.DepthOffset, builtinData.depthOffset && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.DepthOffset)); + context.AddField(HDFields.AlphaFog, systemData.surfaceType != SurfaceType.Opaque && builtinData.transparencyFog); + context.AddField(HDFields.TransparentBackFace, systemData.surfaceType != SurfaceType.Opaque && builtinData.backThenFrontRendering); + } + + protected void AddDistortionFields(ref TargetFieldContext context) + { + // Distortion + context.AddField(HDFields.DistortionDepthTest, builtinData.distortionDepthTest); + context.AddField(HDFields.DistortionAdd, builtinData.distortionMode == DistortionMode.Add); + context.AddField(HDFields.DistortionMultiply, builtinData.distortionMode == DistortionMode.Multiply); + context.AddField(HDFields.DistortionReplace, builtinData.distortionMode == DistortionMode.Replace); + context.AddField(HDFields.TransparentDistortion, systemData.surfaceType != SurfaceType.Opaque && builtinData.distortion); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + // Common block between all "surface" master nodes + // Vertex + context.AddBlock(BlockFields.VertexDescription.Position); + context.AddBlock(BlockFields.VertexDescription.Normal); + context.AddBlock(BlockFields.VertexDescription.Tangent); + + // Surface + context.AddBlock(BlockFields.SurfaceDescription.BaseColor); + context.AddBlock(BlockFields.SurfaceDescription.Emission); + context.AddBlock(BlockFields.SurfaceDescription.Alpha); + context.AddBlock(BlockFields.SurfaceDescription.AlphaClipThreshold, systemData.alphaTest); + + // Alpha Test + context.AddBlock(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass, systemData.surfaceType == SurfaceType.Transparent && systemData.alphaTest && systemData.alphaTestDepthPrepass); + context.AddBlock(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass, systemData.surfaceType == SurfaceType.Transparent && systemData.alphaTest && systemData.alphaTestDepthPostpass); + context.AddBlock(HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow, systemData.alphaTest && builtinData.alphaTestShadow); + + // Misc + context.AddBlock(HDBlockFields.SurfaceDescription.DepthOffset, builtinData.depthOffset); + } + + protected void AddDistortionBlocks(ref TargetActiveBlockContext context) + { + context.AddBlock(HDBlockFields.SurfaceDescription.Distortion, systemData.surfaceType == SurfaceType.Transparent && builtinData.distortion); + context.AddBlock(HDBlockFields.SurfaceDescription.DistortionBlur, systemData.surfaceType == SurfaceType.Transparent && builtinData.distortion); + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + var gui = new SubTargetPropertiesGUI(context, onChange, registerUndo, systemData, builtinData, null); + AddInspectorPropertyBlocks(gui); + context.Add(gui); + } + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) + { + // Trunk currently relies on checking material property "_EmissionColor" to allow emissive GI. If it doesn't find that property, or it is black, GI is forced off. + // ShaderGraph doesn't use this property, so currently it inserts a dummy color (white). This dummy color may be removed entirely once the following PR has been merged in trunk: Pull request #74105 + // The user will then need to explicitly disable emissive GI if it is not needed. + // To be able to automatically disable emission based on the ShaderGraph config when emission is black, + // we will need a more general way to communicate this to the engine (not directly tied to a material property). + collector.AddShaderProperty(new ColorShaderProperty() + { + overrideReferenceName = "_EmissionColor", + hidden = true, + value = new Color(1.0f, 1.0f, 1.0f, 1.0f) + }); + // ShaderGraph only property used to send the RenderQueueType to the material + collector.AddShaderProperty(new Vector1ShaderProperty + { + overrideReferenceName = "_RenderQueueType", + hidden = true, + value = (int)systemData.renderingPass, + }); + + //See SG-ADDITIONALVELOCITY-NOTE + if (builtinData.addPrecomputedVelocity) + { + collector.AddShaderProperty(new BooleanShaderProperty + { + value = true, + hidden = true, + overrideReferenceName = kAddPrecomputedVelocity, + }); + } + + // Common properties for all "surface" master nodes + HDSubShaderUtilities.AddAlphaCutoffShaderProperties(collector, systemData.alphaTest, builtinData.alphaTestShadow); + HDSubShaderUtilities.AddDoubleSidedProperty(collector, systemData.doubleSidedMode); + HDSubShaderUtilities.AddPrePostPassProperties(collector, systemData.alphaTestDepthPrepass, systemData.alphaTestDepthPostpass); + + // Add all shader properties required by the inspector + HDSubShaderUtilities.AddBlendingStatesShaderProperties( + collector, + systemData.surfaceType, + systemData.blendMode, + systemData.sortPriority, + builtinData.alphaToMask, + systemData.zWrite, + systemData.transparentCullMode, + systemData.zTest, + builtinData.backThenFrontRendering, + builtinData.transparencyFog + ); + } + + public override void ProcessPreviewMaterial(Material material) + { + // Fixup the material settings: + material.SetFloat(kSurfaceType, (int)systemData.surfaceType); + material.SetFloat(kDoubleSidedNormalMode, (int)systemData.doubleSidedMode); + material.SetFloat(kAlphaCutoffEnabled, systemData.alphaTest ? 1 : 0); + material.SetFloat(kBlendMode, (int)systemData.blendMode); + material.SetFloat(kEnableFogOnTransparent, builtinData.transparencyFog ? 1.0f : 0.0f); + material.SetFloat(kZTestTransparent, (int)systemData.zTest); + material.SetFloat(kTransparentCullMode, (int)systemData.transparentCullMode); + material.SetFloat(kZWrite, systemData.zWrite ? 1.0f : 0.0f); + + // No sorting priority for shader graph preview + material.renderQueue = (int)HDRenderQueue.ChangeType(systemData.renderingPass, offset: 0, alphaTest: systemData.alphaTest); + + HDLitGUI.SetupMaterialKeywordsAndPass(material); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs.meta new file mode 100644 index 00000000000..228e06f2ac6 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f4df7e8f9b8c23648ae50cbca0221e47 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs index daab72d9ff3..b27794bf50e 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs @@ -1,13 +1,34 @@ +using System; using UnityEditor.ShaderGraph; -namespace UnityEditor.Rendering.HighDefinition +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { static class CreateStackLitShaderGraph { - [MenuItem("Assets/Create/Shader/HDRP/StackLit Graph", false, 208)] - public static void CreateMaterialGraph() + [MenuItem("Assets/Create/Shader/HDRP/StackLit Shader Graph", false, 208)] + public static void CreateStackLitGraph() { - GraphUtil.CreateNewGraph(new StackLitMasterNode()); + var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); + target.TrySetActiveSubTarget(typeof(StackLitSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.Tangent, + BlockFields.SurfaceDescription.Metallic, + HDBlockFields.SurfaceDescription.DielectricIor, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Alpha, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs.meta index 4832c26dabc..b9a40fc741a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 93591f944368c1d48b18a4e485bdda70 +guid: f0325744baba8874687c28cbe3cf4850 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/HDStackLitSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/HDStackLitSubTarget.cs deleted file mode 100644 index 5a2702583ed..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/HDStackLitSubTarget.cs +++ /dev/null @@ -1,771 +0,0 @@ -using UnityEngine.Rendering.HighDefinition; -using UnityEditor.ShaderGraph; - -namespace UnityEditor.Rendering.HighDefinition.ShaderGraph -{ - sealed class HDStackLitSubTarget : SubTarget - { - const string kAssetGuid = "5f7ba34a143e67647b202a662748dae3"; - static string passTemplatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/StackLit/ShaderGraph/StackLitPass.template"; - - public HDStackLitSubTarget() - { - displayName = "StackLit"; - } - - public override void Setup(ref TargetSetupContext context) - { - context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); - context.SetDefaultShaderGUI("Rendering.HighDefinition.StackLitGUI"); - context.AddSubShader(SubShaders.StackLit); - context.AddSubShader(SubShaders.StackLitRaytracing); - } - -#region SubShaders - static class SubShaders - { - public static SubShaderDescriptor StackLit = new SubShaderDescriptor() - { - pipelineTag = HDRenderPipeline.k_ShaderTagName, - generatesPreview = true, - passes = new PassCollection - { - { StackLitPasses.ShadowCaster }, - { StackLitPasses.META }, - { StackLitPasses.SceneSelection }, - { StackLitPasses.DepthForwardOnly }, - { StackLitPasses.MotionVectors }, - { StackLitPasses.Distortion, new FieldCondition(HDFields.TransparentDistortion, true) }, - { StackLitPasses.TransparentDepthPrepass, new FieldCondition[]{ - new FieldCondition(HDFields.TransparentDepthPrePass, true), - new FieldCondition(HDFields.DisableSSRTransparent, true) }}, - { StackLitPasses.TransparentDepthPrepass, new FieldCondition[]{ - new FieldCondition(HDFields.TransparentDepthPrePass, true), - new FieldCondition(HDFields.DisableSSRTransparent, false) }}, - { StackLitPasses.TransparentDepthPrepass, new FieldCondition[]{ - new FieldCondition(HDFields.TransparentDepthPrePass, false), - new FieldCondition(HDFields.DisableSSRTransparent, false) }}, - { StackLitPasses.TransparentDepthPostpass, new FieldCondition(HDFields.TransparentDepthPostPass, true) }, - { StackLitPasses.ForwardOnly }, - }, - }; - - public static SubShaderDescriptor StackLitRaytracing = new SubShaderDescriptor() - { - pipelineTag = HDRenderPipeline.k_ShaderTagName, - generatesPreview = false, - passes = new PassCollection - { - { StackLitPasses.RaytracingIndirect, new FieldCondition(Fields.IsPreview, false) }, - { StackLitPasses.RaytracingVisibility, new FieldCondition(Fields.IsPreview, false) }, - { StackLitPasses.RaytracingForward, new FieldCondition(Fields.IsPreview, false) }, - { StackLitPasses.RaytracingGBuffer, new FieldCondition(Fields.IsPreview, false) }, - { StackLitPasses.RaytracingSubSurface, new FieldCondition(Fields.IsPreview, false) }, - }, - }; - } -#endregion - -#region Passes - public static class StackLitPasses - { - public static PassDescriptor META = new PassDescriptor() - { - // Definition - displayName = "META", - referenceName = "SHADERPASS_LIGHT_TRANSPORT", - lightMode = "META", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - pixelPorts = StackLitPortMasks.FragmentMETA, - - // Collections - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.Meta, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.Meta, - pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, - keywords = CoreKeywords.HDBase, - includes = StackLitIncludes.Meta, - }; - - public static PassDescriptor ShadowCaster = new PassDescriptor() - { - // Definition - displayName = "ShadowCaster", - referenceName = "SHADERPASS_SHADOWS", - lightMode = "ShadowCaster", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.VertexPosition, - pixelPorts = StackLitPortMasks.FragmentAlphaDepth, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = StackLitRenderStates.ShadowCaster, - pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, - keywords = CoreKeywords.HDBase, - includes = StackLitIncludes.DepthOnly, - }; - - public static PassDescriptor SceneSelection = new PassDescriptor() - { - // Definition - displayName = "SceneSelectionPass", - referenceName = "SHADERPASS_DEPTH_ONLY", - lightMode = "SceneSelectionPass", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentAlphaDepth, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.SceneSelection, - pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayerEditorSync, - defines = CoreDefines.SceneSelection, - keywords = CoreKeywords.HDBase, - includes = StackLitIncludes.DepthOnly, - }; - - public static PassDescriptor DepthForwardOnly = new PassDescriptor() - { - // // Code path for WRITE_NORMAL_BUFFER - // See StackLit.hlsl:ConvertSurfaceDataToNormalData() - // which ShaderPassDepthOnly uses: we need to add proper interpolators dependencies depending on WRITE_NORMAL_BUFFER. - // In our case WRITE_NORMAL_BUFFER is always enabled here. - // Also, we need to add PixelShaderSlots dependencies for everything potentially used there. - // See AddPixelShaderSlotsForWriteNormalBufferPasses() - - // Definition - displayName = "DepthForwardOnly", - referenceName = "SHADERPASS_DEPTH_ONLY", - lightMode = "DepthForwardOnly", - useInPreview = true, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentDepthMotionVectors, - - // Collections - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.LitFull, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.DepthOnly, - pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, - defines = CoreDefines.DepthMotionVectors, - keywords = CoreKeywords.DepthMotionVectorsNoNormal, - includes = StackLitIncludes.DepthOnly, - }; - - public static PassDescriptor MotionVectors = new PassDescriptor() - { - // Definition - displayName = "MotionVectors", - referenceName = "SHADERPASS_MOTION_VECTORS", - lightMode = "MotionVectors", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentDepthMotionVectors, - - // Collections - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.LitFull, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.MotionVectors, - pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, - defines = CoreDefines.DepthMotionVectors, - keywords = CoreKeywords.DepthMotionVectorsNoNormal, - includes = StackLitIncludes.MotionVectors, - }; - - public static PassDescriptor Distortion = new PassDescriptor() - { - // Definition - displayName = "DistortionVectors", - referenceName = "SHADERPASS_DISTORTION", - lightMode = "DistortionVectors", - useInPreview = true, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentDistortion, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = StackLitRenderStates.Distortion, - pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, - keywords = CoreKeywords.HDBase, - includes = StackLitIncludes.Distortion, - }; - - public static PassDescriptor TransparentDepthPrepass = new PassDescriptor() - { - // Definition - displayName = "TransparentDepthPrepass", - referenceName = "SHADERPASS_DEPTH_ONLY", - lightMode = "TransparentDepthPrepass", - useInPreview = true, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentTransparentDepthPrepass, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = StackLitRenderStates.TransparentDepthPrePass, - pragmas = CorePragmas.DotsInstancedInV2Only, - defines = CoreDefines.TransparentDepthPrepass, - keywords = CoreKeywords.HDBase, - includes = StackLitIncludes.DepthOnly, - }; - - public static PassDescriptor ForwardOnly = new PassDescriptor() - { - // Definition - displayName = "ForwardOnly", - referenceName = "SHADERPASS_FORWARD", - lightMode = "ForwardOnly", - useInPreview = true, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentForward, - - // Collections - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.LitFull, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.Forward, - pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, - defines = CoreDefines.Forward, - keywords = CoreKeywords.Forward, - includes = StackLitIncludes.ForwardOnly, - }; - - public static PassDescriptor TransparentDepthPostpass = new PassDescriptor() - { - // Definition - displayName = "TransparentDepthPostpass", - referenceName = "SHADERPASS_DEPTH_ONLY", - lightMode = "TransparentDepthPostpass", - useInPreview = true, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentTransparentDepthPostpass, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.TransparentDepthPrePostPass, - pragmas = CorePragmas.DotsInstancedInV2Only, - defines = CoreDefines.ShaderGraphRaytracingHigh, - keywords = CoreKeywords.HDBase, - includes = StackLitIncludes.DepthOnly, - }; - - public static PassDescriptor RaytracingIndirect = new PassDescriptor() - { - // Definition - displayName = "IndirectDXR", - referenceName = "SHADERPASS_RAYTRACING_INDIRECT", - lightMode = "IndirectDXR", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentForward, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - pragmas = CorePragmas.RaytracingBasic, - defines = StackLitDefines.RaytracingIndirect, - keywords = CoreKeywords.RaytracingIndirect, - includes = CoreIncludes.Raytracing, - requiredFields = new FieldCollection(){ HDFields.SubShader.StackLit, HDFields.ShaderPass.RaytracingIndirect }, - }; - - public static PassDescriptor RaytracingVisibility = new PassDescriptor() - { - // Definition - displayName = "VisibilityDXR", - referenceName = "SHADERPASS_RAYTRACING_VISIBILITY", - lightMode = "VisibilityDXR", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentForward, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - pragmas = CorePragmas.RaytracingBasic, - defines = StackLitDefines.RaytracingVisibility, - keywords = CoreKeywords.RaytracingVisiblity, - includes = CoreIncludes.Raytracing, - requiredFields = new FieldCollection(){ HDFields.SubShader.StackLit, HDFields.ShaderPass.RaytracingVisibility }, - }; - - public static PassDescriptor RaytracingForward = new PassDescriptor() - { - // Definition - displayName = "ForwardDXR", - referenceName = "SHADERPASS_RAYTRACING_FORWARD", - lightMode = "ForwardDXR", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentForward, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - pragmas = CorePragmas.RaytracingBasic, - defines = StackLitDefines.RaytracingForward, - keywords = CoreKeywords.RaytracingGBufferForward, - includes = CoreIncludes.Raytracing, - requiredFields = new FieldCollection(){ HDFields.SubShader.StackLit, HDFields.ShaderPass.RaytracingForward }, - }; - - public static PassDescriptor RaytracingGBuffer = new PassDescriptor() - { - // Definition - displayName = "GBufferDXR", - referenceName = "SHADERPASS_RAYTRACING_GBUFFER", - lightMode = "GBufferDXR", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentForward, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - pragmas = CorePragmas.RaytracingBasic, - defines = StackLitDefines.RaytracingGBuffer, - keywords = CoreKeywords.RaytracingGBufferForward, - includes = CoreIncludes.Raytracing, - requiredFields = new FieldCollection(){ HDFields.SubShader.StackLit, HDFields.ShaderPass.RayTracingGBuffer }, - }; - - public static PassDescriptor RaytracingSubSurface = new PassDescriptor() - { - //Definition - displayName = "SubSurfaceDXR", - referenceName = "SHADERPASS_RAYTRACING_SUB_SURFACE", - lightMode = "SubSurfaceDXR", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - //Port mask - vertexPorts = StackLitPortMasks.Vertex, - pixelPorts = StackLitPortMasks.FragmentForward, - - //Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - pragmas = CorePragmas.RaytracingBasic, - defines = StackLitDefines.RaytracingGBuffer, - keywords = CoreKeywords.RaytracingGBufferForward, - includes = CoreIncludes.Raytracing, - requiredFields = new FieldCollection(){ HDFields.SubShader.StackLit, HDFields.ShaderPass.RaytracingSubSurface }, - }; - } -#endregion - -#region PortMasks - static class StackLitPortMasks - { - public static int[] Vertex = new int[] - { - StackLitMasterNode.PositionSlotId, - StackLitMasterNode.VertexNormalSlotId, - StackLitMasterNode.VertexTangentSlotId - }; - - public static int[] VertexPosition = new int[] - { - StackLitMasterNode.PositionSlotId, - }; - - public static int[] FragmentMETA = new int[] - { - StackLitMasterNode.BaseColorSlotId, - StackLitMasterNode.NormalSlotId, - StackLitMasterNode.BentNormalSlotId, - StackLitMasterNode.TangentSlotId, - StackLitMasterNode.SubsurfaceMaskSlotId, - StackLitMasterNode.ThicknessSlotId, - StackLitMasterNode.DiffusionProfileHashSlotId, - StackLitMasterNode.IridescenceMaskSlotId, - StackLitMasterNode.IridescenceThicknessSlotId, - StackLitMasterNode.IridescenceCoatFixupTIRSlotId, - StackLitMasterNode.IridescenceCoatFixupTIRClampSlotId, - StackLitMasterNode.SpecularColorSlotId, - StackLitMasterNode.DielectricIorSlotId, - StackLitMasterNode.MetallicSlotId, - StackLitMasterNode.EmissionSlotId, - StackLitMasterNode.SmoothnessASlotId, - StackLitMasterNode.SmoothnessBSlotId, - StackLitMasterNode.AmbientOcclusionSlotId, - StackLitMasterNode.AlphaSlotId, - StackLitMasterNode.AlphaClipThresholdSlotId, - StackLitMasterNode.AnisotropyASlotId, - StackLitMasterNode.AnisotropyBSlotId, - StackLitMasterNode.SpecularAAScreenSpaceVarianceSlotId, - StackLitMasterNode.SpecularAAThresholdSlotId, - StackLitMasterNode.CoatSmoothnessSlotId, - StackLitMasterNode.CoatIorSlotId, - StackLitMasterNode.CoatThicknessSlotId, - StackLitMasterNode.CoatExtinctionSlotId, - StackLitMasterNode.CoatNormalSlotId, - StackLitMasterNode.CoatMaskSlotId, - StackLitMasterNode.LobeMixSlotId, - StackLitMasterNode.HazinessSlotId, - StackLitMasterNode.HazeExtentSlotId, - StackLitMasterNode.HazyGlossMaxDielectricF0SlotId, - StackLitMasterNode.SpecularOcclusionSlotId, - StackLitMasterNode.SOFixupVisibilityRatioThresholdSlotId, - StackLitMasterNode.SOFixupStrengthFactorSlotId, - StackLitMasterNode.SOFixupMaxAddedRoughnessSlotId, - }; - - public static int[] FragmentAlphaDepth = new int[] - { - StackLitMasterNode.AlphaSlotId, - StackLitMasterNode.AlphaClipThresholdSlotId, - StackLitMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentDepthMotionVectors = new int[] - { - StackLitMasterNode.AlphaSlotId, - StackLitMasterNode.AlphaClipThresholdSlotId, - StackLitMasterNode.DepthOffsetSlotId, - // StackLitMasterNode.coat - StackLitMasterNode.CoatSmoothnessSlotId, - StackLitMasterNode.CoatNormalSlotId, - // !StackLitMasterNode.coat - StackLitMasterNode.NormalSlotId, - StackLitMasterNode.LobeMixSlotId, - StackLitMasterNode.SmoothnessASlotId, - StackLitMasterNode.SmoothnessBSlotId, - // StackLitMasterNode.geometricSpecularAA - StackLitMasterNode.SpecularAAScreenSpaceVarianceSlotId, - StackLitMasterNode.SpecularAAThresholdSlotId, - }; - - public static int[] FragmentDistortion = new int[] - { - StackLitMasterNode.AlphaSlotId, - StackLitMasterNode.AlphaClipThresholdSlotId, - StackLitMasterNode.DistortionSlotId, - StackLitMasterNode.DistortionBlurSlotId, - StackLitMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentTransparentDepthPrepass = new int[] - { - StackLitMasterNode.AlphaSlotId, - StackLitMasterNode.AlphaClipThresholdSlotId, - StackLitMasterNode.DepthOffsetSlotId, - StackLitMasterNode.NormalSlotId, - StackLitMasterNode.SmoothnessASlotId, - StackLitMasterNode.SmoothnessBSlotId, - }; - - public static int[] FragmentForward = new int[] - { - StackLitMasterNode.BaseColorSlotId, - StackLitMasterNode.NormalSlotId, - StackLitMasterNode.BentNormalSlotId, - StackLitMasterNode.TangentSlotId, - StackLitMasterNode.SubsurfaceMaskSlotId, - StackLitMasterNode.ThicknessSlotId, - StackLitMasterNode.DiffusionProfileHashSlotId, - StackLitMasterNode.IridescenceMaskSlotId, - StackLitMasterNode.IridescenceThicknessSlotId, - StackLitMasterNode.IridescenceCoatFixupTIRSlotId, - StackLitMasterNode.IridescenceCoatFixupTIRClampSlotId, - StackLitMasterNode.SpecularColorSlotId, - StackLitMasterNode.DielectricIorSlotId, - StackLitMasterNode.MetallicSlotId, - StackLitMasterNode.EmissionSlotId, - StackLitMasterNode.SmoothnessASlotId, - StackLitMasterNode.SmoothnessBSlotId, - StackLitMasterNode.AmbientOcclusionSlotId, - StackLitMasterNode.AlphaSlotId, - StackLitMasterNode.AlphaClipThresholdSlotId, - StackLitMasterNode.AnisotropyASlotId, - StackLitMasterNode.AnisotropyBSlotId, - StackLitMasterNode.SpecularAAScreenSpaceVarianceSlotId, - StackLitMasterNode.SpecularAAThresholdSlotId, - StackLitMasterNode.CoatSmoothnessSlotId, - StackLitMasterNode.CoatIorSlotId, - StackLitMasterNode.CoatThicknessSlotId, - StackLitMasterNode.CoatExtinctionSlotId, - StackLitMasterNode.CoatNormalSlotId, - StackLitMasterNode.CoatMaskSlotId, - StackLitMasterNode.LobeMixSlotId, - StackLitMasterNode.HazinessSlotId, - StackLitMasterNode.HazeExtentSlotId, - StackLitMasterNode.HazyGlossMaxDielectricF0SlotId, - StackLitMasterNode.SpecularOcclusionSlotId, - StackLitMasterNode.SOFixupVisibilityRatioThresholdSlotId, - StackLitMasterNode.SOFixupStrengthFactorSlotId, - StackLitMasterNode.SOFixupMaxAddedRoughnessSlotId, - StackLitMasterNode.LightingSlotId, - StackLitMasterNode.BackLightingSlotId, - StackLitMasterNode.DepthOffsetSlotId, - }; - - public static int[] FragmentTransparentDepthPostpass = new int[] - { - StackLitMasterNode.AlphaSlotId, - StackLitMasterNode.AlphaClipThresholdSlotId, - StackLitMasterNode.DepthOffsetSlotId, - }; - } -#endregion - -#region RenderStates - static class StackLitRenderStates - { - public static RenderStateCollection ShadowCaster = new RenderStateCollection - { - { RenderState.Blend(Blend.One, Blend.Zero) }, - { RenderState.ZWrite(ZWrite.On) }, - { RenderState.ZClip(CoreRenderStates.Uniforms.zClip) }, - { RenderState.ColorMask("ColorMask 0") }, - }; - - public static RenderStateCollection Distortion = new RenderStateCollection - { - { RenderState.Blend(Blend.One, Blend.One, Blend.One, Blend.One), new FieldCondition(HDFields.DistortionAdd, true) }, - { RenderState.Blend(Blend.DstColor, Blend.Zero, Blend.DstAlpha, Blend.Zero), new FieldCondition(HDFields.DistortionMultiply, true) }, - { RenderState.Blend(Blend.One, Blend.Zero, Blend.One, Blend.Zero), new FieldCondition(HDFields.DistortionReplace, true) }, - { RenderState.BlendOp(BlendOp.Add, BlendOp.Add) }, - { RenderState.Cull(CoreRenderStates.Uniforms.cullMode) }, - { RenderState.ZWrite(ZWrite.Off) }, - { RenderState.ZTest(ZTest.Always), new FieldCondition(HDFields.DistortionDepthTest, false) }, - { RenderState.ZTest(ZTest.LEqual), new FieldCondition(HDFields.DistortionDepthTest, true) }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = $"{(int)StencilUsage.DistortionVectors}", - Ref = $"{(int)StencilUsage.DistortionVectors}", - Comp = "Always", - Pass = "Replace", - }) }, - }; - - public static RenderStateCollection TransparentDepthPrePass = new RenderStateCollection - { - { RenderState.Blend(Blend.One, Blend.Zero) }, - { RenderState.Cull(CoreRenderStates.Uniforms.cullMode) }, - { RenderState.ZWrite(ZWrite.On) }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = CoreRenderStates.Uniforms.stencilWriteMaskDepth, - Ref = CoreRenderStates.Uniforms.stencilRefDepth, - Comp = "Always", - Pass = "Replace", - }) }, - }; - } -#endregion - -#region Defines - static class StackLitDefines - { - public static DefineCollection RaytracingForward = new DefineCollection - { - { CoreKeywordDescriptors.Shadow, 0 }, - { RayTracingNode.GetRayTracingKeyword(), 0 }, - { CoreKeywordDescriptors.HasLightloop, 1 }, - }; - - public static DefineCollection RaytracingIndirect = new DefineCollection - { - { CoreKeywordDescriptors.Shadow, 0 }, - { RayTracingNode.GetRayTracingKeyword(), 1 }, - { CoreKeywordDescriptors.HasLightloop, 1 }, - }; - - public static DefineCollection RaytracingGBuffer = new DefineCollection - { - { CoreKeywordDescriptors.Shadow, 0 }, - { RayTracingNode.GetRayTracingKeyword(), 1 }, - }; - - public static DefineCollection RaytracingVisibility = new DefineCollection - { - { RayTracingNode.GetRayTracingKeyword(), 1 }, - }; - - public static DefineCollection RaytracingPathTracing = new DefineCollection - { - { CoreKeywordDescriptors.Shadow, 0 }, - { RayTracingNode.GetRayTracingKeyword(), 0 }, - { CoreKeywordDescriptors.HasLightloop, 1 }, - }; - } -#endregion - -#region Pragmas - static class StackLitPragmas - { - public static PragmaCollection DotsInstancedInV2OnlyRenderingLayer = new PragmaCollection - { - { CorePragmas.Basic }, - { Pragma.MultiCompileInstancing }, - { Pragma.InstancingOptions(InstancingOptions.RenderingLayer) }, - #if ENABLE_HYBRID_RENDERER_V2 - { Pragma.DOTSInstancing }, - { Pragma.InstancingOptions(InstancingOptions.NoLodFade) }, - #endif - }; - - public static PragmaCollection DotsInstancedInV2OnlyRenderingLayerEditorSync = new PragmaCollection - { - { CorePragmas.Basic }, - { Pragma.MultiCompileInstancing }, - { Pragma.InstancingOptions(InstancingOptions.RenderingLayer) }, - { Pragma.EditorSyncCompilation }, - #if ENABLE_HYBRID_RENDERER_V2 - { Pragma.DOTSInstancing }, - { Pragma.InstancingOptions(InstancingOptions.NoLodFade) }, - #endif - }; - } -#endregion - -#region Includes - static class StackLitIncludes - { - const string kSpecularOcclusionDef = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SphericalCapPivot/SpecularOcclusionDef.hlsl"; - const string kStackLitDecalData = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLitDecalData.hlsl"; - - public static IncludeCollection Common = new IncludeCollection - { - { kSpecularOcclusionDef, IncludeLocation.Pregraph }, - { CoreIncludes.CorePregraph }, - { CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph }, - { CoreIncludes.kStackLit, IncludeLocation.Pregraph }, - { CoreIncludes.CoreUtility }, - { CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph }, - { kStackLitDecalData, IncludeLocation.Pregraph }, - { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph }, - }; - - public static IncludeCollection Meta = new IncludeCollection - { - { Common }, - { CoreIncludes.kPassLightTransport, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection DepthOnly = new IncludeCollection - { - { Common }, - { CoreIncludes.kPassDepthOnly, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection MotionVectors = new IncludeCollection - { - { Common }, - { CoreIncludes.kPassMotionVectors, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection Distortion = new IncludeCollection - { - { Common }, - { CoreIncludes.kDisortionVectors, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection ForwardOnly = new IncludeCollection - { - { kSpecularOcclusionDef, IncludeLocation.Pregraph }, - { CoreIncludes.CorePregraph }, - { CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph }, - { CoreIncludes.kLighting, IncludeLocation.Pregraph }, - { CoreIncludes.kLightLoopDef, IncludeLocation.Pregraph }, - { CoreIncludes.kStackLit, IncludeLocation.Pregraph }, - { CoreIncludes.kLightLoop, IncludeLocation.Pregraph }, - { CoreIncludes.CoreUtility }, - { CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph }, - { kStackLitDecalData, IncludeLocation.Pregraph }, - { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph }, - { CoreIncludes.kPassForward, IncludeLocation.Postgraph }, - }; - } -#endregion - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitData.cs new file mode 100644 index 00000000000..c028789ad15 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitData.cs @@ -0,0 +1,277 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class StackLitData : HDTargetData + { + // In StackLit.hlsl engine side + //public enum BaseParametrization + //public enum DualSpecularLobeParametrization + + // Available options for computing Vs (specular occlusion) based on: + // + // baked diffuse visibility (aka "data based AO") orientation + // (ie baked visibility cone (aka "bent visibility cone") orientation) + // := { normal aligned (default bentnormal value), bent normal } + // X + // baked diffuse visibility solid angle inference algo from baked visibility scalar + // (ie baked visibility cone aperture angle or solid angle) + // := { uniform (solid angle measure), cos weighted (projected solid angle measure with cone oriented with normal), + // cos properly weighted wrt bentnormal (projected solid angle measure with cone oriented with bent normal) } + // X + // Vs (aka specular occlusion) calculation algo from baked diffuse values above and BSDF lobe properties + // := {triACE - not tuned to account for bent normal, cone BSDF proxy intersection with bent cone, precise SPTD BSDF proxy lobe integration against the bent cone} } + // + // Note that in Lit SSAO is used with triACE as a clamp value to combine it with the calculations done with the baked AO, + // by doing a min(VsFromTriACE+SSAO, VsFromBakedVisibility). + // (See in particular Lit.hlsl:PostEvaluateBSDF(), MaterialEvaluation.hlsl:GetScreenSpaceAmbientOcclusionMultibounce(), + // where the handed bsdfData.specularOcclusion is data based (baked texture). + // + // In StackLit, we allow control of the SSAO based SO and also the data based one. + // + // Of the algos described above, we can narrow to these combined options: + // { Off, NoBentNormalTriACE, *ConeCone, *SPTD }, where * is any combination of using the normal or the bentnormal with any of 3 choices to interpret the AO + // measure for the cone aperture. + // + // See also _DebugSpecularOcclusion. + public enum SpecularOcclusionBaseMode + { + Off = 0, + DirectFromAO = 1, // TriACE + ConeConeFromBentAO = 2, + SPTDIntegrationOfBentAO = 3, + Custom = 4, + // Custom user port input: For now, we will only have one input used for all lobes and only for data-based SO + // (TODO: Normally would need a custom input per lobe. + // Main rationale is that roughness can change IBL fetch direction and not only BSDF lobe width, and interface normal changes shading reference frame + // hence it also changes the directional relation between the visibility cone and the BSDF lobe.) + } + + public enum SpecularOcclusionBaseModeSimple + { + Off = 0, + DirectFromAO = 1, // TriACE + SPTDIntegrationOfBentAO = 3, + Custom = 4, + } + + public enum SpecularOcclusionAOConeSize + { + UniformAO, + CosWeightedAO, + CosWeightedBentCorrectAO + } + + // This is in case SSAO-based SO method requires it (the SSAO we have doesn't provide a direction) + public enum SpecularOcclusionAOConeDir + { + GeomNormal, + BentNormal, + ShadingNormal + } + + // SO Bent cone fixup is only for methods using visibility cone and only for the data based SO: + public enum SpecularOcclusionConeFixupMethod + { + Off, + BoostBSDFRoughness, + TiltDirectionToGeomNormal, + BoostAndTilt, + } + + // Features: material surface input parametrizations + [SerializeField] + StackLit.BaseParametrization m_BaseParametrization; + public StackLit.BaseParametrization baseParametrization + { + get => m_BaseParametrization; + set => m_BaseParametrization = value; + } + + [SerializeField] + StackLit.DualSpecularLobeParametrization m_DualSpecularLobeParametrization; + public StackLit.DualSpecularLobeParametrization dualSpecularLobeParametrization + { + get => m_DualSpecularLobeParametrization; + set => m_DualSpecularLobeParametrization = value; + } + + // TODO: Change all to enable* ? + // Features: "physical" material type enables + [SerializeField] + bool m_Anisotropy; + public bool anisotropy + { + get => m_Anisotropy; + set => m_Anisotropy = value; + } + + [SerializeField] + bool m_Coat; + public bool coat + { + get => m_Coat; + set => m_Coat = value; + } + + [SerializeField] + bool m_CoatNormal; + public bool coatNormal + { + get => m_CoatNormal; + set => m_CoatNormal = value; + } + + [SerializeField] + bool m_DualSpecularLobe; + public bool dualSpecularLobe + { + get => m_DualSpecularLobe; + set => m_DualSpecularLobe = value; + } + + [SerializeField] + bool m_CapHazinessWrtMetallic = true; + public bool capHazinessWrtMetallic + { + get => m_CapHazinessWrtMetallic; + set => m_CapHazinessWrtMetallic = value; + } + + [SerializeField] + bool m_Iridescence; + public bool iridescence + { + get => m_Iridescence; + set => m_Iridescence = value; + } + + [SerializeField] + SpecularOcclusionBaseMode m_ScreenSpaceSpecularOcclusionBaseMode = SpecularOcclusionBaseMode.DirectFromAO; + public SpecularOcclusionBaseMode screenSpaceSpecularOcclusionBaseMode + { + get => m_ScreenSpaceSpecularOcclusionBaseMode; + set => m_ScreenSpaceSpecularOcclusionBaseMode = value; + } + + [SerializeField] + SpecularOcclusionBaseMode m_DataBasedSpecularOcclusionBaseMode; + public SpecularOcclusionBaseMode dataBasedSpecularOcclusionBaseMode + { + get => m_DataBasedSpecularOcclusionBaseMode; + set => m_DataBasedSpecularOcclusionBaseMode = value; + } + + [SerializeField] + SpecularOcclusionAOConeSize m_ScreenSpaceSpecularOcclusionAOConeSize; // This is still provided to tweak the effect of SSAO on the SO. + public SpecularOcclusionAOConeSize screenSpaceSpecularOcclusionAOConeSize + { + get => m_ScreenSpaceSpecularOcclusionAOConeSize; + set => m_ScreenSpaceSpecularOcclusionAOConeSize = value; + } + + // See SpecularOcclusionAOConeDir for why we need this only for SSAO-based SO: + [SerializeField] + SpecularOcclusionAOConeDir m_ScreenSpaceSpecularOcclusionAOConeDir; + public SpecularOcclusionAOConeDir screenSpaceSpecularOcclusionAOConeDir + { + get => m_ScreenSpaceSpecularOcclusionAOConeDir; + set => m_ScreenSpaceSpecularOcclusionAOConeDir = value; + } + + [SerializeField] + SpecularOcclusionAOConeSize m_DataBasedSpecularOcclusionAOConeSize = SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO; // Only for SO methods using visibility cones (ie ConeCone and SPTD) + public SpecularOcclusionAOConeSize dataBasedSpecularOcclusionAOConeSize + { + get => m_DataBasedSpecularOcclusionAOConeSize; + set => m_DataBasedSpecularOcclusionAOConeSize = value; + } + + // TODO: This was commented out. Can it be removed? + // TODO: this needs to be per lobe, less useful to have custom input. + // [SerializeField] + // bool m_SpecularOcclusionIsCustom; // allow custom input port for SO (replaces the data based one) + // public bool specularOcclusionIsCustom + // { + // get => m_SpecularOcclusionIsCustom; + // set => m_SpecularOcclusionIsCustom = value; + // } + + // SO Bent cone fixup is only for methods using visibility cone and only for the data based SO: + [SerializeField] + SpecularOcclusionConeFixupMethod m_SpecularOcclusionConeFixupMethod; + public SpecularOcclusionConeFixupMethod specularOcclusionConeFixupMethod + { + get => m_SpecularOcclusionConeFixupMethod; + set => m_SpecularOcclusionConeFixupMethod = value; + } + + // Features: Advanced options + // + [SerializeField] + bool m_AnisotropyForAreaLights = true; + public bool anisotropyForAreaLights + { + get => m_AnisotropyForAreaLights; + set => m_AnisotropyForAreaLights = value; + } + + [SerializeField] + bool m_RecomputeStackPerLight; + public bool recomputeStackPerLight + { + get => m_RecomputeStackPerLight; + set => m_RecomputeStackPerLight = value; + } + + [SerializeField] + bool m_HonorPerLightMinRoughness; + public bool honorPerLightMinRoughness + { + get => m_HonorPerLightMinRoughness; + set => m_HonorPerLightMinRoughness = value; + } + + [SerializeField] + bool m_ShadeBaseUsingRefractedAngles; + public bool shadeBaseUsingRefractedAngles + { + get => m_ShadeBaseUsingRefractedAngles; + set => m_ShadeBaseUsingRefractedAngles = value; + } + + [SerializeField] + bool m_Debug; + public bool debug + { + get => m_Debug; + set => m_Debug = value; + } + + [SerializeField] + bool m_DevMode; + public bool devMode + { + get => m_DevMode; + set => m_DevMode = value; + } + + [SerializeField] + bool m_EnergyConservingSpecular = true; + public bool energyConservingSpecular + { + get => m_EnergyConservingSpecular; + set => m_EnergyConservingSpecular = value; + } + + [SerializeField] + bool m_Transmission = false; + public bool transmission + { + get => m_Transmission; + set => m_Transmission = value; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitData.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitData.cs.meta new file mode 100644 index 00000000000..75081aaad00 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae6ee11cda8c17a41b4636741c63150c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitMasterNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitMasterNode.cs deleted file mode 100644 index 95d62f287a8..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitMasterNode.cs +++ /dev/null @@ -1,1824 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Rendering.HighDefinition.Drawing; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEngine.Rendering.HighDefinition; -using UnityEditor.ShaderGraph.Drawing.Inspector; -using UnityEditor.ShaderGraph.Internal; -using UnityEngine.Rendering; -using UnityEditor.Rendering.HighDefinition.ShaderGraph; - -// Include material common properties names -using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; - -//TODOTODO: -// clamp in shader code the ranged() properties -// or let inputs (eg mask?) follow invalid values ? Lit does that (let them free running). -namespace UnityEditor.Rendering.HighDefinition -{ - [Serializable] - [Title("Master", "StackLit (HDRP)")] - [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.StackLitMasterNode")] - [FormerName("UnityEditor.ShaderGraph.StackLitMasterNode")] - class StackLitMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string PositionSlotName = "Vertex Position"; - public const string PositionSlotDisplayName = "Vertex Position"; - - public const string BaseColorSlotName = "BaseColor"; - - public const string NormalSlotName = "Normal"; - public const string BentNormalSlotName = "BentNormal"; - public const string TangentSlotName = "Tangent"; - - public const string SubsurfaceMaskSlotName = "SubsurfaceMask"; - public const string ThicknessSlotName = "Thickness"; - public const string DiffusionProfileHashSlotName = "DiffusionProfileHash"; - public const string DiffusionProfileHashSlotDisplayName = "Diffusion Profile"; - - public const string IridescenceMaskSlotName = "IridescenceMask"; - public const string IridescenceThicknessSlotName = "IridescenceThickness"; - public const string IridescenceThicknessSlotDisplayName = "Iridescence Layer Thickness"; - public const string IridescenceCoatFixupTIRSlotName = "IridescenceCoatFixupTIR"; - public const string IridescenceCoatFixupTIRClampSlotName = "IridescenceCoatFixupTIRClamp"; - - public const string SpecularColorSlotName = "SpecularColor"; - public const string MetallicSlotName = "Metallic"; - public const string DielectricIorSlotName = "DielectricIor"; - - public const string EmissionSlotName = "Emission"; - public const string SmoothnessASlotName = "SmoothnessA"; - public const string SmoothnessBSlotName = "SmoothnessB"; - public const string AmbientOcclusionSlotName = "AmbientOcclusion"; - public const string AlphaSlotName = "Alpha"; - public const string AlphaClipThresholdSlotName = "AlphaClipThreshold"; - public const string AnisotropyASlotName = "AnisotropyA"; - public const string AnisotropyBSlotName = "AnisotropyB"; - public const string SpecularAAScreenSpaceVarianceSlotName = "SpecularAAScreenSpaceVariance"; - public const string SpecularAAThresholdSlotName = "SpecularAAThreshold"; - public const string DistortionSlotName = "Distortion"; - public const string DistortionSlotDisplayName = "Distortion Vector"; - public const string DistortionBlurSlotName = "DistortionBlur"; - - public const string CoatSmoothnessSlotName = "CoatSmoothness"; - public const string CoatIorSlotName = "CoatIor"; - public const string CoatThicknessSlotName = "CoatThickness"; - public const string CoatExtinctionSlotName = "CoatExtinction"; - public const string CoatNormalSlotName = "CoatNormal"; - public const string CoatMaskSlotName = "CoatMask"; - - public const string LobeMixSlotName = "LobeMix"; - public const string HazinessSlotName = "Haziness"; - public const string HazeExtentSlotName = "HazeExtent"; - public const string HazyGlossMaxDielectricF0SlotName = "HazyGlossMaxDielectricF0"; // only valid if above option enabled and we have a basecolor + metallic input parametrization - - public const string BakedGISlotName = "BakedGI"; - public const string BakedBackGISlotName = "BakedBackGI"; - - // TODO: we would ideally need one value per lobe - public const string SpecularOcclusionSlotName = "SpecularOcclusion"; - - public const string SOFixupVisibilityRatioThresholdSlotName = "SOConeFixupVisibilityThreshold"; - public const string SOFixupStrengthFactorSlotName = "SOConeFixupStrength"; - public const string SOFixupMaxAddedRoughnessSlotName = "SOConeFixupMaxAddedRoughness"; - - public const string DepthOffsetSlotName = "DepthOffset"; - - public const string VertexNormalSlotName = "Vertex Normal"; - public const string VertexTangentSlotName = "Vertex Tangent"; - - public const int PositionSlotId = 0; - public const int BaseColorSlotId = 1; - public const int NormalSlotId = 2; - public const int BentNormalSlotId = 3; - public const int TangentSlotId = 4; - public const int SubsurfaceMaskSlotId = 5; - public const int ThicknessSlotId = 6; - public const int DiffusionProfileHashSlotId = 7; - public const int IridescenceMaskSlotId = 8; - public const int IridescenceThicknessSlotId = 9; - public const int SpecularColorSlotId = 10; - public const int DielectricIorSlotId = 11; - public const int MetallicSlotId = 12; - public const int EmissionSlotId = 13; - public const int SmoothnessASlotId = 14; - public const int SmoothnessBSlotId = 15; - public const int AmbientOcclusionSlotId = 16; - public const int AlphaSlotId = 17; - public const int AlphaClipThresholdSlotId = 18; - public const int AnisotropyASlotId = 19; - public const int AnisotropyBSlotId = 20; - public const int SpecularAAScreenSpaceVarianceSlotId = 21; - public const int SpecularAAThresholdSlotId = 22; - public const int DistortionSlotId = 23; - public const int DistortionBlurSlotId = 24; - - public const int CoatSmoothnessSlotId = 25; - public const int CoatIorSlotId = 26; - public const int CoatThicknessSlotId = 27; - public const int CoatExtinctionSlotId = 28; - public const int CoatNormalSlotId = 29; - - public const int LobeMixSlotId = 30; - public const int HazinessSlotId = 31; - public const int HazeExtentSlotId = 32; - public const int HazyGlossMaxDielectricF0SlotId = 33; - - public const int LightingSlotId = 34; - public const int BackLightingSlotId = 35; - - public const int SOFixupVisibilityRatioThresholdSlotId = 36; - public const int SOFixupStrengthFactorSlotId = 37; - public const int SOFixupMaxAddedRoughnessSlotId = 38; - - public const int CoatMaskSlotId = 39; - public const int IridescenceCoatFixupTIRSlotId = 40; - public const int IridescenceCoatFixupTIRClampSlotId = 41; - - public const int DepthOffsetSlotId = 42; - - public const int VertexNormalSlotId = 44; - public const int VertexTangentSlotId = 45; - - // TODO: we would ideally need one value per lobe - public const int SpecularOcclusionSlotId = 43; // for custom (external) SO replacing data based SO (which normally comes from some func of DataBasedSOMode(dataAO, optional bent normal)) - - // In StackLit.hlsl engine side - //public enum BaseParametrization - //public enum DualSpecularLobeParametrization - - // Available options for computing Vs (specular occlusion) based on: - // - // baked diffuse visibility (aka "data based AO") orientation - // (ie baked visibility cone (aka "bent visibility cone") orientation) - // := { normal aligned (default bentnormal value), bent normal } - // X - // baked diffuse visibility solid angle inference algo from baked visibility scalar - // (ie baked visibility cone aperture angle or solid angle) - // := { uniform (solid angle measure), cos weighted (projected solid angle measure with cone oriented with normal), - // cos properly weighted wrt bentnormal (projected solid angle measure with cone oriented with bent normal) } - // X - // Vs (aka specular occlusion) calculation algo from baked diffuse values above and BSDF lobe properties - // := {triACE - not tuned to account for bent normal, cone BSDF proxy intersection with bent cone, precise SPTD BSDF proxy lobe integration against the bent cone} } - // - // Note that in Lit SSAO is used with triACE as a clamp value to combine it with the calculations done with the baked AO, - // by doing a min(VsFromTriACE+SSAO, VsFromBakedVisibility). - // (See in particular Lit.hlsl:PostEvaluateBSDF(), MaterialEvaluation.hlsl:GetScreenSpaceAmbientOcclusionMultibounce(), - // where the handed bsdfData.specularOcclusion is data based (baked texture). - // - // In StackLit, we allow control of the SSAO based SO and also the data based one. - // - // Of the algos described above, we can narrow to these combined options: - // { Off, NoBentNormalTriACE, *ConeCone, *SPTD }, where * is any combination of using the normal or the bentnormal with any of 3 choices to interpret the AO - // measure for the cone aperture. - // - // See also _DebugSpecularOcclusion. - public enum SpecularOcclusionBaseMode - { - Off = 0, - DirectFromAO = 1, // TriACE - ConeConeFromBentAO = 2, - SPTDIntegrationOfBentAO = 3, - Custom = 4, - // Custom user port input: For now, we will only have one input used for all lobes and only for data-based SO - // (TODO: Normally would need a custom input per lobe. - // Main rationale is that roughness can change IBL fetch direction and not only BSDF lobe width, and interface normal changes shading reference frame - // hence it also changes the directional relation between the visibility cone and the BSDF lobe.) - } - - public enum SpecularOcclusionBaseModeSimple - { - Off = 0, - DirectFromAO = 1, // TriACE - SPTDIntegrationOfBentAO = 3, - Custom = 4, - } - - public enum SpecularOcclusionAOConeSize - { - UniformAO, - CosWeightedAO, - CosWeightedBentCorrectAO - } - - // This is in case SSAO-based SO method requires it (the SSAO we have doesn't provide a direction) - public enum SpecularOcclusionAOConeDir - { - GeomNormal, - BentNormal, - ShadingNormal - } - - // SO Bent cone fixup is only for methods using visibility cone and only for the data based SO: - public enum SpecularOcclusionConeFixupMethod - { - Off, - BoostBSDFRoughness, - TiltDirectionToGeomNormal, - BoostAndTilt, - } - - // Don't support Multiply - public enum AlphaModeLit - { - Alpha, - Premultiply, - Additive, - } - - - // Common surface config: - // - [SerializeField] - SurfaceType m_SurfaceType; - - public SurfaceType surfaceType - { - get { return m_SurfaceType; } - set - { - if (m_SurfaceType == value) - return; - - m_SurfaceType = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - AlphaMode m_AlphaMode; - - public AlphaMode alphaMode - { - get { return m_AlphaMode; } - set - { - if (m_AlphaMode == value) - return; - - m_AlphaMode = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_BlendPreserveSpecular = true; - - public ToggleData blendPreserveSpecular - { - get { return new ToggleData(m_BlendPreserveSpecular); } - set - { - if (m_BlendPreserveSpecular == value.isOn) - return; - m_BlendPreserveSpecular = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_TransparencyFog = true; - - public ToggleData transparencyFog - { - get { return new ToggleData(m_TransparencyFog); } - set - { - if (m_TransparencyFog == value.isOn) - return; - m_TransparencyFog = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_Distortion; - - public ToggleData distortion - { - get { return new ToggleData(m_Distortion); } - set - { - if (m_Distortion == value.isOn) - return; - m_Distortion = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - DistortionMode m_DistortionMode; - - public DistortionMode distortionMode - { - get { return m_DistortionMode; } - set - { - if (m_DistortionMode == value) - return; - - m_DistortionMode = value; - UpdateNodeAfterDeserialization(); // TODOTODO: no need, ModificationScope.Graph is enough? - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_DistortionDepthTest = true; - - public ToggleData distortionDepthTest - { - get { return new ToggleData(m_DistortionDepthTest); } - set - { - if (m_DistortionDepthTest == value.isOn) - return; - m_DistortionDepthTest = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaTest; - - public ToggleData alphaTest - { - get { return new ToggleData(m_AlphaTest); } - set - { - if (m_AlphaTest == value.isOn) - return; - m_AlphaTest = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaToMask = false; - - public ToggleData alphaToMask - { - get { return new ToggleData(m_AlphaToMask); } - set - { - if (m_AlphaToMask == value.isOn) - return; - m_AlphaToMask = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaTestDepthPrepass; - - public ToggleData alphaTestDepthPrepass - { - get { return new ToggleData(m_AlphaTestDepthPrepass); } - set - { - if (m_AlphaTestDepthPrepass == value.isOn) - return; - m_AlphaTestDepthPrepass = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaTestDepthPostpass; - - public ToggleData alphaTestDepthPostpass - { - get { return new ToggleData(m_AlphaTestDepthPostpass); } - set - { - if (m_AlphaTestDepthPostpass == value.isOn) - return; - m_AlphaTestDepthPostpass = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - - [SerializeField] - int m_SortPriority; - - public int sortPriority - { - get { return m_SortPriority; } - set - { - if (m_SortPriority == value) - return; - m_SortPriority = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - DoubleSidedMode m_DoubleSidedMode; - - public DoubleSidedMode doubleSidedMode - { - get { return m_DoubleSidedMode; } - set - { - if (m_DoubleSidedMode == value) - return; - - m_DoubleSidedMode = value; - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - NormalDropOffSpace m_NormalDropOffSpace; - public NormalDropOffSpace normalDropOffSpace - { - get { return m_NormalDropOffSpace; } - set - { - if (m_NormalDropOffSpace == value) - return; - - m_NormalDropOffSpace = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - // Features: material surface input parametrizations - // - [SerializeField] - StackLit.BaseParametrization m_BaseParametrization; - - public StackLit.BaseParametrization baseParametrization - { - get { return m_BaseParametrization; } - set - { - if (m_BaseParametrization == value) - return; - - m_BaseParametrization = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_EnergyConservingSpecular = true; - - public ToggleData energyConservingSpecular - { - get { return new ToggleData(m_EnergyConservingSpecular); } - set - { - if (m_EnergyConservingSpecular == value.isOn) - return; - m_EnergyConservingSpecular = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - StackLit.DualSpecularLobeParametrization m_DualSpecularLobeParametrization; - - public StackLit.DualSpecularLobeParametrization dualSpecularLobeParametrization - { - get { return m_DualSpecularLobeParametrization; } - set - { - if (m_DualSpecularLobeParametrization == value) - return; - - m_DualSpecularLobeParametrization = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - // TODOTODO Change all to enable* ? - - // Features: "physical" material type enables - // - [SerializeField] - bool m_Anisotropy; - - public ToggleData anisotropy - { - get { return new ToggleData(m_Anisotropy); } - set - { - if (m_Anisotropy == value.isOn) - return; - m_Anisotropy = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_Coat; - - public ToggleData coat - { - get { return new ToggleData(m_Coat); } - set - { - if (m_Coat == value.isOn) - return; - m_Coat = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_CoatNormal; - - public ToggleData coatNormal - { - get { return new ToggleData(m_CoatNormal); } - set - { - if (m_CoatNormal == value.isOn) - return; - m_CoatNormal = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_DualSpecularLobe; - - public ToggleData dualSpecularLobe - { - get { return new ToggleData(m_DualSpecularLobe); } - set - { - if (m_DualSpecularLobe == value.isOn) - return; - m_DualSpecularLobe = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_CapHazinessWrtMetallic = true; - - public ToggleData capHazinessWrtMetallic - { - get { return new ToggleData(m_CapHazinessWrtMetallic); } - set - { - if (m_CapHazinessWrtMetallic == value.isOn) - return; - m_CapHazinessWrtMetallic = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_Iridescence; - - public ToggleData iridescence - { - get { return new ToggleData(m_Iridescence); } - set - { - if (m_Iridescence == value.isOn) - return; - m_Iridescence = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_SubsurfaceScattering; - - public ToggleData subsurfaceScattering - { - get { return new ToggleData(m_SubsurfaceScattering); } - set - { - if (m_SubsurfaceScattering == value.isOn) - return; - m_SubsurfaceScattering = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_Transmission; - - public ToggleData transmission - { - get { return new ToggleData(m_Transmission); } - set - { - if (m_Transmission == value.isOn) - return; - m_Transmission = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - // Features: other options - // - [SerializeField] - bool m_ReceiveDecals = true; - - public ToggleData receiveDecals - { - get { return new ToggleData(m_ReceiveDecals); } - set - { - if (m_ReceiveDecals == value.isOn) - return; - m_ReceiveDecals = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_ReceiveSSR = true; - - public ToggleData receiveSSR - { - get { return new ToggleData(m_ReceiveSSR); } - set - { - if (m_ReceiveSSR == value.isOn) - return; - m_ReceiveSSR = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_ReceivesSSRTransparent = false; - public ToggleData receiveSSRTransparent - { - get { return new ToggleData(m_ReceivesSSRTransparent); } - set - { - if (m_ReceivesSSRTransparent == value.isOn) - return; - m_ReceivesSSRTransparent = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AddPrecomputedVelocity = false; - - public ToggleData addPrecomputedVelocity - { - get { return new ToggleData(m_AddPrecomputedVelocity); } - set - { - if (m_AddPrecomputedVelocity == value.isOn) - return; - m_AddPrecomputedVelocity = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_GeometricSpecularAA; - - public ToggleData geometricSpecularAA - { - get { return new ToggleData(m_GeometricSpecularAA); } - set - { - if (m_GeometricSpecularAA == value.isOn) - return; - m_GeometricSpecularAA = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - //[SerializeField] - //bool m_SpecularOcclusion; // Main enable - // - //public ToggleData specularOcclusion - //{ - // get { return new ToggleData(m_SpecularOcclusion); } - // set - // { - // if (m_SpecularOcclusion == value.isOn) - // return; - // m_SpecularOcclusion = value.isOn; - // UpdateNodeAfterDeserialization(); - // Dirty(ModificationScope.Topological); - // } - //} - - [SerializeField] - SpecularOcclusionBaseMode m_ScreenSpaceSpecularOcclusionBaseMode = SpecularOcclusionBaseMode.DirectFromAO; - - public SpecularOcclusionBaseMode screenSpaceSpecularOcclusionBaseMode - { - get { return m_ScreenSpaceSpecularOcclusionBaseMode; } - set - { - if (m_ScreenSpaceSpecularOcclusionBaseMode == value) - return; - - m_ScreenSpaceSpecularOcclusionBaseMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - SpecularOcclusionBaseMode m_DataBasedSpecularOcclusionBaseMode; - - public SpecularOcclusionBaseMode dataBasedSpecularOcclusionBaseMode - { - get { return m_DataBasedSpecularOcclusionBaseMode; } - set - { - if (m_DataBasedSpecularOcclusionBaseMode == value) - return; - - m_DataBasedSpecularOcclusionBaseMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - SpecularOcclusionAOConeSize m_ScreenSpaceSpecularOcclusionAOConeSize; // This is still provided to tweak the effect of SSAO on the SO. - - public SpecularOcclusionAOConeSize screenSpaceSpecularOcclusionAOConeSize - { - get { return m_ScreenSpaceSpecularOcclusionAOConeSize; } - set - { - if (m_ScreenSpaceSpecularOcclusionAOConeSize == value) - return; - - m_ScreenSpaceSpecularOcclusionAOConeSize = value; - Dirty(ModificationScope.Graph); - } - } - - // See SpecularOcclusionAOConeDir for why we need this only for SSAO-based SO: - [SerializeField] - SpecularOcclusionAOConeDir m_ScreenSpaceSpecularOcclusionAOConeDir; - - public SpecularOcclusionAOConeDir screenSpaceSpecularOcclusionAOConeDir - { - get { return m_ScreenSpaceSpecularOcclusionAOConeDir; } - set - { - if (m_ScreenSpaceSpecularOcclusionAOConeDir == value) - return; - - m_ScreenSpaceSpecularOcclusionAOConeDir = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - SpecularOcclusionAOConeSize m_DataBasedSpecularOcclusionAOConeSize = SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO; // Only for SO methods using visibility cones (ie ConeCone and SPTD) - - public SpecularOcclusionAOConeSize dataBasedSpecularOcclusionAOConeSize - { - get { return m_DataBasedSpecularOcclusionAOConeSize; } - set - { - if (m_DataBasedSpecularOcclusionAOConeSize == value) - return; - - m_DataBasedSpecularOcclusionAOConeSize = value; - Dirty(ModificationScope.Graph); - } - } - - // TODO: this needs to be per lobe, less useful to have custom input. - //[SerializeField] - //bool m_SpecularOcclusionIsCustom; // allow custom input port for SO (replaces the data based one) - // - //public ToggleData specularOcclusionIsCustom - //{ - // get { return new ToggleData(m_SpecularOcclusionIsCustom); } - // set - // { - // if (m_SpecularOcclusionIsCustom == value.isOn) - // return; - // m_SpecularOcclusionIsCustom = value.isOn; - // UpdateNodeAfterDeserialization(); - // Dirty(ModificationScope.Topological); - // } - //} - - // SO Bent cone fixup is only for methods using visibility cone and only for the data based SO: - [SerializeField] - SpecularOcclusionConeFixupMethod m_SpecularOcclusionConeFixupMethod; - - public SpecularOcclusionConeFixupMethod specularOcclusionConeFixupMethod - { - get { return m_SpecularOcclusionConeFixupMethod; } - set - { - if (m_SpecularOcclusionConeFixupMethod == value) - return; - - m_SpecularOcclusionConeFixupMethod = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - // Features: Advanced options - // - [SerializeField] - bool m_AnisotropyForAreaLights = true; - - public ToggleData anisotropyForAreaLights - { - get { return new ToggleData(m_AnisotropyForAreaLights); } - set - { - if (m_AnisotropyForAreaLights == value.isOn) - return; - m_AnisotropyForAreaLights = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_RecomputeStackPerLight; - - public ToggleData recomputeStackPerLight - { - get { return new ToggleData(m_RecomputeStackPerLight); } - set - { - if (m_RecomputeStackPerLight == value.isOn) - return; - m_RecomputeStackPerLight = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_HonorPerLightMinRoughness; - - public ToggleData honorPerLightMinRoughness - { - get { return new ToggleData(m_HonorPerLightMinRoughness); } - set - { - if (m_HonorPerLightMinRoughness == value.isOn) - return; - m_HonorPerLightMinRoughness = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_ShadeBaseUsingRefractedAngles; - - public ToggleData shadeBaseUsingRefractedAngles - { - get { return new ToggleData(m_ShadeBaseUsingRefractedAngles); } - set - { - if (m_ShadeBaseUsingRefractedAngles == value.isOn) - return; - m_ShadeBaseUsingRefractedAngles = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_Debug; - - public ToggleData debug - { - get { return new ToggleData(m_Debug); } - set - { - if (m_Debug == value.isOn) - return; - m_Debug = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_DevMode; - - public ToggleData devMode - { - get { return new ToggleData(m_DevMode); } - set - { - if (m_DevMode == value.isOn) - return; - m_DevMode = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_overrideBakedGI; - - public ToggleData overrideBakedGI - { - get { return new ToggleData(m_overrideBakedGI); } - set - { - if (m_overrideBakedGI == value.isOn) - return; - m_overrideBakedGI = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_depthOffset; - - public ToggleData depthOffset - { - get { return new ToggleData(m_depthOffset); } - set - { - if (m_depthOffset == value.isOn) - return; - m_depthOffset = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_ZWrite; - - public ToggleData zWrite - { - get { return new ToggleData(m_ZWrite); } - set - { - if (m_ZWrite == value.isOn) - return; - m_ZWrite = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - TransparentCullMode m_transparentCullMode = TransparentCullMode.Back; - public TransparentCullMode transparentCullMode - { - get => m_transparentCullMode; - set - { - if (m_transparentCullMode == value) - return; - - m_transparentCullMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - CompareFunction m_ZTest = CompareFunction.LessEqual; - public CompareFunction zTest - { - get => m_ZTest; - set - { - if (m_ZTest == value) - return; - - m_ZTest = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_SupportLodCrossFade; - - public ToggleData supportLodCrossFade - { - get { return new ToggleData(m_SupportLodCrossFade); } - set - { - if (m_SupportLodCrossFade == value.isOn) - return; - m_SupportLodCrossFade = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Node); - } - } - [SerializeField] - bool m_DOTSInstancing = false; - - public ToggleData dotsInstancing - { - get { return new ToggleData(m_DOTSInstancing); } - set - { - if (m_DOTSInstancing == value.isOn) - return; - - m_DOTSInstancing = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - int m_MaterialNeedsUpdateHash = 0; - - int ComputeMaterialNeedsUpdateHash() - { - int hash = 0; - - hash |= (alphaTest.isOn ? 0 : 1) << 0; - hash |= (receiveSSR.isOn ? 0 : 1) << 2; - hash |= (RequiresSplitLighting() ? 0 : 1) << 3; - - return hash; - } - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public StackLitMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - public override string documentationURL - { - get { return null; } - } - - public bool HasDistortion() - { - return (surfaceType == SurfaceType.Transparent && distortion.isOn); - } - - public static bool SpecularOcclusionModeUsesVisibilityCone(SpecularOcclusionBaseMode soMethod) - { - return (soMethod == SpecularOcclusionBaseMode.ConeConeFromBentAO - || soMethod == SpecularOcclusionBaseMode.SPTDIntegrationOfBentAO); - } - - public bool SpecularOcclusionUsesBentNormal() - { - return (SpecularOcclusionModeUsesVisibilityCone(dataBasedSpecularOcclusionBaseMode) - || (SpecularOcclusionModeUsesVisibilityCone(screenSpaceSpecularOcclusionBaseMode) - && screenSpaceSpecularOcclusionAOConeDir == SpecularOcclusionAOConeDir.BentNormal)); - } - - public bool DataBasedSpecularOcclusionIsCustom() - { - return dataBasedSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.Custom; - } - - public static bool SpecularOcclusionConeFixupMethodModifiesRoughness(SpecularOcclusionConeFixupMethod soConeFixupMethod) - { - return (soConeFixupMethod == SpecularOcclusionConeFixupMethod.BoostBSDFRoughness - || soConeFixupMethod == SpecularOcclusionConeFixupMethod.BoostAndTilt); - } - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "StackLit Master"; - - List validSlots = new List(); - - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionSlotDisplayName, PositionSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(PositionSlotId); - - AddSlot(new NormalMaterialSlot(VertexNormalSlotId, VertexNormalSlotName, VertexNormalSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexNormalSlotId); - - AddSlot(new TangentMaterialSlot(VertexTangentSlotId, VertexTangentSlotName, VertexTangentSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexTangentSlotId); - - RemoveSlot(NormalSlotId); - var coordSpace = CoordinateSpace.Tangent; - switch (m_NormalDropOffSpace) - { - case NormalDropOffSpace.Tangent: - coordSpace = CoordinateSpace.Tangent; - break; - case NormalDropOffSpace.World: - coordSpace = CoordinateSpace.World; - break; - case NormalDropOffSpace.Object: - coordSpace = CoordinateSpace.Object; - break; - } - AddSlot(new NormalMaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, coordSpace, ShaderStageCapability.Fragment)); - validSlots.Add(NormalSlotId); - - AddSlot(new NormalMaterialSlot(BentNormalSlotId, BentNormalSlotName, BentNormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(BentNormalSlotId); - - AddSlot(new TangentMaterialSlot(TangentSlotId, TangentSlotName, TangentSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(TangentSlotId); - - AddSlot(new ColorRGBMaterialSlot(BaseColorSlotId, BaseColorSlotName, BaseColorSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(BaseColorSlotId); - - if (baseParametrization == StackLit.BaseParametrization.BaseMetallic) - { - AddSlot(new Vector1MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(MetallicSlotId); - AddSlot(new Vector1MaterialSlot(DielectricIorSlotId, DielectricIorSlotName, DielectricIorSlotName, SlotType.Input, 1.5f, ShaderStageCapability.Fragment)); - validSlots.Add(DielectricIorSlotId); - } - else if (baseParametrization == StackLit.BaseParametrization.SpecularColor) - { - AddSlot(new ColorRGBMaterialSlot(SpecularColorSlotId, SpecularColorSlotName, SpecularColorSlotName, SlotType.Input, Color.white, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularColorSlotId); - } - - AddSlot(new Vector1MaterialSlot(SmoothnessASlotId, SmoothnessASlotName, SmoothnessASlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(SmoothnessASlotId); - - if (anisotropy.isOn) - { - AddSlot(new Vector1MaterialSlot(AnisotropyASlotId, AnisotropyASlotName, AnisotropyASlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AnisotropyASlotId); - } - - AddSlot(new Vector1MaterialSlot(AmbientOcclusionSlotId, AmbientOcclusionSlotName, AmbientOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AmbientOcclusionSlotId); - - // TODO: we would ideally need one value per lobe - if (DataBasedSpecularOcclusionIsCustom()) - { - AddSlot(new Vector1MaterialSlot(SpecularOcclusionSlotId, SpecularOcclusionSlotName, SpecularOcclusionSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularOcclusionSlotId); - } - - if (SpecularOcclusionUsesBentNormal() && specularOcclusionConeFixupMethod != SpecularOcclusionConeFixupMethod.Off) - { - AddSlot(new Vector1MaterialSlot(SOFixupVisibilityRatioThresholdSlotId, SOFixupVisibilityRatioThresholdSlotName, SOFixupVisibilityRatioThresholdSlotName, SlotType.Input, 0.2f, ShaderStageCapability.Fragment)); - validSlots.Add(SOFixupVisibilityRatioThresholdSlotId); - AddSlot(new Vector1MaterialSlot(SOFixupStrengthFactorSlotId, SOFixupStrengthFactorSlotName, SOFixupStrengthFactorSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SOFixupStrengthFactorSlotId); - - if (SpecularOcclusionConeFixupMethodModifiesRoughness(specularOcclusionConeFixupMethod)) - { - AddSlot(new Vector1MaterialSlot(SOFixupMaxAddedRoughnessSlotId, SOFixupMaxAddedRoughnessSlotName, SOFixupMaxAddedRoughnessSlotName, SlotType.Input, 0.2f, ShaderStageCapability.Fragment)); - validSlots.Add(SOFixupMaxAddedRoughnessSlotId); - } - } - - if (coat.isOn) - { - AddSlot(new Vector1MaterialSlot(CoatSmoothnessSlotId, CoatSmoothnessSlotName, CoatSmoothnessSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(CoatSmoothnessSlotId); - AddSlot(new Vector1MaterialSlot(CoatIorSlotId, CoatIorSlotName, CoatIorSlotName, SlotType.Input, 1.4f, ShaderStageCapability.Fragment)); - validSlots.Add(CoatIorSlotId); - AddSlot(new Vector1MaterialSlot(CoatThicknessSlotId, CoatThicknessSlotName, CoatThicknessSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(CoatThicknessSlotId); - AddSlot(new ColorRGBMaterialSlot(CoatExtinctionSlotId, CoatExtinctionSlotName, CoatExtinctionSlotName, SlotType.Input, Color.white, ColorMode.HDR, ShaderStageCapability.Fragment)); - validSlots.Add(CoatExtinctionSlotId); - - if (coatNormal.isOn) - { - AddSlot(new NormalMaterialSlot(CoatNormalSlotId, CoatNormalSlotName, CoatNormalSlotName, CoordinateSpace.Tangent, ShaderStageCapability.Fragment)); - validSlots.Add(CoatNormalSlotId); - } - - AddSlot(new Vector1MaterialSlot(CoatMaskSlotId, CoatMaskSlotName, CoatMaskSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(CoatMaskSlotId); - } - - if (dualSpecularLobe.isOn) - { - if (dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.Direct) - { - AddSlot(new Vector1MaterialSlot(SmoothnessBSlotId, SmoothnessBSlotName, SmoothnessBSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(SmoothnessBSlotId); - AddSlot(new Vector1MaterialSlot(LobeMixSlotId, LobeMixSlotName, LobeMixSlotName, SlotType.Input, 0.3f, ShaderStageCapability.Fragment)); - validSlots.Add(LobeMixSlotId); - } - else if (dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss) - { - AddSlot(new Vector1MaterialSlot(HazinessSlotId, HazinessSlotName, HazinessSlotName, SlotType.Input, 0.2f, ShaderStageCapability.Fragment)); - validSlots.Add(HazinessSlotId); - AddSlot(new Vector1MaterialSlot(HazeExtentSlotId, HazeExtentSlotName, HazeExtentSlotName, SlotType.Input, 3.0f, ShaderStageCapability.Fragment)); - validSlots.Add(HazeExtentSlotId); - - if (capHazinessWrtMetallic.isOn && baseParametrization == StackLit.BaseParametrization.BaseMetallic) // the later should be an assert really - { - AddSlot(new Vector1MaterialSlot(HazyGlossMaxDielectricF0SlotId, HazyGlossMaxDielectricF0SlotName, HazyGlossMaxDielectricF0SlotName, SlotType.Input, 0.25f, ShaderStageCapability.Fragment)); - validSlots.Add(HazyGlossMaxDielectricF0SlotId); - } - } - - if (anisotropy.isOn) - { - AddSlot(new Vector1MaterialSlot(AnisotropyBSlotId, AnisotropyBSlotName, AnisotropyBSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AnisotropyBSlotId); - } - } - - if (iridescence.isOn) - { - AddSlot(new Vector1MaterialSlot(IridescenceMaskSlotId, IridescenceMaskSlotName, IridescenceMaskSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(IridescenceMaskSlotId); - AddSlot(new Vector1MaterialSlot(IridescenceThicknessSlotId, IridescenceThicknessSlotDisplayName, IridescenceThicknessSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(IridescenceThicknessSlotId); - if (coat.isOn) - { - AddSlot(new Vector1MaterialSlot(IridescenceCoatFixupTIRSlotId, IridescenceCoatFixupTIRSlotName, IridescenceCoatFixupTIRSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(IridescenceCoatFixupTIRSlotId); - AddSlot(new Vector1MaterialSlot(IridescenceCoatFixupTIRClampSlotId, IridescenceCoatFixupTIRClampSlotName, IridescenceCoatFixupTIRClampSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(IridescenceCoatFixupTIRClampSlotId); - } - } - - if (subsurfaceScattering.isOn) - { - AddSlot(new Vector1MaterialSlot(SubsurfaceMaskSlotId, SubsurfaceMaskSlotName, SubsurfaceMaskSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(SubsurfaceMaskSlotId); - } - - if (transmission.isOn) - { - AddSlot(new Vector1MaterialSlot(ThicknessSlotId, ThicknessSlotName, ThicknessSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(ThicknessSlotId); - } - - if (subsurfaceScattering.isOn || transmission.isOn) - { - AddSlot(new DiffusionProfileInputMaterialSlot(DiffusionProfileHashSlotId, DiffusionProfileHashSlotDisplayName, DiffusionProfileHashSlotName, ShaderStageCapability.Fragment)); - validSlots.Add(DiffusionProfileHashSlotId); - } - - AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaSlotId); - - if (alphaTest.isOn) - { - AddSlot(new Vector1MaterialSlot(AlphaClipThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaClipThresholdSlotId); - } - - AddSlot(new ColorRGBMaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Color.black, ColorMode.HDR, ShaderStageCapability.Fragment)); - validSlots.Add(EmissionSlotId); - - if (HasDistortion()) - { - AddSlot(new Vector2MaterialSlot(DistortionSlotId, DistortionSlotDisplayName, DistortionSlotName, SlotType.Input, new Vector2(2.0f, -1.0f), ShaderStageCapability.Fragment)); - validSlots.Add(DistortionSlotId); - - AddSlot(new Vector1MaterialSlot(DistortionBlurSlotId, DistortionBlurSlotName, DistortionBlurSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(DistortionBlurSlotId); - } - - if (geometricSpecularAA.isOn) - { - AddSlot(new Vector1MaterialSlot(SpecularAAScreenSpaceVarianceSlotId, SpecularAAScreenSpaceVarianceSlotName, SpecularAAScreenSpaceVarianceSlotName, SlotType.Input, 0.1f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularAAScreenSpaceVarianceSlotId); - - AddSlot(new Vector1MaterialSlot(SpecularAAThresholdSlotId, SpecularAAThresholdSlotName, SpecularAAThresholdSlotName, SlotType.Input, 0.2f, ShaderStageCapability.Fragment)); - validSlots.Add(SpecularAAThresholdSlotId); - } - - if (overrideBakedGI.isOn) - { - AddSlot(new DefaultMaterialSlot(LightingSlotId, BakedGISlotName, BakedGISlotName, ShaderStageCapability.Fragment)); - validSlots.Add(LightingSlotId); - AddSlot(new DefaultMaterialSlot(BackLightingSlotId, BakedBackGISlotName, BakedBackGISlotName, ShaderStageCapability.Fragment)); - validSlots.Add(BackLightingSlotId); - } - - if (depthOffset.isOn) - { - AddSlot(new Vector1MaterialSlot(DepthOffsetSlotId, DepthOffsetSlotName, DepthOffsetSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - validSlots.Add(DepthOffsetSlotId); - } - - RemoveSlotsNameNotMatching(validSlots, true); - } - - public VisualElement CreateSettingsElement() - { - return new StackLitSettingsView(this); - } - - public string renderQueueTag - { - get - { - var renderingPass = surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; - int queue = HDRenderQueue.ChangeType(renderingPass, sortPriority, alphaTest.isOn); - return HDRenderQueue.GetShaderTagValue(queue); - } - } - - public string renderTypeTag => HDRenderTypeTags.HDLitShader.ToString(); - - // Reference for GetConditionalFields - // ------------------------------------------- - // - // Properties (enables etc): - // - // ok+MFD -> material feature define: means we need a predicate, because we will transform it into a #define that match the material feature, shader_feature-defined, that the rest of the shader code uses. - // - // ok+MFD masterNode.baseParametrization --> even though we can just always transfer present fields (check with $SurfaceDescription.*) like specularcolor and metallic, - // we need to translate this into the _MATERIAL_FEATURE_SPECULAR_COLOR define. - // - // ok masterNode.energyConservingSpecular - // - // ~~~~ ok+MFD: these are almost all material features: - // masterNode.anisotropy - // masterNode.coat - // masterNode.coatNormal - // masterNode.dualSpecularLobe - // masterNode.dualSpecularLobeParametrization - // masterNode.capHazinessWrtMetallic -> not a material feature define, as such, we will create a combined predicate for the HazyGlossMaxDielectricF0 slot dependency - // instead of adding a #define in the template... - // masterNode.iridescence - // masterNode.subsurfaceScattering - // masterNode.transmission - // - // ~~~~ ...ok+MFD: these are all material features - // - // ok masterNode.receiveDecals - // ok masterNode.receiveSSR - // ok masterNode.geometricSpecularAA --> check, a way to combine predicates and/or exclude passes: TODOTODO What about WRITE_NORMAL_BUFFER passes ? (ie smoothness) - // ok masterNode.specularOcclusion --> no use for it though! see comments. - // - // ~~~~ ok+D: these require translation to defines also... - // - // masterNode.anisotropyForAreaLights - // masterNode.recomputeStackPerLight - // masterNode.shadeBaseUsingRefractedAngles - // masterNode.debug - - // Inputs: Most inputs don't need a specific predicate in addition to the "present field predicate", ie the $SurfaceDescription.*, - // but in some special cases we check connectivity to avoid processing the default value for nothing... - // (see specular occlusion with _MASKMAP and _BENTNORMALMAP in LitData, or _TANGENTMAP, _BENTNORMALMAP, etc. which act a bit like that - // although they also avoid sampling in that case, but default tiny texture map sampling isn't a big hit since they are all cached once - // a default "unityTexWhite" is sampled, it is cached for everyone defaulting to white...) - // - // ok+ means there's a specific additional predicate - // - // ok masterNode.BaseColorSlotId - // ok masterNode.NormalSlotId - // - // ok+ masterNode.BentNormalSlotId --> Dependency of the predicate on IsSlotConnected avoids processing even if the slots - // ok+ masterNode.TangentSlotId are always there so any pass that declares its use in PixelShaderSlots will have the field in SurfaceDescription, - // but it's not necessarily useful (if slot isnt connected, waste processing on potentially static expressions if - // shader compiler cant optimize...and even then, useless to have static override value for those.) - // - // TODOTODO: Note you could have the same argument for NormalSlot (which we dont exclude with a predicate). - // Also and anyways, the compiler is smart enough not to do the TS to WS matrix multiply on a (0,0,1) vector. - // - // ok+ masterNode.CoatNormalSlotId -> we already have a "material feature" coat normal map so can use that instead, although using that former, we assume the coat normal slot - // will be there, but it's ok, we can #ifdef the code on the material feature define, and use the $SurfaceDescription.CoatNormal predicate - // for the actual assignment, - // although for that one we could again - // use the "connected" condition like for tangent and bentnormal - // - // The following are all ok, no need beyond present field predicate, ie $SurfaceDescription.*, - // except special cases where noted - // - // ok masterNode.SubsurfaceMaskSlotId - // ok masterNode.ThicknessSlotId - // ok masterNode.DiffusionProfileHashSlotId - // ok masterNode.IridescenceMaskSlotId - // ok masterNode.IridescenceThicknessSlotId - // ok masterNode.SpecularColorSlotId - // ok masterNode.DielectricIorSlotId - // ok masterNode.MetallicSlotId - // ok masterNode.EmissionSlotId - // ok masterNode.SmoothnessASlotId - // ok masterNode.SmoothnessBSlotId - // ok+ masterNode.AmbientOcclusionSlotId -> defined a specific predicate, but not used, see StackLitData. - // ok masterNode.AlphaSlotId - // ok masterNode.AlphaClipThresholdSlotId - // ok masterNode.AnisotropyASlotId - // ok masterNode.AnisotropyBSlotId - // ok masterNode.SpecularAAScreenSpaceVarianceSlotId - // ok masterNode.SpecularAAThresholdSlotId - // ok masterNode.CoatSmoothnessSlotId - // ok masterNode.CoatIorSlotId - // ok masterNode.CoatThicknessSlotId - // ok masterNode.CoatExtinctionSlotId - // ok masterNode.LobeMixSlotId - // ok masterNode.HazinessSlotId - // ok masterNode.HazeExtentSlotId - // ok masterNode.HazyGlossMaxDielectricF0SlotId -> No need for a predicate, the needed predicate is the combined (capHazinessWrtMetallic + HazyGlossMaxDielectricF0) - // "leaking case": if the 2 are true, but we're not in metallic mode, the capHazinessWrtMetallic property is wrong, - // that means the master node is really misconfigured, spew an error, should never happen... - // If it happens, it's because we forgot UpdateNodeAfterDeserialization() call when modifying the capHazinessWrtMetallic or baseParametrization - // properties, maybe through debug etc. - // - // ok masterNode.DistortionSlotId -> Warning: peculiarly, instead of using $SurfaceDescription.Distortion and DistortionBlur, - // ok masterNode.DistortionBlurSlotId we do an #if (SHADERPASS == SHADERPASS_DISTORTION) in the template, instead of - // relying on other passed NOT to include the DistortionSlotId in their PixelShaderSlots!! - - // Other to deal with, and - // Common between Lit and StackLit: - // - // doubleSidedMode, alphaTest, receiveDecals, - // surfaceType, alphaMode, blendPreserveSpecular, transparencyFog, - // distortion, distortionMode, distortionDepthTest, - // sortPriority (int) - // geometricSpecularAA, energyConservingSpecular, specularOcclusion - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - var ambientOcclusionSlot = FindSlot(AmbientOcclusionSlotId); - - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PositionSlotId) || - IsSlotConnected(VertexNormalSlotId) || - IsSlotConnected(VertexTangentSlotId)), - new ConditionalField(Fields.GraphPixel, true), - - // Surface Type - new ConditionalField(Fields.SurfaceOpaque, surfaceType == SurfaceType.Opaque), - new ConditionalField(Fields.SurfaceTransparent, surfaceType != SurfaceType.Opaque), - - // Structs - new ConditionalField(HDStructFields.FragInputs.IsFrontFace,doubleSidedMode != DoubleSidedMode.Disabled && - !pass.Equals(HDStackLitSubTarget.StackLitPasses.MotionVectors)), - - // Material - new ConditionalField(HDFields.Anisotropy, anisotropy.isOn), - new ConditionalField(HDFields.Coat, coat.isOn), - new ConditionalField(HDFields.CoatMask, coat.isOn && pass.pixelPorts.Contains(CoatMaskSlotId) && - (IsSlotConnected(CoatMaskSlotId) || - (FindSlot(CoatMaskSlotId).value != 0.0f && - FindSlot(CoatMaskSlotId).value != 1.0f))), - new ConditionalField(HDFields.CoatMaskZero, coat.isOn && pass.pixelPorts.Contains(CoatMaskSlotId) && - FindSlot(CoatMaskSlotId).value == 0.0f), - new ConditionalField(HDFields.CoatMaskOne, coat.isOn && pass.pixelPorts.Contains(CoatMaskSlotId) && - FindSlot(CoatMaskSlotId).value == 1.0f), - new ConditionalField(HDFields.CoatNormal, coatNormal.isOn && pass.pixelPorts.Contains(CoatNormalSlotId)), - new ConditionalField(HDFields.Iridescence, iridescence.isOn), - new ConditionalField(HDFields.SubsurfaceScattering, subsurfaceScattering.isOn && surfaceType != SurfaceType.Transparent), - new ConditionalField(HDFields.Transmission, transmission.isOn), - new ConditionalField(HDFields.DualSpecularLobe, dualSpecularLobe.isOn), - - // Normal Drop Off Space - new ConditionalField(Fields.NormalDropOffOS, normalDropOffSpace == NormalDropOffSpace.Object), - new ConditionalField(Fields.NormalDropOffTS, normalDropOffSpace == NormalDropOffSpace.Tangent), - new ConditionalField(Fields.NormalDropOffWS, normalDropOffSpace == NormalDropOffSpace.World), - - // Distortion - new ConditionalField(HDFields.DistortionDepthTest, distortionDepthTest.isOn), - new ConditionalField(HDFields.DistortionAdd, distortionMode == DistortionMode.Add), - new ConditionalField(HDFields.DistortionMultiply, distortionMode == DistortionMode.Multiply), - new ConditionalField(HDFields.DistortionReplace, distortionMode == DistortionMode.Replace), - new ConditionalField(HDFields.TransparentDistortion, surfaceType != SurfaceType.Opaque && distortion.isOn), - - // Transparency - new ConditionalField(HDFields.TransparentDepthPrePass, surfaceType != SurfaceType.Opaque && alphaTestDepthPrepass.isOn), - new ConditionalField(HDFields.TransparentDepthPostPass, surfaceType != SurfaceType.Opaque && alphaTestDepthPrepass.isOn), - - // Base Parametrization - // Even though we can just always transfer the present (check with $SurfaceDescription.*) fields like specularcolor - // and metallic, we still need to know the baseParametrization in the template to translate into the - // _MATERIAL_FEATURE_SPECULAR_COLOR define: - new ConditionalField(HDFields.BaseParamSpecularColor, baseParametrization == StackLit.BaseParametrization.SpecularColor), - - // Dual Specular Lobe Parametrization - new ConditionalField(HDFields.HazyGloss, dualSpecularLobe.isOn && - dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss), - - // Misc - new ConditionalField(Fields.AlphaTest, alphaTest.isOn && pass.pixelPorts.Contains(AlphaClipThresholdSlotId)), - new ConditionalField(HDFields.DoAlphaTest, alphaTest.isOn && pass.pixelPorts.Contains(AlphaClipThresholdSlotId)), - new ConditionalField(Fields.AlphaToMask, alphaTest.isOn && pass.pixelPorts.Contains(AlphaClipThresholdSlotId) && alphaToMask.isOn), - new ConditionalField(HDFields.AlphaFog, surfaceType != SurfaceType.Opaque && transparencyFog.isOn), - new ConditionalField(HDFields.BlendPreserveSpecular, surfaceType != SurfaceType.Opaque && blendPreserveSpecular.isOn), - new ConditionalField(HDFields.EnergyConservingSpecular, energyConservingSpecular.isOn), - new ConditionalField(HDFields.DisableDecals, !receiveDecals.isOn), - new ConditionalField(HDFields.DisableSSR, !receiveSSR.isOn), - new ConditionalField(HDFields.DisableSSRTransparent, !receiveSSRTransparent.isOn), - new ConditionalField(Fields.VelocityPrecomputed, addPrecomputedVelocity.isOn), - new ConditionalField(HDFields.BentNormal, IsSlotConnected(BentNormalSlotId) && - pass.pixelPorts.Contains(BentNormalSlotId)), - new ConditionalField(HDFields.AmbientOcclusion, pass.pixelPorts.Contains(AmbientOcclusionSlotId) && - (IsSlotConnected(AmbientOcclusionSlotId) || - ambientOcclusionSlot.value != ambientOcclusionSlot.defaultValue)), - new ConditionalField(HDFields.Tangent, IsSlotConnected(TangentSlotId) && - pass.pixelPorts.Contains(TangentSlotId)), - new ConditionalField(HDFields.LightingGI, IsSlotConnected(LightingSlotId) && - pass.pixelPorts.Contains(LightingSlotId)), - new ConditionalField(HDFields.BackLightingGI, IsSlotConnected(BackLightingSlotId) && - pass.pixelPorts.Contains(BackLightingSlotId)), - new ConditionalField(HDFields.DepthOffset, depthOffset.isOn && pass.pixelPorts.Contains(DepthOffsetSlotId)), - // Option for baseParametrization == Metallic && DualSpecularLobeParametrization == HazyGloss: - // Again we assume masternode has HazyGlossMaxDielectricF0 which should always be the case - // if capHazinessWrtMetallic.isOn. - new ConditionalField(HDFields.CapHazinessIfNotMetallic, dualSpecularLobe.isOn && - dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss && - capHazinessWrtMetallic.isOn && baseParametrization == StackLit.BaseParametrization.BaseMetallic - && pass.pixelPorts.Contains(HazyGlossMaxDielectricF0SlotId)), - // Note here we combine an "enable"-like predicate and the $SurfaceDescription.(slotname) predicate - // into a single $GeometricSpecularAA pedicate. - // - // ($SurfaceDescription.* predicates are useful to make sure the field is present in the struct in the template. - // The field will be present if both the master node and pass have the slotid, see this set intersection we make - // in GenerateSurfaceDescriptionStruct(), with HDSubShaderUtilities.FindMaterialSlotsOnNode().) - // - // Normally, since the feature enable adds the required slots, only the $SurfaceDescription.* would be required, - // but some passes might not need it and not declare the PixelShaderSlot, or, inversely, the pass might not - // declare it as a way to avoid it. - // - // IE this has also the side effect to disable geometricSpecularAA - even if "on" - for passes that don't explicitly - // advertise these slots(eg for a general feature, with separate "enable" and "field present" predicates, the - // template could take a default value and process it anyway if a feature is "on"). - // - // (Note we can achieve the same results in the template on just single predicates by making defines out of them, - // and using #if defined() && etc) - new ConditionalField(HDFields.GeometricSpecularAA, geometricSpecularAA.isOn && - pass.pixelPorts.Contains(SpecularAAThresholdSlotId) && - pass.pixelPorts.Contains(SpecularAAScreenSpaceVarianceSlotId)), - new ConditionalField(HDFields.SpecularAA, geometricSpecularAA.isOn && - pass.pixelPorts.Contains(SpecularAAThresholdSlotId) && - pass.pixelPorts.Contains(SpecularAAScreenSpaceVarianceSlotId)), - new ConditionalField(HDFields.SpecularOcclusion, screenSpaceSpecularOcclusionBaseMode != SpecularOcclusionBaseMode.Off || - dataBasedSpecularOcclusionBaseMode != SpecularOcclusionBaseMode.Off), - - // Advanced - new ConditionalField(HDFields.AnisotropyForAreaLights, anisotropyForAreaLights.isOn), - new ConditionalField(HDFields.RecomputeStackPerLight, recomputeStackPerLight.isOn), - new ConditionalField(HDFields.HonorPerLightMinRoughness, honorPerLightMinRoughness.isOn), - new ConditionalField(HDFields.ShadeBaseUsingRefractedAngles, shadeBaseUsingRefractedAngles.isOn), - new ConditionalField(HDFields.StackLitDebug, debug.isOn), - - // Screen Space Specular Occlusion Base Mode - new ConditionalField(HDFields.SSSpecularOcclusionBaseModeOff, screenSpaceSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.Off), - new ConditionalField(HDFields.SSSpecularOcclusionBaseModeDirectFromAO, screenSpaceSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.DirectFromAO), - new ConditionalField(HDFields.SSSpecularOcclusionBaseModeConeConeFromBentAO, screenSpaceSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.ConeConeFromBentAO), - new ConditionalField(HDFields.SSSpecularOcclusionBaseModeSPTDIntegrationOfBentAO, screenSpaceSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.SPTDIntegrationOfBentAO), - new ConditionalField(HDFields.SSSpecularOcclusionBaseModeCustom, screenSpaceSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.Custom), - - // Screen Space Specular Occlusion AO Cone Size - new ConditionalField(HDFields.SSSpecularOcclusionAOConeSizeUniformAO, SpecularOcclusionModeUsesVisibilityCone(screenSpaceSpecularOcclusionBaseMode) && - screenSpaceSpecularOcclusionAOConeSize == SpecularOcclusionAOConeSize.UniformAO), - new ConditionalField(HDFields.SSSpecularOcclusionAOConeSizeCosWeightedAO, SpecularOcclusionModeUsesVisibilityCone(screenSpaceSpecularOcclusionBaseMode) && - screenSpaceSpecularOcclusionAOConeSize == SpecularOcclusionAOConeSize.CosWeightedAO), - new ConditionalField(HDFields.SSSpecularOcclusionAOConeSizeCosWeightedBentCorrectAO, SpecularOcclusionModeUsesVisibilityCone(screenSpaceSpecularOcclusionBaseMode) && - screenSpaceSpecularOcclusionAOConeSize == SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO), - - // Screen Space Specular Occlusion AO Cone Dir - new ConditionalField(HDFields.SSSpecularOcclusionAOConeDirGeomNormal, SpecularOcclusionModeUsesVisibilityCone(screenSpaceSpecularOcclusionBaseMode) && - screenSpaceSpecularOcclusionAOConeDir == SpecularOcclusionAOConeDir.GeomNormal), - new ConditionalField(HDFields.SSSpecularOcclusionAOConeDirBentNormal, SpecularOcclusionModeUsesVisibilityCone(screenSpaceSpecularOcclusionBaseMode) && - screenSpaceSpecularOcclusionAOConeDir == SpecularOcclusionAOConeDir.BentNormal), - new ConditionalField(HDFields.SSSpecularOcclusionAOConeDirShadingNormal, SpecularOcclusionModeUsesVisibilityCone(screenSpaceSpecularOcclusionBaseMode) && - screenSpaceSpecularOcclusionAOConeDir == SpecularOcclusionAOConeDir.ShadingNormal), - - // Data Based Specular Occlusion Base Mode - new ConditionalField(HDFields.DataBasedSpecularOcclusionBaseModeOff, dataBasedSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.Off), - new ConditionalField(HDFields.DataBasedSpecularOcclusionBaseModeDirectFromAO, dataBasedSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.DirectFromAO), - new ConditionalField(HDFields.DataBasedSpecularOcclusionBaseModeConeConeFromBentAO, dataBasedSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.ConeConeFromBentAO), - new ConditionalField(HDFields.DataBasedSpecularOcclusionBaseModeSPTDIntegrationOfBentAO, dataBasedSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.SPTDIntegrationOfBentAO), - new ConditionalField(HDFields.DataBasedSpecularOcclusionBaseModeCustom, dataBasedSpecularOcclusionBaseMode == SpecularOcclusionBaseMode.Custom), - - // Data Based Specular Occlusion AO Cone Size - new ConditionalField(HDFields.DataBasedSpecularOcclusionAOConeSizeUniformAO, SpecularOcclusionModeUsesVisibilityCone(dataBasedSpecularOcclusionBaseMode) && - dataBasedSpecularOcclusionAOConeSize == SpecularOcclusionAOConeSize.UniformAO), - new ConditionalField(HDFields.DataBasedSpecularOcclusionAOConeSizeCosWeightedAO, SpecularOcclusionModeUsesVisibilityCone(dataBasedSpecularOcclusionBaseMode) && - dataBasedSpecularOcclusionAOConeSize == SpecularOcclusionAOConeSize.CosWeightedAO), - new ConditionalField(HDFields.DataBasedSpecularOcclusionAOConeSizeCosWeightedBentCorrectAO, SpecularOcclusionModeUsesVisibilityCone(dataBasedSpecularOcclusionBaseMode) && - dataBasedSpecularOcclusionAOConeSize == SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO), - - // Specular Occlusion Cone Fixup Method - new ConditionalField(HDFields.SpecularOcclusionConeFixupMethodOff, SpecularOcclusionUsesBentNormal() && - specularOcclusionConeFixupMethod == SpecularOcclusionConeFixupMethod.Off), - new ConditionalField(HDFields.SpecularOcclusionConeFixupMethodBoostBSDFRoughness, SpecularOcclusionUsesBentNormal() && - specularOcclusionConeFixupMethod == SpecularOcclusionConeFixupMethod.BoostBSDFRoughness), - new ConditionalField(HDFields.SpecularOcclusionConeFixupMethodTiltDirectionToGeomNormal, SpecularOcclusionUsesBentNormal() && - specularOcclusionConeFixupMethod == SpecularOcclusionConeFixupMethod.TiltDirectionToGeomNormal), - new ConditionalField(HDFields.SpecularOcclusionConeFixupMethodBoostAndTilt, SpecularOcclusionUsesBentNormal() && - specularOcclusionConeFixupMethod == SpecularOcclusionConeFixupMethod.BoostAndTilt), - }; - } - - public void ProcessPreviewMaterial(Material material) - { - // Fixup the material settings: - material.SetFloat(kSurfaceType, (int)(SurfaceType)surfaceType); - material.SetFloat(kDoubleSidedNormalMode, (int)doubleSidedMode); - material.SetFloat(kDoubleSidedEnable, doubleSidedMode != DoubleSidedMode.Disabled ? 1.0f : 0.0f); - material.SetFloat(kAlphaCutoffEnabled, alphaTest.isOn ? 1 : 0); - material.SetFloat(kBlendMode, (int)HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode)); - material.SetFloat(kEnableFogOnTransparent, transparencyFog.isOn ? 1.0f : 0.0f); - material.SetFloat(kZTestTransparent, (int)zTest); - material.SetFloat(kTransparentCullMode, (int)transparentCullMode); - material.SetFloat(kZWrite, zWrite.isOn ? 1.0f : 0.0f); - // No sorting priority for shader graph preview - var renderingPass = surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; - material.renderQueue = (int)HDRenderQueue.ChangeType(renderingPass, offset: 0, alphaTest: alphaTest.isOn); - - StackLitGUI.SetupMaterialKeywordsAndPass(material); - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public bool RequiresSplitLighting() - { - return subsurfaceScattering.isOn; - } - - public override object saveContext - { - get - { - int hash = ComputeMaterialNeedsUpdateHash(); - - bool needsUpdate = hash != m_MaterialNeedsUpdateHash; - - if (needsUpdate) - m_MaterialNeedsUpdateHash = hash; - - return new HDSaveContext{ updateMaterials = needsUpdate }; - } - } - - public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) - { - if (debug.isOn) - { - // We have useful debug options in StackLit, so add them always, and let the UI editor (non shadergraph) handle displaying them - // since this is also the editor that controls the keyword switching for the debug mode. - collector.AddShaderProperty(new Vector4ShaderProperty() - { - overrideReferenceName = "_DebugEnvLobeMask", // xyz is environments lights lobe 0 1 2 Enable, w is Enable VLayering - displayName = "_DebugEnvLobeMask", - value = new Vector4(1.0f, 1.0f, 1.0f, 1.0f) - }); - collector.AddShaderProperty(new Vector4ShaderProperty() - { - overrideReferenceName = "_DebugLobeMask", // xyz is analytical dirac lights lobe 0 1 2 Enable", false), - displayName = "_DebugLobeMask", - value = new Vector4(1.0f, 1.0f, 1.0f, 1.0f) - }); - collector.AddShaderProperty(new Vector4ShaderProperty() - { - overrideReferenceName = "_DebugAniso", // x is Hack Enable, w is factor - displayName = "_DebugAniso", - value = new Vector4(1.0f, 0.0f, 0.0f, 1000.0f) - }); - // _DebugSpecularOcclusion: - // - // eg (2,2,1,2) : - // .x = SO method {0 = fromAO, 1 = conecone, 2 = SPTD}, - // .y = bentao algo {0 = uniform, cos, bent cos}, - // .z = use upper visible hemisphere clipping, - // .w = The last component of _DebugSpecularOcclusion controls debug visualization: - // -1 colors the object according to the SO algorithm used, - // and values from 1 to 4 controls what the lighting debug display mode will show when set to show "indirect specular occlusion": - // Since there's not one value in our case, - // 0 will show the object all red to indicate to choose one, 1-4 corresponds to showing - // 1 = coat SO, 2 = base lobe A SO, 3 = base lobe B SO, 4 = shows the result of sampling the SSAO texture (screenSpaceAmbientOcclusion). - collector.AddShaderProperty(new Vector4ShaderProperty() - { - overrideReferenceName = "_DebugSpecularOcclusion", - displayName = "_DebugSpecularOcclusion", - value = new Vector4(2.0f, 2.0f, 1.0f, 2.0f) - }); - } - - // Trunk currently relies on checking material property "_EmissionColor" to allow emissive GI. If it doesn't find that property, or it is black, GI is forced off. - // ShaderGraph doesn't use this property, so currently it inserts a dummy color (white). This dummy color may be removed entirely once the following PR has been merged in trunk: Pull request #74105 - // The user will then need to explicitly disable emissive GI if it is not needed. - // To be able to automatically disable emission based on the ShaderGraph config when emission is black, - // we will need a more general way to communicate this to the engine (not directly tied to a material property). - collector.AddShaderProperty(new ColorShaderProperty() - { - overrideReferenceName = "_EmissionColor", - hidden = true, - value = new Color(1.0f, 1.0f, 1.0f, 1.0f) - }); - - //See SG-ADDITIONALVELOCITY-NOTE - if (addPrecomputedVelocity.isOn) - { - collector.AddShaderProperty(new BooleanShaderProperty - { - value = true, - hidden = true, - overrideReferenceName = kAddPrecomputedVelocity, - }); - } - - // Add all shader properties required by the inspector - HDSubShaderUtilities.AddStencilShaderProperties(collector, RequiresSplitLighting(), surfaceType == SurfaceType.Opaque ? receiveSSR.isOn : receiveSSRTransparent.isOn, receiveSSR.isOn, receiveSSRTransparent.isOn); - HDSubShaderUtilities.AddBlendingStatesShaderProperties( - collector, - surfaceType, - HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode), - sortPriority, - alphaToMask.isOn, - zWrite.isOn, - transparentCullMode, - zTest, - false, - transparencyFog.isOn - ); - HDSubShaderUtilities.AddAlphaCutoffShaderProperties(collector, alphaTest.isOn, false); - HDSubShaderUtilities.AddDoubleSidedProperty(collector, doubleSidedMode); - HDSubShaderUtilities.AddPrePostPassProperties(collector, false, false); - - base.CollectShaderProperties(collector, generationMode); - } - - public bool supportsVirtualTexturing => true; - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitMasterNode.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitMasterNode.cs.meta deleted file mode 100644 index 33efa8ba2f5..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitMasterNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cea496ea923eec14794fe54593117587 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitPass.template b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitPass.template index 0762c756039..3f9b8f0c73a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitPass.template +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitPass.template @@ -309,19 +309,19 @@ Pass $SurfaceDescription.IridescenceThickness: surfaceData.iridescenceThickness = surfaceDescription.IridescenceThickness; $SurfaceDescription.IridescenceCoatFixupTIR: surfaceData.iridescenceCoatFixupTIR = surfaceDescription.IridescenceCoatFixupTIR; $SurfaceDescription.IridescenceCoatFixupTIRClamp: surfaceData.iridescenceCoatFixupTIRClamp = surfaceDescription.IridescenceCoatFixupTIRClamp; - $SurfaceDescription.SpecularColor: surfaceData.specularColor = surfaceDescription.SpecularColor; + $SurfaceDescription.Specular: surfaceData.specularColor = surfaceDescription.Specular; $SurfaceDescription.DielectricIor: surfaceData.dielectricIor = surfaceDescription.DielectricIor; $SurfaceDescription.Metallic: surfaceData.metallic = surfaceDescription.Metallic; - $SurfaceDescription.SmoothnessA: surfaceData.perceptualSmoothnessA = surfaceDescription.SmoothnessA; + $SurfaceDescription.Smoothness: surfaceData.perceptualSmoothnessA = surfaceDescription.Smoothness; $SurfaceDescription.SmoothnessB: surfaceData.perceptualSmoothnessB = surfaceDescription.SmoothnessB; - $SurfaceDescription.AmbientOcclusion: surfaceData.ambientOcclusion = surfaceDescription.AmbientOcclusion; + $SurfaceDescription.Occlusion: surfaceData.ambientOcclusion = surfaceDescription.Occlusion; //TODO: if custom external values are wanted, we would ideally need one SO value per lobe. $SurfaceDescription.SpecularOcclusion: surfaceData.specularOcclusionCustomInput = surfaceDescription.SpecularOcclusion; - $SurfaceDescription.SOConeFixupVisibilityThreshold: surfaceData.soFixupVisibilityRatioThreshold = surfaceDescription.SOConeFixupVisibilityThreshold; - $SurfaceDescription.SOConeFixupStrength: surfaceData.soFixupStrengthFactor = surfaceDescription.SOConeFixupStrength; - $SurfaceDescription.SOConeFixupMaxAddedRoughness: surfaceData.soFixupMaxAddedRoughness = surfaceDescription.SOConeFixupMaxAddedRoughness; + $SurfaceDescription.SOFixupVisibilityRatioThreshold: surfaceData.soFixupVisibilityRatioThreshold = surfaceDescription.SOFixupVisibilityRatioThreshold; + $SurfaceDescription.SOFixupStrengthFactor: surfaceData.soFixupStrengthFactor = surfaceDescription.SOFixupStrengthFactor; + $SurfaceDescription.SOFixupMaxAddedRoughness: surfaceData.soFixupMaxAddedRoughness = surfaceDescription.SOFixupMaxAddedRoughness; - $SurfaceDescription.AnisotropyA: surfaceData.anisotropyA = surfaceDescription.AnisotropyA; + $SurfaceDescription.Anisotropy: surfaceData.anisotropyA = surfaceDescription.Anisotropy; $SurfaceDescription.AnisotropyB: surfaceData.anisotropyB = surfaceDescription.AnisotropyB; $SurfaceDescription.CoatSmoothness: surfaceData.coatPerceptualSmoothness = surfaceDescription.CoatSmoothness; $SurfaceDescription.CoatMask: surfaceData.coatMask = surfaceDescription.CoatMask; @@ -392,7 +392,9 @@ Pass // normal delivered to master node float3 normalSrc = float3(0.0f, 0.0f, 1.0f); - $SurfaceDescription.Normal: normalSrc = surfaceDescription.Normal; + $SurfaceDescription.NormalOS: normalSrc = surfaceDescription.NormalOS; + $SurfaceDescription.NormalTS: normalSrc = surfaceDescription.NormalTS; + $SurfaceDescription.NormalWS: normalSrc = surfaceDescription.NormalWS; // compute world space normal #if _NORMAL_DROPOFF_TS diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSettingsView.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSettingsView.cs deleted file mode 100644 index 7243f56b749..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSettingsView.cs +++ /dev/null @@ -1,1109 +0,0 @@ -using System; -using UnityEditor.UIElements; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEditor.Graphing.Util; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Internal; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEditor.Rendering.HighDefinition; -using UnityEngine.Rendering.HighDefinition; -using UnityEngine.Rendering; - -namespace UnityEditor.Rendering.HighDefinition.Drawing -{ - class StackLitSettingsView : MasterNodeSettingsView - { - StackLitMasterNode m_Node; - - IntegerField m_SortPiorityField; - - Label CreateLabel(string text, int indentLevel) - { - string label = ""; - for (var i = 0; i < indentLevel; i++) - { - label += " "; - } - return new Label(label + text); - } - - public StackLitSettingsView(StackLitMasterNode node) : base(node) - { - m_Node = node; - PropertySheet ps = new PropertySheet(); - - int indentLevel = 0; - ps.Add(new PropertyRow(CreateLabel("Surface Type", indentLevel)), (row) => - { - row.Add(new EnumField(SurfaceType.Opaque), (field) => - { - field.value = m_Node.surfaceType; - field.RegisterValueChangedCallback(ChangeSurfaceType); - }); - }); - - if (m_Node.surfaceType == SurfaceType.Transparent) - { - ++indentLevel; - - // No refraction in StackLit, always show this: - ps.Add(new PropertyRow(CreateLabel("Blending Mode", indentLevel)), (row) => - { - row.Add(new EnumField(StackLitMasterNode.AlphaModeLit.Additive), (field) => - { - field.value = GetAlphaModeLit(m_Node.alphaMode); - field.RegisterValueChangedCallback(ChangeBlendMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Blend Preserves Specular", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.blendPreserveSpecular.isOn; - toggle.OnToggleChanged(ChangeBlendPreserveSpecular); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Fog", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.transparencyFog.isOn; - toggle.OnToggleChanged(ChangeTransparencyFog); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Distortion", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.distortion.isOn; - toggle.OnToggleChanged(ChangeDistortion); - }); - }); - - if (m_Node.distortion.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Distortion Blend Mode", indentLevel)), (row) => - { - row.Add(new EnumField(DistortionMode.Add), (field) => - { - field.value = m_Node.distortionMode; - field.RegisterValueChangedCallback(ChangeDistortionMode); - }); - }); - ps.Add(new PropertyRow(CreateLabel("Distortion Depth Test", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.distortionDepthTest.isOn; - toggle.OnToggleChanged(ChangeDistortionDepthTest); - }); - }); - --indentLevel; - } - - m_SortPiorityField = new IntegerField(); - ps.Add(new PropertyRow(CreateLabel("Sort Priority", indentLevel)), (row) => - { - row.Add(m_SortPiorityField, (field) => - { - field.value = m_Node.sortPriority; - field.RegisterValueChangedCallback(ChangeSortPriority); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Transparent Depth Prepass", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestDepthPrepass.isOn; - toggle.OnToggleChanged(ChangeAlphaTestPrepass); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Transparent Depth Postpass", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTestDepthPostpass.isOn; - toggle.OnToggleChanged(ChangeAlphaTestPostpass); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Depth Write", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.zWrite.isOn; - toggle.OnToggleChanged(ChangeZWrite); - }); - }); - - if (m_Node.doubleSidedMode == DoubleSidedMode.Disabled) - { - ps.Add(new PropertyRow(CreateLabel("Cull Mode", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.transparentCullMode), (e) => - { - e.value = m_Node.transparentCullMode; - e.RegisterValueChangedCallback(ChangeTransparentCullMode); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Depth Test", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.zTest), (e) => - { - e.value = m_Node.zTest; - e.RegisterValueChangedCallback(ChangeZTest); - }); - }); - - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Alpha Clipping", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTest.isOn; - toggle.OnToggleChanged(ChangeAlphaTest); - }); - }); - - if (m_Node.alphaTest.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Alpha to Mask", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaToMask.isOn; - toggle.OnToggleChanged(ChangeAlphaToMask); - }); - }); - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Double-Sided", indentLevel)), (row) => - { - row.Add(new EnumField(DoubleSidedMode.Disabled), (field) => - { - field.value = m_Node.doubleSidedMode; - field.RegisterValueChangedCallback(ChangeDoubleSidedMode); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Fragment Normal Space", indentLevel)), (row) => - { - row.Add(new EnumField(NormalDropOffSpace.Tangent), (field) => - { - field.value = m_Node.normalDropOffSpace; - field.RegisterValueChangedCallback(ChangeSpaceOfNormalDropOffMode); - }); - }); - - // Rest of UI looks like this: - // - // baseParametrization - // energyConservingSpecular - // - // anisotropy - // coat - // coatNormal - // dualSpecularLobe - // dualSpecularLobeParametrization - // capHazinessWrtMetallic - // iridescence - // subsurfaceScattering - // transmission - // - // receiveDecals - // receiveSSR - // addPrecomputedVelocity - // geometricSpecularAA - // specularOcclusion - // - // anisotropyForAreaLights - // recomputeStackPerLight - // shadeBaseUsingRefractedAngles - - // Base parametrization: - - ps.Add(new PropertyRow(CreateLabel("Base Color Parametrization", indentLevel)), (row) => - { - row.Add(new EnumField(StackLit.BaseParametrization.BaseMetallic), (field) => - { - field.value = m_Node.baseParametrization; - field.RegisterValueChangedCallback(ChangeBaseParametrization); - }); - }); - - if (m_Node.baseParametrization == StackLit.BaseParametrization.SpecularColor) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Energy Conserving Specular", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.energyConservingSpecular.isOn; - toggle.OnToggleChanged(ChangeEnergyConservingSpecular); - }); - }); - --indentLevel; - } - - // Material type enables: - ps.Add(new PropertyRow(CreateLabel("Material Core Features", indentLevel)), (row) => {} ); - ++indentLevel; - - ps.Add(new PropertyRow(CreateLabel("Anisotropy", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.anisotropy.isOn; - toggle.OnToggleChanged(ChangeAnisotropy); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Coat", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.coat.isOn; - toggle.OnToggleChanged(ChangeCoat); - }); - }); - - if (m_Node.coat.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Coat Normal", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.coatNormal.isOn; - toggle.OnToggleChanged(ChangeCoatNormal); - }); - }); - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Dual Specular Lobe", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.dualSpecularLobe.isOn; - toggle.OnToggleChanged(ChangeDualSpecularLobe); - }); - }); - - if (m_Node.dualSpecularLobe.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Dual SpecularLobe Parametrization", indentLevel)), (row) => - { - row.Add(new EnumField(StackLit.DualSpecularLobeParametrization.HazyGloss), (field) => - { - field.value = m_Node.dualSpecularLobeParametrization; - field.RegisterValueChangedCallback(ChangeDualSpecularLobeParametrization); - }); - }); - if ((m_Node.baseParametrization == StackLit.BaseParametrization.BaseMetallic) - && (m_Node.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss)) - { - ps.Add(new PropertyRow(CreateLabel("Cap Haziness For Non Metallic", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.capHazinessWrtMetallic.isOn; - toggle.OnToggleChanged(ChangeCapHazinessWrtMetallic); - }); - }); - } - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Iridescence", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.iridescence.isOn; - toggle.OnToggleChanged(ChangeIridescence); - }); - }); - - if (m_Node.surfaceType != SurfaceType.Transparent) - { - ps.Add(new PropertyRow(CreateLabel("Subsurface Scattering", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.subsurfaceScattering.isOn; - toggle.OnToggleChanged(ChangeSubsurfaceScattering); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Transmission", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.transmission.isOn; - toggle.OnToggleChanged(ChangeTransmission); - }); - }); - --indentLevel; // ...Material type enables. - - ps.Add(new PropertyRow(CreateLabel("Receive Decals", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.receiveDecals.isOn; - toggle.OnToggleChanged(ChangeReceiveDecals); - }); - }); - - ps.Add(new PropertyRow(CreateLabel((m_Node.surfaceType == SurfaceType.Transparent) ? "Receive SSR Transparent" : "Receive SSR", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - if (m_Node.surfaceType == SurfaceType.Transparent) - { - toggle.value = m_Node.receiveSSRTransparent.isOn; - toggle.OnToggleChanged(ChangeReceiveSSRTransparent); - } - else - { - toggle.value = m_Node.receiveSSR.isOn; - toggle.OnToggleChanged(ChangeReceiveSSR); - } - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Add Precomputed Velocity", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.addPrecomputedVelocity.isOn; - toggle.OnToggleChanged(ChangeAddPrecomputedVelocity); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Geometric Specular AA", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.geometricSpecularAA.isOn; - toggle.OnToggleChanged(ChangeGeometricSpecularAA); - }); - }); - - //ps.Add(new PropertyRow(CreateLabel("Specular Occlusion (main enable)", indentLevel)), (row) => - //{ - // row.Add(new Toggle(), (toggle) => - // { - // toggle.value = m_Node.specularOcclusion.isOn; - // toggle.OnToggleChanged(ChangeSpecularOcclusion); - // }); - //}); - - // SpecularOcclusion from SSAO - if (m_Node.devMode.isOn) - { - // Only in dev mode do we show controls for SO fed from SSAO: otherwise, we keep the default which is DirectFromAO - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion (from SSAO)", indentLevel)), (row) => - { - row.Add(new EnumField(StackLitMasterNode.SpecularOcclusionBaseMode.DirectFromAO), (field) => - { - field.value = m_Node.screenSpaceSpecularOcclusionBaseMode; - field.RegisterValueChangedCallback(ChangeScreenSpaceSpecularOcclusionBaseMode); - }); - - }); - if (StackLitMasterNode.SpecularOcclusionModeUsesVisibilityCone(m_Node.screenSpaceSpecularOcclusionBaseMode)) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion (SS) AO Cone Weight", indentLevel)), (row) => - { - row.Add(new EnumField(StackLitMasterNode.SpecularOcclusionAOConeSize.CosWeightedAO), (field) => - { - field.value = m_Node.screenSpaceSpecularOcclusionAOConeSize; - field.RegisterValueChangedCallback(ChangeScreenSpaceSpecularOcclusionAOConeSize); - }); - }); - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion (SS) AO Cone Dir", indentLevel)), (row) => - { - row.Add(new EnumField(StackLitMasterNode.SpecularOcclusionAOConeDir.ShadingNormal), (field) => - { - field.value = m_Node.screenSpaceSpecularOcclusionAOConeDir; - field.RegisterValueChangedCallback(ChangeScreenSpaceSpecularOcclusionAOConeDir); - }); - }); - --indentLevel; - } - } - - // SpecularOcclusion from input AO (baked or data-based SO) - { - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion (from input AO)", indentLevel)), (row) => - { - if (m_Node.devMode.isOn) - { - row.Add(new EnumField(StackLitMasterNode.SpecularOcclusionBaseMode.DirectFromAO), (field) => - { - field.value = m_Node.dataBasedSpecularOcclusionBaseMode; - field.RegisterValueChangedCallback(ChangeDataBasedSpecularOcclusionBaseMode); - }); - } - else - { - row.Add(new EnumField(StackLitMasterNode.SpecularOcclusionBaseModeSimple.DirectFromAO), (field) => - { - // In non-dev mode, parse any enum value set to a method not shown in the simple UI as SPTD (highest quality) method: - StackLitMasterNode.SpecularOcclusionBaseModeSimple simpleUIEnumValue = - Enum.TryParse(m_Node.dataBasedSpecularOcclusionBaseMode.ToString(), out StackLitMasterNode.SpecularOcclusionBaseModeSimple parsedValue) ? - parsedValue : StackLitMasterNode.SpecularOcclusionBaseModeSimple.SPTDIntegrationOfBentAO; - field.value = simpleUIEnumValue; - field.RegisterValueChangedCallback(ChangeDataBasedSpecularOcclusionBaseModeSimpleUI); - }); - } - }); - if (StackLitMasterNode.SpecularOcclusionModeUsesVisibilityCone(m_Node.dataBasedSpecularOcclusionBaseMode)) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion AO Cone Weight", indentLevel)), (row) => - { - row.Add(new EnumField(StackLitMasterNode.SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO), (field) => - { - field.value = m_Node.dataBasedSpecularOcclusionAOConeSize; - field.RegisterValueChangedCallback(ChangeDataBasedSpecularOcclusionAOConeSize); - }); - }); - --indentLevel; - } - } - - if (m_Node.SpecularOcclusionUsesBentNormal()) - { - if (m_Node.devMode.isOn) - { - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion Bent Cone Fixup", indentLevel)), (row) => - { - row.Add(new EnumField(StackLitMasterNode.SpecularOcclusionConeFixupMethod.Off), (field) => - { - field.value = m_Node.specularOcclusionConeFixupMethod; - field.RegisterValueChangedCallback(ChangeSpecularOcclusionConeFixupMethod); - }); - }); - } - else - { - // Just show a simple toggle when not in dev mode - ps.Add(new PropertyRow(CreateLabel("Specular Occlusion Bent Cone Fixup", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.specularOcclusionConeFixupMethod != StackLitMasterNode.SpecularOcclusionConeFixupMethod.Off; - toggle.OnToggleChanged(ChangeSpecularOcclusionConeFixupMethodSimpleUI); - }); - }); - } - } - - ps.Add(new PropertyRow(CreateLabel("Support LOD CrossFade", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.supportLodCrossFade.isOn; - toggle.OnToggleChanged(ChangeSupportLODCrossFade); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Advanced Options", indentLevel)), (row) => {} ); - ++indentLevel; - - ps.Add(new PropertyRow(CreateLabel("Anisotropy For Area Lights", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.anisotropyForAreaLights.isOn; - toggle.OnToggleChanged(ChangeAnisotropyForAreaLights); - }); - }); - - // Per Punctual/Directional Lights - { - ps.Add(new PropertyRow(CreateLabel("Per Punctual/Directional Lights:", indentLevel)), (row) => { }); - ++indentLevel; - - if (m_Node.coat.isOn) - { - ps.Add(new PropertyRow(CreateLabel("Base Layer Uses Refracted Angles", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.shadeBaseUsingRefractedAngles.isOn; - toggle.OnToggleChanged(ChangeShadeBaseUsingRefractedAngles); - }); - }); - } - if (m_Node.coat.isOn || m_Node.iridescence.isOn) - { - ps.Add(new PropertyRow(CreateLabel("Recompute Stack & Iridescence", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.recomputeStackPerLight.isOn; - toggle.OnToggleChanged(ChangeRecomputeStackPerLight); - }); - }); - } - ps.Add(new PropertyRow(CreateLabel("Honor Per Light Max Smoothness", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.honorPerLightMinRoughness.isOn; - toggle.OnToggleChanged(ChangeHonorPerLightMinRoughness); - }); - }); - - --indentLevel; - } // Per Punctual/Directional Lights - - // Uncomment to show the dev mode UI: - // - //ps.Add(new PropertyRow(CreateLabel("Enable Dev Mode", indentLevel)), (row) => - //{ - // row.Add(new Toggle(), (toggle) => - // { - // toggle.value = m_Node.devMode.isOn; - // toggle.OnToggleChanged(ChangeDevMode); - // }); - //}); - - if (m_Node.devMode.isOn) - { - ps.Add(new PropertyRow(CreateLabel("Show And Enable StackLit Debugs", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.debug.isOn; - toggle.OnToggleChanged(ChangeDebug); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Override Baked GI", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.overrideBakedGI.isOn; - toggle.OnToggleChanged(ChangeoverrideBakedGI); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Depth Offset", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.depthOffset.isOn; - toggle.OnToggleChanged(ChangeDepthOffset); - }); - }); - - --indentLevel; //...Advanced options - - Add(ps); - Add(GetShaderGUIOverridePropertySheet()); - } - - void ChangeSurfaceType(ChangeEvent evt) - { - if (Equals(m_Node.surfaceType, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Surface Type Change"); - m_Node.surfaceType = (SurfaceType)evt.newValue; - } - - void ChangeDoubleSidedMode(ChangeEvent evt) - { - if (Equals(m_Node.doubleSidedMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Double-Sided Mode Change"); - m_Node.doubleSidedMode = (DoubleSidedMode)evt.newValue; - } - - void ChangeSpaceOfNormalDropOffMode(ChangeEvent evt) - { - if (Equals(m_Node.normalDropOffSpace, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Normal Space Drop-Off Mode Change"); - m_Node.normalDropOffSpace = (NormalDropOffSpace)evt.newValue; - } - - void ChangeBaseParametrization(ChangeEvent evt) - { - if (Equals(m_Node.baseParametrization, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Base Parametrization Change"); - m_Node.baseParametrization = (StackLit.BaseParametrization)evt.newValue; - } - - void ChangeDualSpecularLobeParametrization(ChangeEvent evt) - { - if (Equals(m_Node.dualSpecularLobeParametrization, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Dual Specular Lobe Parametrization Change"); - m_Node.dualSpecularLobeParametrization = (StackLit.DualSpecularLobeParametrization)evt.newValue; - } - - void ChangeBlendMode(ChangeEvent evt) - { - // Make sure the mapping is correct by handling each case. - AlphaMode alphaMode = GetAlphaMode((StackLitMasterNode.AlphaModeLit)evt.newValue); - - if (Equals(m_Node.alphaMode, alphaMode)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Mode Change"); - m_Node.alphaMode = alphaMode; - } - - void ChangeBlendPreserveSpecular(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Blend Preserve Specular Change"); - ToggleData td = m_Node.blendPreserveSpecular; - td.isOn = evt.newValue; - m_Node.blendPreserveSpecular = td; - } - - void ChangeTransparencyFog(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparency Fog Change"); - ToggleData td = m_Node.transparencyFog; - td.isOn = evt.newValue; - m_Node.transparencyFog = td; - } - - void ChangeDistortion(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Change"); - ToggleData td = m_Node.distortion; - td.isOn = evt.newValue; - m_Node.distortion = td; - } - - void ChangeDistortionMode(ChangeEvent evt) - { - if (Equals(m_Node.distortionMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Mode Change"); - m_Node.distortionMode = (DistortionMode)evt.newValue; - } - - void ChangeDistortionDepthTest(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Depth Test Change"); - ToggleData td = m_Node.distortionDepthTest; - td.isOn = evt.newValue; - m_Node.distortionDepthTest = td; - } - - void ChangeSortPriority(ChangeEvent evt) - { - m_Node.sortPriority = HDRenderQueue.ClampsTransparentRangePriority(evt.newValue); - // Force the text to match. - m_SortPiorityField.value = m_Node.sortPriority; - if (Equals(m_Node.sortPriority, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Sort Priority Change"); - } - - void ChangeAlphaTest(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Change"); - ToggleData td = m_Node.alphaTest; - td.isOn = evt.newValue; - m_Node.alphaTest = td; - } - - void ChangeAlphaToMask(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha to Mask Change"); - ToggleData td = m_Node.alphaToMask; - td.isOn = evt.newValue; - m_Node.alphaToMask = td; - } - - void ChangeAlphaTestPrepass(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Prepass Change"); - ToggleData td = m_Node.alphaTestDepthPrepass; - td.isOn = evt.newValue; - m_Node.alphaTestDepthPrepass = td; - } - - void ChangeAlphaTestPostpass(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Postpass Change"); - ToggleData td = m_Node.alphaTestDepthPostpass; - td.isOn = evt.newValue; - m_Node.alphaTestDepthPostpass = td; - } - - void ChangeReceiveDecals(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Receive Decals Change"); - ToggleData td = m_Node.receiveDecals; - td.isOn = evt.newValue; - m_Node.receiveDecals = td; - } - - void ChangeReceiveSSR(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Receive SSR Change"); - ToggleData td = m_Node.receiveSSR; - td.isOn = evt.newValue; - m_Node.receiveSSR = td; - } - void ChangeReceiveSSRTransparent(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Receive SSR Transparent Change"); - ToggleData td = m_Node.receiveSSRTransparent; - td.isOn = evt.newValue; - m_Node.receiveSSR = td; - } - - void ChangeAddPrecomputedVelocity(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Add Precomputed Velocity"); - ToggleData td = m_Node.addPrecomputedVelocity; - td.isOn = evt.newValue; - m_Node.addPrecomputedVelocity = td; - } - - void ChangeGeometricSpecularAA(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Specular AA Change"); - ToggleData td = m_Node.geometricSpecularAA; - td.isOn = evt.newValue; - m_Node.geometricSpecularAA = td; - } - - void ChangeEnergyConservingSpecular(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Energy Conserving Specular Change"); - ToggleData td = m_Node.energyConservingSpecular; - td.isOn = evt.newValue; - m_Node.energyConservingSpecular = td; - } - - void ChangeAnisotropy(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Anisotropy Change"); - ToggleData td = m_Node.anisotropy; - td.isOn = evt.newValue; - m_Node.anisotropy = td; - } - - void ChangeCoat(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Coat Change"); - ToggleData td = m_Node.coat; - td.isOn = evt.newValue; - m_Node.coat = td; - } - - void ChangeCoatNormal(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Coat Normal Change"); - ToggleData td = m_Node.coatNormal; - td.isOn = evt.newValue; - m_Node.coatNormal = td; - } - - void ChangeDualSpecularLobe(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("DualSpecularLobe Change"); - ToggleData td = m_Node.dualSpecularLobe; - td.isOn = evt.newValue; - m_Node.dualSpecularLobe = td; - } - - void ChangeCapHazinessWrtMetallic(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("CapHazinessWrtMetallic Change"); - ToggleData td = m_Node.capHazinessWrtMetallic; - td.isOn = evt.newValue; - m_Node.capHazinessWrtMetallic = td; - } - - void ChangeIridescence(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Iridescence Change"); - ToggleData td = m_Node.iridescence; - td.isOn = evt.newValue; - m_Node.iridescence = td; - } - - void ChangeSubsurfaceScattering(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("SubsurfaceScattering Change"); - ToggleData td = m_Node.subsurfaceScattering; - td.isOn = evt.newValue; - m_Node.subsurfaceScattering = td; - } - - void ChangeTransmission(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Transmission Change"); - ToggleData td = m_Node.transmission; - td.isOn = evt.newValue; - m_Node.transmission = td; - } - - //void ChangeSpecularOcclusion(ChangeEvent evt) - //{ - // m_Node.owner.owner.RegisterCompleteObjectUndo("SpecularOcclusion Change"); - // ToggleData td = m_Node.specularOcclusion; - // td.isOn = evt.newValue; - // m_Node.specularOcclusion = td; - //} - - void ChangeScreenSpaceSpecularOcclusionBaseMode(ChangeEvent evt) - { - if (Equals(m_Node.screenSpaceSpecularOcclusionBaseMode, evt.newValue)) - return; - - if (Equals(evt.newValue, StackLitMasterNode.SpecularOcclusionBaseMode.Custom)) - { - Debug.LogWarning("Custom input not supported for SSAO based specular occlusion."); - // Make sure the UI field doesn't switch and stays in synch with the master node property: - if (evt.currentTarget is EnumField enumField) - { - enumField.value = m_Node.screenSpaceSpecularOcclusionBaseMode; - } - return; - } - - m_Node.owner.owner.RegisterCompleteObjectUndo("ScreenSpaceSpecularOcclusionBaseMode Change"); - m_Node.screenSpaceSpecularOcclusionBaseMode = (StackLitMasterNode.SpecularOcclusionBaseMode)evt.newValue; - } - - void ChangeScreenSpaceSpecularOcclusionAOConeSize(ChangeEvent evt) - { - if (Equals(m_Node.screenSpaceSpecularOcclusionAOConeSize, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("ScreenSpaceSpecularOcclusionAOConeSize Change"); - m_Node.screenSpaceSpecularOcclusionAOConeSize = (StackLitMasterNode.SpecularOcclusionAOConeSize)evt.newValue; - } - - void ChangeScreenSpaceSpecularOcclusionAOConeDir(ChangeEvent evt) - { - if (Equals(m_Node.screenSpaceSpecularOcclusionAOConeDir, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("ScreenSpaceSpecularOcclusionAOConeDir Change"); - m_Node.screenSpaceSpecularOcclusionAOConeDir = (StackLitMasterNode.SpecularOcclusionAOConeDir)evt.newValue; - } - - void ChangeDataBasedSpecularOcclusionBaseMode(ChangeEvent evt) - { - if (Equals(m_Node.dataBasedSpecularOcclusionBaseMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("DataBasedSpecularOcclusionBaseMode Change"); - m_Node.dataBasedSpecularOcclusionBaseMode = (StackLitMasterNode.SpecularOcclusionBaseMode)evt.newValue; - } - - void ChangeDataBasedSpecularOcclusionBaseModeSimpleUI(ChangeEvent evt) - { - // StackLitMasterNode.SpecularOcclusionBaseModeSimple should always be a subset of StackLitMasterNode.SpecularOcclusionBaseMode: - if (Equals(m_Node.dataBasedSpecularOcclusionBaseMode, (StackLitMasterNode.SpecularOcclusionBaseMode) evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("DataBasedSpecularOcclusionBaseMode (simple UI) Change"); - m_Node.dataBasedSpecularOcclusionBaseMode = (StackLitMasterNode.SpecularOcclusionBaseMode)evt.newValue; - } - - void ChangeDataBasedSpecularOcclusionAOConeSize(ChangeEvent evt) - { - if (Equals(m_Node.dataBasedSpecularOcclusionAOConeSize, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("DataBasedSpecularOcclusionAOConeSize Change"); - m_Node.dataBasedSpecularOcclusionAOConeSize = (StackLitMasterNode.SpecularOcclusionAOConeSize)evt.newValue; - } - - void ChangeSpecularOcclusionConeFixupMethod(ChangeEvent evt) - { - if (Equals(m_Node.specularOcclusionConeFixupMethod, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("SpecularOcclusionConeFixupMethod Change"); - m_Node.specularOcclusionConeFixupMethod = (StackLitMasterNode.SpecularOcclusionConeFixupMethod)evt.newValue; - } - - void ChangeSpecularOcclusionConeFixupMethodSimpleUI(ChangeEvent evt) - { - if ( (evt.newValue == false && Equals(m_Node.specularOcclusionConeFixupMethod, StackLitMasterNode.SpecularOcclusionConeFixupMethod.Off)) - || (evt.newValue == true && Equals(m_Node.specularOcclusionConeFixupMethod, StackLitMasterNode.SpecularOcclusionConeFixupMethod.BoostAndTilt)) ) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("SpecularOcclusionConeFixupMethod Change"); - - m_Node.specularOcclusionConeFixupMethod = evt.newValue ? StackLitMasterNode.SpecularOcclusionConeFixupMethod.BoostAndTilt - : StackLitMasterNode.SpecularOcclusionConeFixupMethod.Off; - } - - void ChangeAnisotropyForAreaLights(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("AnisotropyForAreaLights Change"); - ToggleData td = m_Node.anisotropyForAreaLights; - td.isOn = evt.newValue; - m_Node.anisotropyForAreaLights = td; - } - - void ChangeoverrideBakedGI(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("overrideBakedGI Change"); - ToggleData td = m_Node.overrideBakedGI; - td.isOn = evt.newValue; - m_Node.overrideBakedGI = td; - } - - void ChangeRecomputeStackPerLight(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("RecomputeStackPerLight Change"); - ToggleData td = m_Node.recomputeStackPerLight; - td.isOn = evt.newValue; - m_Node.recomputeStackPerLight = td; - } - - void ChangeHonorPerLightMinRoughness(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("HonorPerLightMinRoughness Change"); - ToggleData td = m_Node.honorPerLightMinRoughness; - td.isOn = evt.newValue; - m_Node.honorPerLightMinRoughness = td; - } - - void ChangeShadeBaseUsingRefractedAngles(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("ShadeBaseUsingRefractedAngles Change"); - ToggleData td = m_Node.shadeBaseUsingRefractedAngles; - td.isOn = evt.newValue; - m_Node.shadeBaseUsingRefractedAngles = td; - } - - void ChangeDevMode(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("StackLit DevMode Change"); - ToggleData td = m_Node.devMode; - td.isOn = evt.newValue; - m_Node.devMode = td; - } - - void ChangeDebug(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("StackLit Debug Change"); - ToggleData td = m_Node.debug; - td.isOn = evt.newValue; - m_Node.debug = td; - } - - void ChangeDepthOffset(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("DepthOffset Change"); - ToggleData td = m_Node.depthOffset; - td.isOn = evt.newValue; - m_Node.depthOffset = td; - } - - void ChangeZWrite(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("ZWrite Change"); - ToggleData td = m_Node.zWrite; - td.isOn = evt.newValue; - m_Node.zWrite = td; - } - - void ChangeTransparentCullMode(ChangeEvent evt) - { - if (Equals(m_Node.transparentCullMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparent Cull Mode Change"); - m_Node.transparentCullMode = (TransparentCullMode)evt.newValue; - } - - void ChangeZTest(ChangeEvent evt) - { - if (Equals(m_Node.zTest, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("ZTest Change"); - m_Node.zTest = (CompareFunction)evt.newValue; - } - - void ChangeSupportLODCrossFade(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Support LOD CrossFade Change"); - ToggleData td = m_Node.supportLodCrossFade; - td.isOn = evt.newValue; - m_Node.supportLodCrossFade = td; - } - - public AlphaMode GetAlphaMode(StackLitMasterNode.AlphaModeLit alphaModeLit) - { - switch (alphaModeLit) - { - case StackLitMasterNode.AlphaModeLit.Alpha: - return AlphaMode.Alpha; - case StackLitMasterNode.AlphaModeLit.Premultiply: - return AlphaMode.Premultiply; - case StackLitMasterNode.AlphaModeLit.Additive: - return AlphaMode.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaModeLit); - return AlphaMode.Alpha; - } - - } - } - - public StackLitMasterNode.AlphaModeLit GetAlphaModeLit(AlphaMode alphaMode) - { - switch (alphaMode) - { - case AlphaMode.Alpha: - return StackLitMasterNode.AlphaModeLit.Alpha; - case AlphaMode.Premultiply: - return StackLitMasterNode.AlphaModeLit.Premultiply; - case AlphaMode.Additive: - return StackLitMasterNode.AlphaModeLit.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaMode); - return StackLitMasterNode.AlphaModeLit.Alpha; - } - } - } - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSettingsView.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSettingsView.cs.meta deleted file mode 100644 index 8315539b31c..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSettingsView.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8181fef146d3d7a4ab3a814e8963dbf2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs new file mode 100644 index 00000000000..60919f77fec --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs @@ -0,0 +1,243 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + sealed partial class StackLitSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData + { + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is StackLitMasterNode1 stackLitMasterNode)) + return false; + + // Set data + systemData.surfaceType = (SurfaceType)stackLitMasterNode.m_SurfaceType; + systemData.blendMode = HDSubShaderUtilities.UpgradeLegacyAlphaModeToBlendMode((int)stackLitMasterNode.m_AlphaMode); + // Previous master node wasn't having any renderingPass. Assign it correctly now. + systemData.renderingPass = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; + systemData.alphaTest = stackLitMasterNode.m_AlphaTest; + systemData.sortPriority = stackLitMasterNode.m_SortPriority; + systemData.doubleSidedMode = stackLitMasterNode.m_DoubleSidedMode; + systemData.zWrite = stackLitMasterNode.m_ZWrite; + systemData.transparentCullMode = stackLitMasterNode.m_transparentCullMode; + systemData.zTest = stackLitMasterNode.m_ZTest; + systemData.supportLodCrossFade = stackLitMasterNode.m_SupportLodCrossFade; + systemData.dotsInstancing = stackLitMasterNode.m_DOTSInstancing; + systemData.materialNeedsUpdateHash = stackLitMasterNode.m_MaterialNeedsUpdateHash; + + builtinData.transparencyFog = stackLitMasterNode.m_TransparencyFog; + builtinData.distortion = stackLitMasterNode.m_Distortion; + builtinData.distortionMode = stackLitMasterNode.m_DistortionMode; + builtinData.distortionDepthTest = stackLitMasterNode.m_DistortionDepthTest; + builtinData.addPrecomputedVelocity = stackLitMasterNode.m_AddPrecomputedVelocity; + builtinData.depthOffset = stackLitMasterNode.m_depthOffset; + builtinData.alphaToMask = stackLitMasterNode.m_AlphaToMask; + + lightingData.normalDropOffSpace = stackLitMasterNode.m_NormalDropOffSpace; + lightingData.blendPreserveSpecular = stackLitMasterNode.m_BlendPreserveSpecular; + lightingData.receiveDecals = stackLitMasterNode.m_ReceiveDecals; + lightingData.receiveSSR = stackLitMasterNode.m_ReceiveSSR; + lightingData.receiveSSRTransparent = stackLitMasterNode.m_ReceivesSSRTransparent; + lightingData.subsurfaceScattering = stackLitMasterNode.m_SubsurfaceScattering; + lightingData.overrideBakedGI = stackLitMasterNode.m_overrideBakedGI; + lightingData.specularAA = stackLitMasterNode.m_GeometricSpecularAA; + + stackLitData.transmission = stackLitMasterNode.m_Transmission; + stackLitData.energyConservingSpecular = stackLitMasterNode.m_EnergyConservingSpecular; + stackLitData.baseParametrization = stackLitMasterNode.m_BaseParametrization; + stackLitData.dualSpecularLobeParametrization = stackLitMasterNode.m_DualSpecularLobeParametrization; + stackLitData.anisotropy = stackLitMasterNode.m_Anisotropy; + stackLitData.coat = stackLitMasterNode.m_Coat; + stackLitData.coatNormal = stackLitMasterNode.m_CoatNormal; + stackLitData.dualSpecularLobe = stackLitMasterNode.m_DualSpecularLobe; + stackLitData.capHazinessWrtMetallic = stackLitMasterNode.m_CapHazinessWrtMetallic; + stackLitData.iridescence = stackLitMasterNode.m_Iridescence; + stackLitData.screenSpaceSpecularOcclusionBaseMode = (StackLitData.SpecularOcclusionBaseMode)stackLitMasterNode.m_ScreenSpaceSpecularOcclusionBaseMode; + stackLitData.dataBasedSpecularOcclusionBaseMode = (StackLitData.SpecularOcclusionBaseMode)stackLitMasterNode.m_DataBasedSpecularOcclusionBaseMode; + stackLitData.screenSpaceSpecularOcclusionAOConeSize = (StackLitData.SpecularOcclusionAOConeSize)stackLitMasterNode.m_ScreenSpaceSpecularOcclusionAOConeSize; + stackLitData.screenSpaceSpecularOcclusionAOConeDir = (StackLitData.SpecularOcclusionAOConeDir)stackLitMasterNode.m_ScreenSpaceSpecularOcclusionAOConeDir; + stackLitData.dataBasedSpecularOcclusionAOConeSize = (StackLitData.SpecularOcclusionAOConeSize)stackLitMasterNode.m_DataBasedSpecularOcclusionAOConeSize; + stackLitData.specularOcclusionConeFixupMethod = (StackLitData.SpecularOcclusionConeFixupMethod)stackLitMasterNode.m_SpecularOcclusionConeFixupMethod; + stackLitData.anisotropyForAreaLights = stackLitMasterNode.m_AnisotropyForAreaLights; + stackLitData.recomputeStackPerLight = stackLitMasterNode.m_RecomputeStackPerLight; + stackLitData.honorPerLightMinRoughness = stackLitMasterNode.m_HonorPerLightMinRoughness; + stackLitData.shadeBaseUsingRefractedAngles = stackLitMasterNode.m_ShadeBaseUsingRefractedAngles; + stackLitData.debug = stackLitMasterNode.m_Debug; + stackLitData.devMode = stackLitMasterNode.m_DevMode; + + target.customEditorGUI = stackLitMasterNode.m_OverrideEnabled ? stackLitMasterNode.m_ShaderGUIOverride : ""; + + // Set blockmap + blockMap = new Dictionary(); + blockMap.Add(BlockFields.VertexDescription.Position, StackLitMasterNode1.PositionSlotId); + blockMap.Add(BlockFields.VertexDescription.Normal, StackLitMasterNode1.VertexNormalSlotId); + blockMap.Add(BlockFields.VertexDescription.Tangent, StackLitMasterNode1.VertexTangentSlotId); + + // Handle mapping of Normal block specifically + BlockFieldDescriptor normalBlock; + switch(lightingData.normalDropOffSpace) + { + case NormalDropOffSpace.Object: + normalBlock = BlockFields.SurfaceDescription.NormalOS; + break; + case NormalDropOffSpace.World: + normalBlock = BlockFields.SurfaceDescription.NormalWS; + break; + default: + normalBlock = BlockFields.SurfaceDescription.NormalTS; + break; + } + blockMap.Add(normalBlock, StackLitMasterNode1.NormalSlotId); + + blockMap.Add(HDBlockFields.SurfaceDescription.BentNormal, StackLitMasterNode1.BentNormalSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.Tangent, StackLitMasterNode1.TangentSlotId); + blockMap.Add(BlockFields.SurfaceDescription.BaseColor, StackLitMasterNode1.BaseColorSlotId); + + if (stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic) + { + blockMap.Add(BlockFields.SurfaceDescription.Metallic, StackLitMasterNode1.MetallicSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.DielectricIor, StackLitMasterNode1.DielectricIorSlotId); + } + else if (stackLitData.baseParametrization == StackLit.BaseParametrization.SpecularColor) + { + blockMap.Add(BlockFields.SurfaceDescription.Specular, StackLitMasterNode1.SpecularColorSlotId); + } + + blockMap.Add(BlockFields.SurfaceDescription.Smoothness, StackLitMasterNode1.SmoothnessASlotId); + + if (stackLitData.anisotropy) + { + blockMap.Add(HDBlockFields.SurfaceDescription.Anisotropy, StackLitMasterNode1.AnisotropyASlotId); + } + + blockMap.Add(BlockFields.SurfaceDescription.Occlusion, StackLitMasterNode1.AmbientOcclusionSlotId); + + if (stackLitData.dataBasedSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.Custom) + { + blockMap.Add(HDBlockFields.SurfaceDescription.SpecularOcclusion, StackLitMasterNode1.SpecularOcclusionSlotId); + } + + if (SpecularOcclusionUsesBentNormal(stackLitData) && stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off) + { + blockMap.Add(HDBlockFields.SurfaceDescription.SOFixupVisibilityRatioThreshold, StackLitMasterNode1.SOFixupVisibilityRatioThresholdSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.SOFixupStrengthFactor, StackLitMasterNode1.SOFixupStrengthFactorSlotId); + + if (SpecularOcclusionConeFixupMethodModifiesRoughness(stackLitData.specularOcclusionConeFixupMethod)) + { + blockMap.Add(HDBlockFields.SurfaceDescription.SOFixupMaxAddedRoughness, StackLitMasterNode1.SOFixupMaxAddedRoughnessSlotId); + } + } + + if (stackLitData.coat) + { + blockMap.Add(HDBlockFields.SurfaceDescription.CoatSmoothness, StackLitMasterNode1.CoatSmoothnessSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.CoatIor, StackLitMasterNode1.CoatIorSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.CoatThickness, StackLitMasterNode1.CoatThicknessSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.CoatExtinction, StackLitMasterNode1.CoatExtinctionSlotId); + + if (stackLitData.coatNormal) + { + blockMap.Add(HDBlockFields.SurfaceDescription.CoatNormal, StackLitMasterNode1.CoatNormalSlotId); + } + + blockMap.Add(HDBlockFields.SurfaceDescription.CoatMask, StackLitMasterNode1.CoatMaskSlotId); + } + + if (stackLitData.dualSpecularLobe) + { + if (stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.Direct) + { + blockMap.Add(HDBlockFields.SurfaceDescription.SmoothnessB, StackLitMasterNode1.SmoothnessBSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.LobeMix, StackLitMasterNode1.LobeMixSlotId); + } + else if (stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss) + { + blockMap.Add(HDBlockFields.SurfaceDescription.Haziness, StackLitMasterNode1.HazinessSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.HazeExtent, StackLitMasterNode1.HazeExtentSlotId); + + if (stackLitData.capHazinessWrtMetallic && stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic) // the later should be an assert really + { + blockMap.Add(HDBlockFields.SurfaceDescription.HazyGlossMaxDielectricF0, StackLitMasterNode1.HazyGlossMaxDielectricF0SlotId); + } + } + + if (stackLitData.anisotropy) + { + blockMap.Add(HDBlockFields.SurfaceDescription.AnisotropyB, StackLitMasterNode1.AnisotropyBSlotId); + } + } + + if (stackLitData.iridescence) + { + blockMap.Add(HDBlockFields.SurfaceDescription.IridescenceMask, StackLitMasterNode1.IridescenceMaskSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.IridescenceThickness, StackLitMasterNode1.IridescenceThicknessSlotId); + + if (stackLitData.coat) + { + blockMap.Add(HDBlockFields.SurfaceDescription.IridescenceCoatFixupTIR, StackLitMasterNode1.IridescenceCoatFixupTIRSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.IridescenceCoatFixupTIRClamp, StackLitMasterNode1.IridescenceCoatFixupTIRClampSlotId); + } + } + + if (lightingData.subsurfaceScattering) + { + blockMap.Add(HDBlockFields.SurfaceDescription.SubsurfaceMask, StackLitMasterNode1.SubsurfaceMaskSlotId); + } + + if (stackLitData.transmission) + { + blockMap.Add(HDBlockFields.SurfaceDescription.Thickness, StackLitMasterNode1.ThicknessSlotId); + } + + if (lightingData.subsurfaceScattering || stackLitData.transmission) + { + blockMap.Add(HDBlockFields.SurfaceDescription.DiffusionProfileHash, StackLitMasterNode1.DiffusionProfileHashSlotId); + } + + blockMap.Add(BlockFields.SurfaceDescription.Alpha, StackLitMasterNode1.AlphaSlotId); + + if (systemData.alphaTest) + { + blockMap.Add(BlockFields.SurfaceDescription.AlphaClipThreshold, StackLitMasterNode1.AlphaClipThresholdSlotId); + } + + blockMap.Add(BlockFields.SurfaceDescription.Emission, StackLitMasterNode1.EmissionSlotId); + + if (systemData.surfaceType == SurfaceType.Transparent && builtinData.distortion) + { + blockMap.Add(HDBlockFields.SurfaceDescription.Distortion, StackLitMasterNode1.DistortionSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.DistortionBlur, StackLitMasterNode1.DistortionBlurSlotId); + } + + if (lightingData.specularAA) + { + blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, StackLitMasterNode1.SpecularAAScreenSpaceVarianceSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAThreshold, StackLitMasterNode1.SpecularAAThresholdSlotId); + } + + if (lightingData.overrideBakedGI) + { + blockMap.Add(HDBlockFields.SurfaceDescription.BakedGI, StackLitMasterNode1.LightingSlotId); + blockMap.Add(HDBlockFields.SurfaceDescription.BakedBackGI, StackLitMasterNode1.BackLightingSlotId); + } + + if (builtinData.depthOffset) + { + blockMap.Add(HDBlockFields.SurfaceDescription.DepthOffset, StackLitMasterNode1.DepthOffsetSlotId); + } + + return true; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs.meta new file mode 100644 index 00000000000..99f267d60c2 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fc78ab5e3cde02647aab936f10d6f44a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.cs new file mode 100644 index 00000000000..6ed14f65412 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.cs @@ -0,0 +1,1162 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + //TODO: + // clamp in shader code the ranged() properties + // or let inputs (eg mask?) follow invalid values ? Lit does that (let them free running). + sealed partial class StackLitSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData + { + const string kAssetGuid = "5f7ba34a143e67647b202a662748dae3"; + static string passTemplatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/StackLit/ShaderGraph/StackLitPass.template"; + protected override string customInspector => "Rendering.HighDefinition.StackLitGUI"; + protected override string subTargetAssetGuid => "5f7ba34a143e67647b202a662748dae3"; // StackLitSubTarget.cs + protected override ShaderID shaderID => HDShaderUtils.ShaderID.SG_StackLit; + + public StackLitSubTarget() => displayName = "StackLit"; + + StackLitData m_StackLitData; + + StackLitData IRequiresData.data + { + get => m_StackLitData; + set => m_StackLitData = value; + } + + public StackLitData stackLitData + { + get => m_StackLitData; + set => m_StackLitData = value; + } + + protected override IEnumerable EnumerateSubShaders() + { + yield return SubShaders.StackLit; + yield return SubShaders.StackLitRaytracing; + } + + // Reference for GetFields + // ------------------------------------------- + // + // Properties (enables etc): + // + // ok+MFD -> material feature define: means we need a predicate, because we will transform it into a #define that match the material feature, shader_feature-defined, that the rest of the shader code uses. + // + // ok+MFD masterNode.baseParametrization --> even though we can just always transfer present fields (check with $SurfaceDescription.*) like specularcolor and metallic, + // we need to translate this into the _MATERIAL_FEATURE_SPECULAR_COLOR define. + // + // ok masterNode.energyConservingSpecular + // + // ~~~~ ok+MFD: these are almost all material features: + // masterNode.anisotropy + // masterNode.coat + // masterNode.coatNormal + // masterNode.dualSpecularLobe + // masterNode.dualSpecularLobeParametrization + // masterNode.capHazinessWrtMetallic -> not a material feature define, as such, we will create a combined predicate for the HazyGlossMaxDielectricF0 slot dependency + // instead of adding a #define in the template... + // masterNode.iridescence + // masterNode.subsurfaceScattering + // masterNode.transmission + // + // ~~~~ ...ok+MFD: these are all material features + // + // ok masterNode.receiveDecals + // ok masterNode.receiveSSR + // ok masterNode.geometricSpecularAA --> check, a way to combine predicates and/or exclude passes: TODOTODO What about WRITE_NORMAL_BUFFER passes ? (ie smoothness) + // ok masterNode.specularOcclusion --> no use for it though! see comments. + // + // ~~~~ ok+D: these require translation to defines also... + // + // masterNode.anisotropyForAreaLights + // masterNode.recomputeStackPerLight + // masterNode.shadeBaseUsingRefractedAngles + // masterNode.debug + + // Inputs: Most inputs don't need a specific predicate in addition to the "present field predicate", ie the $SurfaceDescription.*, + // but in some special cases we check connectivity to avoid processing the default value for nothing... + // (see specular occlusion with _MASKMAP and _BENTNORMALMAP in LitData, or _TANGENTMAP, _BENTNORMALMAP, etc. which act a bit like that + // although they also avoid sampling in that case, but default tiny texture map sampling isn't a big hit since they are all cached once + // a default "unityTexWhite" is sampled, it is cached for everyone defaulting to white...) + // + // ok+ means there's a specific additional predicate + // + // ok masterNode.BaseColorSlotId + // ok masterNode.NormalSlotId + // + // ok+ masterNode.BentNormalSlotId --> Dependency of the predicate on IsSlotConnected avoids processing even if the slots + // ok+ masterNode.TangentSlotId are always there so any pass that declares its use in PixelShaderSlots will have the field in SurfaceDescription, + // but it's not necessarily useful (if slot isnt connected, waste processing on potentially static expressions if + // shader compiler cant optimize...and even then, useless to have static override value for those.) + // + // TODOTODO: Note you could have the same argument for NormalSlot (which we dont exclude with a predicate). + // Also and anyways, the compiler is smart enough not to do the TS to WS matrix multiply on a (0,0,1) vector. + // + // ok+ masterNode.CoatNormalSlotId -> we already have a "material feature" coat normal map so can use that instead, although using that former, we assume the coat normal slot + // will be there, but it's ok, we can #ifdef the code on the material feature define, and use the $SurfaceDescription.CoatNormal predicate + // for the actual assignment, + // although for that one we could again + // use the "connected" condition like for tangent and bentnormal + // + // The following are all ok, no need beyond present field predicate, ie $SurfaceDescription.*, + // except special cases where noted + // + // ok masterNode.SubsurfaceMaskSlotId + // ok masterNode.ThicknessSlotId + // ok masterNode.DiffusionProfileHashSlotId + // ok masterNode.IridescenceMaskSlotId + // ok masterNode.IridescenceThicknessSlotId + // ok masterNode.SpecularColorSlotId + // ok masterNode.DielectricIorSlotId + // ok masterNode.MetallicSlotId + // ok masterNode.EmissionSlotId + // ok masterNode.SmoothnessASlotId + // ok masterNode.SmoothnessBSlotId + // ok+ masterNode.AmbientOcclusionSlotId -> defined a specific predicate, but not used, see StackLitData. + // ok masterNode.AlphaSlotId + // ok masterNode.AlphaClipThresholdSlotId + // ok masterNode.AnisotropyASlotId + // ok masterNode.AnisotropyBSlotId + // ok masterNode.SpecularAAScreenSpaceVarianceSlotId + // ok masterNode.SpecularAAThresholdSlotId + // ok masterNode.CoatSmoothnessSlotId + // ok masterNode.CoatIorSlotId + // ok masterNode.CoatThicknessSlotId + // ok masterNode.CoatExtinctionSlotId + // ok masterNode.LobeMixSlotId + // ok masterNode.HazinessSlotId + // ok masterNode.HazeExtentSlotId + // ok masterNode.HazyGlossMaxDielectricF0SlotId -> No need for a predicate, the needed predicate is the combined (capHazinessWrtMetallic + HazyGlossMaxDielectricF0) + // "leaking case": if the 2 are true, but we're not in metallic mode, the capHazinessWrtMetallic property is wrong, + // that means the master node is really misconfigured, spew an error, should never happen... + // If it happens, it's because we forgot UpdateNodeAfterDeserialization() call when modifying the capHazinessWrtMetallic or baseParametrization + // properties, maybe through debug etc. + // + // ok masterNode.DistortionSlotId -> Warning: peculiarly, instead of using $SurfaceDescription.Distortion and DistortionBlur, + // ok masterNode.DistortionBlurSlotId we do an #if (SHADERPASS == SHADERPASS_DISTORTION) in the template, instead of + // relying on other passed NOT to include the DistortionSlotId in their PixelShaderSlots!! + + // Other to deal with, and + // Common between Lit and StackLit: + // + // doubleSidedMode, alphaTest, receiveDecals, + // surfaceType, alphaMode, blendPreserveSpecular, transparencyFog, + // distortion, distortionMode, distortionDepthTest, + // sortPriority (int) + // geometricSpecularAA, energyConservingSpecular, specularOcclusion + + public override void GetFields(ref TargetFieldContext context) + { + base.GetFields(ref context); + AddDistortionFields(ref context); + var descs = context.blocks.Select(x => x.descriptor); + + // StackLit specific properties + context.AddField(HDStructFields.FragInputs.IsFrontFace, systemData.doubleSidedMode != DoubleSidedMode.Disabled && !context.pass.Equals(StackLitSubTarget.StackLitPasses.MotionVectors)); + + // Material + context.AddField(HDFields.Anisotropy, stackLitData.anisotropy); + context.AddField(HDFields.Coat, stackLitData.coat); + context.AddField(HDFields.CoatMask, stackLitData.coat && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.CoatMask) && + descs.Contains(HDBlockFields.SurfaceDescription.CoatMask)); + // context.AddField(HDFields.CoatMaskZero, coat.isOn && pass.pixelBlocks.Contains(CoatMaskSlotId) && + // FindSlot(CoatMaskSlotId).value == 0.0f), + // context.AddField(HDFields.CoatMaskOne, coat.isOn && pass.pixelBlocks.Contains(CoatMaskSlotId) && + // FindSlot(CoatMaskSlotId).value == 1.0f), + context.AddField(HDFields.CoatNormal, stackLitData.coatNormal && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.CoatNormal)); + context.AddField(HDFields.Iridescence, stackLitData.iridescence); + context.AddField(HDFields.SubsurfaceScattering, lightingData.subsurfaceScattering && systemData.surfaceType != SurfaceType.Transparent); + context.AddField(HDFields.Transmission, stackLitData.transmission); + context.AddField(HDFields.DualSpecularLobe, stackLitData.dualSpecularLobe); + + // Base Parametrization + // Even though we can just always transfer the present (check with $SurfaceDescription.*) fields like specularcolor + // and metallic, we still need to know the baseParametrization in the template to translate into the + // _MATERIAL_FEATURE_SPECULAR_COLOR define: + context.AddField(HDFields.BaseParamSpecularColor, stackLitData.baseParametrization == StackLit.BaseParametrization.SpecularColor); + + // Dual Specular Lobe Parametrization + context.AddField(HDFields.HazyGloss, stackLitData.dualSpecularLobe && + stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss); + + // Misc + context.AddField(HDFields.DoAlphaTest, systemData.alphaTest && context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.AlphaClipThreshold)); + context.AddField(HDFields.EnergyConservingSpecular, stackLitData.energyConservingSpecular); + context.AddField(HDFields.Tangent, descs.Contains(HDBlockFields.SurfaceDescription.Tangent) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.Tangent)); + // Option for baseParametrization == Metallic && DualSpecularLobeParametrization == HazyGloss: + // Again we assume masternode has HazyGlossMaxDielectricF0 which should always be the case + // if capHazinessWrtMetallic.isOn. + context.AddField(HDFields.CapHazinessIfNotMetallic, stackLitData.dualSpecularLobe && + stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss && + stackLitData.capHazinessWrtMetallic && stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic + && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.HazyGlossMaxDielectricF0)); + // Note here we combine an "enable"-like predicate and the $SurfaceDescription.(slotname) predicate + // into a single $GeometricSpecularAA pedicate. + // + // ($SurfaceDescription.* predicates are useful to make sure the field is present in the struct in the template. + // The field will be present if both the master node and pass have the slotid, see this set intersection we make + // in GenerateSurfaceDescriptionStruct(), with HDSubShaderUtilities.FindMaterialSlotsOnNode().) + // + // Normally, since the feature enable adds the required slots, only the $SurfaceDescription.* would be required, + // but some passes might not need it and not declare the PixelShaderSlot, or, inversely, the pass might not + // declare it as a way to avoid it. + // + // IE this has also the side effect to disable geometricSpecularAA - even if "on" - for passes that don't explicitly + // advertise these slots(eg for a general feature, with separate "enable" and "field present" predicates, the + // template could take a default value and process it anyway if a feature is "on"). + // + // (Note we can achieve the same results in the template on just single predicates by making defines out of them, + // and using #if defined() && etc) + context.AddField(HDFields.GeometricSpecularAA, lightingData.specularAA && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold)); + context.AddField(HDFields.SpecularAA, lightingData.specularAA && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold)); + context.AddField(HDFields.SpecularOcclusion, stackLitData.screenSpaceSpecularOcclusionBaseMode != StackLitData.SpecularOcclusionBaseMode.Off || + stackLitData.dataBasedSpecularOcclusionBaseMode != StackLitData.SpecularOcclusionBaseMode.Off); + + // Advanced + context.AddField(HDFields.AnisotropyForAreaLights, stackLitData.anisotropyForAreaLights); + context.AddField(HDFields.RecomputeStackPerLight, stackLitData.recomputeStackPerLight); + context.AddField(HDFields.HonorPerLightMinRoughness, stackLitData.honorPerLightMinRoughness); + context.AddField(HDFields.ShadeBaseUsingRefractedAngles, stackLitData.shadeBaseUsingRefractedAngles); + context.AddField(HDFields.StackLitDebug, stackLitData.debug); + + // Screen Space Specular Occlusion Base Mode + context.AddField(HDFields.SSSpecularOcclusionBaseModeOff, stackLitData.screenSpaceSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.Off); + context.AddField(HDFields.SSSpecularOcclusionBaseModeDirectFromAO, stackLitData.screenSpaceSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.DirectFromAO); + context.AddField(HDFields.SSSpecularOcclusionBaseModeConeConeFromBentAO, stackLitData.screenSpaceSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.ConeConeFromBentAO); + context.AddField(HDFields.SSSpecularOcclusionBaseModeSPTDIntegrationOfBentAO, stackLitData.screenSpaceSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.SPTDIntegrationOfBentAO); + context.AddField(HDFields.SSSpecularOcclusionBaseModeCustom, stackLitData.screenSpaceSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.Custom); + + // Screen Space Specular Occlusion AO Cone Size + context.AddField(HDFields.SSSpecularOcclusionAOConeSizeUniformAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && + stackLitData.screenSpaceSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.UniformAO); + context.AddField(HDFields.SSSpecularOcclusionAOConeSizeCosWeightedAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && + stackLitData.screenSpaceSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedAO); + context.AddField(HDFields.SSSpecularOcclusionAOConeSizeCosWeightedBentCorrectAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && + stackLitData.screenSpaceSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO); + + // Screen Space Specular Occlusion AO Cone Dir + context.AddField(HDFields.SSSpecularOcclusionAOConeDirGeomNormal, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && + stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.GeomNormal); + context.AddField(HDFields.SSSpecularOcclusionAOConeDirBentNormal, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && + stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.BentNormal); + context.AddField(HDFields.SSSpecularOcclusionAOConeDirShadingNormal, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && + stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.ShadingNormal); + + // Data Based Specular Occlusion Base Mode + context.AddField(HDFields.DataBasedSpecularOcclusionBaseModeOff, stackLitData.dataBasedSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.Off); + context.AddField(HDFields.DataBasedSpecularOcclusionBaseModeDirectFromAO, stackLitData.dataBasedSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.DirectFromAO); + context.AddField(HDFields.DataBasedSpecularOcclusionBaseModeConeConeFromBentAO, stackLitData.dataBasedSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.ConeConeFromBentAO); + context.AddField(HDFields.DataBasedSpecularOcclusionBaseModeSPTDIntegrationOfBentAO, stackLitData.dataBasedSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.SPTDIntegrationOfBentAO); + context.AddField(HDFields.DataBasedSpecularOcclusionBaseModeCustom, stackLitData.dataBasedSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.Custom); + + // Data Based Specular Occlusion AO Cone Size + context.AddField(HDFields.DataBasedSpecularOcclusionAOConeSizeUniformAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.dataBasedSpecularOcclusionBaseMode) && + stackLitData.dataBasedSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.UniformAO); + context.AddField(HDFields.DataBasedSpecularOcclusionAOConeSizeCosWeightedAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.dataBasedSpecularOcclusionBaseMode) && + stackLitData.dataBasedSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedAO); + context.AddField(HDFields.DataBasedSpecularOcclusionAOConeSizeCosWeightedBentCorrectAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.dataBasedSpecularOcclusionBaseMode) && + stackLitData.dataBasedSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO); + + // Specular Occlusion Cone Fixup Method + context.AddField(HDFields.SpecularOcclusionConeFixupMethodOff, SpecularOcclusionUsesBentNormal(stackLitData) && + stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.Off); + context.AddField(HDFields.SpecularOcclusionConeFixupMethodBoostBSDFRoughness, SpecularOcclusionUsesBentNormal(stackLitData) && + stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.BoostBSDFRoughness); + context.AddField(HDFields.SpecularOcclusionConeFixupMethodTiltDirectionToGeomNormal, SpecularOcclusionUsesBentNormal(stackLitData) && + stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.TiltDirectionToGeomNormal); + context.AddField(HDFields.SpecularOcclusionConeFixupMethodBoostAndTilt, SpecularOcclusionUsesBentNormal(stackLitData) && + stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.BoostAndTilt); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + base.GetActiveBlocks(ref context); + AddDistortionBlocks(ref context); + + // Common + context.AddBlock(HDBlockFields.SurfaceDescription.BentNormal); + context.AddBlock(HDBlockFields.SurfaceDescription.Tangent); + context.AddBlock(BlockFields.SurfaceDescription.Smoothness); + context.AddBlock(BlockFields.SurfaceDescription.Occlusion); + context.AddBlock(HDBlockFields.SurfaceDescription.Anisotropy, stackLitData.anisotropy); + context.AddBlock(HDBlockFields.SurfaceDescription.SubsurfaceMask, lightingData.subsurfaceScattering); + context.AddBlock(HDBlockFields.SurfaceDescription.Thickness, stackLitData.transmission); + context.AddBlock(HDBlockFields.SurfaceDescription.DiffusionProfileHash, lightingData.subsurfaceScattering || stackLitData.transmission); + + // Base Metallic + context.AddBlock(BlockFields.SurfaceDescription.Metallic, stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic); + context.AddBlock(HDBlockFields.SurfaceDescription.DielectricIor, stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic); + + // Base Specular + context.AddBlock(BlockFields.SurfaceDescription.Specular, stackLitData.baseParametrization == StackLit.BaseParametrization.SpecularColor); + + // Specular Occlusion + // for custom (external) SO replacing data based SO (which normally comes from some func of DataBasedSOMode(dataAO, optional bent normal)) + // TODO: we would ideally need one value per lobe + context.AddBlock(HDBlockFields.SurfaceDescription.SpecularOcclusion, DataBasedSpecularOcclusionIsCustom()); + context.AddBlock(HDBlockFields.SurfaceDescription.SOFixupVisibilityRatioThreshold, SpecularOcclusionUsesBentNormal(stackLitData) && + stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off); + context.AddBlock(HDBlockFields.SurfaceDescription.SOFixupStrengthFactor, SpecularOcclusionUsesBentNormal(stackLitData) && + stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off); + context.AddBlock(HDBlockFields.SurfaceDescription.SOFixupMaxAddedRoughness, SpecularOcclusionUsesBentNormal(stackLitData) && SpecularOcclusionConeFixupMethodModifiesRoughness(stackLitData.specularOcclusionConeFixupMethod) && + stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off); + + // Coat + context.AddBlock(HDBlockFields.SurfaceDescription.CoatSmoothness, stackLitData.coat); + context.AddBlock(HDBlockFields.SurfaceDescription.CoatIor, stackLitData.coat); + context.AddBlock(HDBlockFields.SurfaceDescription.CoatThickness, stackLitData.coat); + context.AddBlock(HDBlockFields.SurfaceDescription.CoatExtinction, stackLitData.coat); + context.AddBlock(HDBlockFields.SurfaceDescription.CoatNormal, stackLitData.coat && stackLitData.coatNormal); + context.AddBlock(HDBlockFields.SurfaceDescription.CoatMask, stackLitData.coat); + + // Dual Specular Lobe + context.AddBlock(HDBlockFields.SurfaceDescription.SmoothnessB, stackLitData.dualSpecularLobe && stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.Direct); + context.AddBlock(HDBlockFields.SurfaceDescription.LobeMix, stackLitData.dualSpecularLobe && stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.Direct); + + context.AddBlock(HDBlockFields.SurfaceDescription.Haziness, stackLitData.dualSpecularLobe && stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss); + context.AddBlock(HDBlockFields.SurfaceDescription.HazeExtent, stackLitData.dualSpecularLobe && stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss); + context.AddBlock(HDBlockFields.SurfaceDescription.HazyGlossMaxDielectricF0, stackLitData.dualSpecularLobe && stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss && + stackLitData.capHazinessWrtMetallic && stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic); + context.AddBlock(HDBlockFields.SurfaceDescription.AnisotropyB, stackLitData.dualSpecularLobe && stackLitData.anisotropy); + + // Iridescence + context.AddBlock(HDBlockFields.SurfaceDescription.IridescenceMask, stackLitData.iridescence); + context.AddBlock(HDBlockFields.SurfaceDescription.IridescenceThickness, stackLitData.iridescence); + context.AddBlock(HDBlockFields.SurfaceDescription.IridescenceCoatFixupTIR, stackLitData.iridescence && stackLitData.coat); + context.AddBlock(HDBlockFields.SurfaceDescription.IridescenceCoatFixupTIRClamp, stackLitData.iridescence && stackLitData.coat); + + // Specular AA + context.AddBlock(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, lightingData.specularAA); + context.AddBlock(HDBlockFields.SurfaceDescription.SpecularAAThreshold, lightingData.specularAA); + } + + protected override void AddInspectorPropertyBlocks(SubTargetPropertiesGUI blockList) + { + blockList.AddPropertyBlock(new StackLitSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features.Lit, stackLitData)); + if (systemData.surfaceType == SurfaceType.Transparent) + blockList.AddPropertyBlock(new DistortionPropertyBlock()); + blockList.AddPropertyBlock(new AdvancedOptionsPropertyBlock()); + } + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) + { + base.CollectShaderProperties(collector, generationMode); + + if (stackLitData.debug) + { + // We have useful debug options in StackLit, so add them always, and let the UI editor (non shadergraph) handle displaying them + // since this is also the editor that controls the keyword switching for the debug mode. + collector.AddShaderProperty(new Vector4ShaderProperty() + { + overrideReferenceName = "_DebugEnvLobeMask", // xyz is environments lights lobe 0 1 2 Enable, w is Enable VLayering + displayName = "_DebugEnvLobeMask", + value = new Vector4(1.0f, 1.0f, 1.0f, 1.0f) + }); + collector.AddShaderProperty(new Vector4ShaderProperty() + { + overrideReferenceName = "_DebugLobeMask", // xyz is analytical dirac lights lobe 0 1 2 Enable", false), + displayName = "_DebugLobeMask", + value = new Vector4(1.0f, 1.0f, 1.0f, 1.0f) + }); + collector.AddShaderProperty(new Vector4ShaderProperty() + { + overrideReferenceName = "_DebugAniso", // x is Hack Enable, w is factor + displayName = "_DebugAniso", + value = new Vector4(1.0f, 0.0f, 0.0f, 1000.0f) + }); + // _DebugSpecularOcclusion: + // + // eg (2,2,1,2) : + // .x = SO method {0 = fromAO, 1 = conecone, 2 = SPTD}, + // .y = bentao algo {0 = uniform, cos, bent cos}, + // .z = use upper visible hemisphere clipping, + // .w = The last component of _DebugSpecularOcclusion controls debug visualization: + // -1 colors the object according to the SO algorithm used, + // and values from 1 to 4 controls what the lighting debug display mode will show when set to show "indirect specular occlusion": + // Since there's not one value in our case, + // 0 will show the object all red to indicate to choose one, 1-4 corresponds to showing + // 1 = coat SO, 2 = base lobe A SO, 3 = base lobe B SO, 4 = shows the result of sampling the SSAO texture (screenSpaceAmbientOcclusion). + collector.AddShaderProperty(new Vector4ShaderProperty() + { + overrideReferenceName = "_DebugSpecularOcclusion", + displayName = "_DebugSpecularOcclusion", + value = new Vector4(2.0f, 2.0f, 1.0f, 2.0f) + }); + } + } + + public static bool SpecularOcclusionModeUsesVisibilityCone(StackLitData.SpecularOcclusionBaseMode soMethod) + { + return (soMethod == StackLitData.SpecularOcclusionBaseMode.ConeConeFromBentAO + || soMethod == StackLitData.SpecularOcclusionBaseMode.SPTDIntegrationOfBentAO); + } + + public static bool SpecularOcclusionUsesBentNormal(StackLitData stackLitData) + { + return (SpecularOcclusionModeUsesVisibilityCone(stackLitData.dataBasedSpecularOcclusionBaseMode) + || (SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) + && stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.BentNormal)); + } + + bool DataBasedSpecularOcclusionIsCustom() + { + return stackLitData.dataBasedSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.Custom; + } + + public static bool SpecularOcclusionConeFixupMethodModifiesRoughness(StackLitData.SpecularOcclusionConeFixupMethod soConeFixupMethod) + { + return (soConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.BoostBSDFRoughness + || soConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.BoostAndTilt); + } + +#region SubShaders + static class SubShaders + { + public static SubShaderDescriptor StackLit = new SubShaderDescriptor() + { + pipelineTag = HDRenderPipeline.k_ShaderTagName, + generatesPreview = true, + passes = new PassCollection + { + { StackLitPasses.ShadowCaster }, + { StackLitPasses.META }, + { StackLitPasses.SceneSelection }, + { StackLitPasses.DepthForwardOnly }, + { StackLitPasses.MotionVectors }, + { StackLitPasses.Distortion, new FieldCondition(HDFields.TransparentDistortion, true) }, + { StackLitPasses.TransparentDepthPrepass, new FieldCondition[]{ + new FieldCondition(HDFields.TransparentDepthPrePass, true), + new FieldCondition(HDFields.DisableSSRTransparent, true) }}, + { StackLitPasses.TransparentDepthPrepass, new FieldCondition[]{ + new FieldCondition(HDFields.TransparentDepthPrePass, true), + new FieldCondition(HDFields.DisableSSRTransparent, false) }}, + { StackLitPasses.TransparentDepthPrepass, new FieldCondition[]{ + new FieldCondition(HDFields.TransparentDepthPrePass, false), + new FieldCondition(HDFields.DisableSSRTransparent, false) }}, + { StackLitPasses.ForwardOnly }, + { StackLitPasses.TransparentDepthPostpass, new FieldCondition(HDFields.TransparentDepthPostPass, true) }, + }, + }; + + public static SubShaderDescriptor StackLitRaytracing = new SubShaderDescriptor() + { + pipelineTag = HDRenderPipeline.k_ShaderTagName, + generatesPreview = false, + passes = new PassCollection + { + { StackLitPasses.RaytracingIndirect, new FieldCondition(Fields.IsPreview, false) }, + { StackLitPasses.RaytracingVisibility, new FieldCondition(Fields.IsPreview, false) }, + { StackLitPasses.RaytracingForward, new FieldCondition(Fields.IsPreview, false) }, + { StackLitPasses.RaytracingGBuffer, new FieldCondition(Fields.IsPreview, false) }, + { StackLitPasses.RaytracingSubSurface, new FieldCondition(Fields.IsPreview, false) }, + }, + }; + } +#endregion + +#region Passes + public static class StackLitPasses + { + public static PassDescriptor META = new PassDescriptor() + { + // Definition + displayName = "META", + referenceName = "SHADERPASS_LIGHT_TRANSPORT", + lightMode = "META", + useInPreview = false, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validPixelBlocks = StackLitBlockMasks.FragmentMETA, + + // Collections + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.Meta, + fieldDependencies = CoreFieldDependencies.Default, + renderStates = CoreRenderStates.Meta, + pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, + keywords = CoreKeywords.HDBase, + includes = StackLitIncludes.Meta, + }; + + public static PassDescriptor ShadowCaster = new PassDescriptor() + { + // Definition + displayName = "ShadowCaster", + referenceName = "SHADERPASS_SHADOWS", + lightMode = "ShadowCaster", + useInPreview = false, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = StackLitBlockMasks.VertexPosition, + validPixelBlocks = StackLitBlockMasks.FragmentAlphaDepth, + + // Collections + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + renderStates = StackLitRenderStates.ShadowCaster, + pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, + keywords = CoreKeywords.HDBase, + includes = StackLitIncludes.DepthOnly, + }; + + public static PassDescriptor SceneSelection = new PassDescriptor() + { + // Definition + displayName = "SceneSelectionPass", + referenceName = "SHADERPASS_DEPTH_ONLY", + lightMode = "SceneSelectionPass", + useInPreview = false, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentAlphaDepth, + + // Collections + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + renderStates = CoreRenderStates.SceneSelection, + pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayerEditorSync, + defines = CoreDefines.SceneSelection, + keywords = CoreKeywords.HDBase, + includes = StackLitIncludes.DepthOnly, + }; + + public static PassDescriptor DepthForwardOnly = new PassDescriptor() + { + // // Code path for WRITE_NORMAL_BUFFER + // See StackLit.hlsl:ConvertSurfaceDataToNormalData() + // which ShaderPassDepthOnly uses: we need to add proper interpolators dependencies depending on WRITE_NORMAL_BUFFER. + // In our case WRITE_NORMAL_BUFFER is always enabled here. + // Also, we need to add PixelShaderSlots dependencies for everything potentially used there. + // See AddPixelShaderSlotsForWriteNormalBufferPasses() + + // Definition + displayName = "DepthForwardOnly", + referenceName = "SHADERPASS_DEPTH_ONLY", + lightMode = "DepthForwardOnly", + useInPreview = true, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentDepthMotionVectors, + + // Collections + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.LitFull, + fieldDependencies = CoreFieldDependencies.Default, + renderStates = CoreRenderStates.DepthOnly, + pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, + defines = CoreDefines.DepthMotionVectors, + keywords = CoreKeywords.DepthMotionVectorsNoNormal, + includes = StackLitIncludes.DepthOnly, + }; + + public static PassDescriptor MotionVectors = new PassDescriptor() + { + // Definition + displayName = "MotionVectors", + referenceName = "SHADERPASS_MOTION_VECTORS", + lightMode = "MotionVectors", + useInPreview = false, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentDepthMotionVectors, + + // Collections + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.LitFull, + fieldDependencies = CoreFieldDependencies.Default, + renderStates = CoreRenderStates.MotionVectors, + pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, + defines = CoreDefines.DepthMotionVectors, + keywords = CoreKeywords.DepthMotionVectorsNoNormal, + includes = StackLitIncludes.MotionVectors, + }; + + public static PassDescriptor Distortion = new PassDescriptor() + { + // Definition + displayName = "DistortionVectors", + referenceName = "SHADERPASS_DISTORTION", + lightMode = "DistortionVectors", + useInPreview = true, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentDistortion, + + // Collections + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + renderStates = StackLitRenderStates.Distortion, + pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, + keywords = CoreKeywords.HDBase, + includes = StackLitIncludes.Distortion, + }; + + public static PassDescriptor TransparentDepthPrepass = new PassDescriptor() + { + // Definition + displayName = "TransparentDepthPrepass", + referenceName = "SHADERPASS_DEPTH_ONLY", + lightMode = "TransparentDepthPrepass", + useInPreview = true, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentTransparentDepthPrepass, + + // Collections + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.LitFull, + fieldDependencies = CoreFieldDependencies.Default, + renderStates = CoreRenderStates.TransparentDepthPrePass, + pragmas = CorePragmas.DotsInstancedInV2Only, + defines = CoreDefines.TransparentDepthPrepass, + keywords = CoreKeywords.HDBase, + includes = StackLitIncludes.DepthOnly, + }; + + public static PassDescriptor ForwardOnly = new PassDescriptor() + { + // Definition + displayName = "ForwardOnly", + referenceName = "SHADERPASS_FORWARD", + lightMode = "ForwardOnly", + useInPreview = true, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentForward, + + // Collections + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.LitFull, + fieldDependencies = CoreFieldDependencies.Default, + renderStates = CoreRenderStates.Forward, + pragmas = StackLitPragmas.DotsInstancedInV2OnlyRenderingLayer, + defines = CoreDefines.Forward, + keywords = CoreKeywords.Forward, + includes = StackLitIncludes.ForwardOnly, + }; + + public static PassDescriptor TransparentDepthPostpass = new PassDescriptor() + { + // Definition + displayName = "TransparentDepthPostpass", + referenceName = "SHADERPASS_DEPTH_ONLY", + lightMode = "TransparentDepthPostpass", + useInPreview = true, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentTransparentDepthPostpass, + + // Collections + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + renderStates = CoreRenderStates.TransparentDepthPostPass, + pragmas = CorePragmas.DotsInstancedInV2Only, + defines = CoreDefines.ShaderGraphRaytracingHigh, + keywords = CoreKeywords.HDBase, + includes = StackLitIncludes.DepthOnly, + }; + + public static PassDescriptor RaytracingIndirect = new PassDescriptor() + { + // Definition + displayName = "IndirectDXR", + referenceName = "SHADERPASS_RAYTRACING_INDIRECT", + lightMode = "IndirectDXR", + useInPreview = false, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentForward, + + // Collections + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + pragmas = CorePragmas.RaytracingBasic, + defines = StackLitDefines.RaytracingIndirect, + keywords = CoreKeywords.RaytracingIndirect, + includes = CoreIncludes.Raytracing, + requiredFields = new FieldCollection(){ HDFields.SubShader.StackLit, HDFields.ShaderPass.RaytracingIndirect }, + }; + + public static PassDescriptor RaytracingVisibility = new PassDescriptor() + { + // Definition + displayName = "VisibilityDXR", + referenceName = "SHADERPASS_RAYTRACING_VISIBILITY", + lightMode = "VisibilityDXR", + useInPreview = false, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentForward, + + // Collections + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + pragmas = CorePragmas.RaytracingBasic, + defines = StackLitDefines.RaytracingVisibility, + keywords = CoreKeywords.RaytracingVisiblity, + includes = CoreIncludes.Raytracing, + requiredFields = new FieldCollection(){ HDFields.SubShader.StackLit, HDFields.ShaderPass.RaytracingVisibility }, + }; + + public static PassDescriptor RaytracingForward = new PassDescriptor() + { + // Definition + displayName = "ForwardDXR", + referenceName = "SHADERPASS_RAYTRACING_FORWARD", + lightMode = "ForwardDXR", + useInPreview = false, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentForward, + + // Collections + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + pragmas = CorePragmas.RaytracingBasic, + defines = StackLitDefines.RaytracingForward, + keywords = CoreKeywords.RaytracingGBufferForward, + includes = CoreIncludes.Raytracing, + requiredFields = new FieldCollection(){ HDFields.SubShader.StackLit, HDFields.ShaderPass.RaytracingForward }, + }; + + public static PassDescriptor RaytracingGBuffer = new PassDescriptor() + { + // Definition + displayName = "GBufferDXR", + referenceName = "SHADERPASS_RAYTRACING_GBUFFER", + lightMode = "GBufferDXR", + useInPreview = false, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentForward, + + // Collections + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + pragmas = CorePragmas.RaytracingBasic, + defines = StackLitDefines.RaytracingGBuffer, + keywords = CoreKeywords.RaytracingGBufferForward, + includes = CoreIncludes.Raytracing, + requiredFields = new FieldCollection(){ HDFields.SubShader.StackLit, HDFields.ShaderPass.RayTracingGBuffer }, + }; + + public static PassDescriptor RaytracingSubSurface = new PassDescriptor() + { + //Definition + displayName = "SubSurfaceDXR", + referenceName = "SHADERPASS_RAYTRACING_SUB_SURFACE", + lightMode = "SubSurfaceDXR", + useInPreview = false, + + // Template + passTemplatePath = passTemplatePath, + sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, + + //Port mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = StackLitBlockMasks.FragmentForward, + + //Collections + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + pragmas = CorePragmas.RaytracingBasic, + defines = StackLitDefines.RaytracingGBuffer, + keywords = CoreKeywords.RaytracingGBufferForward, + includes = CoreIncludes.Raytracing, + requiredFields = new FieldCollection(){ HDFields.SubShader.StackLit, HDFields.ShaderPass.RaytracingSubSurface }, + }; + } +#endregion + +#region PortMasks + static class StackLitBlockMasks + { + public static BlockFieldDescriptor[] VertexPosition = new BlockFieldDescriptor[] + { + BlockFields.VertexDescription.Position, + }; + + public static BlockFieldDescriptor[] FragmentMETA = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.Tangent, + HDBlockFields.SurfaceDescription.SubsurfaceMask, + HDBlockFields.SurfaceDescription.Thickness, + HDBlockFields.SurfaceDescription.DiffusionProfileHash, + HDBlockFields.SurfaceDescription.IridescenceMask, + HDBlockFields.SurfaceDescription.IridescenceThickness, + HDBlockFields.SurfaceDescription.IridescenceCoatFixupTIR, + HDBlockFields.SurfaceDescription.IridescenceCoatFixupTIRClamp, + BlockFields.SurfaceDescription.Specular, + HDBlockFields.SurfaceDescription.DielectricIor, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Smoothness, + HDBlockFields.SurfaceDescription.SmoothnessB, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.Anisotropy, + HDBlockFields.SurfaceDescription.AnisotropyB, + HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, + HDBlockFields.SurfaceDescription.SpecularAAThreshold, + HDBlockFields.SurfaceDescription.CoatSmoothness, + HDBlockFields.SurfaceDescription.CoatIor, + HDBlockFields.SurfaceDescription.CoatThickness, + HDBlockFields.SurfaceDescription.CoatExtinction, + HDBlockFields.SurfaceDescription.CoatNormal, + HDBlockFields.SurfaceDescription.CoatMask, + HDBlockFields.SurfaceDescription.LobeMix, + HDBlockFields.SurfaceDescription.Haziness, + HDBlockFields.SurfaceDescription.HazeExtent, + HDBlockFields.SurfaceDescription.HazyGlossMaxDielectricF0, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + HDBlockFields.SurfaceDescription.SOFixupVisibilityRatioThreshold, + HDBlockFields.SurfaceDescription.SOFixupStrengthFactor, + HDBlockFields.SurfaceDescription.SOFixupMaxAddedRoughness, + }; + + public static BlockFieldDescriptor[] FragmentAlphaDepth = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentDepthMotionVectors = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, + // StackLitMasterNode.coat + HDBlockFields.SurfaceDescription.CoatSmoothness, + HDBlockFields.SurfaceDescription.CoatNormal, + // !StackLitMasterNode.coat + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + HDBlockFields.SurfaceDescription.LobeMix, + BlockFields.SurfaceDescription.Smoothness, + HDBlockFields.SurfaceDescription.SmoothnessB, + // StackLitMasterNode.geometricSpecularAA + HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, + HDBlockFields.SurfaceDescription.SpecularAAThreshold, + }; + + public static BlockFieldDescriptor[] FragmentDistortion = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.Distortion, + HDBlockFields.SurfaceDescription.DistortionBlur, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentTransparentDepthPrepass = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass, + HDBlockFields.SurfaceDescription.DepthOffset, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.Smoothness, + }; + + public static BlockFieldDescriptor[] FragmentForward = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + HDBlockFields.SurfaceDescription.BentNormal, + HDBlockFields.SurfaceDescription.Tangent, + HDBlockFields.SurfaceDescription.SubsurfaceMask, + HDBlockFields.SurfaceDescription.Thickness, + HDBlockFields.SurfaceDescription.DiffusionProfileHash, + HDBlockFields.SurfaceDescription.IridescenceMask, + HDBlockFields.SurfaceDescription.IridescenceThickness, + HDBlockFields.SurfaceDescription.IridescenceCoatFixupTIR, + HDBlockFields.SurfaceDescription.IridescenceCoatFixupTIRClamp, + BlockFields.SurfaceDescription.Specular, + HDBlockFields.SurfaceDescription.DielectricIor, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Smoothness, + HDBlockFields.SurfaceDescription.SmoothnessB, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.Anisotropy, + HDBlockFields.SurfaceDescription.AnisotropyB, + HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, + HDBlockFields.SurfaceDescription.SpecularAAThreshold, + HDBlockFields.SurfaceDescription.CoatSmoothness, + HDBlockFields.SurfaceDescription.CoatIor, + HDBlockFields.SurfaceDescription.CoatThickness, + HDBlockFields.SurfaceDescription.CoatExtinction, + HDBlockFields.SurfaceDescription.CoatNormal, + HDBlockFields.SurfaceDescription.CoatMask, + HDBlockFields.SurfaceDescription.LobeMix, + HDBlockFields.SurfaceDescription.Haziness, + HDBlockFields.SurfaceDescription.HazeExtent, + HDBlockFields.SurfaceDescription.HazyGlossMaxDielectricF0, + HDBlockFields.SurfaceDescription.SpecularOcclusion, + HDBlockFields.SurfaceDescription.SOFixupVisibilityRatioThreshold, + HDBlockFields.SurfaceDescription.SOFixupStrengthFactor, + HDBlockFields.SurfaceDescription.SOFixupMaxAddedRoughness, + HDBlockFields.SurfaceDescription.BakedGI, + HDBlockFields.SurfaceDescription.BakedBackGI, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + + public static BlockFieldDescriptor[] FragmentTransparentDepthPostpass = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass, + HDBlockFields.SurfaceDescription.DepthOffset, + }; + } +#endregion + +#region RenderStates + static class StackLitRenderStates + { + public static RenderStateCollection ShadowCaster = new RenderStateCollection + { + { RenderState.Blend(Blend.One, Blend.Zero) }, + { RenderState.ZWrite(ZWrite.On) }, + { RenderState.ZClip(CoreRenderStates.Uniforms.zClip) }, + { RenderState.ColorMask("ColorMask 0") }, + }; + + public static RenderStateCollection Distortion = new RenderStateCollection + { + { RenderState.Blend(Blend.One, Blend.One, Blend.One, Blend.One), new FieldCondition(HDFields.DistortionAdd, true) }, + { RenderState.Blend(Blend.DstColor, Blend.Zero, Blend.DstAlpha, Blend.Zero), new FieldCondition(HDFields.DistortionMultiply, true) }, + { RenderState.Blend(Blend.One, Blend.Zero, Blend.One, Blend.Zero), new FieldCondition(HDFields.DistortionReplace, true) }, + { RenderState.BlendOp(BlendOp.Add, BlendOp.Add) }, + { RenderState.Cull(CoreRenderStates.Uniforms.cullMode) }, + { RenderState.ZWrite(ZWrite.Off) }, + { RenderState.ZTest(ZTest.Always), new FieldCondition(HDFields.DistortionDepthTest, false) }, + { RenderState.ZTest(ZTest.LEqual), new FieldCondition(HDFields.DistortionDepthTest, true) }, + { RenderState.Stencil(new StencilDescriptor() + { + WriteMask = $"{(int)StencilUsage.DistortionVectors}", + Ref = $"{(int)StencilUsage.DistortionVectors}", + Comp = "Always", + Pass = "Replace", + }) }, + }; + } +#endregion + +#region Defines + static class StackLitDefines + { + public static DefineCollection RaytracingForward = new DefineCollection + { + { CoreKeywordDescriptors.Shadow, 0 }, + { RayTracingNode.GetRayTracingKeyword(), 0 }, + { CoreKeywordDescriptors.HasLightloop, 1 }, + }; + + public static DefineCollection RaytracingIndirect = new DefineCollection + { + { CoreKeywordDescriptors.Shadow, 0 }, + { RayTracingNode.GetRayTracingKeyword(), 1 }, + { CoreKeywordDescriptors.HasLightloop, 1 }, + }; + + public static DefineCollection RaytracingGBuffer = new DefineCollection + { + { CoreKeywordDescriptors.Shadow, 0 }, + { RayTracingNode.GetRayTracingKeyword(), 1 }, + }; + + public static DefineCollection RaytracingVisibility = new DefineCollection + { + { RayTracingNode.GetRayTracingKeyword(), 1 }, + }; + + public static DefineCollection RaytracingPathTracing = new DefineCollection + { + { CoreKeywordDescriptors.Shadow, 0 }, + { RayTracingNode.GetRayTracingKeyword(), 0 }, + { CoreKeywordDescriptors.HasLightloop, 1 }, + }; + } +#endregion + +#region Pragmas + static class StackLitPragmas + { + public static PragmaCollection DotsInstancedInV2OnlyRenderingLayer = new PragmaCollection + { + { CorePragmas.Basic }, + { Pragma.MultiCompileInstancing }, + { Pragma.InstancingOptions(InstancingOptions.RenderingLayer) }, + #if ENABLE_HYBRID_RENDERER_V2 + { Pragma.DOTSInstancing }, + { Pragma.InstancingOptions(InstancingOptions.NoLodFade) }, + #endif + }; + + public static PragmaCollection DotsInstancedInV2OnlyRenderingLayerEditorSync = new PragmaCollection + { + { CorePragmas.Basic }, + { Pragma.MultiCompileInstancing }, + { Pragma.InstancingOptions(InstancingOptions.RenderingLayer) }, + { Pragma.EditorSyncCompilation }, + #if ENABLE_HYBRID_RENDERER_V2 + { Pragma.DOTSInstancing }, + { Pragma.InstancingOptions(InstancingOptions.NoLodFade) }, + #endif + }; + } +#endregion + +#region Includes + static class StackLitIncludes + { + const string kSpecularOcclusionDef = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SphericalCapPivot/SpecularOcclusionDef.hlsl"; + const string kStackLitDecalData = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLitDecalData.hlsl"; + + public static IncludeCollection Common = new IncludeCollection + { + { kSpecularOcclusionDef, IncludeLocation.Pregraph }, + { CoreIncludes.CorePregraph }, + { CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph }, + { CoreIncludes.kStackLit, IncludeLocation.Pregraph }, + { CoreIncludes.CoreUtility }, + { CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph }, + { kStackLitDecalData, IncludeLocation.Pregraph }, + { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph }, + }; + + public static IncludeCollection Meta = new IncludeCollection + { + { Common }, + { CoreIncludes.kPassLightTransport, IncludeLocation.Postgraph }, + }; + + public static IncludeCollection DepthOnly = new IncludeCollection + { + { Common }, + { CoreIncludes.kPassDepthOnly, IncludeLocation.Postgraph }, + }; + + public static IncludeCollection MotionVectors = new IncludeCollection + { + { Common }, + { CoreIncludes.kPassMotionVectors, IncludeLocation.Postgraph }, + }; + + public static IncludeCollection Distortion = new IncludeCollection + { + { Common }, + { CoreIncludes.kDisortionVectors, IncludeLocation.Postgraph }, + }; + + public static IncludeCollection ForwardOnly = new IncludeCollection + { + { kSpecularOcclusionDef, IncludeLocation.Pregraph }, + { CoreIncludes.CorePregraph }, + { CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph }, + { CoreIncludes.kLighting, IncludeLocation.Pregraph }, + { CoreIncludes.kLightLoopDef, IncludeLocation.Pregraph }, + { CoreIncludes.kStackLit, IncludeLocation.Pregraph }, + { CoreIncludes.kLightLoop, IncludeLocation.Pregraph }, + { CoreIncludes.CoreUtility }, + { CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph }, + { kStackLitDecalData, IncludeLocation.Pregraph }, + { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph }, + { CoreIncludes.kPassForward, IncludeLocation.Postgraph }, + }; + } +#endregion + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/HDStackLitSubTarget.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.cs.meta similarity index 100% rename from com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/HDStackLitSubTarget.cs.meta rename to com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSurfaceOptionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSurfaceOptionPropertyBlock.cs new file mode 100644 index 00000000000..0fb625e6f81 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSurfaceOptionPropertyBlock.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.LitSurfaceInputsUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.SurfaceOptionUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.RefractionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class StackLitSurfaceOptionPropertyBlock : SurfaceOptionPropertyBlock + { + class Styles + { + public static GUIContent materialType = new GUIContent("Material Type", "TODO"); + } + + StackLitData stackLitData; + + public StackLitSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features features, StackLitData stackLitData) : base(features) + => this.stackLitData = stackLitData; + + protected override void CreatePropertyGUI() + { + base.CreatePropertyGUI(); + + // StackLit specific properties: + + AddProperty("Base Color Parametrization", () => stackLitData.baseParametrization, (newValue) => stackLitData.baseParametrization = newValue); + AddProperty("Energy Conserving Specular", () => stackLitData.energyConservingSpecular, (newValue) => stackLitData.energyConservingSpecular = newValue, 1); + + // Material type enables: + context.AddLabel("Material Core Features", 0); + AddProperty("Anisotropy", () => stackLitData.anisotropy, (newValue) => stackLitData.anisotropy = newValue); + AddProperty("Coat", () => stackLitData.coat, (newValue) => stackLitData.coat = newValue, 1); + AddProperty("Coat Normal", () => stackLitData.coatNormal, (newValue) => stackLitData.coatNormal = newValue, 2); + AddProperty("Dual Specular Lobe", () => stackLitData.dualSpecularLobe, (newValue) => stackLitData.dualSpecularLobe = newValue, 1); + AddProperty("Dual SpecularLobe Parametrization", () => stackLitData.dualSpecularLobeParametrization, (newValue) => stackLitData.dualSpecularLobeParametrization = newValue, 2); + if (stackLitData.dualSpecularLobe && (stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic) && (stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss)) + AddProperty("Cap Haziness For Non Metallic", () => stackLitData.capHazinessWrtMetallic, (newValue) => stackLitData.capHazinessWrtMetallic = newValue, 2); + AddProperty("Iridescence", () => stackLitData.iridescence, (newValue) => stackLitData.iridescence = newValue, 1); + if (systemData.surfaceType != SurfaceType.Transparent) + AddProperty("Subsurface Scattering", () => lightingData.subsurfaceScattering, (newValue) => lightingData.subsurfaceScattering = newValue, 1); + AddProperty("Transmission", () => stackLitData.transmission, (newValue) => stackLitData.transmission = newValue, 1); + + // SpecularOcclusion from SSAO + if (stackLitData.devMode) + AddProperty("Specular Occlusion (from SSAO)", () => stackLitData.screenSpaceSpecularOcclusionBaseMode, (newValue) => stackLitData.screenSpaceSpecularOcclusionBaseMode = newValue, 0); + var specularOcclusionSSUsesVisibilityCone = stackLitData.devMode && StackLitSubTarget.SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode); + if (specularOcclusionSSUsesVisibilityCone) + { + AddProperty("Specular Occlusion (SS) AO Cone Weight", () => stackLitData.screenSpaceSpecularOcclusionAOConeSize, (newValue) => stackLitData.screenSpaceSpecularOcclusionAOConeSize = newValue, 1); + AddProperty("Specular Occlusion (SS) AO Cone Dir", () => stackLitData.screenSpaceSpecularOcclusionAOConeDir, (newValue) => stackLitData.screenSpaceSpecularOcclusionAOConeDir = newValue, 1); + } + + // SpecularOcclusion from input AO (baked or data-based SO) + EnumField specularOcclusionFromInputAOField; + if(stackLitData.devMode) + { + specularOcclusionFromInputAOField = new EnumField(StackLitData.SpecularOcclusionBaseMode.DirectFromAO); + specularOcclusionFromInputAOField.value = stackLitData.dataBasedSpecularOcclusionBaseMode; + } + else + { + specularOcclusionFromInputAOField = new EnumField(StackLitData.SpecularOcclusionBaseModeSimple.DirectFromAO); + specularOcclusionFromInputAOField.value = Enum.TryParse(stackLitData.dataBasedSpecularOcclusionBaseMode.ToString(), out StackLitData.SpecularOcclusionBaseModeSimple parsedValue) ? + parsedValue : StackLitData.SpecularOcclusionBaseModeSimple.SPTDIntegrationOfBentAO; + } + context.AddProperty("Specular Occlusion (from input AO)", 0, specularOcclusionFromInputAOField, (evt) => + { + if (Equals(stackLitData.dataBasedSpecularOcclusionBaseMode, evt.newValue)) + return; + + registerUndo("Specular Occlusion (from input AO)"); + stackLitData.dataBasedSpecularOcclusionBaseMode = (StackLitData.SpecularOcclusionBaseMode)evt.newValue; + onChange(); + }); + var specularOcclusionUsesVisibilityCone = StackLitSubTarget.SpecularOcclusionModeUsesVisibilityCone(stackLitData.dataBasedSpecularOcclusionBaseMode); + if (specularOcclusionUsesVisibilityCone) + AddProperty("Specular Occlusion AO Cone Weight", () => stackLitData.dataBasedSpecularOcclusionAOConeSize, (newValue) => stackLitData.dataBasedSpecularOcclusionAOConeSize = newValue, 1); + + // Specular Occlusion Bent Normal + var useBentConeFixup = StackLitSubTarget.SpecularOcclusionUsesBentNormal(stackLitData); + if (useBentConeFixup) + { + AddProperty("Specular Occlusion Bent Cone Fixup", () => stackLitData.specularOcclusionConeFixupMethod, (newValue) => stackLitData.specularOcclusionConeFixupMethod = newValue, 0); + AddProperty("Specular Occlusion Bent Cone Fixup", () => stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off, (newValue) => + { + stackLitData.specularOcclusionConeFixupMethod = newValue ? StackLitData.SpecularOcclusionConeFixupMethod.BoostAndTilt + : StackLitData.SpecularOcclusionConeFixupMethod.Off; + }, 0); + } + + // Misc Cont. + // Advanced Options + context.AddLabel("Advanced Options", 0); + AddProperty("Anisotropy For Area Lights", () => stackLitData.anisotropyForAreaLights, (newValue) => stackLitData.anisotropyForAreaLights = newValue, 1); + + // Per Punctual/Directional Lights + context.AddLabel("Per Punctual/Directional Lights:", 1); + if (stackLitData.coat) + AddProperty("Base Layer Uses Refracted Angles", () => stackLitData.shadeBaseUsingRefractedAngles, (newValue) => stackLitData.shadeBaseUsingRefractedAngles = newValue, 2); + if (stackLitData.coat || stackLitData.iridescence) + AddProperty("Recompute Stack & Iridescence", () => stackLitData.recomputeStackPerLight, (newValue) => stackLitData.recomputeStackPerLight = newValue, 2); + AddProperty("Honor Per Light Max Smoothness", () => stackLitData.honorPerLightMinRoughness, (newValue) => stackLitData.honorPerLightMinRoughness = newValue, 2); + + // Debug + // Uncomment to show the dev mode UI: + // if (stackLitData.devMode) + // AddProperty("Enable Dev Mode", () => stackLitData.devMode, (newValue) => stackLitData.devMode = newValue, 1); + if (stackLitData.devMode) + AddProperty("Show And Enable StackLit Debugs", () => stackLitData.debug, (newValue) => stackLitData.debug = newValue, 1); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSurfaceOptionPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSurfaceOptionPropertyBlock.cs.meta new file mode 100644 index 00000000000..7370f3f848b --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSurfaceOptionPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 975437fb4199b8c48a2b9e540239bf50 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceInputsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceInputsUIBlock.cs index 23f9f91c38f..2ea7ac2be49 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceInputsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceInputsUIBlock.cs @@ -21,6 +21,7 @@ public class Styles public static GUIContent normalMapText = new GUIContent("Normal Map", "Specifies the normal map for this Material (BC7/BC5/DXT5(nm))."); public static GUIContent decalBlendText = new GUIContent("Global Opacity", "Controls the opacity of the entire decal."); public static GUIContent albedoModeText = new GUIContent("Affect BaseColor", "Base color + Opacity, Opacity only."); + public static GUIContent normalModeText = new GUIContent("Affect Normal", "TODO"); public static GUIContent normalOpacityChannelText = new GUIContent("Normal Opacity Channel", "Specifies the source this Material uses as opacity for its Normal Map."); public static GUIContent smoothnessRemappingText = new GUIContent("Smoothness Remapping", "Controls a remap for the smoothness channel in the Mask Map."); public static GUIContent metallicText = new GUIContent("Metallic Scale", "Controls a scale factor for the metallic channel in the Mask Map."); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DistortionUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DistortionUIBlock.cs index cdcf1add479..a77a4ae9bc6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DistortionUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DistortionUIBlock.cs @@ -7,7 +7,7 @@ namespace UnityEditor.Rendering.HighDefinition { class DistortionUIBlock : MaterialUIBlock { - protected static class Styles + internal static class Styles { public static GUIContent distortionEnableText = new GUIContent("Distortion", "When enabled, HDRP processes distortion for this Material."); public static GUIContent distortionOnlyText = new GUIContent("Distortion Only", "When enabled, HDRP only uses this Material to render distortion."); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitSurfaceInputsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitSurfaceInputsUIBlock.cs index 004228f7c63..c90c9a06bc2 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitSurfaceInputsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitSurfaceInputsUIBlock.cs @@ -69,6 +69,7 @@ public class Styles // Subsurface public static GUIContent diffusionProfileText = new GUIContent("Diffusion Profile", "Specifies the Diffusion Profie HDRP uses to determine the behavior of the subsurface scattering/transmission effect."); + public static GUIContent subsurfaceEnableText = new GUIContent("Subsurface Scattering", "Enables the subsurface scattering on the material."); public static GUIContent subsurfaceMaskText = new GUIContent("Subsurface Mask", "Controls the overall strength of the subsurface scattering effect."); public static GUIContent subsurfaceMaskMapText = new GUIContent("Subsurface Mask Map", "Specifies the Subsurface mask map (R) for this Material - This map controls the strength of the subsurface scattering effect."); public static GUIContent thicknessText = new GUIContent("Thickness", "Controls the strength of the Thickness Map, low values allow some light to transmit through the object."); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/RefractionUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/RefractionUIBlock.cs index 22804b829bd..52993cd879a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/RefractionUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/RefractionUIBlock.cs @@ -10,7 +10,7 @@ namespace UnityEditor.Rendering.HighDefinition { class RefractionUIBlock : MaterialUIBlock { - protected static class Styles + internal static class Styles { public static string refractionModelText = "Refraction Model"; public static GUIContent refractionIorText = new GUIContent("Index Of Refraction", "Controls the index of refraction for this Material."); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/SurfaceOptionUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/SurfaceOptionUIBlock.cs index 677dc24ac30..9cbc2afbd6e 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/SurfaceOptionUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/SurfaceOptionUIBlock.cs @@ -9,7 +9,7 @@ namespace UnityEditor.Rendering.HighDefinition { - class SurfaceOptionUIBlock : MaterialUIBlock + internal class SurfaceOptionUIBlock : MaterialUIBlock { [Flags] public enum Features @@ -32,7 +32,7 @@ public enum Features All = ~0, } - static class Styles + internal static class Styles { public const string optionText = "Surface Options"; public const string surfaceTypeText = "Surface Type"; @@ -580,7 +580,7 @@ void SurfaceTypePopup() var newMode = (SurfaceType)EditorGUILayout.Popup(Styles.surfaceTypeText, (int)mode, Styles.surfaceTypeNames); if (newMode != mode) //EditorGUI.EndChangeCheck is called even if value remain the same after the popup. Prefer not to use it here { - materialEditor.RegisterPropertyChangeUndo("Surface Type"); + materialEditor.RegisterPropertyChangeUndo(Styles.surfaceTypeText); surfaceType.floatValue = (float)newMode; HDRenderQueue.RenderQueueType targetQueueType; switch(newMode) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs index adf10bd6f3e..b1aa150d61d 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs @@ -1,15 +1,27 @@ -using System.IO; -using UnityEditor.ProjectWindowCallback; +using System; using UnityEditor.ShaderGraph; -namespace UnityEditor.Rendering.HighDefinition +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { - static class CreateHDUnlitShaderGraph + static class CreateUnlitShaderGraph { - [MenuItem("Assets/Create/Shader/HDRP/Unlit Graph", false, 208)] - public static void CreateMaterialGraph() + [MenuItem("Assets/Create/Shader/HDRP/Unlit Shader Graph", false, 208)] + public static void CreateHDUnlitGraph() { - GraphUtil.CreateNewGraph(new HDUnlitMasterNode()); + var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); + target.TrySetActiveSubTarget(typeof(HDUnlitSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs.meta index 21be91b3e72..06f73c2ed0e 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs.meta +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: ba0ffd782e187fc4486b762f67621be6 +guid: 1703bfc139ae22a4faa011b24dd26fca MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitData.cs new file mode 100644 index 00000000000..8d229a24df1 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitData.cs @@ -0,0 +1,25 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class HDUnlitData : HDTargetData + { + [SerializeField] + bool m_EnableShadowMatte = false; + public bool enableShadowMatte + { + get => m_EnableShadowMatte; + set => m_EnableShadowMatte = value; + } + + [SerializeField] + bool m_DistortionOnly = false; + public bool distortionOnly + { + get => m_DistortionOnly; + set => m_DistortionOnly = value; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitData.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitData.cs.meta new file mode 100644 index 00000000000..b11c86fd614 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3c681ab36327fd947bb5eecfdd3bb5d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitDistortionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitDistortionPropertyBlock.cs new file mode 100644 index 00000000000..b52e23c356c --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitDistortionPropertyBlock.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.DistortionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class HDUnlitDistortionPropertyBlock : DistortionPropertyBlock + { + HDUnlitData unlitData; + + public HDUnlitDistortionPropertyBlock(HDUnlitData unlitData) => this.unlitData = unlitData; + + protected override void CreatePropertyGUI() + { + AddProperty(distortionOnlyText, () => unlitData.distortionOnly, (newValue) => unlitData.distortionOnly = newValue); + base.CreatePropertyGUI(); + } + } +} \ No newline at end of file diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitDistortionPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitDistortionPropertyBlock.cs.meta new file mode 100644 index 00000000000..a60954392f9 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitDistortionPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4905ec7b1708c8d4aad3bebdab1a6ef8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitMasterNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitMasterNode.cs deleted file mode 100644 index 79b49b4cd8e..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitMasterNode.cs +++ /dev/null @@ -1,593 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Rendering.HighDefinition.Drawing; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEngine.Rendering.HighDefinition; -using UnityEditor.ShaderGraph.Drawing.Inspector; -using UnityEditor.ShaderGraph.Internal; -using UnityEngine.Rendering; -using UnityEditor.Rendering.HighDefinition.ShaderGraph; - -// Include material common properties names -using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; - -namespace UnityEditor.Rendering.HighDefinition -{ - [Serializable] - [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.HDUnlitMasterNode")] - [Title("Master", "Unlit (HDRP)")] - class HDUnlitMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string ColorSlotName = "Color"; - public const string AlphaSlotName = "Alpha"; - public const string AlphaClipThresholdSlotName = "AlphaClipThreshold"; - public const string DistortionSlotName = "Distortion"; - public const string DistortionSlotDisplayName = "Distortion Vector"; - public const string DistortionBlurSlotName = "DistortionBlur"; - public const string PositionSlotName = "Vertex Position"; - public const string PositionSlotDisplayName = "Vertex Position"; - public const string EmissionSlotName = "Emission"; - public const string VertexNormalSlotName = "Vertex Normal"; - public const string VertexTangentSlotName = "Vertex Tangent"; - public const string ShadowTintSlotName = "Shadow Tint"; - - public const int ColorSlotId = 0; - public const int AlphaSlotId = 7; - public const int AlphaThresholdSlotId = 8; - public const int PositionSlotId = 9; - public const int DistortionSlotId = 10; - public const int DistortionBlurSlotId = 11; - public const int EmissionSlotId = 12; - public const int VertexNormalSlotId = 13; - public const int VertexTangentSlotId = 14; - public const int ShadowTintSlotId = 15; - - // Don't support Multiply - public enum AlphaModeLit - { - Alpha, - Premultiply, - Additive, - } - - [SerializeField] - SurfaceType m_SurfaceType; - - public SurfaceType surfaceType - { - get { return m_SurfaceType; } - set - { - if (m_SurfaceType == value) - return; - - m_SurfaceType = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - AlphaMode m_AlphaMode; - - public AlphaMode alphaMode - { - get { return m_AlphaMode; } - set - { - if (m_AlphaMode == value) - return; - - m_AlphaMode = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - HDRenderQueue.RenderQueueType m_RenderingPass = HDRenderQueue.RenderQueueType.Opaque; - - public HDRenderQueue.RenderQueueType renderingPass - { - get { return m_RenderingPass; } - set - { - if (m_RenderingPass == value) - return; - - m_RenderingPass = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_TransparencyFog = true; - - public ToggleData transparencyFog - { - get { return new ToggleData(m_TransparencyFog); } - set - { - if (m_TransparencyFog == value.isOn) - return; - m_TransparencyFog = value.isOn; - Dirty(ModificationScope.Graph); - } - } - -#pragma warning disable 649 - [SerializeField, Obsolete("Kept for data migration")] - internal bool m_DrawBeforeRefraction; -#pragma warning restore 649 - - [SerializeField] - bool m_Distortion; - - public ToggleData distortion - { - get { return new ToggleData(m_Distortion); } - set - { - if (m_Distortion == value.isOn) - return; - m_Distortion = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - DistortionMode m_DistortionMode; - - public DistortionMode distortionMode - { - get { return m_DistortionMode; } - set - { - if (m_DistortionMode == value) - return; - - m_DistortionMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_DistortionOnly = true; - - public ToggleData distortionOnly - { - get { return new ToggleData(m_DistortionOnly); } - set - { - if (m_DistortionOnly == value.isOn) - return; - m_DistortionOnly = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_DistortionDepthTest = true; - - public ToggleData distortionDepthTest - { - get { return new ToggleData(m_DistortionDepthTest); } - set - { - if (m_DistortionDepthTest == value.isOn) - return; - m_DistortionDepthTest = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AlphaTest; - - public ToggleData alphaTest - { - get { return new ToggleData(m_AlphaTest); } - set - { - if (m_AlphaTest == value.isOn) - return; - m_AlphaTest = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaToMask = false; - - public ToggleData alphaToMask - { - get { return new ToggleData(m_AlphaToMask); } - set - { - if (m_AlphaToMask == value.isOn) - return; - - m_AlphaToMask = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - int m_SortPriority; - - public int sortPriority - { - get { return m_SortPriority; } - set - { - if (m_SortPriority == value) - return; - m_SortPriority = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_DoubleSided; - - public ToggleData doubleSided - { - get { return new ToggleData(m_DoubleSided); } - set - { - if (m_DoubleSided == value.isOn) - return; - m_DoubleSided = value.isOn; - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_ZWrite = true; - - public ToggleData zWrite - { - get { return new ToggleData(m_ZWrite); } - set - { - if (m_ZWrite == value.isOn) - return; - m_ZWrite = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - TransparentCullMode m_transparentCullMode = TransparentCullMode.Back; - public TransparentCullMode transparentCullMode - { - get => m_transparentCullMode; - set - { - if (m_transparentCullMode == value) - return; - - m_transparentCullMode = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - CompareFunction m_ZTest = CompareFunction.LessEqual; - public CompareFunction zTest - { - get => m_ZTest; - set - { - if (m_ZTest == value) - return; - - m_ZTest = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AddPrecomputedVelocity = false; - - public ToggleData addPrecomputedVelocity - { - get { return new ToggleData(m_AddPrecomputedVelocity); } - set - { - if (m_AddPrecomputedVelocity == value.isOn) - return; - m_AddPrecomputedVelocity = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_EnableShadowMatte = false; - - public ToggleData enableShadowMatte - { - get { return new ToggleData(m_EnableShadowMatte); } - set - { - if (m_EnableShadowMatte == value.isOn) - return; - m_EnableShadowMatte = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_DOTSInstancing = false; - - public ToggleData dotsInstancing - { - get { return new ToggleData(m_DOTSInstancing); } - set - { - if (m_DOTSInstancing == value.isOn) - return; - - m_DOTSInstancing = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public HDUnlitMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - public override string documentationURL => Documentation.GetPageLink("Master-Node-Unlit"); - - public bool HasDistortion() - { - return (surfaceType == SurfaceType.Transparent && distortion.isOn); - } - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "Unlit Master"; - - List validSlots = new List(); - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionSlotDisplayName, PositionSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(PositionSlotId); - AddSlot(new NormalMaterialSlot(VertexNormalSlotId, VertexNormalSlotName, VertexNormalSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexNormalSlotId); - AddSlot(new TangentMaterialSlot(VertexTangentSlotId, VertexTangentSlotName, VertexTangentSlotName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - validSlots.Add(VertexTangentSlotId); - AddSlot(new ColorRGBMaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); - validSlots.Add(ColorSlotId); - AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaSlotId); - AddSlot(new Vector1MaterialSlot(AlphaThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - validSlots.Add(AlphaThresholdSlotId); - AddSlot(new ColorRGBMaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Color.black, ColorMode.HDR, ShaderStageCapability.Fragment)); - validSlots.Add(EmissionSlotId); - - if (HasDistortion()) - { - AddSlot(new Vector2MaterialSlot(DistortionSlotId, DistortionSlotDisplayName, DistortionSlotName, SlotType.Input, new Vector2(0.0f, 0.0f), ShaderStageCapability.Fragment)); - validSlots.Add(DistortionSlotId); - - AddSlot(new Vector1MaterialSlot(DistortionBlurSlotId, DistortionBlurSlotName, DistortionBlurSlotName, SlotType.Input, 1.0f, ShaderStageCapability.Fragment)); - validSlots.Add(DistortionBlurSlotId); - } - - if (enableShadowMatte.isOn) - { - AddSlot(new ColorRGBAMaterialSlot(ShadowTintSlotId, ShadowTintSlotName, ShadowTintSlotName, SlotType.Input, Color.black, ShaderStageCapability.Fragment)); - validSlots.Add(ShadowTintSlotId); - } - - RemoveSlotsNameNotMatching(validSlots, true); - } - - public VisualElement CreateSettingsElement() - { - return new HDUnlitSettingsView(this); - } - - public string renderQueueTag - { - get - { - int queue = HDRenderQueue.ChangeType(renderingPass, sortPriority, alphaTest.isOn); - return HDRenderQueue.GetShaderTagValue(queue); - } - } - - public string renderTypeTag => HDRenderTypeTags.HDUnlitShader.ToString(); - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PositionSlotId) || - IsSlotConnected(VertexNormalSlotId) || - IsSlotConnected(VertexTangentSlotId)), - new ConditionalField(Fields.GraphPixel, true), - - // Distortion - new ConditionalField(HDFields.DistortionDepthTest, distortionDepthTest.isOn), - new ConditionalField(HDFields.DistortionAdd, distortionMode == DistortionMode.Add), - new ConditionalField(HDFields.DistortionMultiply, distortionMode == DistortionMode.Multiply), - new ConditionalField(HDFields.DistortionReplace, distortionMode == DistortionMode.Replace), - new ConditionalField(HDFields.TransparentDistortion, surfaceType != SurfaceType.Opaque && distortion.isOn), - - // Misc - new ConditionalField(Fields.AlphaTest, alphaTest.isOn && pass.pixelPorts.Contains(AlphaThresholdSlotId)), - new ConditionalField(HDFields.DoAlphaTest, alphaTest.isOn && pass.pixelPorts.Contains(AlphaThresholdSlotId)), - new ConditionalField(Fields.AlphaToMask, alphaTest.isOn && pass.pixelPorts.Contains(AlphaThresholdSlotId) && alphaToMask.isOn), - new ConditionalField(HDFields.AlphaFog, surfaceType != SurfaceType.Opaque && transparencyFog.isOn), - new ConditionalField(Fields.VelocityPrecomputed, addPrecomputedVelocity.isOn), - new ConditionalField(HDFields.EnableShadowMatte, enableShadowMatte.isOn), - }; - } - - public void ProcessPreviewMaterial(Material material) - { - // Fixup the material settings: - material.SetFloat(kSurfaceType, (int)(SurfaceType)surfaceType); - material.SetFloat(kDoubleSidedEnable, doubleSided.isOn ? 1.0f : 0.0f); - material.SetFloat(kAlphaCutoffEnabled, alphaTest.isOn ? 1 : 0); - material.SetFloat(kBlendMode, (int)HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode)); - material.SetFloat(kEnableFogOnTransparent, transparencyFog.isOn ? 1.0f : 0.0f); - material.SetFloat(kZTestTransparent, (int)zTest); - material.SetFloat(kTransparentCullMode, (int)transparentCullMode); - material.SetFloat(kZWrite, zWrite.isOn ? 1.0f : 0.0f); - // No sorting priority for shader graph preview - material.renderQueue = (int)HDRenderQueue.ChangeType(renderingPass, offset: 0, alphaTest: alphaTest.isOn); - - HDUnlitGUI.SetupMaterialKeywordsAndPass(material); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - var slotRequirements = validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - - return slotRequirements | (transparencyFog.isOn ? NeededCoordinateSpace.World : 0); - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - var slotRequirements = validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - return (enableShadowMatte.isOn ? 0 : slotRequirements); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - var slotRequirements = validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - return (enableShadowMatte.isOn ? 0 : slotRequirements); - } - - public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) - { - // Trunk currently relies on checking material property "_EmissionColor" to allow emissive GI. If it doesn't find that property, or it is black, GI is forced off. - // ShaderGraph doesn't use this property, so currently it inserts a dummy color (white). This dummy color may be removed entirely once the following PR has been merged in trunk: Pull request #74105 - // The user will then need to explicitly disable emissive GI if it is not needed. - // To be able to automatically disable emission based on the ShaderGraph config when emission is black, - // we will need a more general way to communicate this to the engine (not directly tied to a material property). - collector.AddShaderProperty(new ColorShaderProperty() - { - overrideReferenceName = "_EmissionColor", - hidden = true, - value = new Color(1.0f, 1.0f, 1.0f, 1.0f) - }); - - // ShaderGraph only property used to send the RenderQueueType to the material - collector.AddShaderProperty(new Vector1ShaderProperty - { - overrideReferenceName = "_RenderQueueType", - hidden = true, - value = (int)renderingPass, - }); - - //See SG-ADDITIONALVELOCITY-NOTE - if (addPrecomputedVelocity.isOn) - { - collector.AddShaderProperty(new BooleanShaderProperty - { - value = true, - hidden = true, - overrideReferenceName = kAddPrecomputedVelocity, - }); - } - - if (enableShadowMatte.isOn) - { - uint mantissa = ((uint)LightFeatureFlags.Punctual | (uint)LightFeatureFlags.Directional | (uint)LightFeatureFlags.Area) & 0x007FFFFFu; - uint exponent = 0b10000000u; // 0 as exponent - collector.AddShaderProperty(new Vector1ShaderProperty - { - hidden = true, - value = HDShadowUtils.Asfloat((exponent << 23) | mantissa), - overrideReferenceName = HDMaterialProperties.kShadowMatteFilter - }); - } - - // Add all shader properties required by the inspector - HDSubShaderUtilities.AddStencilShaderProperties(collector, false, false, false, false); - HDSubShaderUtilities.AddBlendingStatesShaderProperties( - collector, - surfaceType, - HDSubShaderUtilities.ConvertAlphaModeToBlendMode(alphaMode), - sortPriority, - alphaTest.isOn, - zWrite.isOn, - transparentCullMode, - zTest, - false, - transparencyFog.isOn - ); - HDSubShaderUtilities.AddAlphaCutoffShaderProperties(collector, alphaTest.isOn, false); - HDSubShaderUtilities.AddDoubleSidedProperty(collector, doubleSided.isOn ? DoubleSidedMode.Enabled : DoubleSidedMode.Disabled); - HDSubShaderUtilities.AddPrePostPassProperties(collector, false, false); - - base.CollectShaderProperties(collector, generationMode); - } - - public bool supportsVirtualTexturing => true; - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitMasterNode.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitMasterNode.cs.meta deleted file mode 100644 index d1f14c59069..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitMasterNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ef07057e81190cb4a8f456250f15df2a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitPass.template b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitPass.template index 6a0af19ec16..f89d07d5885 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitPass.template +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitPass.template @@ -99,7 +99,7 @@ Pass ZERO_INITIALIZE(SurfaceData, surfaceData); // copy across graph values, if defined - $SurfaceDescription.Color: surfaceData.color = surfaceDescription.Color; + $SurfaceDescription.BaseColor: surfaceData.color = surfaceDescription.BaseColor; #if defined(DEBUG_DISPLAY) if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSettingsView.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSettingsView.cs deleted file mode 100644 index ff53f62f509..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSettingsView.cs +++ /dev/null @@ -1,461 +0,0 @@ -using System; -using UnityEditor.UIElements; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEditor.Graphing.Util; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEditor.Rendering.HighDefinition; -using UnityEngine.Rendering.HighDefinition; -using UnityEngine.Rendering; - -namespace UnityEditor.Rendering.HighDefinition.Drawing -{ - class HDUnlitSettingsView : MasterNodeSettingsView - { - HDUnlitMasterNode m_Node; - - IntegerField m_SortPiorityField; - - Label CreateLabel(string text, int indentLevel) - { - string label = ""; - for (var i = 0; i < indentLevel; i++) - { - label += " "; - } - return new Label(label + text); - } - - public HDUnlitSettingsView(HDUnlitMasterNode node) : base(node) - { - m_Node = node; - PropertySheet ps = new PropertySheet(); - - int indentLevel = 0; - ps.Add(new PropertyRow(CreateLabel("Surface Type", indentLevel)), (row) => - { - row.Add(new EnumField(SurfaceType.Opaque), (field) => - { - field.value = m_Node.surfaceType; - field.RegisterValueChangedCallback(ChangeSurfaceType); - }); - }); - - ++indentLevel; - switch (m_Node.surfaceType) - { - case SurfaceType.Opaque: - ps.Add(new PropertyRow(CreateLabel("Rendering Pass", indentLevel)), (row) => - { - var valueList = HDSubShaderUtilities.GetRenderingPassList(true, true); - - row.Add(new PopupField(valueList, HDRenderQueue.RenderQueueType.Opaque, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName), (field) => - { - field.value = HDRenderQueue.GetOpaqueEquivalent(m_Node.renderingPass); - field.RegisterValueChangedCallback(ChangeRenderingPass); - }); - }); - break; - case SurfaceType.Transparent: - ps.Add(new PropertyRow(CreateLabel("Rendering Pass", indentLevel)), (row) => - { - Enum defaultValue; - switch (m_Node.renderingPass) // Migration - { - default: //when deserializing without issue, we still need to init the default to something even if not used. - case HDRenderQueue.RenderQueueType.Transparent: - defaultValue = HDRenderQueue.TransparentRenderQueue.Default; - break; - case HDRenderQueue.RenderQueueType.PreRefraction: - defaultValue = HDRenderQueue.TransparentRenderQueue.BeforeRefraction; - break; - } - - var valueList = HDSubShaderUtilities.GetRenderingPassList(false, true); - - row.Add(new PopupField(valueList, HDRenderQueue.RenderQueueType.Transparent, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName), (field) => - { - field.value = HDRenderQueue.GetTransparentEquivalent(m_Node.renderingPass); - field.RegisterValueChangedCallback(ChangeRenderingPass); - }); - }); - break; - default: - throw new ArgumentException("Unknown SurfaceType"); - } - --indentLevel; - - if (m_Node.surfaceType == SurfaceType.Transparent) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Blending Mode", indentLevel)), (row) => - { - row.Add(new EnumField(HDUnlitMasterNode.AlphaModeLit.Additive), (field) => - { - field.value = GetAlphaModeLit(m_Node.alphaMode); - field.RegisterValueChangedCallback(ChangeBlendMode); - }); - }); - - m_SortPiorityField = new IntegerField(); - ps.Add(new PropertyRow(CreateLabel("Sorting Priority", indentLevel)), (row) => - { - row.Add(m_SortPiorityField, (field) => - { - field.value = m_Node.sortPriority; - field.RegisterValueChangedCallback(ChangeSortPriority); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Receive Fog", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.transparencyFog.isOn; - toggle.OnToggleChanged(ChangeTransparencyFog); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Distortion", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.distortion.isOn; - toggle.OnToggleChanged(ChangeDistortion); - }); - }); - - if (m_Node.distortion.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Distortion Blend Mode", indentLevel)), (row) => - { - row.Add(new EnumField(DistortionMode.Add), (field) => - { - field.value = m_Node.distortionMode; - field.RegisterValueChangedCallback(ChangeDistortionMode); - }); - }); - ps.Add(new PropertyRow(CreateLabel("Distortion Only", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.distortionOnly.isOn; - toggle.OnToggleChanged(ChangeDistortionOnly); - }); - }); - ps.Add(new PropertyRow(CreateLabel("Distortion Depth Test", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.distortionDepthTest.isOn; - toggle.OnToggleChanged(ChangeDistortionDepthTest); - }); - }); - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Depth Write", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.zWrite.isOn; - toggle.OnToggleChanged(ChangeZWrite); - }); - }); - - if (!m_Node.doubleSided.isOn) - { - ps.Add(new PropertyRow(CreateLabel("Cull Mode", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.transparentCullMode), (e) => - { - e.value = m_Node.transparentCullMode; - e.RegisterValueChangedCallback(ChangeTransparentCullMode); - }); - }); - } - - ps.Add(new PropertyRow(CreateLabel("Depth Test", indentLevel)), (row) => - { - row.Add(new EnumField(m_Node.zTest), (e) => - { - e.value = m_Node.zTest; - e.RegisterValueChangedCallback(ChangeZTest); - }); - }); - - --indentLevel; - } - - ps.Add(new PropertyRow(new Label("Double-Sided")), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.doubleSided.isOn; - toggle.OnToggleChanged(ChangeDoubleSided); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Alpha Clipping", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTest.isOn; - toggle.OnToggleChanged(ChangeAlphaTest); - }); - }); - - if (m_Node.alphaTest.isOn) - { - ++indentLevel; - ps.Add(new PropertyRow(CreateLabel("Alpha to Mask", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaToMask.isOn; - toggle.OnToggleChanged(ChangeAlphaToMask); - }); - }); - --indentLevel; - } - - ps.Add(new PropertyRow(CreateLabel("Add Precomputed Velocity", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.addPrecomputedVelocity.isOn; - toggle.OnToggleChanged(ChangeAddPrecomputedVelocity); - }); - }); - - ps.Add(new PropertyRow(CreateLabel("Shadow Matte", indentLevel)), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.enableShadowMatte.isOn; - toggle.OnToggleChanged(ChangeEnableShadowMatte); - }); - }); - - Add(ps); - Add(GetShaderGUIOverridePropertySheet()); - } - - void ChangeSurfaceType(ChangeEvent evt) - { - if (Equals(m_Node.surfaceType, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Surface Type Change"); - m_Node.surfaceType = (SurfaceType)evt.newValue; - - UpdateRenderingPassValue(m_Node.renderingPass); - } - - void ChangeDoubleSided(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Double-Sided Change"); - ToggleData td = m_Node.doubleSided; - td.isOn = evt.newValue; - m_Node.doubleSided = td; - } - - void ChangeBlendMode(ChangeEvent evt) - { - // Make sure the mapping is correct by handling each case. - - AlphaMode alphaMode = GetAlphaMode((HDUnlitMasterNode.AlphaModeLit)evt.newValue); - - if (Equals(m_Node.alphaMode, alphaMode)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Mode Change"); - m_Node.alphaMode = alphaMode; - } - - void ChangeTransparencyFog(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparency Fog Change"); - ToggleData td = m_Node.transparencyFog; - td.isOn = evt.newValue; - m_Node.transparencyFog = td; - } - - void ChangeRenderingPass(ChangeEvent evt) - { - switch (evt.newValue) - { - case HDRenderQueue.RenderQueueType.Overlay: - case HDRenderQueue.RenderQueueType.Unknown: - case HDRenderQueue.RenderQueueType.Background: - throw new ArgumentException("Unexpected kind of RenderQueue, was " + evt.newValue); - default: - break; - }; - UpdateRenderingPassValue(evt.newValue); - } - - void UpdateRenderingPassValue(HDRenderQueue.RenderQueueType newValue) - { - HDRenderQueue.RenderQueueType renderingPass; - switch (m_Node.surfaceType) - { - case SurfaceType.Opaque: - renderingPass = HDRenderQueue.GetOpaqueEquivalent(newValue); - break; - case SurfaceType.Transparent: - renderingPass = HDRenderQueue.GetTransparentEquivalent(newValue); - break; - default: - throw new ArgumentException("Unknown SurfaceType"); - } - - if (Equals(m_Node.renderingPass, renderingPass)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Rendering Pass Change"); - m_Node.renderingPass = renderingPass; - } - - void ChangeDistortion(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Change"); - ToggleData td = m_Node.distortion; - td.isOn = evt.newValue; - m_Node.distortion = td; - } - - void ChangeDistortionMode(ChangeEvent evt) - { - if (Equals(m_Node.distortionMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Mode Change"); - m_Node.distortionMode = (DistortionMode)evt.newValue; - } - - void ChangeDistortionOnly(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Only Change"); - ToggleData td = m_Node.distortionOnly; - td.isOn = evt.newValue; - m_Node.distortionDepthTest = td; - } - - void ChangeDistortionDepthTest(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Depth Test Change"); - ToggleData td = m_Node.distortionDepthTest; - td.isOn = evt.newValue; - m_Node.distortionDepthTest = td; - } - - void ChangeSortPriority(ChangeEvent evt) - { - m_Node.sortPriority = HDRenderQueue.ClampsTransparentRangePriority(evt.newValue); - // Force the text to match. - m_SortPiorityField.value = m_Node.sortPriority; - if (Equals(m_Node.sortPriority, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Sort Priority Change"); - } - - void ChangeAlphaTest(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Change"); - ToggleData td = m_Node.alphaTest; - td.isOn = evt.newValue; - m_Node.alphaTest = td; - } - - void ChangeAlphaToMask(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha to Mask Change"); - ToggleData td = m_Node.alphaToMask; - td.isOn = evt.newValue; - m_Node.alphaToMask = td; - } - - void ChangeAddPrecomputedVelocity(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Add Precomputed Velocity"); - ToggleData td = m_Node.addPrecomputedVelocity; - td.isOn = evt.newValue; - m_Node.addPrecomputedVelocity = td; - } - - void ChangeEnableShadowMatte(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("Shadow Matte"); - ToggleData td = m_Node.enableShadowMatte; - td.isOn = evt.newValue; - m_Node.enableShadowMatte = td; - } - - void ChangeZWrite(ChangeEvent evt) - { - m_Node.owner.owner.RegisterCompleteObjectUndo("ZWrite Change"); - ToggleData td = m_Node.zWrite; - td.isOn = evt.newValue; - m_Node.zWrite = td; - } - - void ChangeTransparentCullMode(ChangeEvent evt) - { - if (Equals(m_Node.transparentCullMode, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Transparent Cull Mode Change"); - m_Node.transparentCullMode = (TransparentCullMode)evt.newValue; - } - - void ChangeZTest(ChangeEvent evt) - { - if (Equals(m_Node.zTest, evt.newValue)) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("ZTest Change"); - m_Node.zTest = (CompareFunction)evt.newValue; - } - - public AlphaMode GetAlphaMode(HDUnlitMasterNode.AlphaModeLit alphaModeLit) - { - switch (alphaModeLit) - { - case HDUnlitMasterNode.AlphaModeLit.Alpha: - return AlphaMode.Alpha; - case HDUnlitMasterNode.AlphaModeLit.Premultiply: - return AlphaMode.Premultiply; - case HDUnlitMasterNode.AlphaModeLit.Additive: - return AlphaMode.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaModeLit); - return AlphaMode.Alpha; - } - } - } - - public HDUnlitMasterNode.AlphaModeLit GetAlphaModeLit(AlphaMode alphaMode) - { - switch (alphaMode) - { - case AlphaMode.Alpha: - return HDUnlitMasterNode.AlphaModeLit.Alpha; - case AlphaMode.Premultiply: - return HDUnlitMasterNode.AlphaModeLit.Premultiply; - case AlphaMode.Additive: - return HDUnlitMasterNode.AlphaModeLit.Additive; - default: - { - Debug.LogWarning("Not supported: " + alphaMode); - return HDUnlitMasterNode.AlphaModeLit.Alpha; - } - } - } - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSettingsView.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSettingsView.cs.meta deleted file mode 100644 index 27342fdb336..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSettingsView.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 775f9331f25e19640bcba701363f3f36 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.Migration.cs new file mode 100644 index 00000000000..87f43f75dfc --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.Migration.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + sealed partial class HDUnlitSubTarget : SurfaceSubTarget, ILegacyTarget, IRequiresData + { + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + switch(masterNode) + { + case UnlitMasterNode1 unlitMasterNode: + UpgradeUnlitMasterNode(unlitMasterNode, out blockMap); + return true; + case HDUnlitMasterNode1 hdUnlitMasterNode: + UpgradeHDUnlitMasterNode(hdUnlitMasterNode, out blockMap); + return true; + default: + return false; + } + } + + void UpgradeUnlitMasterNode(UnlitMasterNode1 unlitMasterNode, out Dictionary blockMap) + { + m_MigrateFromOldCrossPipelineSG = true; + + // Set data + systemData.surfaceType = (SurfaceType)unlitMasterNode.m_SurfaceType; + systemData.blendMode = HDSubShaderUtilities.UpgradeLegacyAlphaModeToBlendMode((int)unlitMasterNode.m_AlphaMode); + // Previous master node wasn't having any renderingPass. Assign it correctly now. + systemData.renderingPass = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent; + systemData.doubleSidedMode = unlitMasterNode.m_TwoSided ? DoubleSidedMode.Enabled : DoubleSidedMode.Disabled; + systemData.alphaTest = HDSubShaderUtilities.UpgradeLegacyAlphaClip(unlitMasterNode); + systemData.dotsInstancing = false; + systemData.zWrite = false; + builtinData.addPrecomputedVelocity = false; + target.customEditorGUI = unlitMasterNode.m_OverrideEnabled ? unlitMasterNode.m_ShaderGUIOverride : ""; + + // Set blockmap + blockMap = new Dictionary() + { + { BlockFields.VertexDescription.Position, 9 }, + { BlockFields.VertexDescription.Normal, 10 }, + { BlockFields.VertexDescription.Tangent, 11 }, + { BlockFields.SurfaceDescription.BaseColor, 0 }, + { BlockFields.SurfaceDescription.Alpha, 7 }, + { BlockFields.SurfaceDescription.AlphaClipThreshold, 8 }, + }; + } + + void UpgradeHDUnlitMasterNode(HDUnlitMasterNode1 hdUnlitMasterNode, out Dictionary blockMap) + { + // Set data + systemData.surfaceType = (SurfaceType)hdUnlitMasterNode.m_SurfaceType; + systemData.blendMode = HDSubShaderUtilities.UpgradeLegacyAlphaModeToBlendMode((int)hdUnlitMasterNode.m_AlphaMode); + systemData.renderingPass = hdUnlitMasterNode.m_RenderingPass; + // Patch rendering pass in case the master node had an old configuration + if (systemData.renderingPass == HDRenderQueue.RenderQueueType.Background) + systemData.renderingPass = HDRenderQueue.RenderQueueType.Opaque; + systemData.alphaTest = hdUnlitMasterNode.m_AlphaTest; + systemData.sortPriority = hdUnlitMasterNode.m_SortPriority; + systemData.doubleSidedMode = hdUnlitMasterNode.m_DoubleSided ? DoubleSidedMode.Enabled : DoubleSidedMode.Disabled; + systemData.zWrite = hdUnlitMasterNode.m_ZWrite; + systemData.transparentCullMode = hdUnlitMasterNode.m_transparentCullMode; + systemData.zTest = hdUnlitMasterNode.m_ZTest; + systemData.dotsInstancing = hdUnlitMasterNode.m_DOTSInstancing; + + builtinData.transparencyFog = hdUnlitMasterNode.m_TransparencyFog; + builtinData.distortion = hdUnlitMasterNode.m_Distortion; + builtinData.distortionMode = hdUnlitMasterNode.m_DistortionMode; + builtinData.distortionDepthTest = hdUnlitMasterNode.m_DistortionDepthTest; + builtinData.alphaToMask = hdUnlitMasterNode.m_AlphaToMask; + builtinData.addPrecomputedVelocity = hdUnlitMasterNode.m_AddPrecomputedVelocity; + + unlitData.enableShadowMatte = hdUnlitMasterNode.m_EnableShadowMatte; + target.customEditorGUI = hdUnlitMasterNode.m_OverrideEnabled ? hdUnlitMasterNode.m_ShaderGUIOverride : ""; + + // Set blockmap + blockMap = new Dictionary() + { + { BlockFields.VertexDescription.Position, 9 }, + { BlockFields.VertexDescription.Normal, 13 }, + { BlockFields.VertexDescription.Tangent, 14 }, + { BlockFields.SurfaceDescription.BaseColor, 0 }, + { BlockFields.SurfaceDescription.Alpha, 7 }, + { BlockFields.SurfaceDescription.AlphaClipThreshold, 8 }, + { BlockFields.SurfaceDescription.Emission, 12 }, + }; + + // Distortion + if(systemData.surfaceType == SurfaceType.Transparent && builtinData.distortion) + { + blockMap.Add(HDBlockFields.SurfaceDescription.Distortion, 10); + blockMap.Add(HDBlockFields.SurfaceDescription.DistortionBlur, 11); + } + + // Shadow Matte + if(unlitData.enableShadowMatte) + { + blockMap.Add(HDBlockFields.SurfaceDescription.ShadowTint, 15); + } + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.Migration.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.Migration.cs.meta new file mode 100644 index 00000000000..bd0d178a115 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.Migration.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e482c35cd40244042ba665e0ec08a4b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.cs index fbb341b84cf..a1567fe2fa4 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.cs @@ -1,25 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; using UnityEngine.Rendering.HighDefinition; using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy; +using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties; +using static UnityEditor.Rendering.HighDefinition.HDShaderUtils; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { - sealed class HDUnlitSubTarget : SubTarget + sealed partial class HDUnlitSubTarget : SurfaceSubTarget, ILegacyTarget, IRequiresData { - const string kAssetGuid = "4516595d40fa52047a77940183dc8e74"; - + // Templates + // TODO: Why do the raytracing passes use the template for the pipeline agnostic Unlit master node? + // TODO: This should be resolved so we can delete the second pass template static string passTemplatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/Unlit/ShaderGraph/HDUnlitPass.template"; + protected override ShaderID shaderID => HDShaderUtils.ShaderID.SG_Unlit; + protected override string renderType => HDRenderTypeTags.HDUnlitShader.ToString(); + protected override string subTargetAssetGuid => "4516595d40fa52047a77940183dc8e74"; // HDUnlitSubTarget + protected override string customInspector => "Rendering.HighDefinition.HDUnlitGUI"; + + public HDUnlitSubTarget() => displayName = "Unlit"; - public HDUnlitSubTarget() + HDUnlitData m_UnlitData; + + HDUnlitData IRequiresData.data { - displayName = "Unlit"; + get => m_UnlitData; + set => m_UnlitData = value; } - public override void Setup(ref TargetSetupContext context) + public HDUnlitData unlitData { - context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); - context.SetDefaultShaderGUI("Rendering.HighDefinition.HDUnlitGUI"); - context.AddSubShader(SubShaders.Unlit); - context.AddSubShader(SubShaders.UnlitRaytracing); + get => m_UnlitData; + set => m_UnlitData = value; + } + + protected override IEnumerable EnumerateSubShaders() + { + yield return SubShaders.Unlit; + yield return SubShaders.UnlitRaytracing; + } + + public override void GetFields(ref TargetFieldContext context) + { + base.GetFields(ref context); + AddDistortionFields(ref context); + + // Unlit specific properties + context.AddField(HDFields.EnableShadowMatte, unlitData.enableShadowMatte); + context.AddField(HDFields.DoAlphaTest, systemData.alphaTest && context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.AlphaClipThreshold)); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + base.GetActiveBlocks(ref context); + AddDistortionBlocks(ref context); + + // Unlit specific blocks + context.AddBlock(HDBlockFields.SurfaceDescription.ShadowTint, unlitData.enableShadowMatte); + } + + protected override void AddInspectorPropertyBlocks(SubTargetPropertiesGUI blockList) + { + blockList.AddPropertyBlock(new HDUnlitSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features.Unlit, unlitData)); + if (systemData.surfaceType == SurfaceType.Transparent) + blockList.AddPropertyBlock(new HDUnlitDistortionPropertyBlock(unlitData)); + blockList.AddPropertyBlock(new AdvancedOptionsPropertyBlock()); + } + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) + { + base.CollectShaderProperties(collector, generationMode); + + if (unlitData.enableShadowMatte) + { + uint mantissa = ((uint)LightFeatureFlags.Punctual | (uint)LightFeatureFlags.Directional | (uint)LightFeatureFlags.Area) & 0x007FFFFFu; + uint exponent = 0b10000000u; // 0 as exponent + collector.AddShaderProperty(new Vector1ShaderProperty + { + hidden = true, + value = HDShadowUtils.Asfloat((exponent << 23) | mantissa), + overrideReferenceName = HDMaterialProperties.kShadowMatteFilter + }); + } + + // Stencil state for unlit: + HDSubShaderUtilities.AddStencilShaderProperties(collector, systemData, null); } #region SubShaders @@ -72,8 +143,8 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - pixelPorts = UnlitPortMasks.FragmentDefault, + // Block Mask + validPixelBlocks = UnlitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -97,9 +168,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentOnlyAlpha, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentOnlyAlpha, // Collections structs = CoreStructCollections.Default, @@ -123,9 +194,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentOnlyAlpha, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentOnlyAlpha, // Collections structs = CoreStructCollections.Default, @@ -150,9 +221,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentOnlyAlpha, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentOnlyAlpha, // Collections structs = CoreStructCollections.Default, @@ -176,9 +247,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentOnlyAlpha, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentOnlyAlpha, // Collections structs = CoreStructCollections.Default, @@ -202,9 +273,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentDistortion, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentDistortion, // Collections structs = CoreStructCollections.Default, @@ -228,9 +299,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentForward, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentForward, // Collections structs = CoreStructCollections.Default, @@ -256,9 +327,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentDefault, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -281,9 +352,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentDefault, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -306,9 +377,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentDefault, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -331,9 +402,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentDefault, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -356,9 +427,9 @@ static class UnlitPasses passTemplatePath = passTemplatePath, sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentDefault, + // Block Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentDefault, // Collections structs = CoreStructCollections.Default, @@ -371,45 +442,38 @@ static class UnlitPasses } #endregion -#region PortMasks - static class UnlitPortMasks +#region BlockMasks + static class UnlitBlockMasks { - public static int[] Vertex = new int[] - { - HDUnlitMasterNode.PositionSlotId, - HDUnlitMasterNode.VertexNormalSlotId, - HDUnlitMasterNode.VertexTangentSlotId, - }; - - public static int[] FragmentDefault = new int[] + public static BlockFieldDescriptor[] FragmentDefault = new BlockFieldDescriptor[] { - HDUnlitMasterNode.ColorSlotId, - HDUnlitMasterNode.AlphaSlotId, - HDUnlitMasterNode.AlphaThresholdSlotId, - HDUnlitMasterNode.EmissionSlotId, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + BlockFields.SurfaceDescription.Emission, }; - public static int[] FragmentOnlyAlpha = new int[] + public static BlockFieldDescriptor[] FragmentOnlyAlpha = new BlockFieldDescriptor[] { - HDUnlitMasterNode.AlphaSlotId, - HDUnlitMasterNode.AlphaThresholdSlotId, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, }; - public static int[] FragmentDistortion = new int[] + public static BlockFieldDescriptor[] FragmentDistortion = new BlockFieldDescriptor[] { - HDUnlitMasterNode.AlphaSlotId, - HDUnlitMasterNode.AlphaThresholdSlotId, - HDUnlitMasterNode.DistortionSlotId, - HDUnlitMasterNode.DistortionBlurSlotId, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.Distortion, + HDBlockFields.SurfaceDescription.DistortionBlur, }; - public static int[] FragmentForward = new int[] + public static BlockFieldDescriptor[] FragmentForward = new BlockFieldDescriptor[] { - HDUnlitMasterNode.ColorSlotId, - HDUnlitMasterNode.AlphaSlotId, - HDUnlitMasterNode.AlphaThresholdSlotId, - HDUnlitMasterNode.EmissionSlotId, - HDUnlitMasterNode.ShadowTintSlotId, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + BlockFields.SurfaceDescription.Emission, + HDBlockFields.SurfaceDescription.ShadowTint, }; } #endregion diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSurfaceOptionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSurfaceOptionPropertyBlock.cs new file mode 100644 index 00000000000..7b1a9b1f558 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSurfaceOptionPropertyBlock.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEngine.UIElements; +using UnityEditor.UIElements; +using UnityEngine; + +// We share the name of the properties in the UI to avoid duplication +using static UnityEditor.Rendering.HighDefinition.LitSurfaceInputsUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.SurfaceOptionUIBlock.Styles; +using static UnityEditor.Rendering.HighDefinition.RefractionUIBlock.Styles; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class HDUnlitSurfaceOptionPropertyBlock : SurfaceOptionPropertyBlock + { + class Styles + { + public static GUIContent shadowMatte = new GUIContent("Shadow Matte", "TODO"); + } + + HDUnlitData unlitData; + + public HDUnlitSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features features, HDUnlitData unlitData) : base(features) + => this.unlitData = unlitData; + + protected override void CreatePropertyGUI() + { + base.CreatePropertyGUI(); + + // HDUnlit specific properties: + AddProperty(Styles.shadowMatte, () => unlitData.enableShadowMatte, (newValue) => unlitData.enableShadowMatte = newValue); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSurfaceOptionPropertyBlock.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSurfaceOptionPropertyBlock.cs.meta new file mode 100644 index 00000000000..3440865c67d --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSurfaceOptionPropertyBlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d0de5ce599107e548b5600cff185256e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitPass.template b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitPass.template deleted file mode 100644 index c67d7288488..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitPass.template +++ /dev/null @@ -1,134 +0,0 @@ -Pass -{ - $splice(PassName) - Tags - { - $splice(LightMode) - } - - // Render State - $splice(RenderState) - - // Debug - $splice(Debug) - - // -------------------------------------------------- - // Pass - - HLSLPROGRAM - - // Pragmas - $splice(PassPragmas) - - // Keywords - $splice(PassKeywords) - $splice(GraphKeywords) - - // Defines - $SurfaceType.Transparent: #define _SURFACE_TYPE_TRANSPARENT 1 - $BlendMode.Alpha: #define _BLENDMODE_ALPHA 1 - $BlendMode.Add: #define _BLENDMODE_ADD 1 - $BlendMode.Premultiply: #define _BLENDMODE_PRE_MULTIPLY 1 - $AddPrecomputedVelocity: #define _ADD_PRECOMPUTED_VELOCITY - $AttributesMesh.normalOS: #define ATTRIBUTES_NEED_NORMAL - $AttributesMesh.tangentOS: #define ATTRIBUTES_NEED_TANGENT - $AttributesMesh.uv0: #define ATTRIBUTES_NEED_TEXCOORD0 - $AttributesMesh.uv1: #define ATTRIBUTES_NEED_TEXCOORD1 - $AttributesMesh.uv2: #define ATTRIBUTES_NEED_TEXCOORD2 - $AttributesMesh.uv3: #define ATTRIBUTES_NEED_TEXCOORD3 - $AttributesMesh.color: #define ATTRIBUTES_NEED_COLOR - $VaryingsMeshToPS.positionRWS: #define VARYINGS_NEED_POSITION_WS - $VaryingsMeshToPS.normalWS: #define VARYINGS_NEED_TANGENT_TO_WORLD - $VaryingsMeshToPS.texCoord0: #define VARYINGS_NEED_TEXCOORD0 - $VaryingsMeshToPS.texCoord1: #define VARYINGS_NEED_TEXCOORD1 - $VaryingsMeshToPS.texCoord2: #define VARYINGS_NEED_TEXCOORD2 - $VaryingsMeshToPS.texCoord3: #define VARYINGS_NEED_TEXCOORD3 - $VaryingsMeshToPS.color: #define VARYINGS_NEED_COLOR - $VaryingsMeshToPS.cullFace: #define VARYINGS_NEED_CULLFACE - $features.graphVertex: #define HAVE_MESH_MODIFICATION - $splice(GraphDefines) - - $splice(HybridV1InjectedBuiltinProperties) - - // Includes - $splice(PreGraphIncludes) - - // Used by SceneSelectionPass - int _ObjectId; - int _PassValue; - - // -------------------------------------------------- - // Structs and Packing - - $splice(PassStructs) - - $splice(InterpolatorPack) - - // -------------------------------------------------- - // Graph - - // Graph Properties - $splice(GraphProperties) - - // Graph Functions - $splice(GraphFunctions) - - // Graph Vertex - $splice(GraphVertex) - - // Graph Pixel - $splice(GraphPixel) - - // -------------------------------------------------- - // Build Graph Inputs - - $features.graphVertex: $include("VertexAnimation.template.hlsl") - $features.graphPixel: $include("SharedCode.template.hlsl") - - // -------------------------------------------------- - // Build Surface Data - - void BuildSurfaceData(FragInputs fragInputs, inout SurfaceDescription surfaceDescription, float3 V, PositionInputs posInput, out SurfaceData surfaceData) - { - // setup defaults -- these are used if the graph doesn't output a value - ZERO_INITIALIZE(SurfaceData, surfaceData); - - // copy across graph values, if defined - $SurfaceDescription.Color: surfaceData.color = surfaceDescription.Color; - - #if defined(DEBUG_DISPLAY) - if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE) - { - // TODO - } - #endif - } - - void GetSurfaceAndBuiltinData(FragInputs fragInputs, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData RAY_TRACING_OPTIONAL_PARAMETERS) - { - SurfaceDescriptionInputs surfaceDescriptionInputs = FragInputsToSurfaceDescriptionInputs(fragInputs, V); - SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs); - - // Perform alpha test very early to save performance (a killed pixel will not sample textures) - // TODO: split graph evaluation to grab just alpha dependencies first? tricky.. - $AlphaTest: GENERIC_ALPHA_TEST(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold); - - BuildSurfaceData(fragInputs, surfaceDescription, V, posInput, surfaceData); - - // Builtin Data - ZERO_INITIALIZE(BuiltinData, builtinData); // No call to InitBuiltinData as we don't have any lighting - builtinData.opacity = surfaceDescription.Alpha; - -#if !defined(_SURFACE_TYPE_TRANSPARENT) - $SurfaceDescription.VTPackedFeedback: builtinData.vtPackedFeedback = surfaceDescription.VTPackedFeedback; -#endif - RAY_TRACING_OPTIONAL_ALPHA_TEST_PASS - } - - // -------------------------------------------------- - // Main - - $splice(PostGraphIncludes) - - ENDHLSL -} \ No newline at end of file diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitPass.template.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitPass.template.meta deleted file mode 100644 index cd4a400d871..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitPass.template.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 1dcf57b107a24784cb16ec0278437fbd -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitSubTarget.cs deleted file mode 100644 index edb4a25e4da..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitSubTarget.cs +++ /dev/null @@ -1,355 +0,0 @@ -using UnityEngine.Rendering.HighDefinition; -using UnityEditor.ShaderGraph; - -namespace UnityEditor.Rendering.HighDefinition.ShaderGraph -{ - sealed class UnlitSubTarget : SubTarget - { - const string kAssetGuid = "625d75e9f0cb52546993731fe9ceeb47"; - static string passTemplatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/Unlit/ShaderGraph/UnlitPass.template"; - - public UnlitSubTarget() - { - displayName = "Unlit"; - } - - public override void Setup(ref TargetSetupContext context) - { - context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); - context.SetDefaultShaderGUI("Rendering.HighDefinition.UnlitUI"); - context.AddSubShader(SubShaders.Unlit); - } - -#region SubShaders - static class SubShaders - { - public static SubShaderDescriptor Unlit = new SubShaderDescriptor() - { - pipelineTag = HDRenderPipeline.k_ShaderTagName, - renderTypeOverride = HDRenderTypeTags.HDUnlitShader.ToString(), - generatesPreview = true, - passes = new PassCollection - { - { UnlitPasses.ShadowCaster }, - { UnlitPasses.META }, - { UnlitPasses.SceneSelection }, - { UnlitPasses.DepthForwardOnly, new FieldCondition(Fields.SurfaceOpaque, true) }, - { UnlitPasses.MotionVectors, new FieldCondition(Fields.SurfaceOpaque, true) }, - { UnlitPasses.ForwardOnly }, - }, - }; - } -#endregion - -#region Passes - static class UnlitPasses - { - public static PassDescriptor META = new PassDescriptor() - { - // Definition - displayName = "META", - referenceName = "SHADERPASS_LIGHT_TRANSPORT", - lightMode = "META", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - pixelPorts = UnlitPortMasks.FragmentDefault, - - // Collections - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.Meta, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = CoreRenderStates.Meta, - pragmas = CorePragmas.DotsInstancedInV2Only, - includes = UnlitIncludes.Meta, - }; - - public static PassDescriptor ShadowCaster = new PassDescriptor() - { - // Definition - displayName = "ShadowCaster", - referenceName = "SHADERPASS_SHADOWS", - lightMode = "ShadowCaster", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentOnlyAlpha, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = UnlitRenderStates.ShadowCaster, - pragmas = CorePragmas.DotsInstancedInV2Only, - includes = UnlitIncludes.DepthOnly, - }; - - public static PassDescriptor SceneSelection = new PassDescriptor() - { - // Definition - displayName = "SceneSelectionPass", - referenceName = "SHADERPASS_DEPTH_ONLY", - lightMode = "SceneSelectionPass", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentOnlyAlpha, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = UnlitRenderStates.SceneSelection, - pragmas = CorePragmas.DotsInstancedInV2OnlyEditorSync, - defines = CoreDefines.SceneSelection, - includes = UnlitIncludes.DepthOnly, - }; - - public static PassDescriptor DepthForwardOnly = new PassDescriptor() - { - // Definition - displayName = "DepthForwardOnly", - referenceName = "SHADERPASS_DEPTH_ONLY", - lightMode = "DepthForwardOnly", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentOnlyAlpha, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = UnlitRenderStates.DepthForwardOnly, - pragmas = CorePragmas.DotsInstancedInV2Only, - keywords = CoreKeywords.WriteMsaaDepth, - includes = UnlitIncludes.DepthOnly, - }; - - public static PassDescriptor MotionVectors = new PassDescriptor() - { - // Definition - displayName = "MotionVectors", - referenceName = "SHADERPASS_MOTION_VECTORS", - lightMode = "MotionVectors", - useInPreview = false, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentOnlyAlpha, - - // Collections - structs = CoreStructCollections.Default, - requiredFields = CoreRequiredFields.PositionRWS, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = UnlitRenderStates.MotionVectors, - pragmas = CorePragmas.DotsInstancedInV2Only, - keywords = CoreKeywords.WriteMsaaDepth, - includes = UnlitIncludes.MotionVectors, - }; - - public static PassDescriptor ForwardOnly = new PassDescriptor() - { - // Definition - displayName = "ForwardOnly", - referenceName = "SHADERPASS_FORWARD_UNLIT", - lightMode = "ForwardOnly", - useInPreview = true, - - // Template - passTemplatePath = passTemplatePath, - sharedTemplateDirectory = HDTarget.sharedTemplateDirectory, - - // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.FragmentDefault, - - // Collections - structs = CoreStructCollections.Default, - fieldDependencies = CoreFieldDependencies.Default, - renderStates = UnlitRenderStates.Forward, - pragmas = CorePragmas.DotsInstancedInV2Only, - keywords = CoreKeywords.DebugDisplay, - includes = UnlitIncludes.ForwardOnly, - - virtualTextureFeedback = true, - }; - } -#endregion - -#region PortMasks - static class UnlitPortMasks - { - public static int[] Vertex = new int[] - { - UnlitMasterNode.PositionSlotId, - UnlitMasterNode.VertNormalSlotId, - UnlitMasterNode.VertTangentSlotId, - }; - - public static int[] FragmentDefault = new int[] - { - UnlitMasterNode.ColorSlotId, - UnlitMasterNode.AlphaSlotId, - UnlitMasterNode.AlphaThresholdSlotId, - }; - - public static int[] FragmentOnlyAlpha = new int[] - { - UnlitMasterNode.AlphaSlotId, - UnlitMasterNode.AlphaThresholdSlotId, - }; - } -#endregion - -#region RenderStates - static class UnlitRenderStates - { - public static RenderStateCollection ShadowCaster = new RenderStateCollection - { - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.ZWrite(ZWrite.On) }, - { RenderState.ColorMask("ColorMask 0") }, - }; - - public static RenderStateCollection SceneSelection = new RenderStateCollection - { - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.ZWrite(ZWrite.On), new FieldCondition(Fields.SurfaceOpaque, true) }, - { RenderState.ZWrite(ZWrite.Off), new FieldCondition(Fields.SurfaceTransparent, true) }, - { RenderState.ColorMask("ColorMask 0") }, - }; - - // Caution: When using MSAA we have normal and depth buffer bind. - // Unlit objects need to NOT write in normal buffer (or write 0) - Disable color mask for this RT - // Note: ShaderLab doesn't allow to have a variable on the second parameter of ColorMask - // - When MSAA: disable target 1 (normal buffer) - // - When no MSAA: disable target 0 (normal buffer) and 1 (unused) - public static RenderStateCollection DepthForwardOnly = new RenderStateCollection - { - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.ZWrite(ZWrite.On), new FieldCondition(Fields.SurfaceOpaque, true) }, - { RenderState.ZWrite(ZWrite.Off), new FieldCondition(Fields.SurfaceTransparent, true) }, - { RenderState.ColorMask("ColorMask [_ColorMaskNormal]") }, - { RenderState.ColorMask("ColorMask 0 1") }, - }; - - // Caution: When using MSAA we have motion vector, normal and depth buffer bind. - // Mean unlit object need to not write in it (or write 0) - Disable color mask for this RT - // This is not a problem in no MSAA mode as there is no buffer bind - public static RenderStateCollection MotionVectors = new RenderStateCollection - { - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.ColorMask("ColorMask [_ColorMaskNormal] 1") }, - { RenderState.ColorMask("ColorMask 0 2") }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = $"{(int)StencilUsage.ObjectMotionVector}", - Ref = $"{(int)StencilUsage.ObjectMotionVector}", - Comp = "Always", - Pass = "Replace", - }) }, - }; - - public static RenderStateCollection Forward = new RenderStateCollection - { - { RenderState.Blend(Blend.One, Blend.Zero, Blend.One, Blend.Zero), new FieldCondition(Fields.SurfaceOpaque, true) }, - { RenderState.Blend(Blend.One, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha), new FieldCondition[] { - new FieldCondition(Fields.SurfaceTransparent, true), - new FieldCondition(Fields.BlendAlpha, true) } }, - { RenderState.Blend(Blend.One, Blend.One, Blend.One, Blend.One), new FieldCondition[] { - new FieldCondition(Fields.SurfaceTransparent, true), - new FieldCondition(Fields.BlendAdd, true) } }, - { RenderState.Blend(Blend.One, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha), new FieldCondition[] { - new FieldCondition(Fields.SurfaceTransparent, true), - new FieldCondition(Fields.BlendPremultiply, true) } }, - { RenderState.Blend(Blend.One, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha), new FieldCondition[] { - new FieldCondition(Fields.SurfaceTransparent, true), - new FieldCondition(Fields.BlendMultiply, true) } }, - - { RenderState.Cull(Cull.Off), new FieldCondition(Fields.DoubleSided, true) }, - { RenderState.ZWrite(ZWrite.On), new FieldCondition(Fields.SurfaceOpaque, true) }, - { RenderState.ZWrite(ZWrite.Off), new FieldCondition(Fields.SurfaceTransparent, true) }, - { RenderState.Stencil(new StencilDescriptor() - { - WriteMask = $"{(int)StencilUsage.RequiresDeferredLighting | (int)StencilUsage.SubsurfaceScattering}", - Ref = $"{(int)StencilUsage.Clear}", - Comp = "Always", - Pass = "Replace", - }) }, - }; - } -#endregion - -#region Includes - static class UnlitIncludes - { - // These are duplicated from HDUnlitSubTarget - // We avoid moving these to CoreIncludes because this SubTarget will be removed with Stacks - - const string kPassForwardUnlit = "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForwardUnlit.hlsl"; - - public static IncludeCollection Meta = new IncludeCollection - { - { CoreIncludes.CorePregraph }, - { CoreIncludes.kUnlit, IncludeLocation.Pregraph }, - { CoreIncludes.CoreUtility }, - { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph }, - { CoreIncludes.kPassLightTransport, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection DepthOnly = new IncludeCollection - { - { CoreIncludes.CorePregraph }, - { CoreIncludes.kUnlit, IncludeLocation.Pregraph }, - { CoreIncludes.CoreUtility }, - { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph }, - { CoreIncludes.kPassDepthOnly, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection MotionVectors = new IncludeCollection - { - { CoreIncludes.CorePregraph }, - { CoreIncludes.kUnlit, IncludeLocation.Pregraph }, - { CoreIncludes.CoreUtility }, - { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph }, - { CoreIncludes.kPassMotionVectors, IncludeLocation.Postgraph }, - }; - - public static IncludeCollection ForwardOnly = new IncludeCollection - { - { CoreIncludes.CorePregraph }, - { CoreIncludes.kUnlit, IncludeLocation.Pregraph }, - { CoreIncludes.CoreUtility }, - { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph }, - { CoreIncludes.kCommonLighting, IncludeLocation.Pregraph, new FieldCondition(HDFields.EnableShadowMatte, true) }, - { CoreIncludes.kHDShadow, IncludeLocation.Pregraph, new FieldCondition(HDFields.EnableShadowMatte, true) }, - { CoreIncludes.kLightLoopDef, IncludeLocation.Pregraph, new FieldCondition(HDFields.EnableShadowMatte, true) }, - { CoreIncludes.kPunctualLightCommon, IncludeLocation.Pregraph, new FieldCondition(HDFields.EnableShadowMatte, true) }, - { CoreIncludes.kHDShadowLoop, IncludeLocation.Pregraph, new FieldCondition(HDFields.EnableShadowMatte, true) }, - { kPassForwardUnlit, IncludeLocation.Postgraph }, - }; - } -#endregion - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitSubTarget.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitSubTarget.cs.meta deleted file mode 100644 index d60dedd2a2d..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitSubTarget.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 625d75e9f0cb52546993731fe9ceeb47 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitUI.cs deleted file mode 100644 index 6be1e077b8c..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitUI.cs +++ /dev/null @@ -1,41 +0,0 @@ -using UnityEngine; -using UnityEngine.Rendering.HighDefinition; - -namespace UnityEditor.Rendering.HighDefinition -{ - class UnlitUI : ShaderGUI - { - public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) - { - materialEditor.PropertiesDefaultGUI(props); - - // Make sure all selected materials are initialized. - string materialTag = "MotionVector"; - foreach (var obj in materialEditor.targets) - { - var material = (Material)obj; - string tag = material.GetTag(materialTag, false, "Nothing"); - if (tag == "Nothing") - { - material.SetShaderPassEnabled(HDShaderPassNames.s_MotionVectorsStr, false); - material.SetOverrideTag(materialTag, "User"); - } - } - - { - // If using multi-select, apply toggled material to all materials. - bool enabled = ((Material)materialEditor.target).GetShaderPassEnabled(HDShaderPassNames.s_MotionVectorsStr); - EditorGUI.BeginChangeCheck(); - enabled = EditorGUILayout.Toggle("Motion Vector For Vertex Animation", enabled); - if (EditorGUI.EndChangeCheck()) - { - foreach (var obj in materialEditor.targets) - { - var material = (Material)obj; - material.SetShaderPassEnabled(HDShaderPassNames.s_MotionVectorsStr, enabled); - } - } - } - } - } -} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitUI.cs.meta b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitUI.cs.meta deleted file mode 100644 index 1ec2ce57f26..00000000000 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/UnlitUI.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 245c1452117cd494983b6fd5bb697699 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDShaderUtils.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDShaderUtils.cs index cfcfa5dd4fa..320dfbba9e9 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDShaderUtils.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDShaderUtils.cs @@ -4,6 +4,7 @@ using System.Linq; using UnityEditor.ShaderGraph; using UnityEngine; +using UnityEditor.Rendering.HighDefinition.ShaderGraph; namespace UnityEditor.Rendering.HighDefinition { @@ -48,18 +49,6 @@ internal enum ShaderID "HDRP/AxF", }; - // exposed shadergraph, for reference while searching the ShaderID - static readonly Type[] s_MasterNodes = - { - typeof(HDUnlitMasterNode), - typeof(HDLitMasterNode), - typeof(HairMasterNode), - typeof(FabricMasterNode), - typeof(StackLitMasterNode), - typeof(DecalMasterNode), - typeof(EyeMasterNode), - }; - // list of methods for resetting keywords delegate void MaterialResetter(Material material); static Dictionary k_MaterialResetters = new Dictionary() @@ -74,7 +63,7 @@ internal enum ShaderID { ShaderID.Decal, DecalUI.SetupMaterialKeywordsAndPass }, { ShaderID.TerrainLit, TerrainLitGUI.SetupMaterialKeywordsAndPass }, { ShaderID.AxF, AxFGUI.SetupMaterialKeywordsAndPass }, - { ShaderID.SG_Unlit, UnlitGUI.SetupUnlitMaterialKeywordsAndPass }, + { ShaderID.SG_Unlit, HDUnlitGUI.SetupMaterialKeywordsAndPass }, { ShaderID.SG_Lit, HDLitGUI.SetupMaterialKeywordsAndPass }, { ShaderID.SG_Hair, HairGUI.SetupMaterialKeywordsAndPass }, { ShaderID.SG_Fabric, FabricGUI.SetupMaterialKeywordsAndPass }, @@ -133,8 +122,8 @@ internal static bool IsHDRPShader(Shader shader, bool upgradable = false) if (shader.IsShaderGraph()) { - var outputNodeType = GraphUtil.GetOutputNodeType(AssetDatabase.GetAssetPath(shader)); - return s_MasterNodes.Contains(outputNodeType); + // All HDRP shader graphs should have HD metadata + return shader.TryGetMetadataOfType(out _); } else if (upgradable) return s_ShaderPaths.Contains(shader.name); @@ -149,15 +138,13 @@ internal static bool IsUnlitHDRPShader(Shader shader) if (shader.IsShaderGraph()) { - string shaderPath = AssetDatabase.GetAssetPath(shader); - switch (GraphUtil.GetOutputNodeType(shaderPath).Name) - { - case nameof(HDUnlitMasterNode): - case nameof(UnlitMasterNode): - return true; - default: - return false; - } + // Throw exception if no metadata is found + // This case should be handled by the Target + HDMetadata obj; + if(!shader.TryGetMetadataOfType(out obj)) + throw new ArgumentException("Unknown shader"); + + return obj.shaderID == ShaderID.SG_Unlit; } else return shader.name == "HDRP/Unlit"; @@ -175,27 +162,17 @@ internal static string GetShaderPath(ShaderID id) return s_ShaderPaths[index]; } - internal static Type GetShaderMasterNodeType(ShaderID id) - { - int index = (int)id - (int)ShaderID.Count_Standard; - if (index < 0 && index >= (int)ShaderID.Count_ShaderGraph) - { - Debug.LogError("Trying to access HDRP shader path out of bounds"); - return null; - } - - return s_MasterNodes[index]; - } - internal static ShaderID GetShaderEnumFromShader(Shader shader) { if (shader.IsShaderGraph()) { - var type = GraphUtil.GetOutputNodeType(AssetDatabase.GetAssetPath(shader)); - var index = Array.FindIndex(s_MasterNodes, m => m == type); - if (index == -1) + // Throw exception if no metadata is found + // This case should be handled by the Target + HDMetadata obj; + if(!shader.TryGetMetadataOfType(out obj)) throw new ArgumentException("Unknown shader"); - return (ShaderID)(index + ShaderID.Count_Standard); + + return obj.shaderID; } else { diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDBlockFields.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDBlockFields.cs new file mode 100644 index 00000000000..3e47e0e08f8 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDBlockFields.cs @@ -0,0 +1,147 @@ +using UnityEngine; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.ShaderGraph; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + internal static class HDBlockFields + { + [GenerateBlocks("High Definition Render Pipeline")] + public struct SurfaceDescription + { + public static string name = "SurfaceDescription"; + + // -------------------------------------------------- + // Unlit + + public static BlockFieldDescriptor Distortion = new BlockFieldDescriptor(SurfaceDescription.name, "Distortion", "SURFACEDESCRIPTION_DISTORTION", + new Vector2Control(Vector2.zero), ShaderStage.Fragment); // TODO: Lit is Vector2(2.0f, -1.0f) + public static BlockFieldDescriptor DistortionBlur = new BlockFieldDescriptor(SurfaceDescription.name, "DistortionBlur", "Distortion Blur", "SURFACEDESCRIPTION_DISTORTIONBLUR", + new FloatControl(1.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor ShadowTint = new BlockFieldDescriptor(SurfaceDescription.name, "ShadowTint", "Shadow Tint", "SURFACEDESCRIPTION_SHADOWTINT", + new ColorRGBAControl(Color.black), ShaderStage.Fragment); + + // -------------------------------------------------- + // Lit + + public static BlockFieldDescriptor BentNormal = new BlockFieldDescriptor(SurfaceDescription.name, "BentNormal", "Bent Normal", "SURFACEDESCRIPTION_BENTNORMAL", + new NormalControl(CoordinateSpace.Tangent), ShaderStage.Fragment); + public static BlockFieldDescriptor Tangent = new BlockFieldDescriptor(SurfaceDescription.name, "Tangent", "SURFACEDESCRIPTION_TANGENT", + new TangentControl(CoordinateSpace.Tangent), ShaderStage.Fragment); + public static BlockFieldDescriptor Anisotropy = new BlockFieldDescriptor(SurfaceDescription.name, "Anisotropy", "SURFACEDESCRIPTION_ANISOTROPY", + new FloatControl(0.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor SubsurfaceMask = new BlockFieldDescriptor(SurfaceDescription.name, "SubsurfaceMask", "Subsurface Mask", "SURFACEDESCRIPTION_SUBSURFACEMASK", + new FloatControl(1.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor Thickness = new BlockFieldDescriptor(SurfaceDescription.name, "Thickness", "SURFACEDESCRIPTION_THICKNESS", + new FloatControl(1.0f), ShaderStage.Fragment); + public static CustomSlotBlockFieldDescriptor DiffusionProfileHash = new CustomSlotBlockFieldDescriptor(SurfaceDescription.name, "DiffusionProfileHash", "Diffusion Profile", "SURFACEDESCRIPTION_DIFFUSIONPROFILEHASH", + () => { return new DiffusionProfileInputMaterialSlot(0, "Diffusion Profile", "DiffusionProfileHash", ShaderStageCapability.Fragment); }); + public static BlockFieldDescriptor IridescenceMask = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceMask", "Iridescence Mask", "SURFACEDESCRIPTION_IRIDESCENCEMASK", + new FloatControl(0.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor IridescenceThickness = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceThickness", "Iridescence Thickness", "SURFACEDESCRIPTION_IRIDESCENCETHICKNESS", + new FloatControl(0.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor CoatMask = new BlockFieldDescriptor(SurfaceDescription.name, "CoatMask", "Coat Mask", "SURFACEDESCRIPTION_COATMASK", + new FloatControl(0.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor SpecularOcclusion = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularOcclusion", "Specular Occlusion", "SURFACEDESCRIPTION_SPECULAROCCLUSION", + new FloatControl(1.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor AlphaClipThresholdDepthPrepass = new BlockFieldDescriptor(SurfaceDescription.name, "AlphaClipThresholdDepthPrepass", "Alpha Clip Threshold Depth Prepass", "SURFACEDESCRIPTION_ALPHACLIPTHRESHOLDDEPTHPREPASS", + new FloatControl(0.5f), ShaderStage.Fragment); + public static BlockFieldDescriptor AlphaClipThresholdDepthPostpass = new BlockFieldDescriptor(SurfaceDescription.name, "AlphaClipThresholdDepthPostpass", "Alpha Clip Threshold Depth Postpass", "SURFACEDESCRIPTION_ALPHACLIPTHRESHOLDDEPTHPOSTPASS", + new FloatControl(0.5f), ShaderStage.Fragment); + public static BlockFieldDescriptor AlphaClipThresholdShadow = new BlockFieldDescriptor(SurfaceDescription.name, "AlphaClipThresholdShadow", "Alpha Clip Threshold Shadow", "SURFACEDESCRIPTION_ALPHACLIPTHRESHOLDSHADOW", + new FloatControl(0.5f), ShaderStage.Fragment); + public static BlockFieldDescriptor SpecularAAScreenSpaceVariance = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularAAScreenSpaceVariance", "Specular AA Screen Space Variance", "SURFACEDESCRIPTION_SPECULARAASCEENSPACEVARIANCE", + new FloatControl(0.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor SpecularAAThreshold = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularAAThreshold", "Specular AA Threshold", "SURFACEDESCRIPTION_SPECULARAATHRESHOLD", + new FloatControl(0.0f), ShaderStage.Fragment); + public static CustomSlotBlockFieldDescriptor BakedGI = new CustomSlotBlockFieldDescriptor(SurfaceDescription.name, "BakedGI", "Baked GI", "SURFACEDESCRIPTION_BAKEDGI", + () => { return new DefaultMaterialSlot(0, "Baked GI", "BakedGI", ShaderStageCapability.Fragment); }); + public static CustomSlotBlockFieldDescriptor BakedBackGI = new CustomSlotBlockFieldDescriptor(SurfaceDescription.name, "BakedBackGI", "Baked Back GI", "SURFACEDESCRIPTION_BAKEDBACKGI", + () => { return new DefaultMaterialSlot(0, "Baked Back GI", "BakedBackGI", ShaderStageCapability.Fragment); }); + public static BlockFieldDescriptor DepthOffset = new BlockFieldDescriptor(SurfaceDescription.name, "DepthOffset", "Depth Offset", "SURFACEDESCRIPTION_DEPTHOFFSET", + new FloatControl(0.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor RefractionIndex = new BlockFieldDescriptor(SurfaceDescription.name, "RefractionIndex", "Refraction Index", "SURFACEDESCRIPTION_REFRACTIONINDEX", + new FloatControl(1.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor RefractionColor = new BlockFieldDescriptor(SurfaceDescription.name, "RefractionColor", "Refraction Color", "SURFACEDESCRIPTION_REFRACTIONCOLOR", + new ColorControl(Color.white, false), ShaderStage.Fragment); + public static BlockFieldDescriptor RefractionDistance = new BlockFieldDescriptor(SurfaceDescription.name, "RefractionDistance", "Refraction Distance", "SURFACEDESCRIPTION_REFRACTIONDISTANCE", + new FloatControl(1.0f), ShaderStage.Fragment); + + // -------------------------------------------------- + // Decal + + public static BlockFieldDescriptor NormalAlpha = new BlockFieldDescriptor(SurfaceDescription.name, "NormalAlpha", "Normal Alpha", "SURFACEDESCRIPTION_NORMALALPHA", + new FloatControl(1.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor MAOSAlpha = new BlockFieldDescriptor(SurfaceDescription.name, "MAOSAlpha", "MAOS Alpha", "SURFACEDESCRIPTION_MAOSALPHA", + new FloatControl(1.0f), ShaderStage.Fragment); + + // -------------------------------------------------- + // Eye + + public static BlockFieldDescriptor IrisNormal = new BlockFieldDescriptor(SurfaceDescription.name, "IrisNormal", "Iris Normal", "SURFACEDESCRIPTION_IRISNORMAL", + new NormalControl(CoordinateSpace.Tangent), ShaderStage.Fragment); + public static BlockFieldDescriptor IOR = new BlockFieldDescriptor(SurfaceDescription.name, "IOR", "SURFACEDESCRIPTION_IOR", + new FloatControl(1.4f), ShaderStage.Fragment); + public static BlockFieldDescriptor Mask = new BlockFieldDescriptor(SurfaceDescription.name, "Mask", "SURFACEDESCRIPTION_MASK", + new Vector2Control(new Vector2(1.0f, 0.0f)), ShaderStage.Fragment); + + // -------------------------------------------------- + // Hair + + public static BlockFieldDescriptor Transmittance = new BlockFieldDescriptor(SurfaceDescription.name, "Transmittance", "SURFACEDESCRIPTION_TRANSMITTANCE", + new Vector3Control(0.3f * new Vector3(1.0f, 0.65f, 0.3f)), ShaderStage.Fragment); + public static BlockFieldDescriptor RimTransmissionIntensity = new BlockFieldDescriptor(SurfaceDescription.name, "RimTransmissionIntensity", "Rim Transmission Intensity", "SURFACEDESCRIPTION_RIMTRANSMISSIONINTENSITY", + new FloatControl(0.2f), ShaderStage.Fragment); + public static BlockFieldDescriptor HairStrandDirection = new BlockFieldDescriptor(SurfaceDescription.name, "HairStrandDirection", "Hair Strand Direction", "SURFACEDESCRIPTION_HAIRSTRANDDIRECTION", + new Vector3Control(new Vector3(0, -1, 0)), ShaderStage.Fragment); + public static BlockFieldDescriptor SpecularTint = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularTint", "Specular Tint", "SURFACEDESCRIPTION_SPECULARTINT", + new ColorControl(Color.white, false), ShaderStage.Fragment); + public static BlockFieldDescriptor SpecularShift = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularShift", "Specular Shift", "SURFACEDESCRIPTION_SPECULARSHIFT", + new FloatControl(0.1f), ShaderStage.Fragment); + public static BlockFieldDescriptor SecondarySpecularTint = new BlockFieldDescriptor(SurfaceDescription.name, "SecondarySpecularTint", "Secondary Specular Tint", "SURFACEDESCRIPTION_SECONDARYSPECULARTINT", + new ColorControl(Color.grey, false), ShaderStage.Fragment); + public static BlockFieldDescriptor SecondarySmoothness = new BlockFieldDescriptor(SurfaceDescription.name, "SecondarySmoothness", "Secondary Smoothness", "SURFACEDESCRIPTION_SECONDARYSMOOTHNESS", + new FloatControl(0.5f), ShaderStage.Fragment); + public static BlockFieldDescriptor SecondarySpecularShift = new BlockFieldDescriptor(SurfaceDescription.name, "SecondarySpecularShift", "Secondary Specular Shift", "SURFACEDESCRIPTION_SECONDARYSPECULARSHIFT", + new FloatControl(-0.1f), ShaderStage.Fragment); + + // -------------------------------------------------- + // StackLit + + public static BlockFieldDescriptor CoatNormal = new BlockFieldDescriptor(SurfaceDescription.name, "CoatNormal", "Coat Normal", "SURFACEDESCRIPTION_COATNORMAL", + new NormalControl(CoordinateSpace.Tangent), ShaderStage.Fragment); + public static BlockFieldDescriptor DielectricIor = new BlockFieldDescriptor(SurfaceDescription.name, "DielectricIor", "Dielectric IOR", "SURFACEDESCRIPTION_DIELECTRICIOR", + new FloatControl(1.5f), ShaderStage.Fragment); + public static BlockFieldDescriptor SmoothnessB = new BlockFieldDescriptor(SurfaceDescription.name, "SmoothnessB", "Smoothness B", "SURFACEDESCRIPTION_SMOOTHNESSB", + new FloatControl(0.5f), ShaderStage.Fragment); + public static BlockFieldDescriptor LobeMix = new BlockFieldDescriptor(SurfaceDescription.name, "LobeMix", "Lobe Mix", "SURFACEDESCRIPTION_LOBEMIX", + new FloatControl(0.3f), ShaderStage.Fragment); + public static BlockFieldDescriptor AnisotropyB = new BlockFieldDescriptor(SurfaceDescription.name, "AnisotropyB", "Anisotropy B", "SURFACEDESCRIPTION_ANISOTROPYB", + new FloatControl(1.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor SOFixupVisibilityRatioThreshold = new BlockFieldDescriptor(SurfaceDescription.name, "SOFixupVisibilityRatioThreshold", "SO Fixup Visibility Ratio Threshold", "SURFACEDESCRIPTION_SOFIXUPVISIBILITYRATIOTHRESHOLD", + new FloatControl(0.2f), ShaderStage.Fragment); + public static BlockFieldDescriptor SOFixupStrengthFactor = new BlockFieldDescriptor(SurfaceDescription.name, "SOFixupStrengthFactor", "SO Fixup Strength Factor", "SURFACEDESCRIPTION_SOFIXUPSTRENGTHFACTOR", + new FloatControl(1.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor SOFixupMaxAddedRoughness = new BlockFieldDescriptor(SurfaceDescription.name, "SOFixupMaxAddedRoughness", "SO Fixup Max Added Roughness", "SURFACEDESCRIPTION_SOFIXUPMAXADDEDROUGHNESS", + new FloatControl(0.2f), ShaderStage.Fragment); + public static BlockFieldDescriptor CoatSmoothness = new BlockFieldDescriptor(SurfaceDescription.name, "CoatSmoothness", "Coat Smoothness", "SURFACEDESCRIPTION_COATSMOOTHNESS", + new FloatControl(1.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor CoatIor = new BlockFieldDescriptor(SurfaceDescription.name, "CoatIor", "Coat IOR", "SURFACEDESCRIPTION_COATIOR", + new FloatControl(1.4f), ShaderStage.Fragment); + public static BlockFieldDescriptor CoatThickness = new BlockFieldDescriptor(SurfaceDescription.name, "CoatThickness", "Coat Thickness", "SURFACEDESCRIPTION_COATTHICKNESS", + new FloatControl(0.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor CoatExtinction = new BlockFieldDescriptor(SurfaceDescription.name, "CoatExtinction", "Coat Extinction", "SURFACEDESCRIPTION_COATEXTINCTION", + new ColorControl(Color.white, true), ShaderStage.Fragment); + public static BlockFieldDescriptor Haziness = new BlockFieldDescriptor(SurfaceDescription.name, "Haziness", "SURFACEDESCRIPTION_HAZINESS", + new FloatControl(0.2f), ShaderStage.Fragment); + public static BlockFieldDescriptor HazeExtent = new BlockFieldDescriptor(SurfaceDescription.name, "HazeExtent", "Haze Extent", "SURFACEDESCRIPTION_HAZEEXTENT", + new FloatControl(3.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor HazyGlossMaxDielectricF0 = new BlockFieldDescriptor(SurfaceDescription.name, "HazyGlossMaxDielectricF0", "Hazy Gloss Max Dielectric F0", "SURFACEDESCRIPTION_HAZYGLOSSMAXDIELECTRICF0", + new FloatControl(0.25f), ShaderStage.Fragment); + public static BlockFieldDescriptor IridescenceCoatFixupTIR = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceCoatFixupTIR", "Iridescence Coat Fixup TIR", "SURFACEDESCRIPTION_IRIDESCENCECOATFIXUPTIR", + new FloatControl(0.0f), ShaderStage.Fragment); + public static BlockFieldDescriptor IridescenceCoatFixupTIRClamp = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceCoatFixupTIRClamp", "Iridescence Coat Fixup TIR Clamp", "SURFACEDESCRIPTION_IRIDESCENCECOATFIXUPTIRCLAMP", + new FloatControl(0.0f), ShaderStage.Fragment); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDBlockFields.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDBlockFields.cs.meta new file mode 100644 index 00000000000..f2c91704e2c --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDBlockFields.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 55b3aee4ed078d942b20b4a453e266e8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDFields.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDFields.cs index 20dd121e5da..be0eb8f1caf 100644 --- a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDFields.cs +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDFields.cs @@ -32,6 +32,7 @@ static class HDFields public static FieldDescriptor Transmission = new FieldDescriptor(kMaterial, "Transmission", "_MATERIAL_FEATURE_TRANSMISSION 1"); public static FieldDescriptor Translucent = new FieldDescriptor(kMaterial, "Translucent", "_MATERIAL_FEATURE_TRANSLUCENT 1"); public static FieldDescriptor Coat = new FieldDescriptor(kMaterial, "Coat", "_MATERIAL_FEATURE_COAT"); + public static FieldDescriptor ClearCoat = new FieldDescriptor(kMaterial, "ClearCoat", "_MATERIAL_FEATURE_CLEAR_COAT"); public static FieldDescriptor CoatNormal = new FieldDescriptor(kMaterial, "CoatNormal", "_MATERIAL_FEATURE_COAT_NORMALMAP"); public static FieldDescriptor DualSpecularLobe = new FieldDescriptor(kMaterial, "DualSpecularLobe", "_MATERIAL_FEATURE_DUAL_SPECULAR_LOBE"); public static FieldDescriptor Eye = new FieldDescriptor(kMaterial, "Eye", "_MATERIAL_FEATURE_EYE 1"); @@ -107,7 +108,7 @@ static class HDFields public static FieldDescriptor BackLightingGI = new FieldDescriptor(string.Empty, "BackLightingGI", "_BACK_LIGHTING_GI 1"); public static FieldDescriptor DepthOffset = new FieldDescriptor(string.Empty, "DepthOffset", "_DEPTH_OFFSET 1"); public static FieldDescriptor TransparentWritesMotionVec = new FieldDescriptor(string.Empty, "TransparentWritesMotionVec", "_WRITE_TRANSPARENT_MOTION_VECTOR 1"); - public static FieldDescriptor HairStrandDirection = new FieldDescriptor(string.Empty, "DepthOffset", "_HAIR_STRAND_DIRECTION 1"); + public static FieldDescriptor HairStrandDirection = new FieldDescriptor(string.Empty, "HairStrandDirection", "_HAIR_STRAND_DIRECTION 1"); public static FieldDescriptor Transmittance = new FieldDescriptor(string.Empty, "Transmittance", "_TRANSMITTANCE 1"); public static FieldDescriptor RimTransmissionIntensity = new FieldDescriptor(string.Empty, "RimTransmissionIntensity", "_RIM_TRANSMISSION_INTENSITY 1"); public static FieldDescriptor UseLightFacingNormal = new FieldDescriptor(string.Empty, "UseLightFacingNormal", "_USE_LIGHT_FACING_NORMAL 1"); diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDMetadata.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDMetadata.cs new file mode 100644 index 00000000000..6ae99f1b850 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDMetadata.cs @@ -0,0 +1,28 @@ +using System; +using UnityEngine; +using UnityEditor.Rendering.HighDefinition; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + [Serializable] + sealed class HDMetadata : ScriptableObject + { + [SerializeField] + HDShaderUtils.ShaderID m_ShaderID; + + [SerializeField] + bool m_MigrateFromOldCrossPipelineSG; // Keep track from which old SG master node we come from + + public HDShaderUtils.ShaderID shaderID + { + get => m_ShaderID; + set => m_ShaderID = value; + } + + public bool migrateFromOldCrossPipelineSG + { + get => m_MigrateFromOldCrossPipelineSG; + set => m_MigrateFromOldCrossPipelineSG = value; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDMetadata.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDMetadata.cs.meta new file mode 100644 index 00000000000..42061380f3d --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDMetadata.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e94bd676ea2b87e4bbb7858cd433b20b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDSubShaderUtilities.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDSubShaderUtilities.cs index 8cd78f4c6ea..e4501c685b3 100644 --- a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDSubShaderUtilities.cs +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDSubShaderUtilities.cs @@ -8,6 +8,8 @@ using UnityEditor.ShaderGraph.Internal; using UnityEngine.Rendering.HighDefinition; using UnityEngine.Rendering; +using UnityEditor.Rendering.HighDefinition.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; using ShaderPass = UnityEditor.ShaderGraph.PassDescriptor; // Include material common properties names @@ -65,8 +67,21 @@ static void AddToggleProperty(this PropertyCollector collector, string reference }); } - public static void AddStencilShaderProperties(PropertyCollector collector, bool splitLighting, bool ssrStencil, bool receiveSSROpaque, bool receiveSSRTransparent) + public static void AddStencilShaderProperties(PropertyCollector collector, SystemData systemData, LightingData lightingData) { + bool ssrStencil = false; + bool splitLighting = false; + bool receiveSSROpaque = false; + bool receiveSSRTransparent = false; + + if (lightingData != null) + { + ssrStencil = systemData.surfaceType == SurfaceType.Opaque ? lightingData.receiveSSR : lightingData.receiveSSRTransparent; + splitLighting = lightingData.subsurfaceScattering; + receiveSSROpaque = lightingData.receiveSSR; + receiveSSRTransparent = lightingData.receiveSSRTransparent; + } + BaseLitGUI.ComputeStencilProperties(ssrStencil, splitLighting, out int stencilRef, out int stencilWriteMask, out int stencilRefDepth, out int stencilWriteMaskDepth, out int stencilRefGBuffer, out int stencilWriteMaskGBuffer, out int stencilRefMV, out int stencilWriteMaskMV @@ -92,7 +107,6 @@ public static void AddStencilShaderProperties(PropertyCollector collector, bool collector.AddToggleProperty(kUseSplitLighting, splitLighting); collector.AddToggleProperty(kReceivesSSR, receiveSSROpaque); collector.AddToggleProperty(kReceivesSSRTransparent, receiveSSRTransparent); - } public static void AddBlendingStatesShaderProperties( @@ -218,20 +232,32 @@ public static string RenderQueueName(HDRenderQueue.RenderQueueType value) return result; } - public static BlendMode ConvertAlphaModeToBlendMode(AlphaMode alphaMode) + public static bool UpgradeLegacyAlphaClip(IMasterNode1 masterNode) + { + var clipThresholdId = 8; + var node = masterNode as AbstractMaterialNode; + var clipThresholdSlot = node.FindSlot(clipThresholdId); + if(clipThresholdSlot == null) + return false; + + clipThresholdSlot.owner = node; + return (clipThresholdSlot.isConnected || clipThresholdSlot.value > 0.0f); + } + + public static BlendMode UpgradeLegacyAlphaModeToBlendMode(int alphaMode) { switch (alphaMode) { - case AlphaMode.Additive: - return BlendMode.Additive; - case AlphaMode.Alpha: + case 0: //AlphaMode.Alpha: return BlendMode.Alpha; - case AlphaMode.Premultiply: + case 1: //AlphaMode.Premultiply: + return BlendMode.Premultiply; + case 2: //AlphaMode.Additive: + return BlendMode.Additive; + case 3: //AlphaMode.Multiply: // In case of multiply we fall back to Premultiply return BlendMode.Premultiply; - case AlphaMode.Multiply: // In case of multiply we fall back to alpha - return BlendMode.Alpha; default: - throw new System.Exception("Unknown AlphaMode: " + alphaMode + ": can't convert to BlendMode."); + throw new System.Exception("Unknown AlphaMode at index: " + alphaMode + ": can't convert to BlendMode."); } } diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDTarget.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDTarget.cs index 24290c320e0..386c85790a1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/HDTarget.cs @@ -1,72 +1,348 @@ using System; using System.Collections.Generic; using System.Linq; +using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; +using UnityEngine.UIElements; +using UnityEditor.Graphing; using UnityEditor.ShaderGraph; +using UnityEditor.UIElements; +using UnityEditor.ShaderGraph.Serialization; +using UnityEditor.ShaderGraph.Legacy; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { - sealed class HDTarget : Target + enum DistortionMode { + Add, + Multiply, + Replace + } + + enum DoubleSidedMode + { + Disabled, + Enabled, + FlippedNormals, + MirroredNormals, + } + + enum SpecularOcclusionMode + { + Off, + FromAO, + FromAOAndBentNormal, + Custom + } + + sealed class HDTarget : Target, IHasMetadata, ILegacyTarget + { + // Constants const string kAssetGuid = "61d9843d4027e3e4a924953135f76f3c"; + + // SubTarget List m_SubTargets; - SubTarget m_ActiveSubTarget; + List m_SubTargetNames; + int activeSubTargetIndex => m_SubTargets.IndexOf(m_ActiveSubTarget); + + // View + PopupField m_SubTargetField; + TextField m_CustomGUIField; + + [SerializeField] + JsonData m_ActiveSubTarget; + + [SerializeField] + List> m_Datas = new List>(); + + [SerializeField] + string m_CustomEditorGUI; + + static NodeTypeCollection s_HDNodeTypes = NodeTypes.AllBuiltin + typeof(HDSceneColorNode) + + typeof(DiffusionProfileNode) + + typeof(ExposureNode) + + typeof(EmissionNode) + + typeof(ParallaxOcclusionMappingNode); + + public override bool IsNodeAllowedByTarget(Type nodeType) + { + return s_HDNodeTypes.Contains(nodeType); + } public HDTarget() { displayName = "HDRP"; - m_SubTargets = TargetUtils.GetSubTargetsOfType(); + m_SubTargets = TargetUtils.GetSubTargets(this); + m_SubTargetNames = m_SubTargets.Select(x => x.displayName).ToList(); + + TargetUtils.ProcessSubTargetList(ref m_ActiveSubTarget, ref m_SubTargets); + ProcessSubTargetDatas(m_ActiveSubTarget.value); } public static string sharedTemplateDirectory => $"{HDUtils.GetHDRenderPipelinePath()}Editor/ShaderGraph/Templates"; + public string customEditorGUI + { + get => m_CustomEditorGUI; + set => m_CustomEditorGUI = value; + } + + public override bool IsActive() + { + if(m_ActiveSubTarget.value == null) + return false; + + bool isHDRenderPipeline = GraphicsSettings.currentRenderPipeline is HDRenderPipelineAsset; + return isHDRenderPipeline && m_ActiveSubTarget.value.IsActive(); + } + public override void Setup(ref TargetSetupContext context) { - // Currently we infer the active SubTarget based on the MasterNode type - void SetActiveSubTargetIndex(IMasterNode masterNode) + // Setup the Target + context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); + + // Process SubTargets + TargetUtils.ProcessSubTargetList(ref m_ActiveSubTarget, ref m_SubTargets); + if(m_ActiveSubTarget.value == null) + return; + + // Setup the active SubTarget + ProcessSubTargetDatas(m_ActiveSubTarget.value); + m_ActiveSubTarget.value.target = this; + m_ActiveSubTarget.value.Setup(ref context); + + // Override EditorGUI + if(!string.IsNullOrEmpty(m_CustomEditorGUI)) + { + context.SetDefaultShaderGUI(m_CustomEditorGUI); + } + } + + public override void GetFields(ref TargetFieldContext context) + { + var descs = context.blocks.Select(x => x.descriptor); + // Stages + context.AddField(Fields.GraphVertex, descs.Contains(BlockFields.VertexDescription.Position) || + descs.Contains(BlockFields.VertexDescription.Normal) || + descs.Contains(BlockFields.VertexDescription.Tangent)); + context.AddField(Fields.GraphPixel); + + // SubTarget + m_ActiveSubTarget.value.GetFields(ref context); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + // SubTarget + m_ActiveSubTarget.value.GetActiveBlocks(ref context); + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + if(m_ActiveSubTarget.value == null) + return; + + context.globalIndentLevel++; + + // Core properties + m_SubTargetField = new PopupField(m_SubTargetNames, activeSubTargetIndex); + context.AddProperty("Material", m_SubTargetField, (evt) => + { + if (Equals(activeSubTargetIndex, m_SubTargetField.index)) + return; + + var systemData = m_Datas.SelectValue().FirstOrDefault(x => x is SystemData) as SystemData; + if(systemData != null) + { + // Force material update hash + systemData.materialNeedsUpdateHash = -1; + } + + m_ActiveSubTarget = m_SubTargets[m_SubTargetField.index]; + ProcessSubTargetDatas(m_ActiveSubTarget.value); + onChange(); + }); + + // SubTarget properties + m_ActiveSubTarget.value.GetPropertiesGUI(ref context, onChange, registerUndo); + + // Custom Editor GUI + m_CustomGUIField = new TextField("") { value = m_CustomEditorGUI }; + m_CustomGUIField.RegisterCallback(s => { - Type activeSubTargetType; - if(!s_SubTargetMap.TryGetValue(masterNode.GetType(), out activeSubTargetType)) + if (Equals(m_CustomEditorGUI, m_CustomGUIField.value)) return; - m_ActiveSubTarget = m_SubTargets.FirstOrDefault(x => x.GetType() == activeSubTargetType); + m_CustomEditorGUI = m_CustomGUIField.value; + onChange(); + }); + context.AddProperty("Custom Editor GUI", m_CustomGUIField, (evt) => {}); + + context.globalIndentLevel--; + } + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) + { + // SubTarget + m_ActiveSubTarget.value.CollectShaderProperties(collector, generationMode); + } + + public override void ProcessPreviewMaterial(Material material) + { + // SubTarget + m_ActiveSubTarget.value.ProcessPreviewMaterial(material); + } + + public override object saveContext => m_ActiveSubTarget.value?.saveContext; + + // IHasMetaData + public string identifier + { + get + { + if(m_ActiveSubTarget.value is IHasMetadata subTargetHasMetaData) + return subTargetHasMetaData.identifier; + + return null; } + } + + public ScriptableObject GetMetadataObject() + { + if(m_ActiveSubTarget.value is IHasMetadata subTargetHasMetaData) + return subTargetHasMetaData.GetMetadataObject(); + + return null; + } + + public bool TrySetActiveSubTarget(Type subTargetType) + { + if(!subTargetType.IsSubclassOf(typeof(SubTarget))) + return false; - // Setup the Target - context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); + foreach(var subTarget in m_SubTargets) + { + if(subTarget.GetType().Equals(subTargetType)) + { + m_ActiveSubTarget = subTarget; + ProcessSubTargetDatas(m_ActiveSubTarget); + return true; + } + } - // Setup the active SubTarget - SetActiveSubTargetIndex(context.masterNode); - m_ActiveSubTarget.Setup(ref context); + return false; + } + + void ProcessSubTargetDatas(SubTarget subTarget) + { + var typeCollection = TypeCache.GetTypesDerivedFrom(); + foreach(var type in typeCollection) + { + // Data requirement interfaces need generic type arguments + // Therefore we need to use reflections to call the method + var methodInfo = typeof(HDTarget).GetMethod("SetDataOnSubTarget"); + var genericMethodInfo = methodInfo.MakeGenericMethod(type); + genericMethodInfo.Invoke(this, new object[] { subTarget }); + } + } + + void ClearUnusedData() + { + for(int i = 0; i < m_Datas.Count; i++) + { + var data = m_Datas[i]; + var type = data.value.GetType(); + + // Data requirement interfaces need generic type arguments + // Therefore we need to use reflections to call the method + var methodInfo = typeof(HDTarget).GetMethod("ValidateDataForSubTarget"); + var genericMethodInfo = methodInfo.MakeGenericMethod(type); + genericMethodInfo.Invoke(this, new object[] { m_ActiveSubTarget.value, data.value }); + } + } + + public void SetDataOnSubTarget(SubTarget subTarget) where T : HDTargetData + { + if(!(subTarget is IRequiresData requiresData)) + return; + + // Ensure data object exists in list + var data = m_Datas.SelectValue().FirstOrDefault(x => x.GetType().Equals(typeof(T))) as T; + if(data == null) + { + data = Activator.CreateInstance(typeof(T)) as T; + m_Datas.Add(data); + } + + // Apply data object to SubTarget + requiresData.data = data; + } + + public void ValidateDataForSubTarget(SubTarget subTarget, T data) where T : HDTargetData + { + if(!(subTarget is IRequiresData requiresData)) + { + m_Datas.Remove(data); + } + } + + public override void OnBeforeSerialize() + { + ClearUnusedData(); } - public override bool IsValid(IMasterNode masterNode) + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { - // Currently we infer the validity based on SubTarget mapping - return s_SubTargetMap.TryGetValue(masterNode.GetType(), out _); + blockMap = null; + + // We need to guarantee any required data object exists + // as we fill out the datas in the same method as determining which SubTarget is valid + // When the graph is serialized any unused data is removed anyway + var typeCollection = TypeCache.GetTypesDerivedFrom(); + foreach(var type in typeCollection) + { + var data = Activator.CreateInstance(type) as HDTargetData; + m_Datas.Add(data); + } + + // Process SubTargets + foreach(var subTarget in m_SubTargets) + { + if(!(subTarget is ILegacyTarget legacySubTarget)) + continue; + + // Ensure all SubTargets have any required data to fill out during upgrade + ProcessSubTargetDatas(subTarget); + subTarget.target = this; + + if(legacySubTarget.TryUpgradeFromMasterNode(masterNode, out blockMap)) + { + m_ActiveSubTarget = subTarget; + return true; + } + } + + return false; } - public override bool IsPipelineCompatible(RenderPipelineAsset currentPipeline) + public override bool WorksWithSRP(RenderPipelineAsset scriptableRenderPipeline) { - return currentPipeline is HDRenderPipelineAsset; + return scriptableRenderPipeline?.GetType() == typeof(HDRenderPipelineAsset); } + } - // Currently we need to map SubTarget type to IMasterNode type - // We do this here to avoid bleeding this into the SubTarget API - static Dictionary s_SubTargetMap = new Dictionary() +#region BlockMasks + static class CoreBlockMasks + { + public static BlockFieldDescriptor[] Vertex = new BlockFieldDescriptor[] { - { typeof(PBRMasterNode), typeof(PBRSubTarget) }, - { typeof(UnlitMasterNode), typeof(UnlitSubTarget) }, - { typeof(HDLitMasterNode), typeof(HDLitSubTarget) }, - { typeof(HDUnlitMasterNode), typeof(HDUnlitSubTarget) }, - { typeof(DecalMasterNode), typeof(HDDecalSubTarget) }, - { typeof(EyeMasterNode), typeof(HDEyeSubTarget) }, - { typeof(FabricMasterNode), typeof(HDFabricSubTarget) }, - { typeof(HairMasterNode), typeof(HDHairSubTarget) }, - { typeof(StackLitMasterNode), typeof(HDStackLitSubTarget) }, + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, }; } +#endregion #region StructCollections static class CoreStructCollections @@ -171,9 +447,9 @@ static class CoreFieldDependencies new FieldDependency(StructFields.VertexDescriptionInputs.uv3, HDStructFields.AttributesMesh.uv3), new FieldDependency(StructFields.VertexDescriptionInputs.VertexColor, HDStructFields.AttributesMesh.color), - new FieldDependency(StructFields.VertexDescriptionInputs.BoneWeights, HDStructFields.AttributesMesh.weights), - new FieldDependency(StructFields.VertexDescriptionInputs.BoneIndices, HDStructFields.AttributesMesh.indices), - new FieldDependency(StructFields.VertexDescriptionInputs.VertexID, HDStructFields.AttributesMesh.vertexID), + new FieldDependency(StructFields.VertexDescriptionInputs.BoneWeights, HDStructFields.AttributesMesh.weights), + new FieldDependency(StructFields.VertexDescriptionInputs.BoneIndices, HDStructFields.AttributesMesh.indices), + new FieldDependency(StructFields.VertexDescriptionInputs.VertexID, HDStructFields.AttributesMesh.vertexID), }; public static DependencyCollection SurfaceDescription = new DependencyCollection @@ -213,10 +489,6 @@ static class CoreFieldDependencies new FieldDependency(StructFields.SurfaceDescriptionInputs.FaceSign, HDStructFields.FragInputs.IsFrontFace), new FieldDependency(HDFields.DepthOffset, HDStructFields.FragInputs.positionRWS), - - new FieldDependency(StructFields.SurfaceDescriptionInputs.BoneWeights, StructFields.SurfaceDescriptionInputs.BoneIndices), - new FieldDependency(StructFields.SurfaceDescriptionInputs.BoneIndices, StructFields.SurfaceDescriptionInputs.BoneWeights), - new FieldDependency(StructFields.SurfaceDescriptionInputs.VertexID, StructFields.SurfaceDescriptionInputs.VertexID), }; public static DependencyCollection Default = new DependencyCollection @@ -368,13 +640,27 @@ public static class Uniforms { RenderState.ColorMask("ColorMask [_ColorMaskTransparentVel] 1") }, }; - public static RenderStateCollection TransparentDepthPrePostPass = new RenderStateCollection + + public static RenderStateCollection TransparentDepthPrePass = new RenderStateCollection + { + { RenderState.Blend(Blend.One, Blend.Zero) }, + { RenderState.Cull(Uniforms.cullMode) }, + { RenderState.ZWrite(ZWrite.On) }, + { RenderState.Stencil(new StencilDescriptor() + { + WriteMask = CoreRenderStates.Uniforms.stencilWriteMaskDepth, + Ref = CoreRenderStates.Uniforms.stencilRefDepth, + Comp = "Always", + Pass = "Replace", + }) }, + }; + + public static RenderStateCollection TransparentDepthPostPass = new RenderStateCollection { { RenderState.Blend(Blend.One, Blend.Zero) }, { RenderState.Cull(Uniforms.cullMode) }, { RenderState.ZWrite(ZWrite.On) }, - { RenderState.ColorMask("ColorMask [_ColorMaskNormal]") }, - { RenderState.ColorMask("ColorMask 0 1") }, + { RenderState.ColorMask("ColorMask 0") }, }; public static RenderStateCollection Forward = new RenderStateCollection @@ -735,6 +1021,7 @@ static class CoreIncludes { // Pregraph includes { kCommon, IncludeLocation.Pregraph }, + { kTextureStack, IncludeLocation.Pregraph }, { kFragInputs, IncludeLocation.Pregraph }, { kShaderPass, IncludeLocation.Pregraph }, diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/PBR.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy.meta similarity index 77% rename from com.unity.render-pipelines.high-definition/Editor/Material/PBR.meta rename to com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy.meta index 7860e5cd86b..52a2d26d626 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/PBR.meta +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 7382299dcb85271448359c1ee3a9255d +guid: 232157eb5bc17b847b630862af164a71 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/DecalMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/DecalMasterNode1.cs new file mode 100644 index 00000000000..1cab30b010f --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/DecalMasterNode1.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.DecalMasterNode")] + [FormerName("UnityEditor.Rendering.HighDefinition.DecalMasterNode")] + class DecalMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public enum SurfaceType + { + Opaque, + Transparent + } + + public const int PositionSlotId = 0; + public const int AlbedoSlotId = 1; + public const int BaseColorOpacitySlotId = 2; + public const int NormalSlotId = 3; + public const int NormaOpacitySlotId = 4; + public const int MetallicSlotId = 5; + public const int AmbientOcclusionSlotId = 6; + public const int SmoothnessSlotId = 7; + public const int MAOSOpacitySlotId = 8; + public const int EmissionSlotId = 9; + public const int VertexNormalSlotID = 10; + public const int VertexTangentSlotID = 11; + + [Flags] + public enum SlotMask + { + None = 0, + Position = 1 << PositionSlotId, + VertexNormal = 1 << VertexNormalSlotID, + VertexTangent = 1 << VertexTangentSlotID, + Albedo = 1 << AlbedoSlotId, + AlphaAlbedo = 1 << BaseColorOpacitySlotId, + Normal = 1 << NormalSlotId, + AlphaNormal = 1 << NormaOpacitySlotId, + Metallic = 1 << MetallicSlotId, + Occlusion = 1 << AmbientOcclusionSlotId, + Smoothness = 1 << SmoothnessSlotId, + AlphaMAOS = 1 << MAOSOpacitySlotId, + Emission = 1 << EmissionSlotId + } + + const SlotMask decalParameter = SlotMask.Position | SlotMask.VertexNormal | SlotMask.VertexTangent | SlotMask.Albedo | SlotMask.AlphaAlbedo | SlotMask.Normal | SlotMask.AlphaNormal | SlotMask.Metallic | SlotMask.Occlusion | SlotMask.Smoothness | SlotMask.AlphaMAOS | SlotMask.Emission; + + SlotMask GetActiveSlotMask() + { + return decalParameter; + } + + public bool MaterialTypeUsesSlotMask(SlotMask mask) + { + SlotMask activeMask = GetActiveSlotMask(); + return (activeMask & mask) != 0; + } + + public SurfaceType m_SurfaceType; + public bool m_AffectsMetal; + public bool m_AffectsAO; + public bool m_AffectsSmoothness; + public bool m_AffectsAlbedo; + public bool m_AffectsNormal; + public bool m_AffectsEmission; + public int m_DrawOrder; + public bool m_DOTSInstancing; + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/DecalMasterNode1.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/DecalMasterNode1.cs.meta new file mode 100644 index 00000000000..7a11bc97f95 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/DecalMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 13ae26293b203fd469279222846fb57a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/EyeMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/EyeMasterNode1.cs new file mode 100644 index 00000000000..33d9131b913 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/EyeMasterNode1.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.Rendering.HighDefinition.EyeMasterNode")] + class EyeMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public enum SurfaceType + { + Opaque, + Transparent + } + + public enum AlphaMode + { + Alpha, + Premultiply, + Additive, + } + + public enum MaterialType + { + Eye, + EyeCinematic + } + + public const int PositionSlotId = 0; + public const int AlbedoSlotId = 1; + public const int SpecularOcclusionSlotId = 2; + public const int NormalSlotId = 3; + public const int IrisNormalSlotId = 4; + public const int SmoothnessSlotId = 5; + public const int IORSlotId = 6; + public const int AmbientOcclusionSlotId = 7; + public const int MaskSlotId = 8; + public const int DiffusionProfileHashSlotId = 9; + public const int SubsurfaceMaskSlotId = 10; + public const int EmissionSlotId = 11; + public const int AlphaSlotId = 12; + public const int AlphaClipThresholdSlotId = 13; + public const int BentNormalSlotId = 14; + public const int LightingSlotId = 15; + public const int BackLightingSlotId = 16; + public const int DepthOffsetSlotId = 17; + public const int VertexNormalSlotID = 18; + public const int VertexTangentSlotID = 19; + + [Flags] + public enum SlotMask + { + None = 0, + Position = 1 << PositionSlotId, + VertexNormal = 1 << VertexNormalSlotID, + VertexTangent = 1 << VertexTangentSlotID, + Albedo = 1 << AlbedoSlotId, + SpecularOcclusion = 1 << SpecularOcclusionSlotId, + Normal = 1 << NormalSlotId, + IrisNormal = 1 << IrisNormalSlotId, + Smoothness = 1 << SmoothnessSlotId, + IOR = 1 << IORSlotId, + Occlusion = 1 << AmbientOcclusionSlotId, + Mask = 1 << MaskSlotId, + DiffusionProfile = 1 << DiffusionProfileHashSlotId, + SubsurfaceMask = 1 << SubsurfaceMaskSlotId, + Emission = 1 << EmissionSlotId, + Alpha = 1 << AlphaSlotId, + AlphaClipThreshold = 1 << AlphaClipThresholdSlotId, + BentNormal = 1 << BentNormalSlotId, + BakedGI = 1 << LightingSlotId, + BakedBackGI = 1 << BackLightingSlotId, + DepthOffset = 1 << DepthOffsetSlotId, + } + + const SlotMask EyeSlotMask = SlotMask.Position | SlotMask.VertexNormal | SlotMask.VertexTangent | SlotMask.Albedo | SlotMask.SpecularOcclusion | SlotMask.Normal | SlotMask.IrisNormal | SlotMask.Smoothness | SlotMask.IOR | SlotMask.Occlusion | SlotMask.Mask | SlotMask.DiffusionProfile | SlotMask.SubsurfaceMask | SlotMask.Emission | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.BentNormal | SlotMask.BakedGI | SlotMask.DepthOffset; + const SlotMask EyeCinematicSlotMask = EyeSlotMask; + + SlotMask GetActiveSlotMask() + { + switch (m_MaterialType) + { + case MaterialType.Eye: + return EyeSlotMask; + + case MaterialType.EyeCinematic: + return EyeCinematicSlotMask; + + default: + return SlotMask.None; + } + } + + public bool MaterialTypeUsesSlotMask(SlotMask mask) + { + SlotMask activeMask = GetActiveSlotMask(); + return (activeMask & mask) != 0; + } + + // public bool m_RayTracing; + public SurfaceType m_SurfaceType; + public AlphaMode m_AlphaMode; + public bool m_BlendPreserveSpecular; + public bool m_TransparencyFog; + public bool m_AlphaTest; + public bool m_AlphaTestDepthPrepass; + public bool m_AlphaTestDepthPostpass; + public int m_SortPriority; + public DoubleSidedMode m_DoubleSidedMode; + public MaterialType m_MaterialType; + public bool m_ReceiveDecals; + public bool m_ReceivesSSR; + public bool m_ReceivesSSRTransparent; + public bool m_AddPrecomputedVelocity; + public SpecularOcclusionMode m_SpecularOcclusionMode; + public bool m_overrideBakedGI; + public bool m_depthOffset; + public bool m_ZWrite; + public TransparentCullMode m_transparentCullMode; + public CompareFunction m_ZTest; + public bool m_SupportLodCrossFade; + public bool m_DOTSInstancing; + public bool m_AlphaToMask; + public int m_MaterialNeedsUpdateHash; + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + public bool m_SubsurfaceScattering; + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/EyeMasterNode1.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/EyeMasterNode1.cs.meta new file mode 100644 index 00000000000..19d4be2f49d --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/EyeMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3ae7c9bbdd1608340b8035789125570d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/FabricMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/FabricMasterNode1.cs new file mode 100644 index 00000000000..3b5a441b799 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/FabricMasterNode1.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.FabricMasterNode")] + [FormerName("UnityEditor.Rendering.HighDefinition.FabricMasterNode")] + [FormerName("UnityEditor.ShaderGraph.FabricMasterNode")] + class FabricMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public enum SurfaceType + { + Opaque, + Transparent + } + + public enum AlphaMode + { + Alpha, + Premultiply, + Additive, + } + + public enum MaterialType + { + CottonWool, + Silk + } + + public const int PositionSlotId = 0; + public const int AlbedoSlotId = 1; + public const int SpecularOcclusionSlotId = 2; + public const int NormalSlotId = 3; + public const int SmoothnessSlotId = 4; + public const int AmbientOcclusionSlotId = 5; + public const int SpecularColorSlotId = 6; + public const int DiffusionProfileHashSlotId = 7; + public const int SubsurfaceMaskSlotId = 8; + public const int ThicknessSlotId = 9; + public const int TangentSlotId = 10; + public const int AnisotropySlotId = 11; + public const int EmissionSlotId = 12; + public const int AlphaSlotId = 13; + public const int AlphaClipThresholdSlotId = 14; + public const int BentNormalSlotId = 15; + public const int LightingSlotId = 16; + public const int BackLightingSlotId = 17; + public const int DepthOffsetSlotId = 18; + public const int VertexNormalSlotId = 19; + public const int VertexTangentSlotId = 20; + + [Flags] + public enum SlotMask + { + None = 0, + Position = 1 << PositionSlotId, + Albedo = 1 << AlbedoSlotId, + SpecularOcclusion = 1 << SpecularOcclusionSlotId, + Normal = 1 << NormalSlotId, + Smoothness = 1 << SmoothnessSlotId, + Occlusion = 1 << AmbientOcclusionSlotId, + Specular = 1 << SpecularColorSlotId, + DiffusionProfile = 1 << DiffusionProfileHashSlotId, + SubsurfaceMask = 1 << SubsurfaceMaskSlotId, + Thickness = 1 << ThicknessSlotId, + Tangent = 1 << TangentSlotId, + Anisotropy = 1 << AnisotropySlotId, + Emission = 1 << EmissionSlotId, + Alpha = 1 << AlphaSlotId, + AlphaClipThreshold = 1 << AlphaClipThresholdSlotId, + BentNormal = 1 << BentNormalSlotId, + BakedGI = 1 << LightingSlotId, + BakedBackGI = 1 << BackLightingSlotId, + DepthOffset = 1 << DepthOffsetSlotId, + VertexNormal = 1 << VertexNormalSlotId, + VertexTangent = 1 << VertexTangentSlotId, + } + + const SlotMask CottonWoolSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.SpecularOcclusion | SlotMask.Normal | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.Specular | SlotMask.DiffusionProfile | SlotMask.SubsurfaceMask | SlotMask.Thickness | SlotMask.Emission | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.BentNormal | SlotMask.BakedGI | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; + const SlotMask SilkSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.SpecularOcclusion | SlotMask.Normal | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.Specular | SlotMask.DiffusionProfile | SlotMask.SubsurfaceMask | SlotMask.Thickness | SlotMask.Tangent | SlotMask.Anisotropy | SlotMask.Emission | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.BentNormal | SlotMask.BakedGI | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; + + // This could also be a simple array. For now, catch any mismatched data. + SlotMask GetActiveSlotMask() + { + switch (m_MaterialType) + { + case MaterialType.CottonWool: + return CottonWoolSlotMask; + + case MaterialType.Silk: + return SilkSlotMask; + + default: + return SlotMask.None; + } + } + + public bool MaterialTypeUsesSlotMask(SlotMask mask) + { + SlotMask activeMask = GetActiveSlotMask(); + return (activeMask & mask) != 0; + } + + public SurfaceType m_SurfaceType; + public AlphaMode m_AlphaMode; + public bool m_BlendPreserveSpecular; + public bool m_TransparencyFog; + public bool m_AlphaTest; + public int m_SortPriority; + public DoubleSidedMode m_DoubleSidedMode; + public MaterialType m_MaterialType; + public bool m_ReceiveDecals; + public bool m_ReceivesSSR; + public bool m_ReceivesSSRTransparent; + public bool m_AddPrecomputedVelocity; + public bool m_EnergyConservingSpecular; + public SpecularOcclusionMode m_SpecularOcclusionMode; + public bool m_overrideBakedGI; + public bool m_depthOffset; + public bool m_ZWrite; + public TransparentCullMode m_transparentCullMode; + public CompareFunction m_ZTest; + public bool m_SupportLodCrossFade; + public bool m_DOTSInstancing; + public bool m_AlphaToMask; + public int m_MaterialNeedsUpdateHash; + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + public bool m_Transmission; + public bool m_SubsurfaceScattering; + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/FabricMasterNode1.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/FabricMasterNode1.cs.meta new file mode 100644 index 00000000000..8030ece4479 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/FabricMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4475f8b9439087a438b9e09eeec7b347 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDLitMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDLitMasterNode1.cs new file mode 100644 index 00000000000..1bda6d3a24f --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDLitMasterNode1.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.HDLitMasterNode")] + [FormerName("UnityEditor.Rendering.HighDefinition.HDLitMasterNode")] + [FormerName("UnityEditor.ShaderGraph.HDLitMasterNode")] + class HDLitMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public enum SurfaceType + { + Opaque, + Transparent + } + + public enum AlphaMode + { + Alpha, + Premultiply, + Additive, + } + + public enum MaterialType + { + Standard, + SubsurfaceScattering, + Anisotropy, + Iridescence, + SpecularColor, + Translucent + } + + public const int PositionSlotId = 0; + public const int AlbedoSlotId = 1; + public const int NormalSlotId = 2; + public const int BentNormalSlotId = 3; + public const int TangentSlotId = 4; + public const int SubsurfaceMaskSlotId = 5; + public const int ThicknessSlotId = 6; + public const int DiffusionProfileHashSlotId = 7; + public const int IridescenceMaskSlotId = 8; + public const int IridescenceThicknessSlotId = 9; + public const int SpecularColorSlotId = 10; + public const int CoatMaskSlotId = 11; + public const int MetallicSlotId = 12; + public const int EmissionSlotId = 13; + public const int SmoothnessSlotId = 14; + public const int AmbientOcclusionSlotId = 15; + public const int AlphaSlotId = 16; + public const int AlphaThresholdSlotId = 17; + public const int AlphaThresholdDepthPrepassSlotId = 18; + public const int AlphaThresholdDepthPostpassSlotId = 19; + public const int AnisotropySlotId = 20; + public const int SpecularAAScreenSpaceVarianceSlotId = 21; + public const int SpecularAAThresholdSlotId = 22; + public const int RefractionIndexSlotId = 23; + public const int RefractionColorSlotId = 24; + public const int RefractionDistanceSlotId = 25; + public const int DistortionSlotId = 26; + public const int DistortionBlurSlotId = 27; + public const int SpecularOcclusionSlotId = 28; + public const int AlphaThresholdShadowSlotId = 29; + public const int LightingSlotId = 30; + public const int BackLightingSlotId = 31; + public const int DepthOffsetSlotId = 32; + public const int VertexNormalSlotID = 33; + public const int VertexTangentSlotID = 34; + + [Flags] + public enum SlotMask + { + None = 0, + Position = 1 << PositionSlotId, + Albedo = 1 << AlbedoSlotId, + Normal = 1 << NormalSlotId, + BentNormal = 1 << BentNormalSlotId, + Tangent = 1 << TangentSlotId, + SubsurfaceMask = 1 << SubsurfaceMaskSlotId, + Thickness = 1 << ThicknessSlotId, + DiffusionProfile = 1 << DiffusionProfileHashSlotId, + IridescenceMask = 1 << IridescenceMaskSlotId, + IridescenceLayerThickness = 1 << IridescenceThicknessSlotId, + Specular = 1 << SpecularColorSlotId, + CoatMask = 1 << CoatMaskSlotId, + Metallic = 1 << MetallicSlotId, + Emission = 1 << EmissionSlotId, + Smoothness = 1 << SmoothnessSlotId, + Occlusion = 1 << AmbientOcclusionSlotId, + Alpha = 1 << AlphaSlotId, + AlphaThreshold = 1 << AlphaThresholdSlotId, + AlphaThresholdDepthPrepass = 1 << AlphaThresholdDepthPrepassSlotId, + AlphaThresholdDepthPostpass = 1 << AlphaThresholdDepthPostpassSlotId, + Anisotropy = 1 << AnisotropySlotId, + SpecularOcclusion = 1 << SpecularOcclusionSlotId, + AlphaThresholdShadow = 1 << AlphaThresholdShadowSlotId, + Lighting = 1 << LightingSlotId, + BackLighting = 1 << BackLightingSlotId, + + // We ran out of bits here. Luckily they always pass SlotMask tests. Upgrade these manally. + // DepthOffset = 1 << DepthOffsetSlotId, + // VertexNormal = 1 << VertexNormalSlotID, + // VertexTangent = 1 << VertexTangentSlotID + } + + const SlotMask StandardSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Metallic | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting;// | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; + const SlotMask SubsurfaceScatteringSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.SubsurfaceMask | SlotMask.Thickness | SlotMask.DiffusionProfile | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting;// | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; + const SlotMask AnisotropySlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.Tangent | SlotMask.Anisotropy | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Metallic | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting;// | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; + const SlotMask IridescenceSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.IridescenceMask | SlotMask.IridescenceLayerThickness | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Metallic | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting;// | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; + const SlotMask SpecularColorSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.Specular | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting;// | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; + const SlotMask TranslucentSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.Thickness | SlotMask.DiffusionProfile | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting;// | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; + + SlotMask GetActiveSlotMask() + { + switch (m_MaterialType) + { + case MaterialType.Standard: + return StandardSlotMask; + + case MaterialType.SubsurfaceScattering: + return SubsurfaceScatteringSlotMask; + + case MaterialType.Anisotropy: + return AnisotropySlotMask; + + case MaterialType.Iridescence: + return IridescenceSlotMask; + + case MaterialType.SpecularColor: + return SpecularColorSlotMask; + + case MaterialType.Translucent: + return TranslucentSlotMask; + + default: + return SlotMask.None; + } + } + + public bool MaterialTypeUsesSlotMask(SlotMask mask) + { + SlotMask activeMask = GetActiveSlotMask(); + return (activeMask & mask) != 0; + } + + public bool m_RayTracing; + public SurfaceType m_SurfaceType; + public AlphaMode m_AlphaMode; + public HDRenderQueue.RenderQueueType m_RenderingPass; + public bool m_BlendPreserveSpecular; + public bool m_TransparencyFog; + public ScreenSpaceRefraction.RefractionModel m_RefractionModel; + public bool m_Distortion; + public DistortionMode m_DistortionMode; + public bool m_DistortionDepthTest; + public bool m_AlphaTest; + public bool m_AlphaTestDepthPrepass; + public bool m_AlphaTestDepthPostpass; + public bool m_TransparentWritesMotionVec; + public bool m_AlphaTestShadow; + public bool m_BackThenFrontRendering; + public int m_SortPriority; + public DoubleSidedMode m_DoubleSidedMode; + public NormalDropOffSpace m_NormalDropOffSpace; + public MaterialType m_MaterialType; + public bool m_SSSTransmission; + public bool m_ReceiveDecals; + public bool m_ReceivesSSR; + public bool m_ReceivesSSRTransparent; + public bool m_AddPrecomputedVelocity; + public bool m_EnergyConservingSpecular; + public bool m_SpecularAA; + public SpecularOcclusionMode m_SpecularOcclusionMode; + public bool m_overrideBakedGI; + public bool m_depthOffset; + public bool m_ZWrite; + public TransparentCullMode m_transparentCullMode; + public CompareFunction m_ZTest; + public bool m_SupportLodCrossFade; + public bool m_DOTSInstancing; + public bool m_AlphaToMask; + public int m_MaterialNeedsUpdateHash; + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDLitMasterNode1.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDLitMasterNode1.cs.meta new file mode 100644 index 00000000000..b395ba607ed --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDLitMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d97948659bc911f458480f0d571eb52d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDUnlitMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDUnlitMasterNode1.cs new file mode 100644 index 00000000000..9d4f2a73055 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDUnlitMasterNode1.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.HDUnlitMasterNode")] + [FormerName("UnityEditor.Rendering.HighDefinition.HDUnlitMasterNode")] + class HDUnlitMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public enum SurfaceType + { + Opaque, + Transparent + } + + public enum AlphaMode + { + Alpha, + Premultiply, + Additive, + } + + public SurfaceType m_SurfaceType; + public AlphaMode m_AlphaMode; + public HDRenderQueue.RenderQueueType m_RenderingPass; + public bool m_TransparencyFog; + public bool m_Distortion; + public DistortionMode m_DistortionMode; + public bool m_DistortionOnly; + public bool m_DistortionDepthTest; + public bool m_AlphaTest; + public bool m_AlphaToMask; + public int m_SortPriority; + public bool m_DoubleSided; + public bool m_ZWrite; + public TransparentCullMode m_transparentCullMode; + public CompareFunction m_ZTest; + public bool m_AddPrecomputedVelocity; + public bool m_EnableShadowMatte; + public bool m_DOTSInstancing; + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDUnlitMasterNode1.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDUnlitMasterNode1.cs.meta new file mode 100644 index 00000000000..c93ce7092eb --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HDUnlitMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 54b5a261f1c358b4aa440db82731bfd7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HairMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HairMasterNode1.cs new file mode 100644 index 00000000000..566a1fea031 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HairMasterNode1.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.HairMasterNode")] + [FormerName("UnityEditor.Rendering.HighDefinition.HairMasterNode")] + class HairMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public enum SurfaceType + { + Opaque, + Transparent + } + + public enum AlphaMode + { + Alpha, + Premultiply, + Additive, + } + + public enum MaterialType + { + KajiyaKay + } + + public const int PositionSlotId = 0; + public const int AlbedoSlotId = 1; + public const int NormalSlotId = 2; + public const int SpecularOcclusionSlotId = 3; + public const int BentNormalSlotId = 4; + public const int HairStrandDirectionSlotId = 5; + public const int UnusedSlot6 = 6; + public const int TransmittanceSlotId = 7; + public const int RimTransmissionIntensitySlotId = 8; + public const int SmoothnessSlotId = 9; + public const int AmbientOcclusionSlotId = 10; + public const int EmissionSlotId = 11; + public const int AlphaSlotId = 12; + public const int AlphaClipThresholdSlotId = 13; + public const int AlphaClipThresholdDepthPrepassSlotId = 14; + public const int AlphaClipThresholdDepthPostpassSlotId = 15; + public const int SpecularAAScreenSpaceVarianceSlotId = 16; + public const int SpecularAAThresholdSlotId = 17; + public const int SpecularTintSlotId = 18; + public const int SpecularShiftSlotId = 19; + public const int SecondarySpecularTintSlotId = 20; + public const int SecondarySmoothnessSlotId = 21; + public const int SecondarySpecularShiftSlotId = 22; + public const int AlphaClipThresholdShadowSlotId = 23; + public const int LightingSlotId = 24; + public const int BackLightingSlotId = 25; + public const int DepthOffsetSlotId = 26; + public const int VertexNormalSlotId = 27; + public const int VertexTangentSlotId = 28; + + [Flags] + public enum SlotMask + { + None = 0, + Position = 1 << PositionSlotId, + Albedo = 1 << AlbedoSlotId, + Normal = 1 << NormalSlotId, + SpecularOcclusion = 1 << SpecularOcclusionSlotId, + BentNormal = 1 << BentNormalSlotId, + HairStrandDirection = 1 << HairStrandDirectionSlotId, + Slot6 = 1 << UnusedSlot6, + Transmittance = 1 << TransmittanceSlotId, + RimTransmissionIntensity = 1 << RimTransmissionIntensitySlotId, + Smoothness = 1 << SmoothnessSlotId, + Occlusion = 1 << AmbientOcclusionSlotId, + Emission = 1 << EmissionSlotId, + Alpha = 1 << AlphaSlotId, + AlphaClipThreshold = 1 << AlphaClipThresholdSlotId, + AlphaClipThresholdDepthPrepass = 1 << AlphaClipThresholdDepthPrepassSlotId, + AlphaClipThresholdDepthPostpass = 1 << AlphaClipThresholdDepthPostpassSlotId, + SpecularTint = 1 << SpecularTintSlotId, + SpecularShift = 1 << SpecularShiftSlotId, + SecondarySpecularTint = 1 << SecondarySpecularTintSlotId, + SecondarySmoothness = 1 << SecondarySmoothnessSlotId, + SecondarySpecularShift = 1 << SecondarySpecularShiftSlotId, + AlphaClipThresholdShadow = 1 << AlphaClipThresholdShadowSlotId, + BakedGI = 1 << LightingSlotId, + BakedBackGI = 1 << BackLightingSlotId, + DepthOffset = 1 << DepthOffsetSlotId, + VertexNormal = 1 << VertexNormalSlotId, + VertexTangent = 1 << VertexTangentSlotId, + } + + const SlotMask KajiyaKaySlotMask = SlotMask.Position | SlotMask.VertexNormal | SlotMask.VertexTangent | SlotMask.Albedo | SlotMask.Normal | SlotMask.SpecularOcclusion | SlotMask.BentNormal | SlotMask.HairStrandDirection | SlotMask.Slot6 + | SlotMask.Transmittance | SlotMask.RimTransmissionIntensity | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.AlphaClipThresholdDepthPrepass + | SlotMask.AlphaClipThresholdDepthPostpass | SlotMask.SpecularTint | SlotMask.SpecularShift | SlotMask.SecondarySpecularTint | SlotMask.SecondarySmoothness | SlotMask.SecondarySpecularShift | SlotMask.AlphaClipThresholdShadow | SlotMask.BakedGI | SlotMask.DepthOffset; + + SlotMask GetActiveSlotMask() + { + return KajiyaKaySlotMask; + } + + public bool MaterialTypeUsesSlotMask(SlotMask mask) + { + SlotMask activeMask = GetActiveSlotMask(); + return (activeMask & mask) != 0; + } + + public SurfaceType m_SurfaceType; + public AlphaMode m_AlphaMode; + public bool m_BlendPreserveSpecular; + public bool m_TransparencyFog; + public bool m_AlphaTest; + public bool m_AlphaTestDepthPrepass; + public bool m_AlphaTestDepthPostpass; + public bool m_TransparentWritesMotionVec; + public bool m_AlphaTestShadow; + public bool m_BackThenFrontRendering; + public int m_SortPriority; + public DoubleSidedMode m_DoubleSidedMode; + public MaterialType m_MaterialType; + public bool m_ReceiveDecals; + public bool m_ReceivesSSR; + public bool m_ReceivesSSRTransparent; + public bool m_AddPrecomputedVelocity; + public bool m_SpecularAA; + public SpecularOcclusionMode m_SpecularOcclusionMode; + public bool m_overrideBakedGI; + public bool m_depthOffset; + public bool m_ZWrite; + public TransparentCullMode m_transparentCullMode; + public CompareFunction m_ZTest; + public bool m_SupportLodCrossFade; + public bool m_DOTSInstancing; + public bool m_AlphaToMask; + public int m_MaterialNeedsUpdateHash; + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + public bool m_UseLightFacingNormal; + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HairMasterNode1.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HairMasterNode1.cs.meta new file mode 100644 index 00000000000..c8aae62d0b7 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/HairMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3a7c21581f1810745bd96532d11076b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/StackLitMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/StackLitMasterNode1.cs new file mode 100644 index 00000000000..d65b2cd8754 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/StackLitMasterNode1.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.StackLitMasterNode")] + [FormerName("UnityEditor.Rendering.HighDefinition.StackLitMasterNode")] + [FormerName("UnityEditor.ShaderGraph.StackLitMasterNode")] + class StackLitMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public enum SurfaceType + { + Opaque, + Transparent + } + + public enum AlphaMode + { + Alpha, + Premultiply, + Additive, + } + + public enum SpecularOcclusionBaseMode + { + Off = 0, + DirectFromAO = 1, // TriACE + ConeConeFromBentAO = 2, + SPTDIntegrationOfBentAO = 3, + Custom = 4, + } + + public enum SpecularOcclusionBaseModeSimple + { + Off = 0, + DirectFromAO = 1, // TriACE + SPTDIntegrationOfBentAO = 3, + Custom = 4, + } + + public enum SpecularOcclusionAOConeSize + { + UniformAO, + CosWeightedAO, + CosWeightedBentCorrectAO + } + + // This is in case SSAO-based SO method requires it (the SSAO we have doesn't provide a direction) + public enum SpecularOcclusionAOConeDir + { + GeomNormal, + BentNormal, + ShadingNormal + } + + // SO Bent cone fixup is only for methods using visibility cone and only for the data based SO: + public enum SpecularOcclusionConeFixupMethod + { + Off, + BoostBSDFRoughness, + TiltDirectionToGeomNormal, + BoostAndTilt, + } + + public const int PositionSlotId = 0; + public const int BaseColorSlotId = 1; + public const int NormalSlotId = 2; + public const int BentNormalSlotId = 3; + public const int TangentSlotId = 4; + public const int SubsurfaceMaskSlotId = 5; + public const int ThicknessSlotId = 6; + public const int DiffusionProfileHashSlotId = 7; + public const int IridescenceMaskSlotId = 8; + public const int IridescenceThicknessSlotId = 9; + public const int SpecularColorSlotId = 10; + public const int DielectricIorSlotId = 11; + public const int MetallicSlotId = 12; + public const int EmissionSlotId = 13; + public const int SmoothnessASlotId = 14; + public const int SmoothnessBSlotId = 15; + public const int AmbientOcclusionSlotId = 16; + public const int AlphaSlotId = 17; + public const int AlphaClipThresholdSlotId = 18; + public const int AnisotropyASlotId = 19; + public const int AnisotropyBSlotId = 20; + public const int SpecularAAScreenSpaceVarianceSlotId = 21; + public const int SpecularAAThresholdSlotId = 22; + public const int DistortionSlotId = 23; + public const int DistortionBlurSlotId = 24; + public const int CoatSmoothnessSlotId = 25; + public const int CoatIorSlotId = 26; + public const int CoatThicknessSlotId = 27; + public const int CoatExtinctionSlotId = 28; + public const int CoatNormalSlotId = 29; + public const int LobeMixSlotId = 30; + public const int HazinessSlotId = 31; + public const int HazeExtentSlotId = 32; + public const int HazyGlossMaxDielectricF0SlotId = 33; + public const int LightingSlotId = 34; + public const int BackLightingSlotId = 35; + public const int SOFixupVisibilityRatioThresholdSlotId = 36; + public const int SOFixupStrengthFactorSlotId = 37; + public const int SOFixupMaxAddedRoughnessSlotId = 38; + public const int CoatMaskSlotId = 39; + public const int IridescenceCoatFixupTIRSlotId = 40; + public const int IridescenceCoatFixupTIRClampSlotId = 41; + public const int DepthOffsetSlotId = 42; + public const int VertexNormalSlotId = 44; + public const int VertexTangentSlotId = 45; + public const int SpecularOcclusionSlotId = 43; // for custom (external) SO replacing data based SO (which normally comes from some func of DataBasedSOMode(dataAO, optional bent normal)) + + public SurfaceType m_SurfaceType; + public AlphaMode m_AlphaMode; + public bool m_BlendPreserveSpecular; + public bool m_TransparencyFog; + public bool m_Distortion; + public DistortionMode m_DistortionMode; + public bool m_DistortionDepthTest; + public bool m_AlphaTest; + public bool m_AlphaToMask; + public int m_SortPriority; + public DoubleSidedMode m_DoubleSidedMode; + public NormalDropOffSpace m_NormalDropOffSpace; + public StackLit.BaseParametrization m_BaseParametrization; + public bool m_EnergyConservingSpecular; + public StackLit.DualSpecularLobeParametrization m_DualSpecularLobeParametrization; + public bool m_Anisotropy; + public bool m_Coat; + public bool m_CoatNormal; + public bool m_DualSpecularLobe; + public bool m_CapHazinessWrtMetallic; + public bool m_Iridescence; + public bool m_SubsurfaceScattering; + public bool m_Transmission; + public bool m_ReceiveDecals; + public bool m_ReceiveSSR; + public bool m_ReceivesSSRTransparent; + public bool m_AddPrecomputedVelocity; + public bool m_GeometricSpecularAA; + public SpecularOcclusionBaseMode m_ScreenSpaceSpecularOcclusionBaseMode; + public SpecularOcclusionBaseMode m_DataBasedSpecularOcclusionBaseMode; + public SpecularOcclusionAOConeSize m_ScreenSpaceSpecularOcclusionAOConeSize; // This is still provided to tweak the effect of SSAO on the SO. + public SpecularOcclusionAOConeDir m_ScreenSpaceSpecularOcclusionAOConeDir; + public SpecularOcclusionAOConeSize m_DataBasedSpecularOcclusionAOConeSize; // Only for SO methods using visibility cones (ie ConeCone and SPTD) + public SpecularOcclusionConeFixupMethod m_SpecularOcclusionConeFixupMethod; + public bool m_AnisotropyForAreaLights; + public bool m_RecomputeStackPerLight; + public bool m_HonorPerLightMinRoughness; + public bool m_ShadeBaseUsingRefractedAngles; + public bool m_Debug; + public bool m_DevMode; + public bool m_overrideBakedGI; + public bool m_depthOffset; + public bool m_ZWrite; + public TransparentCullMode m_transparentCullMode; + public CompareFunction m_ZTest; + public bool m_SupportLodCrossFade; + public bool m_DOTSInstancing; + public int m_MaterialNeedsUpdateHash; + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/StackLitMasterNode1.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/StackLitMasterNode1.cs.meta new file mode 100644 index 00000000000..44527a0e1f1 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Legacy/StackLitMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0b77ade22e5c5ea4f8826f764e2f0a22 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Slots/DiffusionProfileInputMaterialSlot.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Slots/DiffusionProfileInputMaterialSlot.cs index 0c1a038286b..6eaec7a4051 100644 --- a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Slots/DiffusionProfileInputMaterialSlot.cs +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Slots/DiffusionProfileInputMaterialSlot.cs @@ -15,7 +15,8 @@ namespace UnityEditor.Rendering.HighDefinition [Serializable] [FormerName("UnityEditor.ShaderGraph.DiffusionProfileInputMaterialSlot")] [FormerName("UnityEditor.Experimental.Rendering.HDPipeline.DiffusionProfileInputMaterialSlot")] - class DiffusionProfileInputMaterialSlot : Vector1MaterialSlot + [HasDependencies(typeof(DiffusionProfileInputMaterialSlot))] + class DiffusionProfileInputMaterialSlot : Vector1MaterialSlot, IHasDependencies { [SerializeField, Obsolete("Use m_DiffusionProfileAsset instead.")] PopupList m_DiffusionProfile; @@ -26,6 +27,7 @@ private class DiffusionProfileSerializer { [SerializeField] public DiffusionProfileSettings diffusionProfileAsset = null; + } [SerializeField] @@ -68,6 +70,8 @@ public DiffusionProfileSettings diffusionProfile } } + public override bool isDefaultValue => diffusionProfile == null; + public DiffusionProfileInputMaterialSlot() { } @@ -129,6 +133,7 @@ public override void CopyValuesFrom(MaterialSlot foundSlot) if (slot != null) { m_SerializedDiffusionProfile = slot.m_SerializedDiffusionProfile; + m_DiffusionProfileAsset = null; } } @@ -151,5 +156,13 @@ void UpgradeIfNeeded() #pragma warning restore 618 EditorApplication.update -= UpgradeIfNeeded; } + + public void GetSourceAssetDependencies(List paths) + { + if(diffusionProfile != null) + { + paths.Add(AssetDatabase.GetAssetPath(diffusionProfile)); + } + } } } diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData.meta similarity index 77% rename from com.unity.shadergraph/Editor/Data/MasterNodes.meta rename to com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData.meta index f37c53b9e81..838d84014b7 100644 --- a/com.unity.shadergraph/Editor/Data/MasterNodes.meta +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: be7d4ec304eccd8489095f90e0909d93 +guid: 07b9211d927d6ba41afa6a282c8ff813 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/BuiltinData.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/BuiltinData.cs new file mode 100644 index 00000000000..9631c205651 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/BuiltinData.cs @@ -0,0 +1,89 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class BuiltinData : HDTargetData + { + [SerializeField] + bool m_Distortion = false; + public bool distortion + { + get => m_Distortion; + set => m_Distortion = value; + } + + [SerializeField] + DistortionMode m_DistortionMode; + public DistortionMode distortionMode + { + get => m_DistortionMode; + set => m_DistortionMode = value; + } + + [SerializeField] + bool m_DistortionDepthTest = true; + public bool distortionDepthTest + { + get => m_DistortionDepthTest; + set => m_DistortionDepthTest = value; + } + + [SerializeField] + bool m_AddPrecomputedVelocity = false; + public bool addPrecomputedVelocity + { + get => m_AddPrecomputedVelocity; + set => m_AddPrecomputedVelocity = value; + } + + [SerializeField] + bool m_TransparentWritesMotionVec; + public bool transparentWritesMotionVec + { + get => m_TransparentWritesMotionVec; + set => m_TransparentWritesMotionVec = value; + } + + [SerializeField] + bool m_AlphaToMask = false; + public bool alphaToMask + { + get => m_AlphaToMask; + set => m_AlphaToMask = value; + } + + [SerializeField] + bool m_DepthOffset; + public bool depthOffset + { + get => m_DepthOffset; + set => m_DepthOffset = value; + } + + [SerializeField] + bool m_TransparencyFog = true; + public bool transparencyFog + { + get => m_TransparencyFog; + set => m_TransparencyFog = value; + } + + [SerializeField] + bool m_AlphaTestShadow; + public bool alphaTestShadow + { + get => m_AlphaTestShadow; + set => m_AlphaTestShadow = value; + } + + [SerializeField] + bool m_BackThenFrontRendering; + public bool backThenFrontRendering + { + get => m_BackThenFrontRendering; + set => m_BackThenFrontRendering = value; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/BuiltinData.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/BuiltinData.cs.meta new file mode 100644 index 00000000000..a5b8c13640f --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/BuiltinData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2adf56ef084b8a44eb672c3f029e012c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/HDTargetData.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/HDTargetData.cs new file mode 100644 index 00000000000..138eff62bb5 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/HDTargetData.cs @@ -0,0 +1,10 @@ +using System; +using UnityEditor.ShaderGraph.Serialization; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + [Serializable] + abstract class HDTargetData : JsonObject + { + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/HDTargetData.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/HDTargetData.cs.meta new file mode 100644 index 00000000000..b45823b9fca --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/HDTargetData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3ba2725c2e7ea3e4abc6272729f05802 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/IRequiresData.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/IRequiresData.cs new file mode 100644 index 00000000000..9b27c0be9e2 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/IRequiresData.cs @@ -0,0 +1,7 @@ +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + interface IRequiresData where T : HDTargetData + { + T data { get; set; } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/IRequiresData.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/IRequiresData.cs.meta new file mode 100644 index 00000000000..0fb7e9a32ac --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/IRequiresData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0d47693329d2b0048b119eea3e618040 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/LightingData.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/LightingData.cs new file mode 100644 index 00000000000..9cb666960cf --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/LightingData.cs @@ -0,0 +1,100 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering.HighDefinition; +using UnityEditor.ShaderGraph; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class LightingData : HDTargetData + { + [SerializeField] + NormalDropOffSpace m_NormalDropOffSpace; + public NormalDropOffSpace normalDropOffSpace + { + get => m_NormalDropOffSpace; + set => m_NormalDropOffSpace = value; + } + + [SerializeField] + bool m_BlendPreserveSpecular = true; + public bool blendPreserveSpecular + { + get => m_BlendPreserveSpecular; + set => m_BlendPreserveSpecular = value; + } + + [SerializeField] + bool m_ReceiveDecals = true; + public bool receiveDecals + { + get => m_ReceiveDecals; + set => m_ReceiveDecals = value; + } + + [SerializeField] + bool m_ReceiveSSR = true; + public bool receiveSSR + { + get => m_ReceiveSSR; + set => m_ReceiveSSR = value; + } + + [SerializeField] + bool m_ReceiveSSRTransparent = false; + public bool receiveSSRTransparent + { + get => m_ReceiveSSRTransparent; + set => m_ReceiveSSRTransparent = value; + } + + [SerializeField] + bool m_SubsurfaceScattering = false; + public bool subsurfaceScattering + { + get => m_SubsurfaceScattering; + set => m_SubsurfaceScattering = value; + } + + [SerializeField] + bool m_SpecularAA; + public bool specularAA + { + get => m_SpecularAA; + set => m_SpecularAA = value; + } + + // TODO: Was on HDLitMasterNode but seemingly replaced by a Port + // [SerializeField] + // float m_SpecularAAScreenSpaceVariance; + // public float specularAAScreenSpaceVariance + // { + // get => m_SpecularAAScreenSpaceVariance; + // set => m_SpecularAAScreenSpaceVariance = value; + // } + + // TODO: Was on HDLitMasterNode but seemingly replaced by a Port + // [SerializeField] + // float m_SpecularAAThreshold; + // public float specularAAThreshold + // { + // get => m_SpecularAAThreshold; + // set => m_SpecularAAThreshold = value; + // } + + [SerializeField] + SpecularOcclusionMode m_SpecularOcclusionMode; + public SpecularOcclusionMode specularOcclusionMode + { + get => m_SpecularOcclusionMode; + set => m_SpecularOcclusionMode = value; + } + + [SerializeField] + bool m_OverrideBakedGI; + public bool overrideBakedGI + { + get => m_OverrideBakedGI; + set => m_OverrideBakedGI = value; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/LightingData.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/LightingData.cs.meta new file mode 100644 index 00000000000..3a876db198c --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/LightingData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 207523227712d5046bd2f1c5e296b8c7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/SystemData.cs b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/SystemData.cs new file mode 100644 index 00000000000..639a49cd148 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/SystemData.cs @@ -0,0 +1,163 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.HighDefinition; + +using RenderQueueType = UnityEngine.Rendering.HighDefinition.HDRenderQueue.RenderQueueType; + +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +{ + class SystemData : HDTargetData + { + [SerializeField] + int m_MaterialNeedsUpdateHash; + public int materialNeedsUpdateHash + { + get => m_MaterialNeedsUpdateHash; + set => m_MaterialNeedsUpdateHash = value; + } + + [SerializeField] + SurfaceType m_SurfaceType = SurfaceType.Opaque; + public SurfaceType surfaceType + { + get => m_SurfaceType; + set => m_SurfaceType = value; + } + + [SerializeField] + RenderQueueType m_RenderingPass = RenderQueueType.Opaque; + public RenderQueueType renderingPass + { + get => m_RenderingPass; + set => m_RenderingPass = value; + } + + [SerializeField] + BlendMode m_BlendMode = BlendMode.Alpha; + public BlendMode blendMode + { + get => m_BlendMode; + set => m_BlendMode = value; + } + + [SerializeField] + CompareFunction m_ZTest = CompareFunction.LessEqual; + public CompareFunction zTest + { + get => m_ZTest; + set => m_ZTest = value; + } + + [SerializeField] + bool m_ZWrite = true; + public bool zWrite + { + get => m_ZWrite; + set => m_ZWrite = value; + } + + [SerializeField] + TransparentCullMode m_TransparentCullMode = TransparentCullMode.Back; + public TransparentCullMode transparentCullMode + { + get => m_TransparentCullMode; + set => m_TransparentCullMode = value; + } + + [SerializeField] + int m_SortPriority; + public int sortPriority + { + get => m_SortPriority; + set => m_SortPriority = value; + } + + [SerializeField] + bool m_AlphaTest; + public bool alphaTest + { + get => m_AlphaTest; + set => m_AlphaTest = value; + } + + [SerializeField] + bool m_AlphaTestDepthPrepass; + public bool alphaTestDepthPrepass + { + get => m_AlphaTestDepthPrepass; + set => m_AlphaTestDepthPrepass = value; + } + + [SerializeField] + bool m_AlphaTestDepthPostpass; + public bool alphaTestDepthPostpass + { + get => m_AlphaTestDepthPostpass; + set => m_AlphaTestDepthPostpass = value; + } + + [SerializeField] + DoubleSidedMode m_DoubleSidedMode; + public DoubleSidedMode doubleSidedMode + { + get => m_DoubleSidedMode; + set => m_DoubleSidedMode = value; + } + + [SerializeField] + bool m_SupportLodCrossFade; + public bool supportLodCrossFade + { + get => m_SupportLodCrossFade; + set => m_SupportLodCrossFade = value; + } + + // TODO: This was on HDUnlitMaster but not used anywhere + // TODO: On HDLit it adds the field `HDFields.DotsInstancing` + // TODO: Should this be added properly to HDUnlit? + [SerializeField] + bool m_DOTSInstancing = false; + public bool dotsInstancing + { + get => m_DOTSInstancing; + set => m_DOTSInstancing = value; + } + + internal int inspectorFoldoutMask; + } + + static class HDSystemDataExtensions + { + public static bool TryChangeRenderingPass(this SystemData systemData, HDRenderQueue.RenderQueueType value) + { + // Catch invalid rendering pass + switch (value) + { + case HDRenderQueue.RenderQueueType.Overlay: + case HDRenderQueue.RenderQueueType.Unknown: + case HDRenderQueue.RenderQueueType.Background: + throw new ArgumentException("Unexpected kind of RenderQueue, was " + value); + }; + + // Update for SurfaceType + switch (systemData.surfaceType) + { + case SurfaceType.Opaque: + value = HDRenderQueue.GetOpaqueEquivalent(value); + break; + case SurfaceType.Transparent: + value = HDRenderQueue.GetTransparentEquivalent(value); + break; + default: + throw new ArgumentException("Unknown SurfaceType"); + } + + if (Equals(systemData.renderingPass, value)) + return false; + + systemData.renderingPass = value; + return true; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/SystemData.cs.meta b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/SystemData.cs.meta new file mode 100644 index 00000000000..1d2f2298bd5 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/TargetData/SystemData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5e8e733a60ace2f4e8ffda31bcde4945 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Templates/VertexAnimation.template.hlsl b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Templates/VertexAnimation.template.hlsl index 2886517c84c..b4126d74644 100644 --- a/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Templates/VertexAnimation.template.hlsl +++ b/com.unity.render-pipelines.high-definition/Editor/ShaderGraph/Templates/VertexAnimation.template.hlsl @@ -8,7 +8,7 @@ VertexDescriptionInputs AttributesMeshToVertexDescriptionInputs(AttributesMesh i $VertexDescriptionInputs.WorldSpaceNormal: output.WorldSpaceNormal = TransformObjectToWorldNormal(input.normalOS); $VertexDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = TransformWorldToViewDir(output.WorldSpaceNormal); $VertexDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f); - $VertexDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = input.tangentOS; + $VertexDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = input.tangentOS.xyz; $VertexDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = TransformObjectToWorldDir(input.tangentOS.xyz); $VertexDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = TransformWorldToViewDir(output.WorldSpaceTangent); $VertexDescriptionInputs.TangentSpaceTangent: output.TangentSpaceTangent = float3(1.0f, 0.0f, 0.0f); @@ -34,7 +34,7 @@ VertexDescriptionInputs AttributesMeshToVertexDescriptionInputs(AttributesMesh i $VertexDescriptionInputs.VertexColor: output.VertexColor = input.color; $VertexDescriptionInputs.BoneWeights: output.BoneWeights = input.weights; $VertexDescriptionInputs.BoneIndices: output.BoneIndices = input.indices; - $VertexDescriptionInputs.VertexID: output.VertexID = input.vertexID; + $VertexDescriptionInputs.VertexID: output.VertexID = input.vertexID; return output; } @@ -50,9 +50,9 @@ AttributesMesh ApplyMeshModification(AttributesMesh input, float3 timeParameters VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs); // copy graph output to the results - $VertexDescription.VertexPosition: input.positionOS = vertexDescription.VertexPosition; - $VertexDescription.VertexNormal: input.normalOS = vertexDescription.VertexNormal; - $VertexDescription.VertexTangent: input.tangentOS.xyz = vertexDescription.VertexTangent; + $VertexDescription.Position: input.positionOS = vertexDescription.Position; + $VertexDescription.Normal: input.normalOS = vertexDescription.Normal; + $VertexDescription.Tangent: input.tangentOS.xyz = vertexDescription.Tangent; return input; } diff --git a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Shaders/VFXSGSurfaceData.template b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Shaders/VFXSGSurfaceData.template index c067d152055..236915c774d 100644 --- a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Shaders/VFXSGSurfaceData.template +++ b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Shaders/VFXSGSurfaceData.template @@ -23,13 +23,13 @@ surface.subsurfaceMask = 1.0f; surface.baseColor = OUTSG.${SHADERGRAPH_PARAM_BASECOLOR}; #endif -#if HAS_SHADERGRAPH_PARAM_NORMAL - float3 n = OUTSG.${SHADERGRAPH_PARAM_NORMAL}; +#if HAS_SHADERGRAPH_PARAM_NORMALTS + float3 n = OUTSG.${SHADERGRAPH_PARAM_NORMALTS}; normalWS = mul(n,tbn); #endif surface.normalWS = normalWS; -#if HAS_SHADERGRAPH_PARAM_EMISSIVE - builtin.emissiveColor = OUTSG.${SHADERGRAPH_PARAM_EMISSIVE}; +#if HAS_SHADERGRAPH_PARAM_EMISSION + builtin.emissiveColor = OUTSG.${SHADERGRAPH_PARAM_EMISSION}; #endif \ No newline at end of file diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDDecalMaterial.mat b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDDecalMaterial.mat index c6e18675868..3b93a609424 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDDecalMaterial.mat +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDDecalMaterial.mat @@ -315,4 +315,4 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: da692e001514ec24dbc4cca1949ff7e8, type: 3} m_Name: m_EditorClassIdentifier: - version: 3 + version: 4 diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDMaterial.mat b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDMaterial.mat index 7e402bbc054..863b0d54012 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDMaterial.mat +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDMaterial.mat @@ -12,7 +12,7 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: da692e001514ec24dbc4cca1949ff7e8, type: 3} m_Name: m_EditorClassIdentifier: - version: 3 + version: 4 --- !u!21 &2100000 Material: serializedVersion: 6 @@ -181,6 +181,7 @@ Material: - _AlphaCutoffShadow: 0.5 - _AlphaDstBlend: 0 - _AlphaSrcBlend: 1 + - _AlphaToMask: 0 - _Anisotropy: 0 - _BlendMode: 0 - _BumpScale: 1 diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDMirrorMaterial.mat b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDMirrorMaterial.mat index 9b2c94ac668..a5fa5de3909 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDMirrorMaterial.mat +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDMirrorMaterial.mat @@ -12,7 +12,7 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: da692e001514ec24dbc4cca1949ff7e8, type: 3} m_Name: m_EditorClassIdentifier: - version: 3 + version: 4 --- !u!21 &2100000 Material: serializedVersion: 6 @@ -180,6 +180,7 @@ Material: - _AlphaCutoffShadow: 0.5 - _AlphaDstBlend: 0 - _AlphaSrcBlend: 1 + - _AlphaToMask: 0 - _Anisotropy: 0 - _BlendMode: 0 - _BumpScale: 1 diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDParticleMaterial.mat b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDParticleMaterial.mat index 8f4734a99f5..17b27b474e6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDParticleMaterial.mat +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDParticleMaterial.mat @@ -122,6 +122,7 @@ Material: - _AlphaCutoffShadow: 0.5 - _AlphaDstBlend: 0 - _AlphaSrcBlend: 1 + - _AlphaToMask: 0 - _Anisotropy: 0 - _BlendMode: 0 - _CoatMask: 0 @@ -250,6 +251,7 @@ Material: - _UVMappingMask: {r: 1, g: 0, b: 0, a: 0} - _UVMappingMaskEmissive: {r: 1, g: 0, b: 0, a: 0} - _UnlitColor: {r: 1, g: 1, b: 1, a: 1} + - _UnlitColorMap_MipInfo: {r: 0, g: 0, b: 0, a: 0} m_BuildTextureStacks: [] --- !u!114 &6200975693885156646 MonoBehaviour: @@ -263,4 +265,4 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: da692e001514ec24dbc4cca1949ff7e8, type: 3} m_Name: m_EditorClassIdentifier: - version: 3 + version: 4 diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDTerrainMaterial.mat b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDTerrainMaterial.mat index d83539d37e9..fd8bbc78087 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDTerrainMaterial.mat +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDTerrainMaterial.mat @@ -12,7 +12,7 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: da692e001514ec24dbc4cca1949ff7e8, type: 3} m_Name: m_EditorClassIdentifier: - version: 3 + version: 4 --- !u!21 &2100000 Material: serializedVersion: 6 diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks.meta b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks.meta index b6234b3a970..da4f20b7aaa 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks.meta +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 92ce9656ee586234085f20c3dbed1f88 +guid: eea3e26ee6aecd14d8ab3f9b20ccc5d5 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateLitShaderGraph.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateLitShaderGraph.cs new file mode 100644 index 00000000000..9959dd93d9d --- /dev/null +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateLitShaderGraph.cs @@ -0,0 +1,30 @@ +using System; +using UnityEditor.ShaderGraph; + +namespace UnityEditor.Rendering.Universal.ShaderGraph +{ + static class CreateLitShaderGraph + { + [MenuItem("Assets/Create/Shader/Universal Render Pipeline/Lit Shader Graph", false, 300)] + public static void CreateLitGraph() + { + var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget)); + target.TrySetActiveSubTarget(typeof(UniversalLitSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Occlusion, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + } + } +} diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateLitShaderGraph.cs.meta b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateLitShaderGraph.cs.meta new file mode 100644 index 00000000000..b8e3bf66422 --- /dev/null +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateLitShaderGraph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aab9add076be9364aaee067b3c0e3910 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs index ec4ef448b95..85bc87c6737 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs @@ -1,13 +1,28 @@ +using System; using UnityEditor.ShaderGraph; -namespace UnityEditor.Experimental.Rendering.Universal +namespace UnityEditor.Rendering.Universal.ShaderGraph { - class CreateSpriteLitShaderGraph + static class CreateSpriteLitShaderGraph { - [MenuItem("Assets/Create/Shader/2D Renderer/Sprite Lit Graph (Experimental)", false, 208)] - public static void CreateMaterialGraph() + [MenuItem("Assets/Create/Shader/Universal Render Pipeline/Sprite Lit Shader Graph", false, 300)] + public static void CreateSpriteLitGraph() { - GraphUtil.CreateNewGraph(new SpriteLitMasterNode()); + var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget)); + target.TrySetActiveSubTarget(typeof(UniversalSpriteLitSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + UniversalBlockFields.SurfaceDescription.SpriteMask, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.Alpha, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs.meta b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs.meta index eb74b7ff219..a63a55bd54d 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs.meta +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: fd5bf26faac23425db7917a29fb41dce +guid: dc7283e53c0339a40adca7609d7985d7 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs index 3c6ae78d347..0b3ffb356fe 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs @@ -1,13 +1,26 @@ +using System; using UnityEditor.ShaderGraph; -namespace UnityEditor.Experimental.Rendering.Universal +namespace UnityEditor.Rendering.Universal.ShaderGraph { - class CreateSpriteUnlitShaderGraph + static class CreateSpriteUnlitShaderGraph { - [MenuItem("Assets/Create/Shader/2D Renderer/Sprite Unlit Graph (Experimental)", false, 208)] - public static void CreateMaterialGraph() + [MenuItem("Assets/Create/Shader/Universal Render Pipeline/Sprite Unlit Shader Graph", false, 300)] + public static void CreateSpriteUnlitGraph() { - GraphUtil.CreateNewGraph(new SpriteUnlitMasterNode()); + var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget)); + target.TrySetActiveSubTarget(typeof(UniversalSpriteUnlitSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Alpha, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs.meta b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs.meta index 19d786ab397..7f3a72cf8c8 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs.meta +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c705bcf9da993314fb781d5341f7c25a +guid: b1d9d11b6a33b4b4e83c36bd926bbb77 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUnlitShaderGraph.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUnlitShaderGraph.cs new file mode 100644 index 00000000000..2addc87e505 --- /dev/null +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUnlitShaderGraph.cs @@ -0,0 +1,25 @@ +using System; +using UnityEditor.ShaderGraph; + +namespace UnityEditor.Rendering.Universal.ShaderGraph +{ + static class CreateUnlitShaderGraph + { + [MenuItem("Assets/Create/Shader/Universal Render Pipeline/Unlit Shader Graph", false, 300)] + public static void CreateUnlitGraph() + { + var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget)); + target.TrySetActiveSubTarget(typeof(UniversalUnlitSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + } + } +} diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUnlitShaderGraph.cs.meta b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUnlitShaderGraph.cs.meta new file mode 100644 index 00000000000..b80158441c7 --- /dev/null +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUnlitShaderGraph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6120e053fa5537949a54c661e2a57a39 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl index 254778a3223..d5a92431cb8 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl @@ -23,7 +23,7 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET #endif MetaInput metaInput = (MetaInput)0; - metaInput.Albedo = surfaceDescription.Albedo; + metaInput.Albedo = surfaceDescription.BaseColor; metaInput.Emission = surfaceDescription.Emission; return MetaFragment(metaInput); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl index 44f72799948..260eb626d7f 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl @@ -17,9 +17,14 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs); #if _AlphaClip - clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold); + half alpha = surfaceDescription.Alpha; + clip(alpha - surfaceDescription.AlphaClipThreshold); + #elif _SURFACE_TYPE_TRANSPARENT + half alpha = surfaceDescription.Alpha; + #else + half alpha = 1; #endif - half4 color = half4(surfaceDescription.Albedo, surfaceDescription.Alpha); + half4 color = half4(surfaceDescription.BaseColor, alpha); return color; } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRForwardPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRForwardPass.hlsl index 9ac3b77b6fb..1c6942d937e 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRForwardPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRForwardPass.hlsl @@ -1,32 +1,31 @@ -void BuildInputData(Varyings input, float3 normal, out InputData inputData) +void BuildInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData) { inputData.positionWS = input.positionWS; -#ifdef _NORMALMAP -#if _NORMAL_DROPOFF_TS - // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped. - float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale(); - float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz); - inputData.normalWS = TransformTangentToWorld(normal, half3x3(input.tangentWS.xyz, bitangent, input.normalWS.xyz)); -#elif _NORMAL_DROPOFF_OS - inputData.normalWS = TransformObjectToWorldNormal(normal); -#elif _NORMAL_DROPOFF_WS - inputData.normalWS = normal; -#endif - -#else - inputData.normalWS = input.normalWS; -#endif + #ifdef _NORMALMAP + #if _NORMAL_DROPOFF_TS + // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped. + float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale(); + float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz); + inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, half3x3(input.tangentWS.xyz, bitangent, input.normalWS.xyz)); + #elif _NORMAL_DROPOFF_OS + inputData.normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS); + #elif _NORMAL_DROPOFF_WS + inputData.normalWS = surfaceDescription.NormalWS; + #endif + #else + inputData.normalWS = input.normalWS; + #endif inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS); inputData.viewDirectionWS = SafeNormalize(input.viewDirectionWS); -#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR) - inputData.shadowCoord = input.shadowCoord; -#elif defined(MAIN_LIGHT_CALCULATE_SHADOWS) - inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS); -#else - inputData.shadowCoord = float4(0, 0, 0, 0); -#endif + #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR) + inputData.shadowCoord = input.shadowCoord; + #elif defined(MAIN_LIGHT_CALCULATE_SHADOWS) + inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS); + #else + inputData.shadowCoord = float4(0, 0, 0, 0); + #endif inputData.fogCoord = input.fogFactorAndVertexLight.x; inputData.vertexLighting = input.fogFactorAndVertexLight.yzw; @@ -52,11 +51,16 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs); #if _AlphaClip - clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold); + half alpha = surfaceDescription.Alpha; + clip(alpha - surfaceDescription.AlphaClipThreshold); + #elif _SURFACE_TYPE_TRANSPARENT + half alpha = surfaceDescription.Alpha; + #else + half alpha = 1; #endif InputData inputData; - BuildInputData(unpacked, surfaceDescription.Normal, inputData); + BuildInputData(unpacked, surfaceDescription, inputData); #ifdef _SPECULAR_SETUP float3 specular = surfaceDescription.Specular; @@ -68,13 +72,13 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET half4 color = UniversalFragmentPBR( inputData, - surfaceDescription.Albedo, + surfaceDescription.BaseColor, metallic, specular, surfaceDescription.Smoothness, surfaceDescription.Occlusion, surfaceDescription.Emission, - surfaceDescription.Alpha); + alpha); color.rgb = MixFog(color.rgb, inputData.fogCoord); return color; diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl index 3f29c90e21b..ec69bbb6d68 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl @@ -1,22 +1,21 @@ -void BuildInputData(Varyings input, float3 normal, out InputData inputData) +void BuildInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData) { inputData.positionWS = input.positionWS; -#ifdef _NORMALMAP - -#if _NORMAL_DROPOFF_TS - // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped. - float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale(); - float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz); - inputData.normalWS = TransformTangentToWorld(normal, half3x3(input.tangentWS.xyz, bitangent, input.normalWS.xyz)); -#elif _NORMAL_DROPOFF_OS - inputData.normalWS = TransformObjectToWorldNormal(normal); -#elif _NORMAL_DROPOFF_WS - inputData.normalWS = normal; -#endif + #ifdef _NORMALMAP -#else - inputData.normalWS = input.normalWS; -#endif + #if _NORMAL_DROPOFF_TS + // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped. + float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale(); + float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz); + inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, half3x3(input.tangentWS.xyz, bitangent, input.normalWS.xyz)); + #elif _NORMAL_DROPOFF_OS + inputData.normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS); + #elif _NORMAL_DROPOFF_WS + inputData.normalWS = surfaceDescription.NormalWS; + #endif + #else + inputData.normalWS = input.normalWS; + #endif inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS); inputData.viewDirectionWS = SafeNormalize(input.viewDirectionWS); @@ -50,11 +49,16 @@ FragmentOutput frag(PackedVaryings packedInput) SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs); #if _AlphaClip - clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold); + half alpha = surfaceDescription.Alpha; + clip(alpha - surfaceDescription.AlphaClipThreshold); + #elif _SURFACE_TYPE_TRANSPARENT + half alpha = surfaceDescription.Alpha; + #else + half alpha = 1; #endif InputData inputData; - BuildInputData(unpacked, surfaceDescription.Normal, inputData); + BuildInputData(unpacked, surfaceDescription, inputData); #ifdef _SPECULAR_SETUP float3 specular = surfaceDescription.Specular; @@ -67,7 +71,7 @@ FragmentOutput frag(PackedVaryings packedInput) // in LitForwardPass GlobalIllumination (and temporarily LightingPhysicallyBased) are called inside UniversalFragmentPBR // in Deferred rendering we store the sum of these values (and of emission as well) in the GBuffer BRDFData brdfData; - InitializeBRDFData(surfaceDescription.Albedo, metallic, specular, surfaceDescription.Smoothness, surfaceDescription.Alpha, brdfData); + InitializeBRDFData(surfaceDescription.BaseColor, metallic, specular, surfaceDescription.Smoothness, alpha, brdfData); Light mainLight = GetMainLight(inputData.shadowCoord); // TODO move this to a separate full-screen single gbuffer pass? MixRealtimeAndBakedGI(mainLight, inputData.normalWS, inputData.bakedGI, half4(0, 0, 0, 0)); // TODO move this to a separate full-screen single gbuffer pass? diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteForwardPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteForwardPass.hlsl index 1a5be4f5870..5166da42e10 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteForwardPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteForwardPass.hlsl @@ -22,10 +22,15 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET #if ETC1_EXTERNAL_ALPHA float4 alpha = SAMPLE_TEXTURE2D(_AlphaTex, sampler_AlphaTex, unpacked.texCoord0.xy); - surfaceDescription.Color.a = lerp (surfaceDescription.Color.a, alpha.r, _EnableAlphaTexture); + surfaceDescription.Alpha = lerp (surfaceDescription.Alpha, alpha.r, _EnableAlphaTexture); #endif - surfaceDescription.Color *= unpacked.color; +#ifdef UNIVERSAL_USELEGACYSPRITEBLOCKS + half4 color = surfaceDescription.SpriteColor; +#else + half4 color = half4(surfaceDescription.BaseColor, surfaceDescription.Alpha); +#endif - return surfaceDescription.Color; + color *= unpacked.color; + return color; } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteLitPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteLitPass.hlsl index 65ab69dcd02..965d6179169 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteLitPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteLitPass.hlsl @@ -38,12 +38,17 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked); SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs); +#ifdef UNIVERSAL_USELEGACYSPRITEBLOCKS + half4 color = surfaceDescription.SpriteColor; +#else + half4 color = half4(surfaceDescription.BaseColor, surfaceDescription.Alpha); +#endif + #if ETC1_EXTERNAL_ALPHA half4 alpha = SAMPLE_TEXTURE2D(_AlphaTex, sampler_AlphaTex, unpacked.texCoord0.xy); - surfaceDescription.Color.a = lerp (surfaceDescription.Color.a, alpha.r, _EnableAlphaTexture); + color.a = lerp (color.a, alpha.r, _EnableAlphaTexture); #endif - surfaceDescription.Color *= unpacked.color; - - return CombinedShapeLightShared(surfaceDescription.Color, surfaceDescription.Mask, unpacked.screenPosition.xy / unpacked.screenPosition.w); + color *= unpacked.color; + return CombinedShapeLightShared(color, surfaceDescription.SpriteMask, unpacked.screenPosition.xy / unpacked.screenPosition.w); } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteNormalPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteNormalPass.hlsl index 51f4f4da34c..46f73bf1206 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteNormalPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteNormalPass.hlsl @@ -17,5 +17,12 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET half crossSign = (unpacked.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale(); half3 bitangent = crossSign * cross(unpacked.normalWS.xyz, unpacked.tangentWS.xyz); - return NormalsRenderingShared(surfaceDescription.Color, surfaceDescription.Normal, unpacked.tangentWS.xyz, bitangent, unpacked.normalWS); + +#ifdef UNIVERSAL_USELEGACYSPRITEBLOCKS + half4 color = surfaceDescription.SpriteColor; +#else + half4 color = half4(surfaceDescription.BaseColor, surfaceDescription.Alpha); +#endif + + return NormalsRenderingShared(color, surfaceDescription.NormalTS, unpacked.tangentWS.xyz, bitangent, unpacked.normalWS); } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl index 4b622a8e09d..3d45974ac42 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl @@ -21,12 +21,17 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked); SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs); +#ifdef UNIVERSAL_USELEGACYSPRITEBLOCKS + half4 color = surfaceDescription.SpriteColor; +#else + half4 color = half4(surfaceDescription.BaseColor, surfaceDescription.Alpha); +#endif + #if ETC1_EXTERNAL_ALPHA half4 alpha = SAMPLE_TEXTURE2D(_AlphaTex, sampler_AlphaTex, unpacked.texCoord0.xy); - surfaceDescription.Color.a = lerp (surfaceDescription.Color.a, alpha.r, _EnableAlphaTexture); + color.a = lerp (color.a, alpha.r, _EnableAlphaTexture); #endif - surfaceDescription.Color *= unpacked.color * _RendererColor; - - return surfaceDescription.Color; + color *= unpacked.color * _RendererColor; + return color; } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl index c5716e3b4df..701d77b29e5 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl @@ -15,13 +15,18 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked); SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs); -#if _AlphaClip - clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold); -#endif + #if _AlphaClip + half alpha = surfaceDescription.Alpha; + clip(alpha - surfaceDescription.AlphaClipThreshold); + #elif _SURFACE_TYPE_TRANSPARENT + half alpha = surfaceDescription.Alpha; + #else + half alpha = 1; + #endif #ifdef _ALPHAPREMULTIPLY_ON - surfaceDescription.Color *= surfaceDescription.Alpha; + surfaceDescription.BaseColor *= surfaceDescription.Alpha; #endif - return half4(surfaceDescription.Color, surfaceDescription.Alpha); + return half4(surfaceDescription.BaseColor, alpha); } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl index 667f227eb99..077086a63d5 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl @@ -14,14 +14,14 @@ Varyings BuildVaryings(Attributes input) // Evaluate Vertex Graph VertexDescriptionInputs vertexDescriptionInputs = BuildVertexDescriptionInputs(input); VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs); - + // Assign modified vertex attributes - input.positionOS = vertexDescription.VertexPosition; + input.positionOS = vertexDescription.Position; #if defined(VARYINGS_NEED_NORMAL_WS) - input.normalOS = vertexDescription.VertexNormal; + input.normalOS = vertexDescription.Normal; #endif //FEATURES_GRAPH_NORMAL #if defined(VARYINGS_NEED_TANGENT_WS) - input.tangentOS.xyz = vertexDescription.VertexTangent.xyz; + input.tangentOS.xyz = vertexDescription.Tangent.xyz; #endif //FEATURES GRAPH TANGENT #endif //FEATURES_GRAPH_VERTEX diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteLitMasterNode.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteLitMasterNode.cs deleted file mode 100644 index a0a67d8f645..00000000000 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteLitMasterNode.cs +++ /dev/null @@ -1,159 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Graphing; -using UnityEngine; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Internal; -using UnityEngine.UIElements; - -namespace UnityEditor.Experimental.Rendering.Universal -{ - [Serializable] - [Title("Master", "Sprite Lit (Experimental)")] - [FormerName("UnityEditor.Experimental.Rendering.LWRP.SpriteLitMasterNode")] - class SpriteLitMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string PositionName = "Vertex Position"; - public const string NormalName = "Vertex Normal"; - public const string TangentName = "Vertex Tangent"; - public const string ColorSlotName = "Color"; - public const string MaskSlotName = "Mask"; - public const string NormalSlotName = "Normal"; - - public const int PositionSlotId = 9; - public const int ColorSlotId = 0; - public const int MaskSlotId = 1; - public const int NormalSlotId = 2; - public const int VertNormalSlotId = 10; - public const int VertTangentSlotId = 11; - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public SpriteLitMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "Sprite Lit Master"; - - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionName, PositionName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new NormalMaterialSlot(VertNormalSlotId, NormalName, NormalName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new TangentMaterialSlot(VertTangentSlotId, TangentName, TangentName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new ColorRGBAMaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, Color.white, ShaderStageCapability.Fragment)); - AddSlot(new ColorRGBAMaterialSlot(MaskSlotId, MaskSlotName, MaskSlotName, SlotType.Input, Color.white, ShaderStageCapability.Fragment)); - AddSlot(new Vector3MaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, SlotType.Input, new Vector3(0.0f, 0.0f, 1.0f), ShaderStageCapability.Fragment)); - - RemoveSlotsNameNotMatching( - new[] - { - PositionSlotId, - VertNormalSlotId, - VertTangentSlotId, - ColorSlotId, - MaskSlotId, - NormalSlotId, - }); - } - - public VisualElement CreateSettingsElement() - { - return new SpriteSettingsView(this); - } - - public string renderQueueTag => $"{RenderQueue.Transparent}"; - public string renderTypeTag => $"{RenderType.Transparent}"; - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PBRMasterNode.PositionSlotId) || - IsSlotConnected(PBRMasterNode.VertNormalSlotId) || - IsSlotConnected(PBRMasterNode.VertTangentSlotId)), - new ConditionalField(Fields.GraphPixel, true), - - // Surface Type - new ConditionalField(Fields.SurfaceTransparent, true), - - // Blend Mode - new ConditionalField(Fields.BlendAlpha, true), - - // Culling - new ConditionalField(Fields.DoubleSided, true), - }; - } - - public void ProcessPreviewMaterial(Material material) - { - - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); - } - - public bool supportsVirtualTexturing => false; - } -} diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteLitMasterNode.cs.meta b/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteLitMasterNode.cs.meta deleted file mode 100644 index df5e88add29..00000000000 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteLitMasterNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 28a14e6c1f93e424e9ea6a1c938d5d58 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteSettingsView.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteSettingsView.cs deleted file mode 100644 index 61815c589da..00000000000 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteSettingsView.cs +++ /dev/null @@ -1,13 +0,0 @@ -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Drawing; - -namespace UnityEditor.Experimental.Rendering.Universal -{ - class SpriteSettingsView : MasterNodeSettingsView - { - public SpriteSettingsView(AbstractMaterialNode node) : base(node) - { - Add(GetShaderGUIOverridePropertySheet()); - } - } -} diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteSettingsView.cs.meta b/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteSettingsView.cs.meta deleted file mode 100644 index 53ad68a7dfb..00000000000 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteSettingsView.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 80b080eab50bfbe4e80c04b9e39eb969 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteUnlitMasterNode.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteUnlitMasterNode.cs deleted file mode 100644 index 1a6fac62a61..00000000000 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteUnlitMasterNode.cs +++ /dev/null @@ -1,151 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Graphing; -using UnityEngine; -using UnityEngine.UIElements; -using UnityEditor.ShaderGraph; -using UnityEditor.ShaderGraph.Internal; - -namespace UnityEditor.Experimental.Rendering.Universal -{ - [Serializable] - [Title("Master", "Sprite Unlit (Experimental)")] - [FormerName("UnityEditor.Experimental.Rendering.LWRP.SpriteUnlitMasterNode")] - class SpriteUnlitMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string PositionName = "Vertex Position"; - public const string NormalName = "Vertex Normal"; - public const string TangentName = "Vertex Tangent"; - public const string ColorSlotName = "Color"; - - - public const int PositionSlotId = 9; - public const int ColorSlotId = 0; - public const int VertNormalSlotId = 10; - public const int VertTangentSlotId = 11; - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public SpriteUnlitMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "Sprite Unlit Master"; - - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionName, PositionName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new NormalMaterialSlot(VertNormalSlotId, NormalName, NormalName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new TangentMaterialSlot(VertTangentSlotId, TangentName, TangentName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new ColorRGBAMaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, Color.white, ShaderStageCapability.Fragment)); - - RemoveSlotsNameNotMatching( - new[] - { - PositionSlotId, - VertNormalSlotId, - VertTangentSlotId, - ColorSlotId, - }); - } - - public VisualElement CreateSettingsElement() - { - return new SpriteSettingsView(this); - } - - public string renderQueueTag => $"{RenderQueue.Transparent}"; - public string renderTypeTag => $"{RenderType.Transparent}"; - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PBRMasterNode.PositionSlotId) || - IsSlotConnected(PBRMasterNode.VertNormalSlotId) || - IsSlotConnected(PBRMasterNode.VertTangentSlotId)), - new ConditionalField(Fields.GraphPixel, true), - - // Surface Type - new ConditionalField(Fields.SurfaceTransparent, true), - - // Blend Mode - new ConditionalField(Fields.BlendAlpha, true), - - // Culling - new ConditionalField(Fields.DoubleSided, true), - }; - } - - public void ProcessPreviewMaterial(Material material) - { - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); - } - - public bool supportsVirtualTexturing => false; - } -} diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteUnlitMasterNode.cs.meta b/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteUnlitMasterNode.cs.meta deleted file mode 100644 index 07315cc0f02..00000000000 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/MasterNodes/SpriteUnlitMasterNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b98f1695965a77f449e8877343eaecce -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs index c1d0ea113ad..7fc225fa43b 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs @@ -1,26 +1,217 @@ using System; using System.Linq; using System.Collections.Generic; +using UnityEngine; using UnityEditor.ShaderGraph; using UnityEngine.Rendering; +using UnityEditor.UIElements; +using UnityEngine.UIElements; +using UnityEditor.ShaderGraph.Legacy; namespace UnityEditor.Rendering.Universal.ShaderGraph { - sealed class UniversalLitSubTarget : SubTarget + sealed class UniversalLitSubTarget : SubTarget, ILegacyTarget { const string kAssetGuid = "d6c78107b64145745805d963de80cc17"; + [SerializeField] + WorkflowMode m_WorkflowMode = WorkflowMode.Metallic; + + [SerializeField] + NormalDropOffSpace m_NormalDropOffSpace = NormalDropOffSpace.Tangent; + public UniversalLitSubTarget() { displayName = "Lit"; } + public WorkflowMode workflowMode + { + get => m_WorkflowMode; + set => m_WorkflowMode = value; + } + + public NormalDropOffSpace normalDropOffSpace + { + get => m_NormalDropOffSpace; + set => m_NormalDropOffSpace = value; + } + + public override bool IsActive() => true; + public override void Setup(ref TargetSetupContext context) { context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); context.SetDefaultShaderGUI("ShaderGraph.PBRMasterGUI"); // TODO: This should be owned by URP - context.AddSubShader(SubShaders.Lit); - context.AddSubShader(SubShaders.LitDOTS); + + // Process SubShaders + SubShaderDescriptor[] subShaders = { SubShaders.Lit, SubShaders.LitDOTS }; + for(int i = 0; i < subShaders.Length; i++) + { + // Update Render State + subShaders[i].renderType = target.renderType; + subShaders[i].renderQueue = target.renderQueue; + + // Add + context.AddSubShader(subShaders[i]); + } + } + + public override void GetFields(ref TargetFieldContext context) + { + var descs = context.blocks.Select(x => x.descriptor); + // Surface Type & Blend Mode + // These must be set per SubTarget as Sprite SubTargets override them + context.AddField(Fields.SurfaceOpaque, target.surfaceType == SurfaceType.Opaque); + context.AddField(Fields.SurfaceTransparent, target.surfaceType != SurfaceType.Opaque); + context.AddField(Fields.BlendAdd, target.surfaceType != SurfaceType.Opaque && target.alphaMode == AlphaMode.Additive); + context.AddField(Fields.BlendAlpha, target.surfaceType != SurfaceType.Opaque && target.alphaMode == AlphaMode.Alpha); + context.AddField(Fields.BlendMultiply, target.surfaceType != SurfaceType.Opaque && target.alphaMode == AlphaMode.Multiply); + context.AddField(Fields.BlendPremultiply, target.surfaceType != SurfaceType.Opaque && target.alphaMode == AlphaMode.Premultiply); + + // Lit + context.AddField(Fields.NormalDropOffOS, normalDropOffSpace == NormalDropOffSpace.Object); + context.AddField(Fields.NormalDropOffTS, normalDropOffSpace == NormalDropOffSpace.Tangent); + context.AddField(Fields.NormalDropOffWS, normalDropOffSpace == NormalDropOffSpace.World); + context.AddField(Fields.SpecularSetup, workflowMode == WorkflowMode.Specular); + context.AddField(Fields.Normal, descs.Contains(BlockFields.SurfaceDescription.NormalOS) || + descs.Contains(BlockFields.SurfaceDescription.NormalTS) || + descs.Contains(BlockFields.SurfaceDescription.NormalWS)); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + context.AddBlock(BlockFields.SurfaceDescription.Smoothness); + context.AddBlock(BlockFields.SurfaceDescription.NormalOS, normalDropOffSpace == NormalDropOffSpace.Object); + context.AddBlock(BlockFields.SurfaceDescription.NormalTS, normalDropOffSpace == NormalDropOffSpace.Tangent); + context.AddBlock(BlockFields.SurfaceDescription.NormalWS, normalDropOffSpace == NormalDropOffSpace.World); + context.AddBlock(BlockFields.SurfaceDescription.Emission); + context.AddBlock(BlockFields.SurfaceDescription.Occlusion); + context.AddBlock(BlockFields.SurfaceDescription.Specular, workflowMode == WorkflowMode.Specular); + context.AddBlock(BlockFields.SurfaceDescription.Metallic, workflowMode == WorkflowMode.Metallic); + context.AddBlock(BlockFields.SurfaceDescription.Alpha, target.surfaceType == SurfaceType.Transparent || target.alphaClip); + context.AddBlock(BlockFields.SurfaceDescription.AlphaClipThreshold, target.alphaClip); + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + context.AddProperty("Workflow", new EnumField(WorkflowMode.Metallic) { value = workflowMode }, (evt) => + { + if (Equals(workflowMode, evt.newValue)) + return; + + registerUndo("Change Workflow"); + workflowMode = (WorkflowMode)evt.newValue; + onChange(); + }); + + context.AddProperty("Surface", new EnumField(SurfaceType.Opaque) { value = target.surfaceType }, (evt) => + { + if (Equals(target.surfaceType, evt.newValue)) + return; + + registerUndo("Change Surface"); + target.surfaceType = (SurfaceType)evt.newValue; + onChange(); + }); + + context.AddProperty("Blend", new EnumField(AlphaMode.Alpha) { value = target.alphaMode }, target.surfaceType == SurfaceType.Transparent, (evt) => + { + if (Equals(target.alphaMode, evt.newValue)) + return; + + registerUndo("Change Blend"); + target.alphaMode = (AlphaMode)evt.newValue; + onChange(); + }); + + context.AddProperty("Alpha Clip", new Toggle() { value = target.alphaClip }, (evt) => + { + if (Equals(target.alphaClip, evt.newValue)) + return; + + registerUndo("Change Alpha Clip"); + target.alphaClip = evt.newValue; + onChange(); + }); + + context.AddProperty("Two Sided", new Toggle() { value = target.twoSided }, (evt) => + { + if (Equals(target.twoSided, evt.newValue)) + return; + + registerUndo("Change Two Sided"); + target.twoSided = evt.newValue; + onChange(); + }); + + context.AddProperty("Fragment Normal Space", new EnumField(NormalDropOffSpace.Tangent) { value = normalDropOffSpace }, (evt) => + { + if (Equals(normalDropOffSpace, evt.newValue)) + return; + + registerUndo("Change Fragment Normal Space"); + normalDropOffSpace = (NormalDropOffSpace)evt.newValue; + onChange(); + }); + } + + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is PBRMasterNode1 pbrMasterNode)) + return false; + + // Set data + m_WorkflowMode = (WorkflowMode)pbrMasterNode.m_Model; + m_NormalDropOffSpace = (NormalDropOffSpace)pbrMasterNode.m_NormalDropOffSpace; + + // Handle mapping of Normal block specifically + BlockFieldDescriptor normalBlock; + switch(m_NormalDropOffSpace) + { + case NormalDropOffSpace.Object: + normalBlock = BlockFields.SurfaceDescription.NormalOS; + break; + case NormalDropOffSpace.World: + normalBlock = BlockFields.SurfaceDescription.NormalWS; + break; + default: + normalBlock = BlockFields.SurfaceDescription.NormalTS; + break; + } + + // PBRMasterNode adds/removes Metallic/Specular based on settings + BlockFieldDescriptor specularMetallicBlock; + int specularMetallicId; + if(m_WorkflowMode == WorkflowMode.Specular) + { + specularMetallicBlock = BlockFields.SurfaceDescription.Specular; + specularMetallicId = 3; + } + else + { + specularMetallicBlock = BlockFields.SurfaceDescription.Metallic; + specularMetallicId = 2; + } + + // Set blockmap + blockMap = new Dictionary() + { + { BlockFields.VertexDescription.Position, 9 }, + { BlockFields.VertexDescription.Normal, 10 }, + { BlockFields.VertexDescription.Tangent, 11 }, + { BlockFields.SurfaceDescription.BaseColor, 0 }, + { normalBlock, 1 }, + { specularMetallicBlock, specularMetallicId }, + { BlockFields.SurfaceDescription.Emission, 4 }, + { BlockFields.SurfaceDescription.Smoothness, 5 }, + { BlockFields.SurfaceDescription.Occlusion, 6 }, + { BlockFields.SurfaceDescription.Alpha, 7 }, + { BlockFields.SurfaceDescription.AlphaClipThreshold, 8 }, + }; + + return true; } #region SubShader @@ -94,8 +285,8 @@ static class LitPasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = CorePortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentLit, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentLit, // Fields structs = CoreStructCollections.Default, @@ -121,8 +312,8 @@ static class LitPasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = CorePortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentLit, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentLit, // Fields structs = CoreStructCollections.Default, @@ -148,8 +339,8 @@ static class LitPasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = CorePortMasks.Vertex, - pixelPorts = LitPortMasks.FragmentMeta, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentMeta, // Fields structs = CoreStructCollections.Default, @@ -174,8 +365,8 @@ static class LitPasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = CorePortMasks.Vertex, - pixelPorts = LitPortMasks.Fragment2D, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentColorAlpha, // Fields structs = CoreStructCollections.Default, @@ -190,34 +381,29 @@ static class LitPasses #endregion #region PortMasks - static class LitPortMasks + static class LitBlockMasks { - public static int[] FragmentLit = new int[] - { - PBRMasterNode.AlbedoSlotId, - PBRMasterNode.NormalSlotId, - PBRMasterNode.EmissionSlotId, - PBRMasterNode.MetallicSlotId, - PBRMasterNode.SpecularSlotId, - PBRMasterNode.SmoothnessSlotId, - PBRMasterNode.OcclusionSlotId, - PBRMasterNode.AlphaSlotId, - PBRMasterNode.AlphaThresholdSlotId, - }; - - public static int[] FragmentMeta = new int[] + public static BlockFieldDescriptor[] FragmentLit = new BlockFieldDescriptor[] { - PBRMasterNode.AlbedoSlotId, - PBRMasterNode.EmissionSlotId, - PBRMasterNode.AlphaSlotId, - PBRMasterNode.AlphaThresholdSlotId, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Metallic, + BlockFields.SurfaceDescription.Specular, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Occlusion, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, }; - public static int[] Fragment2D = new int[] + public static BlockFieldDescriptor[] FragmentMeta = new BlockFieldDescriptor[] { - PBRMasterNode.AlbedoSlotId, - PBRMasterNode.AlphaSlotId, - PBRMasterNode.AlphaThresholdSlotId + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, }; } #endregion diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs index 546f6bab43c..57415463c8c 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs @@ -1,28 +1,85 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using UnityEditor.ShaderGraph; using UnityEngine.Rendering; using UnityEditor.Experimental.Rendering.Universal; +using UnityEditor.ShaderGraph.Legacy; namespace UnityEditor.Rendering.Universal.ShaderGraph { - sealed class UniversalSpriteLitSubTarget : SubTarget + sealed class UniversalSpriteLitSubTarget : SubTarget, ILegacyTarget { const string kAssetGuid = "ea1514729d7120344b27dcd67fbf34de"; + public UniversalSpriteLitSubTarget() + { + displayName = "Sprite Lit"; + } + + public override bool IsActive() => true; + public override void Setup(ref TargetSetupContext context) { context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); context.AddSubShader(SubShaders.SpriteLit); } + public override void GetFields(ref TargetFieldContext context) + { + // Only support SpriteColor legacy block if BaseColor/Alpha are not active + var descs = context.blocks.Select(x => x.descriptor); + bool useLegacyBlocks = !descs.Contains(BlockFields.SurfaceDescription.BaseColor) && !descs.Contains(BlockFields.SurfaceDescription.Alpha); + context.AddField(CoreFields.UseLegacySpriteBlocks, useLegacyBlocks); + + // Surface Type & Blend Mode + context.AddField(Fields.SurfaceTransparent); + context.AddField(Fields.BlendAlpha); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + // Only support SpriteColor legacy block if BaseColor/Alpha are not active + bool useLegacyBlocks = !context.currentBlocks.Contains(BlockFields.SurfaceDescription.BaseColor) && !context.currentBlocks.Contains(BlockFields.SurfaceDescription.Alpha); + context.AddBlock(BlockFields.SurfaceDescriptionLegacy.SpriteColor, useLegacyBlocks); + + context.AddBlock(UniversalBlockFields.SurfaceDescription.SpriteMask); + context.AddBlock(BlockFields.SurfaceDescription.NormalTS); + context.AddBlock(BlockFields.SurfaceDescription.Alpha); + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + } + + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is SpriteLitMasterNode1 spriteLitMasterNode)) + return false; + + // Set blockmap + blockMap = new Dictionary() + { + { BlockFields.VertexDescription.Position, 9 }, + { BlockFields.VertexDescription.Normal, 10 }, + { BlockFields.VertexDescription.Tangent, 11 }, + { BlockFields.SurfaceDescriptionLegacy.SpriteColor, 0 }, + { UniversalBlockFields.SurfaceDescription.SpriteMask, 1 }, + { BlockFields.SurfaceDescription.NormalTS, 2 }, + }; + + return true; + } + #region SubShader static class SubShaders { public static SubShaderDescriptor SpriteLit = new SubShaderDescriptor() { pipelineTag = UniversalTarget.kPipelineTag, + renderType = $"{RenderType.Transparent}", + renderQueue = $"{UnityEditor.ShaderGraph.RenderQueue.Transparent}", generatesPreview = true, passes = new PassCollection { @@ -50,8 +107,8 @@ static class SpriteLitPasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = SpriteLitPortMasks.Vertex, - pixelPorts = SpriteLitPortMasks.FragmentLit, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = SpriteLitBlockMasks.FragmentLit, // Fields structs = CoreStructCollections.Default, @@ -78,8 +135,8 @@ static class SpriteLitPasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = SpriteLitPortMasks.Vertex, - pixelPorts = SpriteLitPortMasks.FragmentForwardNormal, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = SpriteLitBlockMasks.FragmentForwardNormal, // Fields structs = CoreStructCollections.Default, @@ -105,8 +162,8 @@ static class SpriteLitPasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = SpriteLitPortMasks.Vertex, - pixelPorts = SpriteLitPortMasks.FragmentForwardNormal, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = SpriteLitBlockMasks.FragmentForwardNormal, // Fields structs = CoreStructCollections.Default, @@ -123,25 +180,22 @@ static class SpriteLitPasses #endregion #region PortMasks - static class SpriteLitPortMasks + static class SpriteLitBlockMasks { - public static int[] Vertex = new int[] - { - SpriteLitMasterNode.PositionSlotId, - SpriteLitMasterNode.VertNormalSlotId, - SpriteLitMasterNode.VertTangentSlotId, - }; - - public static int[] FragmentLit = new int[] + public static BlockFieldDescriptor[] FragmentLit = new BlockFieldDescriptor[] { - SpriteLitMasterNode.ColorSlotId, - SpriteLitMasterNode.MaskSlotId, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescriptionLegacy.SpriteColor, + BlockFields.SurfaceDescription.Alpha, + UniversalBlockFields.SurfaceDescription.SpriteMask, }; - public static int[] FragmentForwardNormal = new int[] + public static BlockFieldDescriptor[] FragmentForwardNormal = new BlockFieldDescriptor[] { - SpriteLitMasterNode.ColorSlotId, - SpriteLitMasterNode.NormalSlotId, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescriptionLegacy.SpriteColor, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.NormalTS, }; } #endregion diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSpriteUnlitSubTarget.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSpriteUnlitSubTarget.cs index 7bd3d1677c2..367f56cdd26 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSpriteUnlitSubTarget.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSpriteUnlitSubTarget.cs @@ -1,28 +1,81 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using UnityEditor.ShaderGraph; using UnityEngine.Rendering; using UnityEditor.Experimental.Rendering.Universal; +using UnityEditor.ShaderGraph.Legacy; namespace UnityEditor.Rendering.Universal.ShaderGraph { - sealed class UniversalSpriteUnlitSubTarget : SubTarget + sealed class UniversalSpriteUnlitSubTarget : SubTarget, ILegacyTarget { const string kAssetGuid = "ed7c0aacec26e9646b45c96fb318e5a3"; + public UniversalSpriteUnlitSubTarget() + { + displayName = "Sprite Unlit"; + } + + public override bool IsActive() => true; + public override void Setup(ref TargetSetupContext context) { context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); context.AddSubShader(SubShaders.SpriteUnlit); } + public override void GetFields(ref TargetFieldContext context) + { + var descs = context.blocks.Select(x => x.descriptor); + // Only support SpriteColor legacy block if BaseColor/Alpha are not active + bool useLegacyBlocks = !descs.Contains(BlockFields.SurfaceDescription.BaseColor) && !descs.Contains(BlockFields.SurfaceDescription.Alpha); + context.AddField(CoreFields.UseLegacySpriteBlocks, useLegacyBlocks); + + // Surface Type & Blend Mode + context.AddField(Fields.SurfaceTransparent); + context.AddField(Fields.BlendAlpha); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + // Only support SpriteColor legacy block if BaseColor/Alpha are not active + bool useLegacyBlocks = !context.currentBlocks.Contains(BlockFields.SurfaceDescription.BaseColor) && !context.currentBlocks.Contains(BlockFields.SurfaceDescription.Alpha); + context.AddBlock(BlockFields.SurfaceDescriptionLegacy.SpriteColor, useLegacyBlocks); + + context.AddBlock(BlockFields.SurfaceDescription.Alpha); + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + } + + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is SpriteUnlitMasterNode1 spriteUnlitMasterNode)) + return false; + + // Set blockmap + blockMap = new Dictionary() + { + { BlockFields.VertexDescription.Position, 9 }, + { BlockFields.VertexDescription.Normal, 10 }, + { BlockFields.VertexDescription.Tangent, 11 }, + { BlockFields.SurfaceDescriptionLegacy.SpriteColor, 0 }, + }; + + return true; + } + #region SubShader static class SubShaders { public static SubShaderDescriptor SpriteUnlit = new SubShaderDescriptor() { pipelineTag = UniversalTarget.kPipelineTag, + renderType = $"{RenderType.Transparent}", + renderQueue = $"{UnityEditor.ShaderGraph.RenderQueue.Transparent}", generatesPreview = true, passes = new PassCollection { @@ -46,8 +99,8 @@ static class SpriteUnlitPasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = SpriteUnlitPortMasks.Vertex, - pixelPorts = SpriteUnlitPortMasks.Fragment, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = SpriteUnlitBlockMasks.Fragment, // Fields structs = CoreStructCollections.Default, @@ -64,18 +117,13 @@ static class SpriteUnlitPasses #endregion #region PortMasks - static class SpriteUnlitPortMasks + static class SpriteUnlitBlockMasks { - public static int[] Vertex = new int[] - { - SpriteUnlitMasterNode.PositionSlotId, - SpriteUnlitMasterNode.VertNormalSlotId, - SpriteUnlitMasterNode.VertTangentSlotId - }; - - public static int[] Fragment = new int[] + public static BlockFieldDescriptor[] Fragment = new BlockFieldDescriptor[] { - SpriteUnlitMasterNode.ColorSlotId, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescriptionLegacy.SpriteColor, + BlockFields.SurfaceDescription.Alpha, }; } #endregion diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs index 1026d887205..f20e4924d87 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs @@ -1,67 +1,310 @@ using System; using System.Linq; using System.Collections.Generic; -using UnityEditor.ShaderGraph; +using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; +using UnityEngine.UIElements; +using UnityEditor.ShaderGraph; using UnityEditor.Experimental.Rendering.Universal; +using UnityEditor.Graphing; +using UnityEditor.UIElements; +using UnityEditor.ShaderGraph.Serialization; +using UnityEditor.ShaderGraph.Legacy; namespace UnityEditor.Rendering.Universal.ShaderGraph { - sealed class UniversalTarget : Target + public enum MaterialType + { + Lit, + Unlit, + SpriteLit, + SpriteUnlit, + } + + public enum WorkflowMode + { + Specular, + Metallic, + } + + enum SurfaceType + { + Opaque, + Transparent, + } + + enum AlphaMode + { + Alpha, + Premultiply, + Additive, + Multiply, + } + + sealed class UniversalTarget : Target, ILegacyTarget { + // Constants const string kAssetGuid = "8c72f47fdde33b14a9340e325ce56f4d"; + public const string kPipelineTag = "UniversalPipeline"; + + // SubTarget List m_SubTargets; - SubTarget m_ActiveSubTarget; + List m_SubTargetNames; + int activeSubTargetIndex => m_SubTargets.IndexOf(m_ActiveSubTarget); + + // View + PopupField m_SubTargetField; + TextField m_CustomGUIField; + + [SerializeField] + JsonData m_ActiveSubTarget; + + [SerializeField] + SurfaceType m_SurfaceType = SurfaceType.Opaque; + + [SerializeField] + AlphaMode m_AlphaMode = AlphaMode.Alpha; + + [SerializeField] + bool m_TwoSided = false; + [SerializeField] + bool m_AlphaClip = false; + + [SerializeField] + string m_CustomEditorGUI; + public UniversalTarget() { displayName = "Universal"; - m_SubTargets = TargetUtils.GetSubTargetsOfType(); + m_SubTargets = TargetUtils.GetSubTargets(this); + m_SubTargetNames = m_SubTargets.Select(x => x.displayName).ToList(); + TargetUtils.ProcessSubTargetList(ref m_ActiveSubTarget, ref m_SubTargets); } - public const string kPipelineTag = "UniversalPipeline"; - - public override void Setup(ref TargetSetupContext context) + public string renderType { - // Currently we infer the active SubTarget based on the MasterNode type - void SetActiveSubTargetIndex(IMasterNode masterNode) + get { - Type activeSubTargetType; - if(!s_SubTargetMap.TryGetValue(masterNode.GetType(), out activeSubTargetType)) - return; + if(surfaceType == SurfaceType.Transparent) + return $"{RenderType.Transparent}"; + else + return $"{RenderType.Opaque}"; + } + } - m_ActiveSubTarget = m_SubTargets.FirstOrDefault(x => x.GetType() == activeSubTargetType); + public string renderQueue + { + get + { + if(surfaceType == SurfaceType.Transparent) + return $"{UnityEditor.ShaderGraph.RenderQueue.Transparent}"; + else if(alphaClip) + return $"{UnityEditor.ShaderGraph.RenderQueue.AlphaTest}"; + else + return $"{UnityEditor.ShaderGraph.RenderQueue.Geometry}"; } + } + + public SubTarget activeSubTarget + { + get => m_ActiveSubTarget; + set => m_ActiveSubTarget = value; + } + + public SurfaceType surfaceType + { + get => m_SurfaceType; + set => m_SurfaceType = value; + } + public AlphaMode alphaMode + { + get => m_AlphaMode; + set => m_AlphaMode = value; + } + + public bool twoSided + { + get => m_TwoSided; + set => m_TwoSided = value; + } + + public bool alphaClip + { + get => m_AlphaClip; + set => m_AlphaClip = value; + } + + public string customEditorGUI + { + get => m_CustomEditorGUI; + set => m_CustomEditorGUI = value; + } + + public override bool IsActive() + { + bool isUniversalRenderPipeline = GraphicsSettings.currentRenderPipeline is UniversalRenderPipelineAsset; + return isUniversalRenderPipeline && activeSubTarget.IsActive(); + } + + public override void Setup(ref TargetSetupContext context) + { // Setup the Target context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); // Setup the active SubTarget - SetActiveSubTargetIndex(context.masterNode); - m_ActiveSubTarget.Setup(ref context); + TargetUtils.ProcessSubTargetList(ref m_ActiveSubTarget, ref m_SubTargets); + m_ActiveSubTarget.value.target = this; + m_ActiveSubTarget.value.Setup(ref context); + + // Override EditorGUI + if(!string.IsNullOrEmpty(m_CustomEditorGUI)) + { + context.SetDefaultShaderGUI(m_CustomEditorGUI); + } } - public override bool IsValid(IMasterNode masterNode) + public override void GetFields(ref TargetFieldContext context) { - // Currently we infer the validity based on SubTarget mapping - return s_SubTargetMap.TryGetValue(masterNode.GetType(), out _); + var descs = context.blocks.Select(x => x.descriptor); + // Core fields + context.AddField(Fields.GraphVertex, descs.Contains(BlockFields.VertexDescription.Position) || + descs.Contains(BlockFields.VertexDescription.Normal) || + descs.Contains(BlockFields.VertexDescription.Tangent)); + context.AddField(Fields.GraphPixel); + context.AddField(Fields.AlphaClip, alphaClip); + context.AddField(Fields.DoubleSided, twoSided); + + // SubTarget fields + m_ActiveSubTarget.value.GetFields(ref context); } - public override bool IsPipelineCompatible(RenderPipelineAsset currentPipeline) + public override void GetActiveBlocks(ref TargetActiveBlockContext context) { - return currentPipeline is UniversalRenderPipelineAsset; + // Core blocks + context.AddBlock(BlockFields.VertexDescription.Position); + context.AddBlock(BlockFields.VertexDescription.Normal); + context.AddBlock(BlockFields.VertexDescription.Tangent); + context.AddBlock(BlockFields.SurfaceDescription.BaseColor); + + // SubTarget blocks + m_ActiveSubTarget.value.GetActiveBlocks(ref context); } - // Currently we need to map SubTarget type to IMasterNode type - // We do this here to avoid bleeding this into the SubTarget API - static Dictionary s_SubTargetMap = new Dictionary() + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) { - { typeof(PBRMasterNode), typeof(UniversalLitSubTarget) }, - { typeof(UnlitMasterNode), typeof(UniversalUnlitSubTarget) }, - { typeof(SpriteLitMasterNode), typeof(UniversalSpriteLitSubTarget) }, - { typeof(SpriteUnlitMasterNode), typeof(UniversalSpriteUnlitSubTarget) }, - }; + // Core properties + m_SubTargetField = new PopupField(m_SubTargetNames, activeSubTargetIndex); + context.AddProperty("Material", m_SubTargetField, (evt) => + { + if (Equals(activeSubTargetIndex, m_SubTargetField.index)) + return; + + registerUndo("Change Material"); + m_ActiveSubTarget = m_SubTargets[m_SubTargetField.index]; + onChange(); + }); + + // SubTarget properties + m_ActiveSubTarget.value.GetPropertiesGUI(ref context, onChange, registerUndo); + + // Custom Editor GUI + // Requires FocusOutEvent + m_CustomGUIField = new TextField("") { value = customEditorGUI }; + m_CustomGUIField.RegisterCallback(s => + { + if (Equals(customEditorGUI, m_CustomGUIField.value)) + return; + + registerUndo("Change Custom Editor GUI"); + customEditorGUI = m_CustomGUIField.value; + onChange(); + }); + context.AddProperty("Custom Editor GUI", m_CustomGUIField, (evt) => {}); + } + + public bool TrySetActiveSubTarget(Type subTargetType) + { + if(!subTargetType.IsSubclassOf(typeof(SubTarget))) + return false; + + foreach(var subTarget in m_SubTargets) + { + if(subTarget.GetType().Equals(subTargetType)) + { + m_ActiveSubTarget = subTarget; + return true; + } + } + + return false; + } + + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + void UpgradeAlphaClip() + { + var clipThresholdId = 8; + var node = masterNode as AbstractMaterialNode; + var clipThresholdSlot = node.FindSlot(clipThresholdId); + if(clipThresholdSlot == null) + return; + + clipThresholdSlot.owner = node; + if(clipThresholdSlot.isConnected || clipThresholdSlot.value > 0.0f) + { + m_AlphaClip = true; + } + } + + // Upgrade Target + switch(masterNode) + { + case PBRMasterNode1 pbrMasterNode: + m_SurfaceType = (SurfaceType)pbrMasterNode.m_SurfaceType; + m_AlphaMode = (AlphaMode)pbrMasterNode.m_AlphaMode; + m_TwoSided = pbrMasterNode.m_TwoSided; + UpgradeAlphaClip(); + m_CustomEditorGUI = pbrMasterNode.m_OverrideEnabled ? pbrMasterNode.m_ShaderGUIOverride : ""; + break; + case UnlitMasterNode1 unlitMasterNode: + m_SurfaceType = (SurfaceType)unlitMasterNode.m_SurfaceType; + m_AlphaMode = (AlphaMode)unlitMasterNode.m_AlphaMode; + m_TwoSided = unlitMasterNode.m_TwoSided; + UpgradeAlphaClip(); + m_CustomEditorGUI = unlitMasterNode.m_OverrideEnabled ? unlitMasterNode.m_ShaderGUIOverride : ""; + break; + case SpriteLitMasterNode1 spriteLitMasterNode: + m_CustomEditorGUI = spriteLitMasterNode.m_OverrideEnabled ? spriteLitMasterNode.m_ShaderGUIOverride : ""; + break; + case SpriteUnlitMasterNode1 spriteUnlitMasterNode: + m_CustomEditorGUI = spriteUnlitMasterNode.m_OverrideEnabled ? spriteUnlitMasterNode.m_ShaderGUIOverride : ""; + break; + } + + // Upgrade SubTarget + foreach(var subTarget in m_SubTargets) + { + if(!(subTarget is ILegacyTarget legacySubTarget)) + continue; + + if(legacySubTarget.TryUpgradeFromMasterNode(masterNode, out blockMap)) + { + m_ActiveSubTarget = subTarget; + return true; + } + } + + blockMap = null; + return false; + } + + public override bool WorksWithSRP(RenderPipelineAsset scriptableRenderPipeline) + { + return scriptableRenderPipeline?.GetType() == typeof(UniversalRenderPipelineAsset); + } } #region Passes @@ -80,8 +323,8 @@ static class CorePasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = CorePortMasks.Vertex, - pixelPorts = CorePortMasks.FragmentAlphaOnly, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly, // Fields structs = CoreStructCollections.Default, @@ -105,8 +348,8 @@ static class CorePasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = CorePortMasks.Vertex, - pixelPorts = CorePortMasks.FragmentAlphaOnly, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly, // Fields structs = CoreStructCollections.Default, @@ -122,19 +365,26 @@ static class CorePasses #endregion #region PortMasks - class CorePortMasks + class CoreBlockMasks { - public static int[] Vertex = new int[] + public static BlockFieldDescriptor[] Vertex = new BlockFieldDescriptor[] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + }; + + public static BlockFieldDescriptor[] FragmentAlphaOnly = new BlockFieldDescriptor[] { - PBRMasterNode.PositionSlotId, - PBRMasterNode.VertNormalSlotId, - PBRMasterNode.VertTangentSlotId, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, }; - public static int[] FragmentAlphaOnly = new int[] + public static BlockFieldDescriptor[] FragmentColorAlpha = new BlockFieldDescriptor[] { - PBRMasterNode.AlphaSlotId, - PBRMasterNode.AlphaThresholdSlotId, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, }; } #endregion @@ -398,6 +648,16 @@ static class CoreIncludes } #endregion +#region Defines + static class CoreDefines + { + public static DefineCollection UseLegacySpriteBlocks = new DefineCollection + { + { CoreKeywordDescriptors.UseLegacySpriteBlocks, 1, new FieldCondition(CoreFields.UseLegacySpriteBlocks, true) }, + }; + } +#endregion + #region KeywordDescriptors static class CoreKeywordDescriptors { @@ -541,6 +801,20 @@ static class CoreKeywordDescriptors definition = KeywordDefinition.MultiCompile, scope = KeywordScope.Global, }; + + public static KeywordDescriptor UseLegacySpriteBlocks = new KeywordDescriptor() + { + displayName = "UseLegacySpriteBlocks", + referenceName = "USELEGACYSPRITEBLOCKS", + type = KeywordType.Boolean, + }; + } +#endregion + +#region FieldDescriptors + static class CoreFields + { + public static FieldDescriptor UseLegacySpriteBlocks = new FieldDescriptor("Universal", "UseLegacySpriteBlocks", "UNIVERSAL_USELEGACYSPRITEBLOCKS"); } #endregion } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs index af939c2c670..1e2f65a0ad1 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs @@ -1,12 +1,16 @@ using System; using System.Linq; using System.Collections.Generic; +using UnityEngine; using UnityEditor.ShaderGraph; using UnityEngine.Rendering; +using UnityEditor.UIElements; +using UnityEngine.UIElements; +using UnityEditor.ShaderGraph.Legacy; namespace UnityEditor.Rendering.Universal.ShaderGraph { - sealed class UniversalUnlitSubTarget : SubTarget + sealed class UniversalUnlitSubTarget : SubTarget, ILegacyTarget { const string kAssetGuid = "97c3f7dcb477ec842aa878573640313a"; @@ -15,11 +19,104 @@ public UniversalUnlitSubTarget() displayName = "Unlit"; } + public override bool IsActive() => true; + public override void Setup(ref TargetSetupContext context) { context.AddAssetDependencyPath(AssetDatabase.GUIDToAssetPath(kAssetGuid)); - context.AddSubShader(SubShaders.Unlit); - context.AddSubShader(SubShaders.UnlitDOTS); + + // Process SubShaders + SubShaderDescriptor[] subShaders = { SubShaders.Unlit, SubShaders.UnlitDOTS }; + for(int i = 0; i < subShaders.Length; i++) + { + // Update Render State + subShaders[i].renderType = target.renderType; + subShaders[i].renderQueue = target.renderQueue; + + // Add + context.AddSubShader(subShaders[i]); + } + } + + public override void GetFields(ref TargetFieldContext context) + { + // Surface Type & Blend Mode + // These must be set per SubTarget as Sprite SubTargets override them + context.AddField(Fields.SurfaceOpaque, target.surfaceType == SurfaceType.Opaque); + context.AddField(Fields.SurfaceTransparent, target.surfaceType != SurfaceType.Opaque); + context.AddField(Fields.BlendAdd, target.surfaceType != SurfaceType.Opaque && target.alphaMode == AlphaMode.Additive); + context.AddField(Fields.BlendAlpha, target.surfaceType != SurfaceType.Opaque && target.alphaMode == AlphaMode.Alpha); + context.AddField(Fields.BlendMultiply, target.surfaceType != SurfaceType.Opaque && target.alphaMode == AlphaMode.Multiply); + context.AddField(Fields.BlendPremultiply, target.surfaceType != SurfaceType.Opaque && target.alphaMode == AlphaMode.Premultiply); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + context.AddBlock(BlockFields.SurfaceDescription.Alpha, target.surfaceType == SurfaceType.Transparent || target.alphaClip); + context.AddBlock(BlockFields.SurfaceDescription.AlphaClipThreshold, target.alphaClip); + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + context.AddProperty("Surface", new EnumField(SurfaceType.Opaque) { value = target.surfaceType }, (evt) => + { + if (Equals(target.surfaceType, evt.newValue)) + return; + + registerUndo("Change Surface"); + target.surfaceType = (SurfaceType)evt.newValue; + onChange(); + }); + + context.AddProperty("Blend", new EnumField(AlphaMode.Alpha) { value = target.alphaMode }, target.surfaceType == SurfaceType.Transparent, (evt) => + { + if (Equals(target.alphaMode, evt.newValue)) + return; + + registerUndo("Change Blend"); + target.alphaMode = (AlphaMode)evt.newValue; + onChange(); + }); + + context.AddProperty("Alpha Clip", new Toggle() { value = target.alphaClip }, (evt) => + { + if (Equals(target.alphaClip, evt.newValue)) + return; + + registerUndo("Change Alpha Clip"); + target.alphaClip = evt.newValue; + onChange(); + }); + + context.AddProperty("Two Sided", new Toggle() { value = target.twoSided }, (evt) => + { + if (Equals(target.twoSided, evt.newValue)) + return; + + registerUndo("Change Two Sided"); + target.twoSided = evt.newValue; + onChange(); + }); + } + + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is UnlitMasterNode1 unlitMasterNode)) + return false; + + // Set blockmap + blockMap = new Dictionary() + { + { BlockFields.VertexDescription.Position, 9 }, + { BlockFields.VertexDescription.Normal, 10 }, + { BlockFields.VertexDescription.Tangent, 11 }, + { BlockFields.SurfaceDescription.BaseColor, 0 }, + { BlockFields.SurfaceDescription.Alpha, 7 }, + { BlockFields.SurfaceDescription.AlphaClipThreshold, 8 }, + }; + + return true; } #region SubShader @@ -80,8 +177,8 @@ static class UnlitPasses sharedTemplateDirectory = GenerationUtils.GetDefaultSharedTemplateDirectory(), // Port Mask - vertexPorts = UnlitPortMasks.Vertex, - pixelPorts = UnlitPortMasks.Fragment, + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentColorAlpha, // Fields structs = CoreStructCollections.Default, @@ -96,25 +193,6 @@ static class UnlitPasses } #endregion -#region PortMask - static class UnlitPortMasks - { - public static int[] Vertex = new int[] - { - UnlitMasterNode.PositionSlotId, - UnlitMasterNode.VertNormalSlotId, - UnlitMasterNode.VertTangentSlotId, - }; - - public static int[] Fragment = new int[] - { - UnlitMasterNode.ColorSlotId, - UnlitMasterNode.AlphaSlotId, - UnlitMasterNode.AlphaThresholdSlotId, - }; - } -#endregion - #region Keywords static class UnlitKeywords { diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalBlockFields.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalBlockFields.cs new file mode 100644 index 00000000000..76e076d2940 --- /dev/null +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalBlockFields.cs @@ -0,0 +1,16 @@ +using UnityEngine; +using UnityEditor.ShaderGraph; + +namespace UnityEditor.Rendering.Universal.ShaderGraph +{ + static class UniversalBlockFields + { + [GenerateBlocks("Universal Render Pipeline")] + public struct SurfaceDescription + { + public static string name = "SurfaceDescription"; + public static BlockFieldDescriptor SpriteMask = new BlockFieldDescriptor(SurfaceDescription.name, "SpriteMask", "Sprite Mask", "SURFACEDESCRIPTION_SPRITEMASK", + new ColorRGBAControl(new Color(1, 1, 1, 1)), ShaderStage.Fragment); + } + } +} diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalBlockFields.cs.meta b/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalBlockFields.cs.meta new file mode 100644 index 00000000000..e3e6d1218b5 --- /dev/null +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalBlockFields.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2102cc5328fff429ab79b384a6ba51b2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/AssetCallbacks/CreateShaderGraph.cs b/com.unity.shadergraph/Editor/AssetCallbacks/CreateShaderGraph.cs index 93b7cd6241e..7da1117be8a 100644 --- a/com.unity.shadergraph/Editor/AssetCallbacks/CreateShaderGraph.cs +++ b/com.unity.shadergraph/Editor/AssetCallbacks/CreateShaderGraph.cs @@ -4,22 +4,10 @@ namespace UnityEditor.ShaderGraph { static class CreateShaderGraph { - [MenuItem("Assets/Create/Shader/Unlit Graph", false, 208)] - public static void CreateUnlitMasterMaterialGraph() + [MenuItem("Assets/Create/Shader/Blank Shader Graph", false, 208)] + public static void CreateBlankShaderGraph() { - GraphUtil.CreateNewGraph(new UnlitMasterNode()); - } - - [MenuItem("Assets/Create/Shader/PBR Graph", false, 208)] - public static void CreatePBRMasterMaterialGraph() - { - GraphUtil.CreateNewGraph(new PBRMasterNode()); - } - - [MenuItem("Assets/Create/Shader/VFX Shader Graph", false, 208)] - public static void CreateVfxShaderGraph() - { - GraphUtil.CreateNewGraph(new VfxMasterNode()); + GraphUtil.CreateNewGraph(); } } } diff --git a/com.unity.shadergraph/Editor/AssetCallbacks/CreateVFXShaderGraph.cs b/com.unity.shadergraph/Editor/AssetCallbacks/CreateVFXShaderGraph.cs new file mode 100644 index 00000000000..595f66a993a --- /dev/null +++ b/com.unity.shadergraph/Editor/AssetCallbacks/CreateVFXShaderGraph.cs @@ -0,0 +1,22 @@ +using System; +using UnityEditor.ShaderGraph; + +namespace UnityEditor.ShaderGraph +{ + static class CreateVFXShaderGraph + { + [MenuItem("Assets/Create/Shader/VFX Shader Graph", false, 208)] + public static void CreateVFXGraph() + { + var target = (VFXTarget)Activator.CreateInstance(typeof(VFXTarget)); + + var blockDescriptors = new [] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Alpha, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + } + } +} \ No newline at end of file diff --git a/com.unity.shadergraph/Editor/AssetCallbacks/CreateVFXShaderGraph.cs.meta b/com.unity.shadergraph/Editor/AssetCallbacks/CreateVFXShaderGraph.cs.meta new file mode 100644 index 00000000000..bd6eabcf8be --- /dev/null +++ b/com.unity.shadergraph/Editor/AssetCallbacks/CreateVFXShaderGraph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4aed1be68a7498d468a7ea49a3280138 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/ContextData.cs b/com.unity.shadergraph/Editor/Data/ContextData.cs new file mode 100644 index 00000000000..3b2ee039224 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/ContextData.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.ShaderGraph.Serialization; + +namespace UnityEditor.ShaderGraph +{ + [Serializable] + sealed class ContextData + { + [SerializeField] + Vector2 m_Position; + + [SerializeField] + List> m_Blocks = new List>(); + + [NonSerialized] + ShaderStage m_ShaderStage; + + public ContextData() + { + } + + public List> blocks => m_Blocks; + + public Vector2 position + { + get => m_Position; + set => m_Position = value; + } + + public ShaderStage shaderStage + { + get => m_ShaderStage; + set => m_ShaderStage = value; + } + } +} diff --git a/com.unity.shadergraph/Editor/Data/ContextData.cs.meta b/com.unity.shadergraph/Editor/Data/ContextData.cs.meta new file mode 100644 index 00000000000..e49071002ef --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/ContextData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8dfa4982c4e3ac6429fc1c375d3ceea2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Graphs/BooleanMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/BooleanMaterialSlot.cs index e8407af08e6..85578e0fb45 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/BooleanMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/BooleanMaterialSlot.cs @@ -48,6 +48,8 @@ public bool value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + protected override string ConcreteSlotValueAsVariable() { return (value ? 1 : 0).ToString(); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/CubemapInputMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/CubemapInputMaterialSlot.cs index 97e2de687c3..6b3d36726c9 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/CubemapInputMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/CubemapInputMaterialSlot.cs @@ -21,6 +21,8 @@ public Cubemap cubemap set { m_Cubemap.cubemap = value; } } + public override bool isDefaultValue => cubemap == null; + public CubemapInputMaterialSlot() {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/CubemapMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/CubemapMaterialSlot.cs index 50fc5abe660..5b773b3ec03 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/CubemapMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/CubemapMaterialSlot.cs @@ -21,6 +21,7 @@ public CubemapMaterialSlot( public override SlotValueType valueType { get { return SlotValueType.Cubemap; } } public override ConcreteSlotValueType concreteValueType { get { return ConcreteSlotValueType.Cubemap; } } + public override bool isDefaultValue => true; public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode) {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/DynamicMatrixMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/DynamicMatrixMaterialSlot.cs index fc9cda427df..7d400357ef6 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/DynamicMatrixMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/DynamicMatrixMaterialSlot.cs @@ -48,6 +48,8 @@ public Matrix4x4 value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + public override SlotValueType valueType { get { return SlotValueType.DynamicMatrix; } } public override ConcreteSlotValueType concreteValueType diff --git a/com.unity.shadergraph/Editor/Data/Graphs/DynamicValueMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/DynamicValueMaterialSlot.cs index f40f7fc5c87..6735ff264fa 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/DynamicValueMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/DynamicValueMaterialSlot.cs @@ -48,6 +48,8 @@ public Matrix4x4 value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + public override VisualElement InstantiateControl() { var labels = k_Labels.Take(concreteValueType.GetChannelCount()).ToArray(); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/DynamicVectorMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/DynamicVectorMaterialSlot.cs index 9b7a9e8eb9e..79e20711cb5 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/DynamicVectorMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/DynamicVectorMaterialSlot.cs @@ -48,6 +48,8 @@ public Vector4 value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + public override VisualElement InstantiateControl() { var labels = k_Labels.Take(concreteValueType.GetChannelCount()).ToArray(); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/GradientInputMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/GradientInputMaterialSlot.cs index 49a0f5be29e..6ecdf7c58c3 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/GradientInputMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/GradientInputMaterialSlot.cs @@ -40,6 +40,8 @@ public Gradient value public Gradient defaultValue { get { return m_DefaultValue; } } + public override bool isDefaultValue => value.Equals(defaultValue); + public override VisualElement InstantiateControl() { return new GradientSlotControlView(this); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/GradientMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/GradientMaterialSlot.cs index 11d45915fa4..3bf12e01ac8 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/GradientMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/GradientMaterialSlot.cs @@ -21,6 +21,7 @@ public GradientMaterialSlot( public override SlotValueType valueType { get { return SlotValueType.Gradient; } } public override ConcreteSlotValueType concreteValueType { get { return ConcreteSlotValueType.Gradient; } } + public override bool isDefaultValue => true; public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode) {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs b/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs index d78942565de..6fcd4975a30 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs @@ -13,6 +13,8 @@ using UnityEditor.ShaderGraph.Serialization; using Edge = UnityEditor.Graphing.Edge; +using UnityEngine.UIElements; + namespace UnityEditor.ShaderGraph { [Serializable] @@ -21,7 +23,7 @@ namespace UnityEditor.ShaderGraph [FormerName("UnityEditor.ShaderGraph.AbstractMaterialGraph")] sealed partial class GraphData : JsonObject { - const int k_CurrentVersion = 1; + const int k_CurrentVersion = 2; [SerializeField] int m_Version; @@ -64,6 +66,10 @@ public IEnumerable movedInputs get { return m_MovedInputs; } } + [NonSerialized] + bool m_MovedContexts = false; + public bool movedContexts => m_MovedContexts; + public string assetGuid { get; set; } #endregion @@ -76,6 +82,9 @@ public IEnumerable movedInputs [NonSerialized] Dictionary m_NodeDictionary = new Dictionary(); + [NonSerialized] + Dictionary m_LegacyUpdateDictionary = new Dictionary(); + public IEnumerable GetNodes() { return m_Nodes.SelectValue().OfType(); @@ -218,6 +227,26 @@ public IEnumerable removedEdges #endregion + #region Context Data + + [SerializeField] + ContextData m_VertexContext; + + [SerializeField] + ContextData m_FragmentContext; + + // We build this once and cache it as it uses reflection + // This list is used to build the Create Node menu entries for Blocks + // as well as when deserializing descriptor fields on serialized Blocks + [NonSerialized] + List m_BlockFieldDescriptors; + + public ContextData vertexContext => m_VertexContext; + public ContextData fragmentContext => m_FragmentContext; + public List blockFieldDescriptors => m_BlockFieldDescriptors; + + #endregion + [SerializeField] InspectorPreviewData m_PreviewData = new InspectorPreviewData(); @@ -264,21 +293,151 @@ public AbstractMaterialNode outputNode set => m_OutputNode = value; } + internal delegate void SaveGraphDelegate(Shader shader, object context); + internal static SaveGraphDelegate onSaveGraph; + #region Targets + [SerializeField] + List> m_ActiveTargets = new List>(); + [NonSerialized] List m_ValidTargets = new List(); + [NonSerialized] + List m_UnsupportedTargets = new List(); + + public List unsupportedTargets { get => m_UnsupportedTargets; } + + int m_ActiveTargetBitmask; + public int activeTargetBitmask + { + get => m_ActiveTargetBitmask; + set => m_ActiveTargetBitmask = value; + } + public List validTargets => m_ValidTargets; + public DataValueEnumerable activeTargets => m_ActiveTargets.SelectValue(); + + // TODO: Need a better way to handle this + public bool isVFXTarget => !isSubGraph && activeTargets.Count() > 0 && activeTargets.ElementAt(0).GetType() == typeof(VFXTarget); #endregion - public bool didActiveOutputNodeChange { get; set; } - - internal delegate void SaveGraphDelegate(Shader shader, object context); - internal static SaveGraphDelegate onSaveGraph; + private Comparison targetComparison = new Comparison((a, b) => string.Compare(a.displayName, b.displayName)); public GraphData() { m_GroupItems[null] = new List(); + GetBlockFieldDescriptors(); + GetTargets(); + } + + public void InitializeOutputs(Target[] targets, BlockFieldDescriptor[] blockDescriptors) + { + if(targets == null) + return; + + foreach(var target in targets) + { + if(m_ValidTargets.Any(x => x.GetType().Equals(target.GetType()))) + { + m_ActiveTargets.Add(target); + } + } + + if(blockDescriptors != null) + { + foreach(var descriptor in blockDescriptors) + { + var contextData = descriptor.shaderStage == ShaderStage.Fragment ? m_FragmentContext : m_VertexContext; + var block = (BlockNode)Activator.CreateInstance(typeof(BlockNode)); + block.Init(descriptor); + AddBlockNoValidate(block, contextData, contextData.blocks.Count); + } + } + + ValidateGraph(); + var activeBlocks = GetActiveBlocksForAllActiveTargets(); + UpdateActiveBlocks(activeBlocks); + } + + void GetBlockFieldDescriptors() + { + m_BlockFieldDescriptors = new List(); + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + foreach (var nestedType in assembly.GetTypes().SelectMany(t => t.GetNestedTypes())) + { + var attrs = nestedType.GetCustomAttributes(typeof(GenerateBlocksAttribute), false); + if (attrs == null || attrs.Length <= 0) + continue; + + var attribute = attrs[0] as GenerateBlocksAttribute; + + // Get all fields that are BlockFieldDescriptor + // If field and context stages match add to list + foreach (var fieldInfo in nestedType.GetFields()) + { + if(fieldInfo.GetValue(nestedType) is BlockFieldDescriptor blockFieldDescriptor) + { + blockFieldDescriptor.path = attribute.path; + m_BlockFieldDescriptors.Add(blockFieldDescriptor); + } + } + } + } + } + + void GetTargets() + { + // Find all valid Targets + var typeCollection = TypeCache.GetTypesDerivedFrom(); + foreach(var type in typeCollection) + { + if(type.IsAbstract || type.IsGenericType || !type.IsClass) + continue; + + var target = (Target)Activator.CreateInstance(type); + if(!target.isHidden) + { + m_ValidTargets.Add(target); + } + } + } + + public void UpdateActiveTargets(bool reevaluateActivity = true) + { + // Update active TargetImplementation list + if(m_ActiveTargets != null) + { + m_ActiveTargets.Clear(); + var invalidTargetsToRemove = ListPool.Get(); + var targetCount = m_ValidTargets.Count; + for(int i = 0; i < targetCount; i++) + { + if(((1 << i) & m_ActiveTargetBitmask) == (1 << i)) + { + m_ActiveTargets.Add(m_ValidTargets[i]); + } + //if we no longer have an unknown target as active, remove it + else if(m_ValidTargets[i] is MultiJsonInternal.UnknownTargetType) + { + invalidTargetsToRemove.Add(m_ValidTargets[i]); + } + } + + foreach(var invalidTarget in invalidTargetsToRemove) + { + m_ValidTargets.Remove(invalidTarget); + } + ListPool.Release(invalidTargetsToRemove); + } + if (reevaluateActivity) + { + ValidateGraph(); + NodeUtils.ReevaluateActivityOfNodeList(m_Nodes.SelectValue()); + } + //deal with the fact that target order might switch if unknown targets are collected + activeTargets.Sort(targetComparison); } public void ClearChanges() @@ -299,7 +458,7 @@ public void ClearChanges() m_RemovedNotes.Clear(); m_PastedStickyNotes.Clear(); m_MostRecentlyCreatedGroup = null; - didActiveOutputNodeChange = false; + m_MovedContexts = false; } public void AddNode(AbstractMaterialNode node) @@ -433,6 +592,139 @@ public void SetGroup(IGroupItem node, GroupData group) m_ParentGroupChanges.Add(groupChange); } + public void AddContexts() + { + m_VertexContext = new ContextData(); + m_VertexContext.shaderStage = ShaderStage.Vertex; + m_VertexContext.position = new Vector2(0, 0); + m_FragmentContext = new ContextData(); + m_FragmentContext.shaderStage = ShaderStage.Fragment; + m_FragmentContext.position = new Vector2(0, 200); + } + + public void AddBlock(BlockNode blockNode, ContextData contextData, int index) + { + AddBlockNoValidate(blockNode, contextData, index); + ValidateGraph(); + + var activeBlocks = GetActiveBlocksForAllActiveTargets(); + UpdateActiveBlocks(activeBlocks); + } + + void AddBlockNoValidate(BlockNode blockNode, ContextData contextData, int index) + { + // Regular AddNode path + AddNodeNoValidate(blockNode); + + // Set BlockNode properties + blockNode.contextData = contextData; + + // Add to ContextData + if(index == -1 || index >= contextData.blocks.Count()) + { + contextData.blocks.Add(blockNode); + } + else + { + contextData.blocks.Insert(index, blockNode); + } + } + + public List GetActiveBlocksForAllActiveTargets() + { + // Get list of active Block types + var currentBlocks = GetNodes(); + var context = new TargetActiveBlockContext(currentBlocks.Select(x => x.descriptor).ToList()); + foreach(var target in activeTargets) + { + target.GetActiveBlocks(ref context); + } + + return context.activeBlocks; + } + + public void UpdateActiveBlocks(List activeBlockDescriptors) + { + // Set Blocks as active based on supported Block list + //Note: we never want unknown blocks to be active, so explicitly set them to inactive always + foreach(var vertexBlock in vertexContext.blocks) + { + if (vertexBlock.value?.descriptor?.isUnknown == true) + { + vertexBlock.value.SetOverrideActiveState(AbstractMaterialNode.ActiveState.ExplicitInactive); + } + else + { + vertexBlock.value.SetOverrideActiveState(activeBlockDescriptors.Contains(vertexBlock.value.descriptor) ? AbstractMaterialNode.ActiveState.ExplicitActive + : AbstractMaterialNode.ActiveState.ExplicitInactive); + } + } + foreach(var fragmentBlock in fragmentContext.blocks) + { + if (fragmentBlock.value?.descriptor?.isUnknown == true) + { + fragmentBlock.value.SetOverrideActiveState(AbstractMaterialNode.ActiveState.ExplicitInactive); + } + else + { + fragmentBlock.value.SetOverrideActiveState(activeBlockDescriptors.Contains(fragmentBlock.value.descriptor) ? AbstractMaterialNode.ActiveState.ExplicitActive + : AbstractMaterialNode.ActiveState.ExplicitInactive); + } + } + } + + public void AddRemoveBlocksFromActiveList(List activeBlockDescriptors) + { + var blocksToRemove = ListPool.Get(); + + void GetBlocksToRemoveForContext(ContextData contextData) + { + for(int i = 0; i < contextData.blocks.Count; i++) + { + var block = contextData.blocks[i]; + if(!activeBlockDescriptors.Contains(block.value.descriptor)) + { + var slot = block.value.FindSlot(0); + //Need to check if a slot is not default value OR is an untracked unknown block type + if(slot.IsUsingDefaultValue() || block.value.descriptor.isUnknown) // TODO: How to check default value + { + blocksToRemove.Add(block); + } + } + } + } + + void TryAddBlockToContext(BlockFieldDescriptor descriptor, ContextData contextData) + { + if(descriptor.shaderStage != contextData.shaderStage) + return; + + if(contextData.blocks.Any(x => x.value.descriptor.Equals(descriptor))) + return; + + var node = (BlockNode)Activator.CreateInstance(typeof(BlockNode)); + node.Init(descriptor); + AddBlockNoValidate(node, contextData, contextData.blocks.Count); + } + + // Get inactive Blocks to remove + GetBlocksToRemoveForContext(vertexContext); + GetBlocksToRemoveForContext(fragmentContext); + + // Remove blocks + foreach(var block in blocksToRemove) + { + RemoveNodeNoValidate(block); + } + + // Add active Blocks not currently in Contexts + foreach(var descriptor in activeBlockDescriptors) + { + TryAddBlockToContext(descriptor, vertexContext); + TryAddBlockToContext(descriptor, fragmentContext); + } + } + void AddNodeNoValidate(AbstractMaterialNode node) { if (node.group !=null && !m_GroupItems.ContainsKey(node.group)) @@ -454,6 +746,13 @@ public void RemoveNode(AbstractMaterialNode node) } RemoveNodeNoValidate(node); ValidateGraph(); + + if(node is BlockNode blockNode) + { + var activeBlocks = GetActiveBlocksForAllActiveTargets(); + UpdateActiveBlocks(activeBlocks); + blockNode.Dirty(ModificationScope.Graph); + } } void RemoveNodeNoValidate(AbstractMaterialNode node) @@ -472,6 +771,12 @@ void RemoveNodeNoValidate(AbstractMaterialNode node) { groupItems.Remove(node); } + + if(node is BlockNode blockNode && blockNode.contextData != null) + { + // Remove from ContextData + blockNode.contextData.blocks.Remove(blockNode); + } } void AddEdgeToNodeEdges(IEdge edge) @@ -529,6 +834,7 @@ IEdge ConnectNoValidate(SlotReference fromSlotRef, SlotReference toSlotRef) m_Edges.Add(newEdge); m_AddedEdges.Add(newEdge); AddEdgeToNodeEdges(newEdge); + NodeUtils.ReevaluateActivityOfConnectedNodes(toNode); //Debug.LogFormat("Connected edge: {0} -> {1} ({2} -> {3})\n{4}", newEdge.outputSlot.nodeGuid, newEdge.inputSlot.nodeGuid, fromNode.name, toNode.name, Environment.StackTrace); return newEdge; @@ -592,24 +898,64 @@ public void RemoveElements(AbstractMaterialNode[] nodes, IEdge[] edges, GroupDat } ValidateGraph(); + + if(nodes.Any(x => x is BlockNode)) + { + var activeBlocks = GetActiveBlocksForAllActiveTargets(); + UpdateActiveBlocks(activeBlocks); + } } - void RemoveEdgeNoValidate(IEdge e) + void RemoveEdgeNoValidate(IEdge e, bool reevaluateActivity = true) { e = m_Edges.FirstOrDefault(x => x.Equals(e)); if (e == null) throw new ArgumentException("Trying to remove an edge that does not exist.", "e"); m_Edges.Remove(e as Edge); + BlockNode b = null; + AbstractMaterialNode input = e.inputSlot.node, output = e.outputSlot.node; + if(input != null && ShaderGraphPreferences.autoAddRemoveBlocks) + { + b = input as BlockNode; + } + List inputNodeEdges; - if (m_NodeEdges.TryGetValue(e.inputSlot.node.objectId, out inputNodeEdges)) + if (m_NodeEdges.TryGetValue(input.objectId, out inputNodeEdges)) inputNodeEdges.Remove(e); List outputNodeEdges; - if (m_NodeEdges.TryGetValue(e.outputSlot.node.objectId, out outputNodeEdges)) + if (m_NodeEdges.TryGetValue(output.objectId, out outputNodeEdges)) outputNodeEdges.Remove(e); m_RemovedEdges.Add(e); + if(b != null) + { + var activeBlockDescriptors = GetActiveBlocksForAllActiveTargets(); + if(!activeBlockDescriptors.Contains(b.descriptor)) + { + var slot = b.FindSlot(0); + if(slot.IsUsingDefaultValue()) // TODO: How to check default value + { + RemoveNodeNoValidate(b); + input = null; + } + } + } + + if (reevaluateActivity) + { + if (input != null) + { + NodeUtils.ReevaluateActivityOfConnectedNodes(input); + } + + if (output != null) + { + NodeUtils.ReevaluateActivityOfConnectedNodes(output); + } + } + } public AbstractMaterialNode GetNodeFromId(string nodeId) @@ -626,6 +972,9 @@ public T GetNodeFromId(string nodeId) where T : class public bool ContainsNode(AbstractMaterialNode node) { + if(node == null) + return false; + return m_NodeDictionary.TryGetValue(node.objectId, out var foundNode) && node == foundNode; } @@ -964,7 +1313,7 @@ public void CleanupGraph() || inputSlot == null) { //orphaned edge - RemoveEdgeNoValidate(edge); + RemoveEdgeNoValidate(edge, false); } } } @@ -1031,6 +1380,14 @@ public void ReplaceWith(GraphData other) concretePrecision = other.concretePrecision; m_OutputNode = other.m_OutputNode; + if ((this.vertexContext.position != other.vertexContext.position) || + (this.fragmentContext.position != other.fragmentContext.position)) + { + this.vertexContext.position = other.vertexContext.position; + this.fragmentContext.position = other.fragmentContext.position; + m_MovedContexts = true; + } + using (var inputsToRemove = PooledList.Get()) { foreach (var property in m_Properties.SelectValue()) @@ -1101,7 +1458,17 @@ public void ReplaceWith(GraphData other) } foreach (var node in other.GetNodes()) - AddNodeNoValidate(node); + { + if(node is BlockNode blockNode) + { + var contextData = blockNode.descriptor.shaderStage == ShaderStage.Vertex ? vertexContext : fragmentContext; + AddBlockNoValidate(blockNode, contextData, blockNode.index); + } + else + { + AddNodeNoValidate(node); + } + } foreach (var edge in other.edges) { @@ -1110,6 +1477,19 @@ public void ReplaceWith(GraphData other) outputNode = other.outputNode; + // Copy all targets + m_ActiveTargets.Clear(); + foreach(var target in other.activeTargets) + { + // Ensure target inits correctly + var context = new TargetSetupContext(); + target.Setup(ref context); + m_ActiveTargets.Add(target); + } + + // Active blocks + var activeBlocks = GetActiveBlocksForAllActiveTargets(); + UpdateActiveBlocks(activeBlocks); ValidateGraph(); } @@ -1151,6 +1531,11 @@ internal void PasteGraph(CopyPasteGraph graphToPaste, List var nodeList = graphToPaste.GetNodes(); foreach (var node in nodeList) { + if(node is BlockNode blockNode) + { + continue; + } + AbstractMaterialNode pastedNode = node; // Check if the property nodes need to be made into a concrete node. @@ -1249,18 +1634,36 @@ public override void OnBeforeSerialize() m_Version = k_CurrentVersion; } - static JsonObject DeserializeLegacy(string typeString, string json) + static T DeserializeLegacy(string typeString, string json) where T : JsonObject { - var value = MultiJsonInternal.CreateInstance(typeString); + var jsonObj = MultiJsonInternal.CreateInstance(typeString); + var value = jsonObj as T; if (value == null) { Debug.Log($"Cannot create instance for {typeString}"); return null; } - MultiJsonInternal.Enqueue(value, json); + return value as T; + } + + static AbstractMaterialNode DeserializeLegacy(string typeString, string json) + { + var jsonObj = MultiJsonInternal.CreateInstance(typeString); + var value = jsonObj as AbstractMaterialNode; + if (value == null) + { + //Special case - want to support nodes of unknwon type for cross pipeline compatability + value = new LegacyUnknownTypeNode(typeString, json); + MultiJsonInternal.Enqueue(value, json); + return value as AbstractMaterialNode; + } + else + { + MultiJsonInternal.Enqueue(value, json); + return value as AbstractMaterialNode; + } - return value; } public override void OnAfterDeserialize(string json) @@ -1297,7 +1700,7 @@ public override void OnAfterDeserialize(string json) foreach (var serializedProperty in graphData0.m_SerializedProperties) { - var property = (AbstractShaderProperty)DeserializeLegacy(serializedProperty.typeInfo.fullName, serializedProperty.JSONnodeData); + var property = DeserializeLegacy(serializedProperty.typeInfo.fullName, serializedProperty.JSONnodeData); if (property == null) { continue; @@ -1327,7 +1730,7 @@ public override void OnAfterDeserialize(string json) foreach (var serializedKeyword in graphData0.m_SerializedKeywords) { - var keyword = (ShaderKeyword)DeserializeLegacy(serializedKeyword.typeInfo.fullName, serializedKeyword.JSONnodeData); + var keyword = DeserializeLegacy(serializedKeyword.typeInfo.fullName, serializedKeyword.JSONnodeData); if (keyword == null) { continue; @@ -1343,7 +1746,7 @@ public override void OnAfterDeserialize(string json) { var node0 = JsonUtility.FromJson(serializedNode.JSONnodeData); - var node = (AbstractMaterialNode)DeserializeLegacy(serializedNode.typeInfo.fullName, serializedNode.JSONnodeData); + var node = DeserializeLegacy(serializedNode.typeInfo.fullName, serializedNode.JSONnodeData); if (node == null) { continue; @@ -1367,7 +1770,7 @@ public override void OnAfterDeserialize(string json) foreach (var serializedSlot in node0.m_SerializableSlots) { - var slot = (MaterialSlot)DeserializeLegacy(serializedSlot.typeInfo.fullName, serializedSlot.JSONnodeData); + var slot = DeserializeLegacy(serializedSlot.typeInfo.fullName, serializedSlot.JSONnodeData); if (slot == null) { continue; @@ -1413,7 +1816,7 @@ public override void OnAfterDeserialize(string json) } else { - m_OutputNode = (AbstractMaterialNode)GetNodes().FirstOrDefault(); + m_OutputNode = (AbstractMaterialNode)GetNodes().FirstOrDefault(); } foreach (var serializedElement in graphData0.m_SerializableEdges) @@ -1429,11 +1832,160 @@ public override void OnAfterDeserialize(string json) } } - m_Version = k_CurrentVersion; + + // In V2 we need to defer version set to in OnAfterMultiDeserialize + // This is because we need access to m_OutputNode to convert it to Targets and Stacks + // The JsonObject will not be fully deserialized until OnAfterMultiDeserialize + bool deferredUpgrades = m_Version < 2; + if(!deferredUpgrades) + { + m_Version = k_CurrentVersion; + } } public override void OnAfterMultiDeserialize(string json) { + // Deferred upgrades + if(m_Version != k_CurrentVersion) + { + if(m_Version < 2) + { + var addedBlocks = ListPool.Get(); + + void UpgradeFromBlockMap(Dictionary blockMap) + { + // Map master node ports to blocks + if(blockMap != null) + { + foreach(var blockMapping in blockMap) + { + // Create a new BlockNode for each unique map entry + var descriptor = blockMapping.Key; + if(addedBlocks.Contains(descriptor)) + continue; + + addedBlocks.Add(descriptor); + + var contextData = descriptor.shaderStage == ShaderStage.Fragment ? m_FragmentContext : m_VertexContext; + var block = (BlockNode)Activator.CreateInstance(typeof(BlockNode)); + block.Init(descriptor); + AddBlockNoValidate(block, contextData, contextData.blocks.Count); + + // To avoid having to go around the following deserialization code + // We simply run OnBeforeSerialization here to ensure m_SerializedDescriptor is set + block.OnBeforeSerialize(); + + // Now remap the incoming edges to blocks + var slotId = blockMapping.Value; + var oldSlot = m_OutputNode.value.FindSlot(slotId); + var newSlot = block.FindSlot(0); + if(oldSlot == null) + continue; + + var oldInputSlotRef = m_OutputNode.value.GetSlotReference(slotId); + var newInputSlotRef = block.GetSlotReference(0); + + // Always copy the value over for convenience + newSlot.CopyValuesFrom(oldSlot); + + for(int i = 0; i < m_Edges.Count; i++) + { + // Find all edges connected to the master node using slot ID from the block map + // Remove them and replace them with new edges connected to the block nodes + var edge = m_Edges[i]; + if(edge.inputSlot.Equals(oldInputSlotRef)) + { + var outputSlot = edge.outputSlot; + m_Edges.Remove(edge); + m_Edges.Add(new Edge(outputSlot, newInputSlotRef)); + } + } + } + + // We need to call AddBlockNoValidate but this adds to m_AddedNodes resulting in duplicates + // Therefore we need to clear this list before the view is created + m_AddedNodes.Clear(); + } + } + + var masterNode = m_OutputNode.value as IMasterNode1; + + // This is required for edge lookup during Target upgrade + if (m_OutputNode.value != null) + { + m_OutputNode.value.owner = this; + } + foreach (var edge in m_Edges) + { + AddEdgeToNodeEdges(edge); + } + + // Ensure correct initialization of Contexts + AddContexts(); + + // Position Contexts to the match master node + var oldPosition = Vector2.zero; + if (m_OutputNode.value != null) + { + oldPosition = m_OutputNode.value.drawState.position.position; + } + m_VertexContext.position = oldPosition; + m_FragmentContext.position = new Vector2(oldPosition.x, oldPosition.y + 200); + + // Try to upgrade all valid targets from master node + // On ShaderGraph side we dont know what Targets exist so make no assumptions + if(masterNode != null) + { + foreach(var target in m_ValidTargets) + { + if(!(target is ILegacyTarget legacyTarget)) + continue; + + if(!legacyTarget.TryUpgradeFromMasterNode(masterNode, out var newBlockMap)) + continue; + + m_ActiveTargets.Add(target); + UpgradeFromBlockMap(newBlockMap); + } + } + + // Clean up after upgrade + if(!isSubGraph) + { + m_OutputNode = null; + } + + var masterNodes = GetNodes().ToArray(); + for(int i = 0; i < masterNodes.Length; i++) + { + var node = masterNodes.ElementAt(i) as AbstractMaterialNode; + m_Nodes.Remove(node); + } + + m_NodeEdges.Clear(); + } + + m_Version = k_CurrentVersion; + } + + PooledList<(LegacyUnknownTypeNode, AbstractMaterialNode)> updatedNodes = PooledList<(LegacyUnknownTypeNode,AbstractMaterialNode)>.Get(); + foreach(var node in m_Nodes.SelectValue()) + { + if(node is LegacyUnknownTypeNode lNode && lNode.foundType != null) + { + AbstractMaterialNode legacyNode = (AbstractMaterialNode)Activator.CreateInstance(lNode.foundType); + JsonUtility.FromJsonOverwrite(lNode.serializedData, legacyNode); + legacyNode.group = lNode.group; + updatedNodes.Add((lNode, legacyNode)); + } + } + foreach(var nodePair in updatedNodes) + { + m_Nodes.Add(nodePair.Item2); + ReplaceNodeWithNode(nodePair.Item1, nodePair.Item2); + } + updatedNodes.Dispose(); + m_NodeDictionary = new Dictionary(m_Nodes.Count); foreach (var group in m_GroupDatas.SelectValue()) @@ -1445,6 +1997,7 @@ public override void OnAfterMultiDeserialize(string json) { node.owner = this; node.UpdateNodeAfterDeserialization(); + node.SetupSlots(); m_NodeDictionary.Add(node.objectId, node); if (m_GroupItems.TryGetValue(node.group, out var groupItems)) { @@ -1470,55 +2023,112 @@ public override void OnAfterMultiDeserialize(string json) foreach (var edge in m_Edges) AddEdgeToNodeEdges(edge); - } - public void OnEnable() - { - foreach (var node in GetNodes().OfType()) + // -------------------------------------------------- + // Deserialize Contexts & Blocks + + void DeserializeContextData(ContextData contextData, ShaderStage stage) { - node.OnEnable(); + // Because Vertex/Fragment Contexts are serialized explicitly + // we do not need to serialize the Stage value on the ContextData + contextData.shaderStage = stage; + + var blocks = contextData.blocks.SelectValue().ToList(); + var blockCount = blocks.Count; + for(int i = 0; i < blockCount; i++) + { + // Update NonSerialized data on the BlockNode + var block = blocks[i]; + block.descriptor = m_BlockFieldDescriptors.FirstOrDefault(x => $"{x.tag}.{x.name}" == block.serializedDescriptor); + if(block.descriptor == null) + { + //Hit a descriptor that was not recognized from the assembly (likely from a different SRP) + //create a new entry for it and continue on + if(string.IsNullOrEmpty(block.serializedDescriptor)) + { + throw new Exception($"Block {block} had no serialized descriptor"); + } + + var tmp = block.serializedDescriptor.Split('.'); + if(tmp.Length != 2) + { + throw new Exception($"Block {block}'s serialized descriptor {block.serializedDescriptor} did not match expected format {{x.tag}}.{{x.name}}"); + } + //right thing to do? + block.descriptor = new BlockFieldDescriptor(tmp[0], tmp[1], null, null, stage, true, true); + m_BlockFieldDescriptors.Add(block.descriptor); + } + block.contextData = contextData; + } } - UpdateTargets(); + // First deserialize the ContextDatas + DeserializeContextData(m_VertexContext, ShaderStage.Vertex); + DeserializeContextData(m_FragmentContext, ShaderStage.Fragment); - ShaderGraphPreferences.onVariantLimitChanged += OnKeywordChanged; - } + foreach(var target in m_ActiveTargets.SelectValue()) + { + //need to mark the target as valid just so other logic doesnt break + if(target.GetType() == typeof(MultiJsonInternal.UnknownTargetType)) + { + m_ValidTargets.Add(target); + } + var activeTargetCurrent = m_ValidTargets.FirstOrDefault(x => x.GetType() == target.GetType()); + var targetIndex = m_ValidTargets.IndexOf(activeTargetCurrent); + m_ActiveTargetBitmask = m_ActiveTargetBitmask | (1 << targetIndex); + m_ValidTargets[targetIndex] = target; + } + + UpdateActiveTargets(false); - public void OnDisable() - { - ShaderGraphPreferences.onVariantLimitChanged -= OnKeywordChanged; } - public void UpdateTargets() + private void ReplaceNodeWithNode(LegacyUnknownTypeNode nodeToReplace, AbstractMaterialNode nodeReplacement) { - if(outputNode == null) - return; - - // Clear current Targets - m_ValidTargets.Clear(); + var oldSlots = new List(); + nodeToReplace.GetSlots(oldSlots); + var newSlots = new List(); + nodeReplacement.GetSlots(newSlots); - // SubGraph Target is always PreviewTarget - if(outputNode is SubGraphOutputNode) + for(int i = 0; i < oldSlots.Count; i++) { - m_ValidTargets.Add(new PreviewTarget()); - return; - } - - // Find all valid Targets - var typeCollection = TypeCache.GetTypesDerivedFrom(); - foreach(var type in typeCollection) - { - if(type.IsAbstract || type.IsGenericType || !type.IsClass) - continue; + newSlots[i].CopyValuesFrom(oldSlots[i]); + var oldSlotRef = nodeToReplace.GetSlotReference(oldSlots[i].id); + var newSlotRef = nodeReplacement.GetSlotReference(newSlots[i].id); - var masterNode = outputNode as IMasterNode; - var target = (Target)Activator.CreateInstance(type); - if(!target.isHidden && target.IsValid(masterNode)) + for(int x = 0; x < m_Edges.Count; x++) { - m_ValidTargets.Add(target); + var edge = m_Edges[x]; + if (edge.inputSlot.Equals(oldSlotRef)) + { + var outputSlot = edge.outputSlot; + m_Edges.Remove(edge); + m_Edges.Add(new Edge(outputSlot, newSlotRef)); + } + else if (edge.outputSlot.Equals(oldSlotRef)) + { + var inputSlot = edge.inputSlot; + m_Edges.Remove(edge); + m_Edges.Add(new Edge(newSlotRef, inputSlot)); + } } } } + + public void OnEnable() + { + foreach (var node in GetNodes().OfType()) + { + node.OnEnable(); + } + + ShaderGraphPreferences.onVariantLimitChanged += OnKeywordChanged; + } + + public void OnDisable() + { + ShaderGraphPreferences.onVariantLimitChanged -= OnKeywordChanged; + } } [Serializable] diff --git a/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs b/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs index 42bc474bb24..60a12c311dd 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs @@ -1,3 +1,8 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEditor.Graphing; using UnityEngine; namespace UnityEditor.ShaderGraph @@ -8,11 +13,54 @@ public static class GraphValidation { public static void ValidateNode(AbstractMaterialNode node) { + Type t = node.GetType(); node.ValidateNode(); + if (!(node is BlockNode)) + { + bool disallowedByAnyTargets = false; + bool disallowedByAllTargets = true; + IEnumerable targets = node.owner.activeTargets; + if(node.owner.isSubGraph) + { + targets = node.owner.validTargets; + } + foreach (var target in targets) + { + //if at least one target doesnt allow a node, it is considered invalid + if (!target.IsNodeAllowedByTarget(t)) + { + disallowedByAnyTargets = true; + node.isValid = false; + node.owner.AddValidationError(node.objectId, $"{node.name} Node is not allowed by {target.displayName} implementation", Rendering.ShaderCompilerMessageSeverity.Warning); + node.owner.m_UnsupportedTargets.Add(target); + } + //at least one target does allow node, not going to be explicitly set inactive + else + { + disallowedByAllTargets = false; + } + } + if (!disallowedByAnyTargets) + { + node.isValid = true; + } + + //Set ActiveState based on if all targets disallow this node + if (disallowedByAllTargets) + { + node.SetOverrideActiveState(AbstractMaterialNode.ActiveState.ExplicitInactive); + node.owner.AddValidationError(node.objectId, $"{node.name} Node is not allowed by any active targets, and will not be used in generation", Rendering.ShaderCompilerMessageSeverity.Warning); + } + else + { + node.SetOverrideActiveState(AbstractMaterialNode.ActiveState.Implicit); + } + } } public static void ValidateGraph(GraphData graph) { + graph.m_UnsupportedTargets.Clear(); GraphDataUtils.ApplyActionLeafFirst(graph, ValidateNode); } } diff --git a/com.unity.shadergraph/Editor/Data/Graphs/MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/MaterialSlot.cs index 947bb368a70..312b2b391aa 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/MaterialSlot.cs @@ -220,6 +220,8 @@ public bool isConnected } } + public abstract bool isDefaultValue { get; } + public abstract SlotValueType valueType { get; } public abstract ConcreteSlotValueType concreteValueType { get; } @@ -242,6 +244,14 @@ public bool hasError set { m_HasError = value; } } + public bool IsUsingDefaultValue() + { + if (!isConnected && isDefaultValue) + return true; + else + return false; + } + public bool IsCompatibleWith(MaterialSlot otherSlot) { return otherSlot != null @@ -270,7 +280,7 @@ public virtual string GetDefaultValue(GenerationMode generationMode) if (matOwner == null) throw new Exception(string.Format("Slot {0} either has no owner, or the owner is not a {1}", this, typeof(AbstractMaterialNode))); - if (generationMode.IsPreview()) + if (generationMode.IsPreview() && matOwner.isActive) return matOwner.GetVariableNameForSlot(id); return ConcreteSlotValueAsVariable(); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Matrix2MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Matrix2MaterialSlot.cs index 6b1a303c169..8a4880c537a 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Matrix2MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Matrix2MaterialSlot.cs @@ -46,6 +46,8 @@ public Matrix4x4 value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + protected override string ConcreteSlotValueAsVariable() { return "$precision2x2 (1,0,0,1)"; diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Matrix3MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Matrix3MaterialSlot.cs index b947f62352f..dcec32d0de4 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Matrix3MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Matrix3MaterialSlot.cs @@ -45,6 +45,8 @@ public Matrix4x4 value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + protected override string ConcreteSlotValueAsVariable() { return "$precision3x3 (1,0,0,0,1,0,0,0,1)"; diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Matrix4MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Matrix4MaterialSlot.cs index d03d516f378..63fcfa5dc0e 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Matrix4MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Matrix4MaterialSlot.cs @@ -45,6 +45,8 @@ public Matrix4x4 value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + protected override string ConcreteSlotValueAsVariable() { return "$precision4x4 (1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)"; diff --git a/com.unity.shadergraph/Editor/Data/Graphs/MinimalGraphData.cs b/com.unity.shadergraph/Editor/Data/Graphs/MinimalGraphData.cs index a064c26bdcb..a81a55f8037 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/MinimalGraphData.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/MinimalGraphData.cs @@ -4,6 +4,7 @@ using System.Reflection; using System.Text; using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Legacy; using UnityEditor.ShaderGraph.Serialization; using UnityEngine; @@ -67,6 +68,12 @@ public static void GetDependencyPaths(string assetPath, List dependencie foreach (var node in minimalGraphData.m_SerializableNodes) { entries.Add(new MultiJsonEntry(node.typeInfo.fullName, null, node.JSONnodeData)); + AbstractMaterialNode0 amn = new AbstractMaterialNode0(); + JsonUtility.FromJsonOverwrite(node.JSONnodeData, amn); + foreach(var slot in amn.m_SerializableSlots) + { + entries.Add(new MultiJsonEntry(slot.typeInfo.fullName, null, slot.JSONnodeData)); + } } } diff --git a/com.unity.shadergraph/Editor/Data/Graphs/SamplerStateMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/SamplerStateMaterialSlot.cs index 3c821da82fb..75a559d8ef5 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/SamplerStateMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/SamplerStateMaterialSlot.cs @@ -32,6 +32,8 @@ public override string GetDefaultValue(GenerationMode generationMode) public override SlotValueType valueType { get { return SlotValueType.SamplerState; } } public override ConcreteSlotValueType concreteValueType { get { return ConcreteSlotValueType.SamplerState; } } + public override bool isDefaultValue => true; + public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode) { var matOwner = owner as AbstractMaterialNode; diff --git a/com.unity.shadergraph/Editor/Data/Graphs/ScreenPositionMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/ScreenPositionMaterialSlot.cs index e3147400af6..8a82b84b6e0 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/ScreenPositionMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/ScreenPositionMaterialSlot.cs @@ -18,6 +18,8 @@ public ScreenSpaceType screenSpaceType set { m_ScreenSpaceType = value; } } + public override bool isDefaultValue => screenSpaceType == ScreenSpaceType.Default; + public ScreenPositionMaterialSlot() {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayInputMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayInputMaterialSlot.cs index d263721c184..843b30983d4 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayInputMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayInputMaterialSlot.cs @@ -20,6 +20,8 @@ public Texture2DArray textureArray set { m_TextureArray.textureArray = value; } } + public override bool isDefaultValue => textureArray == null; + public Texture2DArrayInputMaterialSlot() {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayMaterialSlot.cs index db47994662d..b730cec9dc3 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayMaterialSlot.cs @@ -21,6 +21,7 @@ public Texture2DArrayMaterialSlot( public override SlotValueType valueType { get { return SlotValueType.Texture2DArray; } } public override ConcreteSlotValueType concreteValueType { get { return ConcreteSlotValueType.Texture2DArray; } } + public override bool isDefaultValue => true; public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode) {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Texture2DInputMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Texture2DInputMaterialSlot.cs index 3ece4a10a5e..7d45e1f54f4 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Texture2DInputMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Texture2DInputMaterialSlot.cs @@ -29,6 +29,8 @@ public Texture2DShaderProperty.DefaultType defaultType set { m_DefaultType = value; } } + public override bool isDefaultValue => texture == null; + public Texture2DInputMaterialSlot() {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Texture2DMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Texture2DMaterialSlot.cs index de4802d4288..c4296afe354 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Texture2DMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Texture2DMaterialSlot.cs @@ -21,6 +21,7 @@ public Texture2DMaterialSlot( public override SlotValueType valueType { get { return SlotValueType.Texture2D; } } public override ConcreteSlotValueType concreteValueType { get { return ConcreteSlotValueType.Texture2D; } } + public override bool isDefaultValue => true; public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode) {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Texture3DInputMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Texture3DInputMaterialSlot.cs index cbfcb80cbf4..8533b7319bd 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Texture3DInputMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Texture3DInputMaterialSlot.cs @@ -20,6 +20,8 @@ public Texture texture set { m_Texture.texture = value; } } + public override bool isDefaultValue => texture == null; + public Texture3DInputMaterialSlot() {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Texture3DMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Texture3DMaterialSlot.cs index c26e03af688..a9b04c0bbab 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Texture3DMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Texture3DMaterialSlot.cs @@ -21,6 +21,7 @@ public Texture3DMaterialSlot( public override SlotValueType valueType { get { return SlotValueType.Texture3D; } } public override ConcreteSlotValueType concreteValueType { get { return ConcreteSlotValueType.Texture3D; } } + public override bool isDefaultValue => true; public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode) {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/UVMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/UVMaterialSlot.cs index 89727c988a5..f67169c78cb 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/UVMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/UVMaterialSlot.cs @@ -19,6 +19,8 @@ public UVChannel channel set { m_Channel = value; } } + public override bool isDefaultValue => channel == UVChannel.UV0; + public UVMaterialSlot() {} diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Vector1MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Vector1MaterialSlot.cs index 2304331cda6..14c54793bcd 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Vector1MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Vector1MaterialSlot.cs @@ -48,6 +48,8 @@ public float value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + public override VisualElement InstantiateControl() { return new MultiFloatSlotControlView(owner, m_Labels, () => new Vector4(value, 0f, 0f, 0f), (newValue) => value = newValue.x); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Vector2MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Vector2MaterialSlot.cs index 36e7e34aed3..b82a8f02300 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Vector2MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Vector2MaterialSlot.cs @@ -48,6 +48,8 @@ public Vector2 value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + public override VisualElement InstantiateControl() { return new MultiFloatSlotControlView(owner, m_Labels, () => value, (newValue) => value = newValue); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Vector3MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Vector3MaterialSlot.cs index 1c67f61e3b0..58a97d8033d 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Vector3MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Vector3MaterialSlot.cs @@ -49,6 +49,8 @@ public Vector3 value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + public override VisualElement InstantiateControl() { return new MultiFloatSlotControlView(owner, m_Labels, () => value, (newValue) => value = newValue); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Vector4MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Vector4MaterialSlot.cs index 26584b098c3..c3d2c12ff9a 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Vector4MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Vector4MaterialSlot.cs @@ -50,6 +50,8 @@ public Vector4 value set { m_Value = value; } } + public override bool isDefaultValue => value.Equals(defaultValue); + public override VisualElement InstantiateControl() { return new MultiFloatSlotControlView(owner, m_Labels, () => value, (newValue) => value = newValue); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/VirtualTextureMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/VirtualTextureMaterialSlot.cs index 5b31afa58ce..a9b343a16f7 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/VirtualTextureMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/VirtualTextureMaterialSlot.cs @@ -29,5 +29,7 @@ public override void AddDefaultProperty(PropertyCollector properties, Generation public override void CopyValuesFrom(MaterialSlot foundSlot) { } + + public override bool isDefaultValue => throw new Exception(); } } diff --git a/com.unity.shadergraph/Editor/Data/Implementation/NodeUtils.cs b/com.unity.shadergraph/Editor/Data/Implementation/NodeUtils.cs index 78d8f4acb19..467ea5afad3 100644 --- a/com.unity.shadergraph/Editor/Data/Implementation/NodeUtils.cs +++ b/com.unity.shadergraph/Editor/Data/Implementation/NodeUtils.cs @@ -101,7 +101,7 @@ public static SlotReference DepthFirstCollectRedirectNodeFromNode(RedirectNodeDa } public static void DepthFirstCollectNodesFromNode(List nodeList, AbstractMaterialNode node, - IncludeSelf includeSelf = IncludeSelf.Include, IEnumerable slotIds = null, List> keywordPermutation = null) + IncludeSelf includeSelf = IncludeSelf.Include, List> keywordPermutation = null) { // no where to start if (node == null) @@ -120,13 +120,9 @@ public static void DepthFirstCollectNodesFromNode(List nod var valueInPermutation = keywordPermutation.Where(x => x.Key == keywordNode.keyword).FirstOrDefault(); ids = new int[] { keywordNode.GetSlotIdForPermutation(valueInPermutation) }; } - else if (slotIds == null) - { - ids = node.GetInputSlots().Select(x => x.id); - } else { - ids = node.GetInputSlots().Where(x => slotIds.Contains(x.id)).Select(x => x.id); + ids = node.GetInputSlots().Select(x => x.id); } foreach (var slot in ids) @@ -139,7 +135,245 @@ public static void DepthFirstCollectNodesFromNode(List nod } } - if (includeSelf == IncludeSelf.Include) + if (includeSelf == IncludeSelf.Include && node.isActive) + nodeList.Add(node); + } + + private static List GetParentNodes(AbstractMaterialNode node) + { + List nodeList = new List(); + var ids = node.GetInputSlots().Select(x => x.id); + foreach (var slot in ids) + { + foreach (var edge in node.owner.GetEdges(node.FindSlot(slot).slotReference)) + { + var outputNode = ((Edge)edge).outputSlot.node; + if (outputNode != null) + { + nodeList.Add(outputNode); + } + } + } + return nodeList; + } + + private static bool ActiveLeafExists(AbstractMaterialNode node) + { + //if our active state has been explicitly set to a value use it + switch (node.activeState) + { + case AbstractMaterialNode.ActiveState.Implicit: + break; + case AbstractMaterialNode.ActiveState.ExplicitInactive: + return false; + case AbstractMaterialNode.ActiveState.ExplicitActive: + return true; + } + + + + List parentNodes = GetParentNodes(node); + //at this point we know we are not explicitly set to a state, + //so there is no reason to be inactive + if(parentNodes.Count == 0) + { + return true; + } + + bool output = false; + foreach(var parent in parentNodes) + { + output |= ActiveLeafExists(parent); + if(output) + { + break; + } + } + return output; + } + + + private static List GetChildNodes(AbstractMaterialNode node) + { + List nodeList = new List(); + var ids = node.GetOutputSlots().Select(x => x.id); + foreach (var slot in ids) + { + foreach (var edge in node.owner.GetEdges(node.FindSlot(slot).slotReference)) + { + var inputNode = ((Edge)edge).inputSlot.node; + if (inputNode != null) + { + nodeList.Add(inputNode); + } + } + } + return nodeList; + } + + private static bool ActiveRootExists(AbstractMaterialNode node) + { + //if our active state has been explicitly set to a value use it + switch (node.activeState) + { + case AbstractMaterialNode.ActiveState.Implicit: + break; + case AbstractMaterialNode.ActiveState.ExplicitInactive: + return false; + case AbstractMaterialNode.ActiveState.ExplicitActive: + return true; + } + + List childNodes = GetChildNodes(node); + //at this point we know we are not explicitly set to a state, + //so there is no reason to be inactive + if (childNodes.Count == 0) + { + return true; + } + + bool output = false; + foreach (var child in childNodes) + { + output |= ActiveRootExists(child); + if (output) + { + break; + } + } + return output; + + } + + private static void ActiveTreeExists(AbstractMaterialNode node, out bool activeLeaf, out bool activeRoot, out bool activeTree) + { + activeLeaf = ActiveLeafExists(node); + activeRoot = ActiveRootExists(node); + activeTree = activeRoot && activeLeaf; + } + + //First pass check if node is now active after a change, so just check if there is a valid "tree" : a valid upstream input path, + // and a valid downstream output path, or "leaf" and "root". If this changes the node's active state, then anything connected may + // change as well, so update the "forrest" or all connectected trees of this nodes leaves. + // NOTE: I cannot think if there is any case where the entirety of the connected graph would need to change, but if there are bugs + // on certain nodes farther away from the node not updating correctly, a possible solution may be to get the entirety of the connected + // graph instead of just what I have declared as the "local" connected graph + public static void ReevaluateActivityOfConnectedNodes(AbstractMaterialNode node, PooledHashSet changedNodes = null) + { + List forest = GetForest(node); + ReevaluateActivityOfNodeList(forest, changedNodes); + } + + public static void ReevaluateActivityOfNodeList(IEnumerable nodes, PooledHashSet changedNodes = null) + { + bool getChangedNodes = changedNodes != null; + foreach(AbstractMaterialNode n in nodes) + { + if (n.activeState != AbstractMaterialNode.ActiveState.Implicit) + continue; + ActiveTreeExists(n, out _, out _, out bool at); + if(n.isActive != at && getChangedNodes) + { + changedNodes.Add(n); + } + n.SetActive(at, false); + } + + } + + //Go to the leaves of the node, then get all trees with those leaves + private static List GetForest(AbstractMaterialNode node) + { + List leaves = GetLeaves(node); + List forrest = new List(); + foreach(var leaf in leaves) + { + if(!forrest.Contains(leaf)) + { + forrest.Add(leaf); + } + foreach(var child in GetChildNodesRecursive(leaf)) + { + if(!forrest.Contains(child)) + { + forrest.Add(child); + } + } + } + return forrest; + } + + private static List GetChildNodesRecursive(AbstractMaterialNode node) + { + List output = new List() { node }; + List children = GetChildNodes(node); + foreach(var child in children) + { + if(!output.Contains(child)) + { + output.Add(child); + } + foreach(var descendent in GetChildNodesRecursive(child)) + { + if(!output.Contains(descendent)) + { + output.Add(descendent); + } + } + } + return output; + } + + private static List GetLeaves(AbstractMaterialNode node) + { + List parents = GetParentNodes(node); + List output = new List(); + if(parents.Count == 0) + { + output.Add(node); + } + else + { + foreach(var parent in parents) + { + foreach(var leaf in GetLeaves(parent)) + { + if(!output.Contains(leaf)) + { + output.Add(leaf); + } + } + } + } + return output; + } + + public static void GetDownsteamNodesForNode(List nodeList, AbstractMaterialNode node) + { + // no where to start + if (node == null) + return; + + // Recursively traverse downstream from the original node + // Traverse down each edge and continue on any connected downstream nodes + // Only nodes with no nodes further downstream are added to node list + bool hasDownstream = false; + var ids = node.GetOutputSlots().Select(x => x.id); + foreach (var slot in ids) + { + foreach (var edge in node.owner.GetEdges(node.FindSlot(slot).slotReference)) + { + var inputNode = ((Edge)edge).inputSlot.node; + if (inputNode != null) + { + hasDownstream = true; + GetDownsteamNodesForNode(nodeList, inputNode); + } + } + } + + // No more nodes downstream from here + if(!hasDownstream) nodeList.Add(node); } diff --git a/com.unity.shadergraph/Editor/Data/Interfaces/IHasSettings.cs b/com.unity.shadergraph/Editor/Data/Interfaces/IHasSettings.cs deleted file mode 100644 index 257bbb69a12..00000000000 --- a/com.unity.shadergraph/Editor/Data/Interfaces/IHasSettings.cs +++ /dev/null @@ -1,9 +0,0 @@ -using UnityEngine.UIElements; - -namespace UnityEditor.Graphing -{ - interface IHasSettings - { - VisualElement CreateSettingsElement(); - } -} diff --git a/com.unity.shadergraph/Editor/Data/Interfaces/IHasSettings.cs.meta b/com.unity.shadergraph/Editor/Data/Interfaces/IHasSettings.cs.meta deleted file mode 100644 index aca0cf41f9d..00000000000 --- a/com.unity.shadergraph/Editor/Data/Interfaces/IHasSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: aaccc11846e23c84093c0d6780172063 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Interfaces/IInspectable.cs b/com.unity.shadergraph/Editor/Data/Interfaces/IInspectable.cs index 950b179fd1a..8b2ae83427f 100644 --- a/com.unity.shadergraph/Editor/Data/Interfaces/IInspectable.cs +++ b/com.unity.shadergraph/Editor/Data/Interfaces/IInspectable.cs @@ -1,25 +1,23 @@ -using System; -using System.Reflection; -using Data.Interfaces; -using Drawing.Inspector; -using UnityEngine.UIElements; - -namespace UnityEditor.ShaderGraph.Drawing -{ - interface IInspectable - { - // Implementors can override this in order to display their desired string when selected and viewed through the inscetor - string inspectorTitle { get; } - - // This function should return the underlying data object that user wishes to expose to the Inspector - object GetObjectToInspect(); - - // This function should return the property information of whatever object has been marked up for metadata gathering by the inspector - // This might be the same as the object returned by GetObjectToInspect(), it might not - PropertyInfo[] GetPropertyInfo(); - - // Used to provide any data needed by the property drawer from the inspectable - // The inspectorUpdateDelegate is used to trigger an inspector update - void SupplyDataToPropertyDrawer(IPropertyDrawer propertyDrawer, Action inspectorUpdateDelegate); - } -} +using System; +using System.Reflection; +using Data.Interfaces; +using Drawing.Inspector; +using UnityEngine.UIElements; + +namespace UnityEditor.ShaderGraph.Drawing +{ + interface IInspectable + { + // Implementors can override this in order to display their desired string when selected and viewed through the inspector + string inspectorTitle { get; } + + // This function should return the underlying data object that user wishes to expose to the Inspector + // For simple data properties like Integers/Floats this is the object that contains the properties + // For complex types like GraphData this is the GraphData itself, its up to the PropertyDrawer to define what it needs + object GetObjectToInspect(); + + // Used to provide any data needed by the property drawer from the inspectable + // The inspectorUpdateDelegate is used to trigger an inspector update + void SupplyDataToPropertyDrawer(IPropertyDrawer propertyDrawer, Action inspectorUpdateDelegate); + } +} diff --git a/com.unity.shadergraph/Editor/Data/Legacy/ILegacyTarget.cs b/com.unity.shadergraph/Editor/Data/Legacy/ILegacyTarget.cs new file mode 100644 index 00000000000..b15906d0ff4 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/ILegacyTarget.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace UnityEditor.ShaderGraph.Legacy +{ + internal interface ILegacyTarget + { + bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap); + } +} diff --git a/com.unity.shadergraph/Editor/Data/Legacy/ILegacyTarget.cs.meta b/com.unity.shadergraph/Editor/Data/Legacy/ILegacyTarget.cs.meta new file mode 100644 index 00000000000..107090a0fd2 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/ILegacyTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0af67b17919f687478340e3af5ea9a52 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Legacy/IMasterNode1.cs b/com.unity.shadergraph/Editor/Data/Legacy/IMasterNode1.cs new file mode 100644 index 00000000000..e780021561b --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/IMasterNode1.cs @@ -0,0 +1,6 @@ +namespace UnityEditor.ShaderGraph.Legacy +{ + public interface IMasterNode1 + { + } +} diff --git a/com.unity.shadergraph/Editor/Data/Legacy/IMasterNode1.cs.meta b/com.unity.shadergraph/Editor/Data/Legacy/IMasterNode1.cs.meta new file mode 100644 index 00000000000..b80b06d80d5 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/IMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 17362586a4e694d44881897b8a642dcc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Legacy/PBRMasterNode1.cs b/com.unity.shadergraph/Editor/Data/Legacy/PBRMasterNode1.cs new file mode 100644 index 00000000000..63c831bda96 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/PBRMasterNode1.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; + +namespace UnityEditor.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.ShaderGraph.PBRMasterNode")] + class PBRMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public enum SurfaceType + { + Opaque, + Transparent + } + + public enum AlphaMode + { + Alpha, + Premultiply, + Additive, + Multiply + } + + public enum Model + { + Specular, + Metallic + } + + public Model m_Model; + public SurfaceType m_SurfaceType; + public AlphaMode m_AlphaMode; + public bool m_TwoSided; + public NormalDropOffSpace m_NormalDropOffSpace; + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + } +} diff --git a/com.unity.shadergraph/Editor/Data/Legacy/PBRMasterNode1.cs.meta b/com.unity.shadergraph/Editor/Data/Legacy/PBRMasterNode1.cs.meta new file mode 100644 index 00000000000..95ba6684b60 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/PBRMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4085c56d69533334f969abdbd775c7fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Legacy/SpriteLitMasterNode1.cs b/com.unity.shadergraph/Editor/Data/Legacy/SpriteLitMasterNode1.cs new file mode 100644 index 00000000000..7e5dcef55e2 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/SpriteLitMasterNode1.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; + +namespace UnityEditor.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.Experimental.Rendering.Universal.SpriteLitMasterNode")] + [FormerName("UnityEditor.Experimental.Rendering.LWRP.SpriteLitMasterNode")] + class SpriteLitMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + } +} diff --git a/com.unity.shadergraph/Editor/Data/Legacy/SpriteLitMasterNode1.cs.meta b/com.unity.shadergraph/Editor/Data/Legacy/SpriteLitMasterNode1.cs.meta new file mode 100644 index 00000000000..8dbb8047964 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/SpriteLitMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fe59c334e540aec4a85baa797cb6783b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Legacy/SpriteUnlitMasterNode1.cs b/com.unity.shadergraph/Editor/Data/Legacy/SpriteUnlitMasterNode1.cs new file mode 100644 index 00000000000..bb6bfe9daf7 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/SpriteUnlitMasterNode1.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; + +namespace UnityEditor.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.Experimental.Rendering.Universal.SpriteUnlitMasterNode")] + [FormerName("UnityEditor.Experimental.Rendering.LWRP.SpriteUnlitMasterNode")] + class SpriteUnlitMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + } +} diff --git a/com.unity.shadergraph/Editor/Data/Legacy/SpriteUnlitMasterNode1.cs.meta b/com.unity.shadergraph/Editor/Data/Legacy/SpriteUnlitMasterNode1.cs.meta new file mode 100644 index 00000000000..ff16196618b --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/SpriteUnlitMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3de89e7ea2afdda4ab5d861d4ab2e329 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Legacy/UnlitMasterNode1.cs b/com.unity.shadergraph/Editor/Data/Legacy/UnlitMasterNode1.cs new file mode 100644 index 00000000000..919bc5b0589 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/UnlitMasterNode1.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; + +namespace UnityEditor.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.ShaderGraph.UnlitMasterNode")] + class UnlitMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public enum SurfaceType + { + Opaque, + Transparent + } + + public enum AlphaMode + { + Alpha, + Premultiply, + Additive, + Multiply + } + + public SurfaceType m_SurfaceType; + public AlphaMode m_AlphaMode; + public bool m_TwoSided; + public string m_ShaderGUIOverride; + public bool m_OverrideEnabled; + } +} diff --git a/com.unity.shadergraph/Editor/Data/Legacy/UnlitMasterNode1.cs.meta b/com.unity.shadergraph/Editor/Data/Legacy/UnlitMasterNode1.cs.meta new file mode 100644 index 00000000000..715b0b6bbd3 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/UnlitMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 39ad335ce87d56147a9fe6d5a6b99d36 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Legacy/VisualEffectMasterNode1.cs b/com.unity.shadergraph/Editor/Data/Legacy/VisualEffectMasterNode1.cs new file mode 100644 index 00000000000..c27d84718a8 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/VisualEffectMasterNode1.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; + +namespace UnityEditor.ShaderGraph.Legacy +{ + [FormerName("UnityEditor.ShaderGraph.VfxMasterNode")] + class VisualEffectMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public bool m_Lit; + public bool m_AlphaTest; + } +} diff --git a/com.unity.shadergraph/Editor/Data/Legacy/VisualEffectMasterNode1.cs.meta b/com.unity.shadergraph/Editor/Data/Legacy/VisualEffectMasterNode1.cs.meta new file mode 100644 index 00000000000..ec5f1a89c97 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Legacy/VisualEffectMasterNode1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7e471432479a086428e900f698b3d96c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/AlphaMode.cs b/com.unity.shadergraph/Editor/Data/MasterNodes/AlphaMode.cs deleted file mode 100644 index 57f13174275..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/AlphaMode.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace UnityEditor.ShaderGraph -{ - enum SurfaceType - { - Opaque, - Transparent - } - - enum AlphaMode - { - Alpha, - Premultiply, - Additive, - Multiply - } -} diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/AlphaMode.cs.meta b/com.unity.shadergraph/Editor/Data/MasterNodes/AlphaMode.cs.meta deleted file mode 100644 index 0880ea1d578..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/AlphaMode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 05d113c37ee6ad24cbd4b11bbaab371f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/DistortionMode.cs b/com.unity.shadergraph/Editor/Data/MasterNodes/DistortionMode.cs deleted file mode 100644 index 73889e0616f..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/DistortionMode.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace UnityEditor.ShaderGraph -{ - enum DistortionMode - { - Add, - Multiply, - Replace - } -} diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/DistortionMode.cs.meta b/com.unity.shadergraph/Editor/Data/MasterNodes/DistortionMode.cs.meta deleted file mode 100644 index 8e2d60425df..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/DistortionMode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: eb944a5bac991ef4ea8ac032544285d3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/DoubleSidedMode.cs b/com.unity.shadergraph/Editor/Data/MasterNodes/DoubleSidedMode.cs deleted file mode 100644 index 69db7af610e..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/DoubleSidedMode.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace UnityEditor.ShaderGraph -{ - enum DoubleSidedMode - { - Disabled, - Enabled, - FlippedNormals, - MirroredNormals, - } -} diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/DoubleSidedMode.cs.meta b/com.unity.shadergraph/Editor/Data/MasterNodes/DoubleSidedMode.cs.meta deleted file mode 100644 index 9375cfcb1a1..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/DoubleSidedMode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 86dd83ebad5d7f34fb6714a01992d4ea -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/EmissionGIMode.cs b/com.unity.shadergraph/Editor/Data/MasterNodes/EmissionGIMode.cs deleted file mode 100644 index 3495d71ff03..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/EmissionGIMode.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace UnityEditor.ShaderGraph -{ - enum EmissionGIMode - { - Disabled, - Realtime, - Baked, - } -} diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/EmissionGIMode.cs.meta b/com.unity.shadergraph/Editor/Data/MasterNodes/EmissionGIMode.cs.meta deleted file mode 100644 index 3db00d345cd..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/EmissionGIMode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 29c3a6d9896aa9b4dad615133f9de841 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/PBRMasterNode.cs b/com.unity.shadergraph/Editor/Data/MasterNodes/PBRMasterNode.cs deleted file mode 100644 index 75b3922123a..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/PBRMasterNode.cs +++ /dev/null @@ -1,345 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEditor.ShaderGraph.Internal; -using UnityEngine; -using UnityEngine.UIElements; - -namespace UnityEditor.ShaderGraph -{ - [Serializable] - [Title("Master", "PBR")] - class PBRMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string AlbedoSlotName = "Albedo"; - public const string NormalSlotName = "Normal"; - public const string EmissionSlotName = "Emission"; - public const string MetallicSlotName = "Metallic"; - public const string SpecularSlotName = "Specular"; - public const string SmoothnessSlotName = "Smoothness"; - public const string OcclusionSlotName = "Occlusion"; - public const string AlphaSlotName = "Alpha"; - public const string AlphaClipThresholdSlotName = "AlphaClipThreshold"; - public const string PositionName = "Vertex Position"; - public const string NormalName = "Vertex Normal"; - public const string TangentName = "Vertex Tangent"; - - public const int AlbedoSlotId = 0; - public const int NormalSlotId = 1; - public const int MetallicSlotId = 2; - public const int SpecularSlotId = 3; - public const int EmissionSlotId = 4; - public const int SmoothnessSlotId = 5; - public const int OcclusionSlotId = 6; - public const int AlphaSlotId = 7; - public const int AlphaThresholdSlotId = 8; - public const int PositionSlotId = 9; - public const int VertNormalSlotId = 10; - public const int VertTangentSlotId = 11; - - public enum Model - { - Specular, - Metallic - } - - [SerializeField] - Model m_Model = Model.Metallic; - - public Model model - { - get { return m_Model; } - set - { - if (m_Model == value) - return; - - m_Model = value; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - SurfaceType m_SurfaceType; - - public SurfaceType surfaceType - { - get { return m_SurfaceType; } - set - { - if (m_SurfaceType == value) - return; - - m_SurfaceType = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - AlphaMode m_AlphaMode; - - public AlphaMode alphaMode - { - get { return m_AlphaMode; } - set - { - if (m_AlphaMode == value) - return; - - m_AlphaMode = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_TwoSided; - - public ToggleData twoSided - { - get { return new ToggleData(m_TwoSided); } - set - { - if (m_TwoSided == value.isOn) - return; - m_TwoSided = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - NormalDropOffSpace m_NormalDropOffSpace; - public NormalDropOffSpace normalDropOffSpace - { - get { return m_NormalDropOffSpace; } - set - { - if (m_NormalDropOffSpace == value) - return; - - m_NormalDropOffSpace = value; - if(!IsSlotConnected(NormalSlotId)) - updateNormalSlot = true; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - bool updateNormalSlot; - - [SerializeField] - bool m_DOTSInstancing = false; - - public ToggleData dotsInstancing - { - get { return new ToggleData(m_DOTSInstancing); } - set - { - if (m_DOTSInstancing == value.isOn) - return; - - m_DOTSInstancing = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public PBRMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "PBR Master"; - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionName, PositionName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new NormalMaterialSlot(VertNormalSlotId, NormalName, NormalName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new TangentMaterialSlot(VertTangentSlotId, TangentName, TangentName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new ColorRGBMaterialSlot(AlbedoSlotId, AlbedoSlotName, AlbedoSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); - var coordSpace = CoordinateSpace.Tangent; - if (updateNormalSlot) - { - RemoveSlot(NormalSlotId); - //switch drop off delivery space for normal values - switch (m_NormalDropOffSpace) - { - case NormalDropOffSpace.Tangent: - coordSpace = CoordinateSpace.Tangent; - break; - case NormalDropOffSpace.World: - coordSpace = CoordinateSpace.World; - break; - case NormalDropOffSpace.Object: - coordSpace = CoordinateSpace.Object; - break; - } - updateNormalSlot = false; - } - AddSlot(new NormalMaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, coordSpace, ShaderStageCapability.Fragment)); - AddSlot(new ColorRGBMaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Color.black, ColorMode.Default, ShaderStageCapability.Fragment)); - if (model == Model.Metallic) - AddSlot(new Vector1MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, 0, ShaderStageCapability.Fragment)); - else - AddSlot(new ColorRGBMaterialSlot(SpecularSlotId, SpecularSlotName, SpecularSlotName, SlotType.Input, Color.grey, ColorMode.Default, ShaderStageCapability.Fragment)); - AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - AddSlot(new Vector1MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input, 1f, ShaderStageCapability.Fragment)); - AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1f, ShaderStageCapability.Fragment)); - AddSlot(new Vector1MaterialSlot(AlphaThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - - // clear out slot names that do not match the slots - // we support - RemoveSlotsNameNotMatching( - new[] - { - PositionSlotId, - VertNormalSlotId, - VertTangentSlotId, - AlbedoSlotId, - NormalSlotId, - EmissionSlotId, - model == Model.Metallic ? MetallicSlotId : SpecularSlotId, - SmoothnessSlotId, - OcclusionSlotId, - AlphaSlotId, - AlphaThresholdSlotId - }, true); - } - - public VisualElement CreateSettingsElement() - { - return new PBRSettingsView(this); - } - - public string renderQueueTag - { - get - { - if(surfaceType == SurfaceType.Transparent) - return $"{RenderQueue.Transparent}"; - else if(IsSlotConnected(UnlitMasterNode.AlphaThresholdSlotId) || FindSlot(AlphaThresholdSlotId).value > 0.0f) - return $"{RenderQueue.AlphaTest}"; - else - return $"{RenderQueue.Geometry}"; - } - } - - public string renderTypeTag - { - get - { - if(surfaceType == SurfaceType.Transparent) - return $"{RenderType.Transparent}"; - else - return $"{RenderType.Opaque}"; - } - } - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PBRMasterNode.PositionSlotId) || - IsSlotConnected(PBRMasterNode.VertNormalSlotId) || - IsSlotConnected(PBRMasterNode.VertTangentSlotId)), - new ConditionalField(Fields.GraphPixel, true), - - // Surface Type - new ConditionalField(Fields.SurfaceOpaque, surfaceType == ShaderGraph.SurfaceType.Opaque), - new ConditionalField(Fields.SurfaceTransparent, surfaceType != ShaderGraph.SurfaceType.Opaque), - - // Blend Mode - new ConditionalField(Fields.BlendAdd, surfaceType != ShaderGraph.SurfaceType.Opaque && alphaMode == AlphaMode.Additive), - new ConditionalField(Fields.BlendAlpha, surfaceType != ShaderGraph.SurfaceType.Opaque && alphaMode == AlphaMode.Alpha), - new ConditionalField(Fields.BlendMultiply, surfaceType != ShaderGraph.SurfaceType.Opaque && alphaMode == AlphaMode.Multiply), - new ConditionalField(Fields.BlendPremultiply, surfaceType != ShaderGraph.SurfaceType.Opaque && alphaMode == AlphaMode.Premultiply), - - // Normal Drop Off Space - new ConditionalField(Fields.NormalDropOffOS, normalDropOffSpace == NormalDropOffSpace.Object), - new ConditionalField(Fields.NormalDropOffTS, normalDropOffSpace == NormalDropOffSpace.Tangent), - new ConditionalField(Fields.NormalDropOffWS, normalDropOffSpace == NormalDropOffSpace.World), - - // Misc - new ConditionalField(Fields.AlphaClip, IsSlotConnected(UnlitMasterNode.AlphaThresholdSlotId) || - FindSlot(AlphaThresholdSlotId).value > 0.0f), - new ConditionalField(Fields.AlphaTest, IsSlotConnected(UnlitMasterNode.AlphaThresholdSlotId) || - FindSlot(AlphaThresholdSlotId).value > 0.0f), - new ConditionalField(Fields.SpecularSetup, model == PBRMasterNode.Model.Specular), - new ConditionalField(Fields.Normal, IsSlotConnected(PBRMasterNode.NormalSlotId)), - new ConditionalField(Fields.DoubleSided, twoSided.isOn), - }; - } - - public void ProcessPreviewMaterial(Material material) - { - - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); - } - - public bool supportsVirtualTexturing => true; - } -} diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/PBRMasterNode.cs.meta b/com.unity.shadergraph/Editor/Data/MasterNodes/PBRMasterNode.cs.meta deleted file mode 100644 index 704887988bb..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/PBRMasterNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ea7519738e2a9b4469abbff8d5c4d657 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/SpecularOcclusionMode.cs b/com.unity.shadergraph/Editor/Data/MasterNodes/SpecularOcclusionMode.cs deleted file mode 100644 index a581298c9ff..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/SpecularOcclusionMode.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace UnityEditor.ShaderGraph -{ - enum SpecularOcclusionMode - { - Off, - FromAO, - FromAOAndBentNormal, - Custom - } -} diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/SpecularOcclusionMode.cs.meta b/com.unity.shadergraph/Editor/Data/MasterNodes/SpecularOcclusionMode.cs.meta deleted file mode 100644 index fc7640b865a..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/SpecularOcclusionMode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 24b31303b6f59144092900b5b71ef81c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/UnlitMasterNode.cs b/com.unity.shadergraph/Editor/Data/MasterNodes/UnlitMasterNode.cs deleted file mode 100644 index edda64926ee..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/UnlitMasterNode.cs +++ /dev/null @@ -1,268 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEditor.ShaderGraph.Internal; -using UnityEngine; -using UnityEngine.UIElements; - -namespace UnityEditor.ShaderGraph -{ - [Serializable] - [Title("Master", "Unlit")] - class UnlitMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, ICanChangeShaderGUI, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent - { - public const string ColorSlotName = "Color"; - public const string AlphaSlotName = "Alpha"; - public const string AlphaClipThresholdSlotName = "AlphaClipThreshold"; - public const string PositionName = "Vertex Position"; - public const string NormalName = "Vertex Normal"; - public const string TangentName = "Vertex Tangent"; - - public const int ColorSlotId = 0; - public const int AlphaSlotId = 7; - public const int AlphaThresholdSlotId = 8; - public const int PositionSlotId = 9; - public const int VertNormalSlotId = 10; - public const int VertTangentSlotId = 11; - - [SerializeField] - SurfaceType m_SurfaceType; - - public SurfaceType surfaceType - { - get { return m_SurfaceType; } - set - { - if (m_SurfaceType == value) - return; - - m_SurfaceType = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - AlphaMode m_AlphaMode; - - public AlphaMode alphaMode - { - get { return m_AlphaMode; } - set - { - if (m_AlphaMode == value) - return; - - m_AlphaMode = value; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_TwoSided; - - public ToggleData twoSided - { - get { return new ToggleData(m_TwoSided); } - set - { - if (m_TwoSided == value.isOn) - return; - m_TwoSided = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_AddPrecomputedVelocity = false; - - public ToggleData addPrecomputedVelocity - { - get { return new ToggleData(m_AddPrecomputedVelocity); } - set - { - if (m_AddPrecomputedVelocity == value.isOn) - return; - m_AddPrecomputedVelocity = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] - bool m_DOTSInstancing = false; - - public ToggleData dotsInstancing - { - get { return new ToggleData(m_DOTSInstancing); } - set - { - if (m_DOTSInstancing == value.isOn) - return; - - m_DOTSInstancing = value.isOn; - Dirty(ModificationScope.Graph); - } - } - - [SerializeField] private string m_ShaderGUIOverride; - public string ShaderGUIOverride - { - get => m_ShaderGUIOverride; - set => m_ShaderGUIOverride = value; - } - - [SerializeField] private bool m_OverrideEnabled; - public bool OverrideEnabled - { - get => m_OverrideEnabled; - set => m_OverrideEnabled = value; - } - - public UnlitMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - - public sealed override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - name = "Unlit Master"; - AddSlot(new PositionMaterialSlot(PositionSlotId, PositionName, PositionName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new NormalMaterialSlot(VertNormalSlotId, NormalName, NormalName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new TangentMaterialSlot(VertTangentSlotId, TangentName, TangentName, CoordinateSpace.Object, ShaderStageCapability.Vertex)); - AddSlot(new ColorRGBMaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); - AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1, ShaderStageCapability.Fragment)); - AddSlot(new Vector1MaterialSlot(AlphaThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0.0f, ShaderStageCapability.Fragment)); - - // clear out slot names that do not match the slots - // we support - RemoveSlotsNameNotMatching( - new[] - { - PositionSlotId, - VertNormalSlotId, - VertTangentSlotId, - ColorSlotId, - AlphaSlotId, - AlphaThresholdSlotId - }); - } - - public VisualElement CreateSettingsElement() - { - return new UnlitSettingsView(this); - } - - public string renderQueueTag - { - get - { - if(surfaceType == SurfaceType.Transparent) - return $"{RenderQueue.Transparent}"; - else if(IsSlotConnected(UnlitMasterNode.AlphaThresholdSlotId) || FindSlot(AlphaThresholdSlotId).value > 0.0f) - return $"{RenderQueue.AlphaTest}"; - else - return $"{RenderQueue.Geometry}"; - } - } - - public string renderTypeTag - { - get - { - if(surfaceType == SurfaceType.Transparent) - return $"{RenderType.Transparent}"; - else - return $"{RenderType.Opaque}"; - } - } - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - return new ConditionalField[] - { - // Features - new ConditionalField(Fields.GraphVertex, IsSlotConnected(PBRMasterNode.PositionSlotId) || - IsSlotConnected(PBRMasterNode.VertNormalSlotId) || - IsSlotConnected(PBRMasterNode.VertTangentSlotId)), - new ConditionalField(Fields.GraphPixel, true), - - // Surface Type - new ConditionalField(Fields.SurfaceOpaque, surfaceType == ShaderGraph.SurfaceType.Opaque), - new ConditionalField(Fields.SurfaceTransparent, surfaceType != ShaderGraph.SurfaceType.Opaque), - - // Blend Mode - new ConditionalField(Fields.BlendAdd, surfaceType != ShaderGraph.SurfaceType.Opaque && alphaMode == AlphaMode.Additive), - new ConditionalField(Fields.BlendAlpha, surfaceType != ShaderGraph.SurfaceType.Opaque && alphaMode == AlphaMode.Alpha), - new ConditionalField(Fields.BlendMultiply, surfaceType != ShaderGraph.SurfaceType.Opaque && alphaMode == AlphaMode.Multiply), - new ConditionalField(Fields.BlendPremultiply, surfaceType != ShaderGraph.SurfaceType.Opaque && alphaMode == AlphaMode.Premultiply), - - // Misc - new ConditionalField(Fields.AlphaClip, IsSlotConnected(UnlitMasterNode.AlphaThresholdSlotId) || - FindSlot(AlphaThresholdSlotId).value > 0.0f), - new ConditionalField(Fields.AlphaTest, IsSlotConnected(UnlitMasterNode.AlphaThresholdSlotId) || - FindSlot(AlphaThresholdSlotId).value > 0.0f), - new ConditionalField(Fields.VelocityPrecomputed, addPrecomputedVelocity.isOn), - new ConditionalField(Fields.DoubleSided, twoSided.isOn), - }; - } - - public void ProcessPreviewMaterial(Material material) - { - - } - - public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal(stageCapability)); - } - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent(stageCapability)); - } - - public bool supportsVirtualTexturing => true; - } -} diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/UnlitMasterNode.cs.meta b/com.unity.shadergraph/Editor/Data/MasterNodes/UnlitMasterNode.cs.meta deleted file mode 100644 index ef3c0c4d903..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/UnlitMasterNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 50acf8d45249d486e9e5ee72178100f4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/VfxMasterNode.cs b/com.unity.shadergraph/Editor/Data/MasterNodes/VfxMasterNode.cs deleted file mode 100644 index 47d6aeca484..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/VfxMasterNode.cs +++ /dev/null @@ -1,183 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEditor.Graphing; -using UnityEditor.ShaderGraph.Internal; -using UnityEditor.ShaderGraph.Drawing; -using UnityEditor.ShaderGraph.Drawing.Controls; -using UnityEngine; -using UnityEngine.Rendering; -using UnityEngine.UIElements; -using UnityEditor.Graphing.Util; - -namespace UnityEditor.ShaderGraph -{ - [Serializable] - [Title("Master", "Visual Effect")] - sealed class VfxMasterNode : AbstractMaterialNode, IMasterNode, IHasSettings, IMayRequirePosition - { - const string BaseColorSlotName = "Base Color"; - const string MetallicSlotName = "Metallic"; - const string SmoothnessSlotName = "Smoothness"; - const string NormalSlotName = "Normal"; - const string AlphaSlotName = "Alpha"; - const string EmissiveSlotName = "Emissive"; - const string ColorSlotName = "Color"; - const string AlphaThresholdSlotName = "AlphaThreshold"; - - public VfxMasterNode() - { - UpdateNodeAfterDeserialization(); - } - - - [SerializeField] - bool m_Lit; - - public ToggleData lit - { - get { return new ToggleData(m_Lit); } - set - { - if (m_Lit == value.isOn) - return; - m_Lit = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - [SerializeField] - bool m_AlphaTest; - - public ToggleData alphaTest - { - get { return new ToggleData(m_AlphaTest); } - set - { - if (m_AlphaTest == value.isOn) - return; - m_AlphaTest = value.isOn; - UpdateNodeAfterDeserialization(); - Dirty(ModificationScope.Topological); - } - } - - public override void UpdateNodeAfterDeserialization() - { - base.UpdateNodeAfterDeserialization(); - - name = "Visual Effect Master"; - - HashSet usedSlots = new HashSet(); - - if ( lit.isOn) - { - AddSlot(new ColorRGBMaterialSlot(ShaderGraphVfxAsset.BaseColorSlotId, BaseColorSlotName, NodeUtils.GetHLSLSafeName(BaseColorSlotName), SlotType.Input, Color.grey.gamma, ColorMode.Default, ShaderStageCapability.Fragment)); - usedSlots.Add(ShaderGraphVfxAsset.BaseColorSlotId); - - AddSlot(new Vector1MaterialSlot(ShaderGraphVfxAsset.MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - usedSlots.Add(ShaderGraphVfxAsset.MetallicSlotId); - - AddSlot(new Vector1MaterialSlot(ShaderGraphVfxAsset.SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStageCapability.Fragment)); - usedSlots.Add(ShaderGraphVfxAsset.SmoothnessSlotId); - - AddSlot(new Vector3MaterialSlot(ShaderGraphVfxAsset.NormalSlotId, NormalSlotName, NormalSlotName, SlotType.Input, new Vector3(0,0,1), ShaderStageCapability.Fragment)); - usedSlots.Add(ShaderGraphVfxAsset.NormalSlotId); - - AddSlot(new ColorRGBMaterialSlot(ShaderGraphVfxAsset.EmissiveSlotId, EmissiveSlotName, NodeUtils.GetHLSLSafeName(EmissiveSlotName), SlotType.Input, Color.black, ColorMode.HDR, ShaderStageCapability.Fragment)); - usedSlots.Add(ShaderGraphVfxAsset.EmissiveSlotId); - } - else - { - AddSlot(new ColorRGBMaterialSlot(ShaderGraphVfxAsset.ColorSlotId, ColorSlotName, NodeUtils.GetHLSLSafeName(ColorSlotName), SlotType.Input, Color.grey.gamma, ColorMode.HDR, ShaderStageCapability.Fragment)); - usedSlots.Add(ShaderGraphVfxAsset.ColorSlotId); - } - - AddSlot(new Vector1MaterialSlot(ShaderGraphVfxAsset.AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1, ShaderStageCapability.Fragment)); - usedSlots.Add(ShaderGraphVfxAsset.AlphaSlotId); - - if( alphaTest.isOn) - { - AddSlot(new Vector1MaterialSlot(ShaderGraphVfxAsset.AlphaThresholdSlotId, AlphaThresholdSlotName, AlphaThresholdSlotName, SlotType.Input, 1, ShaderStageCapability.Fragment)); - usedSlots.Add(ShaderGraphVfxAsset.AlphaThresholdSlotId); - } - - RemoveSlotsNameNotMatching(usedSlots); - } - - class SettingsView : VisualElement - { - readonly VfxMasterNode m_Node; - public SettingsView(VfxMasterNode node) - { - m_Node = node; - PropertySheet ps = new PropertySheet(); - ps.Add(new PropertyRow(new Label("Alpha Mask")), (row) => - { - row.Add(new Toggle(), (toggle) => - { - toggle.value = m_Node.alphaTest.isOn; - toggle.OnToggleChanged(ChangeAlphaTest); - }); - }); - ps.Add(new PropertyRow(new Label("Lit")), (System.Action)((row) => - { - row.Add(new Toggle(), (System.Action)((toggle) => - { - toggle.value = m_Node.lit.isOn; - toggle.OnToggleChanged(this.ChangeLit); - })); - })); - Add(ps); - } - - void ChangeAlphaTest(ChangeEvent e) - { - m_Node.alphaTest = new ToggleData(e.newValue, m_Node.alphaTest.isEnabled); - } - void ChangeLit(ChangeEvent e) - { - m_Node.lit = new ToggleData(e.newValue, m_Node.alphaTest.isEnabled); - } - } - - public VisualElement CreateSettingsElement() - { - return new SettingsView(this); - } - - public string renderQueueTag => null; - public string renderTypeTag => null; - - public ConditionalField[] GetConditionalFields(PassDescriptor pass) - { - return null; - } - - public void ProcessPreviewMaterial(Material material) - { - - } - - public override bool hasPreview => false; - - public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) - { - List slots = new List(); - GetSlots(slots); - - List validSlots = new List(); - for (int i = 0; i < slots.Count; i++) - { - if (slots[i].stageCapability != ShaderStageCapability.All && slots[i].stageCapability != stageCapability) - continue; - - validSlots.Add(slots[i]); - } - return validSlots.OfType().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition(stageCapability)); - } - - public bool supportsVirtualTexturing => false; - } -} diff --git a/com.unity.shadergraph/Editor/Data/MasterNodes/VfxMasterNode.cs.meta b/com.unity.shadergraph/Editor/Data/MasterNodes/VfxMasterNode.cs.meta deleted file mode 100644 index dc6c5998ffc..00000000000 --- a/com.unity.shadergraph/Editor/Data/MasterNodes/VfxMasterNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8bda76bbd4a3e42f2809a95c732bcd57 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Nodes/AbstractMaterialNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/AbstractMaterialNode.cs index 92d56ecce98..c7b9f7eeda5 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/AbstractMaterialNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/AbstractMaterialNode.cs @@ -28,6 +28,12 @@ abstract class AbstractMaterialNode : JsonObject, IGroupItem [NonSerialized] bool m_HasError; + [NonSerialized] + bool m_IsValid = true; + + [NonSerialized] + bool m_IsActive = true; + [SerializeField] List> m_Slots = new List>(); @@ -92,7 +98,6 @@ public virtual bool canSetPrecision private ConcretePrecision m_ConcretePrecision = ConcretePrecision.Float; - [Inspectable("Precision", ConcretePrecision.Float)] public ConcretePrecision concretePrecision { get => m_ConcretePrecision; @@ -134,9 +139,10 @@ public virtual PreviewMode previewMode get { return PreviewMode.Preview2D; } } + // TODO: Can actually delete this public virtual bool allowedInSubGraph { - get { return !(this is IMasterNode); } + get { return !(this is BlockNode); } } public virtual bool allowedInMainGraph @@ -155,8 +161,114 @@ public virtual bool hasError protected set { m_HasError = value; } } - //needed for HDRP material update system - public virtual object saveContext => null; + public virtual bool isActive + { + get { return m_IsActive; } + } + + //There are times when isActive needs to be set to a value explicitly, and + //not be changed by active forest parsing (what we do when we need to figure out + //what nodes should or should not be active, usually from an edit; see NodeUtils). + //In this case, we allow for explicit setting of an active value that cant be overriden. + //Implicit implies that active forest parsing can edit the nodes isActive property + public enum ActiveState + { + Implicit = 0, + ExplicitInactive = 1, + ExplicitActive = 2 + } + + private ActiveState m_ActiveState = ActiveState.Implicit; + public ActiveState activeState + { + get => m_ActiveState; + } + + public void SetOverrideActiveState(ActiveState overrideState, bool updateConnections = true) + { + if(m_ActiveState == overrideState) + { + return; + } + + m_ActiveState = overrideState; + switch (m_ActiveState) + { + case ActiveState.Implicit: + if (updateConnections) + { + NodeUtils.ReevaluateActivityOfConnectedNodes(this); + } + break; + case ActiveState.ExplicitInactive: + if(m_IsActive == false) + { + break; + } + else + { + m_IsActive = false; + Dirty(ModificationScope.Node); + if (updateConnections) + { + NodeUtils.ReevaluateActivityOfConnectedNodes(this); + } + break; + } + case ActiveState.ExplicitActive: + if(m_IsActive == true) + { + break; + } + else + { + m_IsActive = true; + Dirty(ModificationScope.Node); + if (updateConnections) + { + NodeUtils.ReevaluateActivityOfConnectedNodes(this); + } + break; + } + } + } + + public void SetActive(bool value, bool updateConnections = true) + { + if (m_IsActive == value) + return; + + if(m_ActiveState != ActiveState.Implicit) + { + Debug.LogError($"Cannot set IsActive on Node {this} when value is explicitly overriden by ActiveState {m_ActiveState}"); + return; + } + + // Update this node + m_IsActive = value; + Dirty(ModificationScope.Node); + + if (updateConnections) + { + NodeUtils.ReevaluateActivityOfConnectedNodes(this); + } + + } + + + public virtual bool isValid + { + get { return m_IsValid; } + set + { + if(m_IsValid == value) + return; + + m_IsValid = value; + } + } + + string m_DefaultVariableName; string m_NameForDefaultVariableName; @@ -225,9 +337,9 @@ public void GetOutputSlots(List foundSlots) where T : MaterialSlot public void GetSlots(List foundSlots) where T : MaterialSlot { foreach (var slot in m_Slots.SelectValue()) - { - if (slot is T materialSlot) { + if (slot is T materialSlot) + { foundSlots.Add(materialSlot); } } @@ -238,7 +350,7 @@ public virtual void CollectShaderProperties(PropertyCollector properties, Genera foreach (var inputSlot in this.GetInputSlots()) { var edges = owner.GetEdges(inputSlot.slotReference); - if (edges.Any()) + if (edges.Any(e => e.outputSlot.node.isActive)) continue; inputSlot.AddDefaultProperty(properties, generationMode); @@ -309,7 +421,22 @@ protected virtual string GetOutputForSlot(SlotReference fromSocketRef, Concrete if (slot == null) return string.Empty; + if (fromSocketRef.node.isActive) return GenerationUtils.AdaptNodeOutput(this, slot.id, valueType); + else + return slot.GetDefaultValue(generationMode); + } + + public AbstractMaterialNode GetInputNodeFromSlot(int inputSlotId) + { + var inputSlot = FindSlot(inputSlotId); + if (inputSlot == null) + return null; + + var edges = owner.GetEdges(inputSlot.slotReference).ToArray(); + var fromSocketRef = edges[0].outputSlot; + var fromNode = fromSocketRef.node; + return fromNode; } public static ConcreteSlotValueType ConvertDynamicVectorInputTypeToConcrete(IEnumerable inputTypes) @@ -386,7 +513,7 @@ public virtual void EvaluateConcretePrecision() foreach (var inputSlot in tempSlots) { // If input port doesnt have an edge use the Graph's precision for that input - var edges = owner.GetEdges(inputSlot.slotReference).ToList(); + var edges = owner?.GetEdges(inputSlot.slotReference).ToList(); if (!edges.Any()) { precisionsToCompare.Add((int)owner.concretePrecision); @@ -540,7 +667,7 @@ public virtual void EvaluateDynamicMaterialSlots() public virtual void Concretize() { hasError = false; - owner.ClearErrorsForNode(this); + owner?.ClearErrorsForNode(this); EvaluateConcretePrecision(); EvaluateDynamicMaterialSlots(); if(!hasError) @@ -555,6 +682,7 @@ public virtual void ValidateNode() } public int version { get; set; } + public virtual bool canCutNode => true; public virtual bool canCopyNode => true; protected virtual void CalculateNodeHasError() @@ -736,12 +864,17 @@ public override void OnAfterMultiDeserialize(string json) m_NodeVersion = GetCompiledNodeVersion(); } - foreach (var s in m_Slots.SelectValue()) - s.owner = this; + // UpdateNodeAfterDeserialization(); } + public void SetupSlots() + { + foreach (var s in m_Slots.SelectValue()) + s.owner = this; + } + public virtual void UpdateNodeAfterDeserialization() {} @@ -757,5 +890,13 @@ public bool IsSlotConnected(int slotId) } public virtual void Setup() {} + + protected void EnqueSlotsForSerialization() + { + foreach(var slot in m_Slots) + { + slot.OnBeforeSerialize(); + } + } } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs new file mode 100644 index 00000000000..63d4886abf8 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs @@ -0,0 +1,219 @@ +using System; +using UnityEngine; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Internal; + +namespace UnityEditor.ShaderGraph +{ + class BlockNode : AbstractMaterialNode + , IMayRequireNormal + , IMayRequireTangent + , IMayRequireBitangent + , IMayRequireMeshUV + , IMayRequireScreenPosition + , IMayRequireViewDirection + , IMayRequirePosition + , IMayRequireVertexColor + { + [SerializeField] + string m_SerializedDescriptor; + + [NonSerialized] + ContextData m_ContextData; + + [NonSerialized] + BlockFieldDescriptor m_Descriptor; + + public BlockNode() + { + } + + public override bool canCutNode => false; + public override bool canCopyNode => false; + + // Because the GraphData is deserialized after its child elements + // the descriptor list is not built (and owner is not set) + // at the time of node deserialization + // Therefore we need to deserialize this element at GraphData.OnAfterDeserialize + public string serializedDescriptor => m_SerializedDescriptor; + + public ContextData contextData + { + get => m_ContextData; + set => m_ContextData = value; + } + + public int index => contextData.blocks.IndexOf(this); + + public BlockFieldDescriptor descriptor + { + get => m_Descriptor; + set => m_Descriptor = value; + } + + public void Init(BlockFieldDescriptor fieldDescriptor) + { + name = $"{fieldDescriptor.tag}.{fieldDescriptor.name}"; + m_Descriptor = fieldDescriptor; + + // TODO: This exposes the MaterialSlot API + // TODO: This needs to be removed but is currently required by HDRP for DiffusionProfileInputMaterialSlot + if(m_Descriptor is CustomSlotBlockFieldDescriptor customSlotDescriptor) + { + var newSlot = customSlotDescriptor.createSlot(); + AddSlot(newSlot); + RemoveSlotsNameNotMatching(new int[] {0}); + return; + } + + AddSlotFromControlType(); + } + + void AddSlotFromControlType() + { + // TODO: this should really just use callbacks like the CustomSlotBlockFieldDescriptor.. then we wouldn't need this switch to make a copy + var stageCapability = m_Descriptor.shaderStage.GetShaderStageCapability(); + switch(descriptor.control) + { + case PositionControl positionControl: + AddSlot(new PositionMaterialSlot(0, descriptor.displayName, descriptor.name, positionControl.space, stageCapability)); + break; + case NormalControl normalControl: + AddSlot(new NormalMaterialSlot(0, descriptor.displayName, descriptor.name, normalControl.space, stageCapability)); + break; + case TangentControl tangentControl: + AddSlot(new TangentMaterialSlot(0, descriptor.displayName, descriptor.name, tangentControl.space, stageCapability)); + break; + case ColorControl colorControl: + var colorMode = colorControl.hdr ? ColorMode.HDR : ColorMode.Default; + AddSlot(new ColorRGBMaterialSlot(0, descriptor.displayName, descriptor.name, SlotType.Input, colorControl.value, colorMode, stageCapability)); + break; + case ColorRGBAControl colorRGBAControl: + AddSlot(new ColorRGBAMaterialSlot(0, descriptor.displayName, descriptor.name, SlotType.Input, colorRGBAControl.value, stageCapability)); + break; + case FloatControl floatControl: + AddSlot(new Vector1MaterialSlot(0, descriptor.displayName, descriptor.name, SlotType.Input, floatControl.value, stageCapability)); + break; + case Vector2Control vector2Control: + AddSlot(new Vector2MaterialSlot(0, descriptor.displayName, descriptor.name, SlotType.Input, vector2Control.value, stageCapability)); + break; + case Vector3Control vector3Control: + AddSlot(new Vector3MaterialSlot(0, descriptor.displayName, descriptor.name, SlotType.Input, vector3Control.value, stageCapability)); + break; + } + RemoveSlotsNameNotMatching(new int[] {0}); + } + + public override string GetVariableNameForNode() + { + // Temporary block nodes have temporary guids that cannot be used to set preview data + // Since each block is unique anyway we just omit the guid + return NodeUtils.GetHLSLSafeName(name); + } + + public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) + { + if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + return NeededCoordinateSpace.None; + + if(m_Descriptor.control == null) + return NeededCoordinateSpace.None; + + var requirements = m_Descriptor.control.GetRequirements(); + return requirements.requiresNormal; + } + + public NeededCoordinateSpace RequiresViewDirection(ShaderStageCapability stageCapability) + { + if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + return NeededCoordinateSpace.None; + + if(m_Descriptor.control == null) + return NeededCoordinateSpace.None; + + var requirements = m_Descriptor.control.GetRequirements(); + return requirements.requiresViewDir; + } + + public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) + { + if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + return NeededCoordinateSpace.None; + + if(m_Descriptor.control == null) + return NeededCoordinateSpace.None; + + var requirements = m_Descriptor.control.GetRequirements(); + return requirements.requiresPosition; + } + + public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) + { + if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + return NeededCoordinateSpace.None; + + if(m_Descriptor.control == null) + return NeededCoordinateSpace.None; + + var requirements = m_Descriptor.control.GetRequirements(); + return requirements.requiresTangent; + } + + public NeededCoordinateSpace RequiresBitangent(ShaderStageCapability stageCapability) + { + if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + return NeededCoordinateSpace.None; + + if(m_Descriptor.control == null) + return NeededCoordinateSpace.None; + + var requirements = m_Descriptor.control.GetRequirements(); + return requirements.requiresBitangent; + } + + public bool RequiresMeshUV(UVChannel channel, ShaderStageCapability stageCapability) + { + if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + return false; + + if(m_Descriptor.control == null) + return false; + + var requirements = m_Descriptor.control.GetRequirements(); + return requirements.requiresMeshUVs.Contains(channel); + } + + public bool RequiresScreenPosition(ShaderStageCapability stageCapability) + { + if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + return false; + + if(m_Descriptor.control == null) + return false; + + var requirements = m_Descriptor.control.GetRequirements(); + return requirements.requiresScreenPosition; + } + + public bool RequiresVertexColor(ShaderStageCapability stageCapability) + { + if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + return false; + + if(m_Descriptor.control == null) + return false; + + var requirements = m_Descriptor.control.GetRequirements(); + return requirements.requiresVertexColor; + } + + public override void OnBeforeSerialize() + { + base.OnBeforeSerialize(); + if (descriptor != null) + { + m_SerializedDescriptor = $"{m_Descriptor.tag}.{m_Descriptor.name}"; + } + } + } +} diff --git a/com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs.meta b/com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs.meta new file mode 100644 index 00000000000..6bd4813a739 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs.meta @@ -0,0 +1,17 @@ +fileFormatVersion: 2 +<<<<<<< HEAD:com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs.meta +guid: bd5e1b91fdc2348ac9ce3733135e9901 +timeCreated: 1495966736 +licenseType: Pro +======= +guid: 9bf52003256740c4ba5a1f6dac0544f4 +>>>>>>> origin/master:TestProjects/ShaderGraph/Assets/CommonAssets/Editor/ImportUpdateTests.cs.meta +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs index a3408be5251..9bdf9bba7a0 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs @@ -211,7 +211,6 @@ public override void EvaluateConcretePrecision() concretePrecision = precision.ToConcrete(); else concretePrecision = owner.concretePrecision; - } - + } } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleVirtualTextureNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleVirtualTextureNode.cs index 8c5512d9b9e..14af83afa88 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleVirtualTextureNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleVirtualTextureNode.cs @@ -14,7 +14,7 @@ namespace UnityEditor.ShaderGraph { [Title("Input", "Texture", SampleVirtualTextureNode.DefaultNodeTitle)] - class SampleVirtualTextureNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireMeshUV, IMayRequireTime, IMayRequireScreenPosition, IHasSettings + class SampleVirtualTextureNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireMeshUV, IMayRequireTime, IMayRequireScreenPosition { public const string DefaultNodeTitle = "Sample Virtual Texture"; @@ -144,6 +144,8 @@ public bool noFeedback } } + public TextureType[] textureTypes => m_TextureTypes; + [SerializeField] protected TextureType[] m_TextureTypes = { TextureType.Default, TextureType.Default, TextureType.Default, TextureType.Default }; @@ -164,143 +166,6 @@ public NormalMapSpace normalMapSpace } } - /* - The panel behind the cogwheel node settings - */ - class SampleVirtualTextureNodeSettingsView : VisualElement - { - SampleVirtualTextureNode m_Node; - public SampleVirtualTextureNodeSettingsView(SampleVirtualTextureNode node) - { - m_Node = node; - - PropertySheet ps = new PropertySheet(); - - ps.Add(new PropertyRow(new Label("Lod Mode")), (row) => - { - row.Add(new UIElements.EnumField(m_Node.lodCalculation), (field) => - { - field.value = m_Node.lodCalculation; - field.RegisterValueChangedCallback(evt => - { - if (m_Node.lodCalculation == (LodCalculation)evt.newValue) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Lod Mode Change"); - m_Node.lodCalculation = (LodCalculation)evt.newValue; - }); - }); - }); - - ps.Add(new PropertyRow(new Label("Quality")), (row) => - { - row.Add(new UIElements.EnumField(m_Node.sampleQuality), (field) => - { - field.value = m_Node.sampleQuality; - field.RegisterValueChangedCallback(evt => - { - if (m_Node.sampleQuality == (QualityMode)evt.newValue) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Quality Change"); - m_Node.sampleQuality = (QualityMode)evt.newValue; - }); - }); - }); - - ps.Add(new PropertyRow(new Label("No Feedback")), (row) => - { - row.Add(new UnityEngine.UIElements.Toggle(), (field) => - { - field.value = m_Node.noFeedback; - field.RegisterValueChangedCallback(evt => - { - if (m_Node.noFeedback == evt.newValue) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Feedback Settings Change"); - m_Node.noFeedback = evt.newValue; - }); - }); - }); - - var vtProperty = m_Node.GetSlotProperty(VirtualTextureInputId) as VirtualTextureShaderProperty; - if (vtProperty == null) - { - ps.Add(new HelpBoxRow(MessageType.Warning), (row) => row.Add(new Label("Please connect a VirtualTexture property to configure texture sampling type."))); - } - else - { - int numLayers = vtProperty.value.layers.Count; - - for (int i = 0; i < numLayers; i++) - { - int currentIndex = i; // to make lambda by-ref capturing happy - ps.Add(new PropertyRow(new Label("Layer " + (i + 1) + " Type")), (row) => - { - row.Add(new UIElements.EnumField(m_Node.m_TextureTypes[i]), (field) => - { - field.value = m_Node.m_TextureTypes[i]; - field.RegisterValueChangedCallback(evt => - { - if (m_Node.m_TextureTypes[currentIndex] == (TextureType)evt.newValue) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Texture Type Change"); - m_Node.m_TextureTypes[currentIndex] = (TextureType)evt.newValue; - m_Node.Dirty(ModificationScope.Graph); - }); - }); - }); - } - } - - ps.Add(new PropertyRow(new Label("Normal Space")), (row) => - { - row.Add(new UIElements.EnumField(m_Node.normalMapSpace), (field) => - { - field.value = m_Node.normalMapSpace; - field.RegisterValueChangedCallback(evt => - { - if (m_Node.normalMapSpace == (NormalMapSpace)evt.newValue) - return; - - m_Node.owner.owner.RegisterCompleteObjectUndo("Normal Map space Change"); - m_Node.normalMapSpace = (NormalMapSpace)evt.newValue; - }); - }); - }); - - // display warning if the current master node doesn't support virtual texturing - if (!m_Node.owner.isSubGraph) - { - bool supportedByMasterNode = m_Node.owner.GetNodes().FirstOrDefault()?.supportsVirtualTexturing ?? false; - if (!supportedByMasterNode) - ps.Add(new HelpBoxRow(MessageType.Warning), (row) => row.Add(new Label("The current master node does not support Virtual Texturing, this node will do regular 2D sampling."))); - } - - // display warning if the current render pipeline doesn't support virtual texturing - IVirtualTexturingEnabledRenderPipeline vtRp = GraphicsSettings.currentRenderPipeline as IVirtualTexturingEnabledRenderPipeline; - if (vtRp == null) - ps.Add(new HelpBoxRow(MessageType.Warning), (row) => row.Add(new Label("The current render pipeline does not support Virtual Texturing, this node will do regular 2D sampling."))); - else if (vtRp.virtualTexturingEnabled == false) - ps.Add(new HelpBoxRow(MessageType.Warning), (row) => row.Add(new Label("The current render pipeline has disabled Virtual Texturing, this node will do regular 2D sampling."))); - else - { -#if !ENABLE_VIRTUALTEXTURES - ps.Add(new HelpBoxRow(MessageType.Warning), (row) => row.Add(new Label("Virtual Texturing is disabled globally (possibly by the render pipeline settings), this node will do regular 2D sampling."))); -#endif - } - - Add(ps); - } - } - - public VisualElement CreateSettingsElement() - { - return new SampleVirtualTextureNodeSettingsView(this); - } - public SampleVirtualTextureNode() : this(false, false) { } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/LegacyUnknownTypeNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/LegacyUnknownTypeNode.cs new file mode 100644 index 00000000000..471b7c0f4c6 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Nodes/LegacyUnknownTypeNode.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph.Drawing.Colors; +using UnityEditor.ShaderGraph.Internal; +using static UnityEditor.Graphing.SerializationHelper; +using UnityEditor.Rendering; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.ShaderGraph.Serialization; + +namespace UnityEditor.ShaderGraph +{ + [Serializable] + class LegacyUnknownTypeNode : AbstractMaterialNode + { + public string serializedType; + public string serializedData; + + [NonSerialized] + public Type foundType = null; + + public LegacyUnknownTypeNode() : base() + { + serializedData = null; + isValid = false; + } + public LegacyUnknownTypeNode(string typeData, string serializedNodeData) : base() + { + serializedType = typeData; + serializedData = serializedNodeData; + isValid = false; + } + + public override void OnAfterDeserialize(string json) + { + base.OnAfterDeserialize(json); + + } + + public override void ValidateNode() + { + base.ValidateNode(); + + owner.AddValidationError(objectId, "This node type could not be found. No function will be generated in the shader.", ShaderCompilerMessageSeverity.Warning); + } + } +} + diff --git a/com.unity.shadergraph/Editor/Data/Nodes/LegacyUnknownTypeNode.cs.meta b/com.unity.shadergraph/Editor/Data/Nodes/LegacyUnknownTypeNode.cs.meta new file mode 100644 index 00000000000..91fa8a541b8 --- /dev/null +++ b/com.unity.shadergraph/Editor/Data/Nodes/LegacyUnknownTypeNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a8f1b9181107ac644a363625fa793f9a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.shadergraph/Editor/Data/Nodes/ShaderStage.cs b/com.unity.shadergraph/Editor/Data/Nodes/ShaderStage.cs index d7068af7094..b348de60f6a 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/ShaderStage.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/ShaderStage.cs @@ -39,5 +39,18 @@ public static bool TryGetShaderStage(this ShaderStageCapability capability, out return false; } } + + public static ShaderStageCapability GetShaderStageCapability(this ShaderStage stage) + { + switch (stage) + { + case ShaderStage.Vertex: + return ShaderStageCapability.Vertex; + case ShaderStage.Fragment: + return ShaderStageCapability.Fragment; + default: + return ShaderStageCapability.Fragment; + } + } } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/CustomFunctionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/CustomFunctionNode.cs index da018bf7446..0361da2a704 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/CustomFunctionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/CustomFunctionNode.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Collections.Generic; using System.Linq; @@ -12,7 +12,7 @@ namespace UnityEditor.ShaderGraph { [HasDependencies(typeof(MinimalCustomFunctionNode))] [Title("Utility", "Custom Function")] - class CustomFunctionNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IHasSettings + class CustomFunctionNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction { [Serializable] public class MinimalCustomFunctionNode : IHasDependencies @@ -33,7 +33,9 @@ public void GetSourceAssetDependencies(List paths) m_FunctionSource = UpgradeFunctionSource(m_FunctionSource); if (IsValidFunction(m_SourceType, m_FunctionName, m_FunctionSource, null)) { - paths.Add(AssetDatabase.GUIDToAssetPath(m_FunctionSource)); + var assetPath = AssetDatabase.GUIDToAssetPath(m_FunctionSource); + if (!string.IsNullOrEmpty(assetPath)) // Ideally, we would record the GUID as a missing dependency here + paths.Add(assetPath); } } } @@ -317,15 +319,6 @@ public void Reload(HashSet changedFileDependencies) } } - public VisualElement CreateSettingsElement() - { - PropertySheet ps = new PropertySheet(); - ps.Add(new ReorderableSlotListView(this, SlotType.Input)); - ps.Add(new ReorderableSlotListView(this, SlotType.Output)); - ps.Add(new HlslFunctionView(this)); - return ps; - } - public static string UpgradeFunctionSource(string functionSource) { // Handle upgrade from legacy asset path version diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs index ec2433d44f9..6e9af479800 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs @@ -40,7 +40,9 @@ public void GetSourceAssetDependencies(List paths) var guid = assetReference?.subGraph?.guid; if (guid != null) { - paths.Add(AssetDatabase.GUIDToAssetPath(guid)); + var assetPath = AssetDatabase.GUIDToAssetPath(guid); + if (!string.IsNullOrEmpty(assetPath)) // Ideally, we would record the GUID as a missing dependency here + paths.Add(assetPath); } } } @@ -107,12 +109,20 @@ void LoadSubGraph() var graphGuid = subGraphGuid; var assetPath = AssetDatabase.GUIDToAssetPath(graphGuid); + if (string.IsNullOrEmpty(assetPath)) + { + // this happens if the editor has never seen the GUID + // error will be printed by validation code in this case + return; + } m_SubGraph = AssetDatabase.LoadAssetAtPath(assetPath); - m_SubGraph.LoadGraphData(); if (m_SubGraph == null) { + // this happens if the editor has seen the GUID, but the file has been deleted since then + // error will be printed by validation code in this case return; } + m_SubGraph.LoadGraphData(); name = m_SubGraph.name; concretePrecision = m_SubGraph.outputPrecision; @@ -461,6 +471,11 @@ public override void ValidateNode() hasError = true; owner.AddValidationError(objectId, $"Invalid Sub Graph asset at \"{AssetDatabase.GUIDToAssetPath(subGraphGuid)}\" with GUID {subGraphGuid}."); } + else if(!owner.isSubGraph && owner.activeTargets.Any(x => asset.unsupportedTargets.Contains(x))) + { + SetOverrideActiveState(ActiveState.ExplicitInactive); + owner.AddValidationError(objectId, $"Subgraph asset at \"{AssetDatabase.GUIDToAssetPath(subGraphGuid)}\" with GUID {subGraphGuid} contains nodes that are unsuported by the current active targets"); + } // detect VT layer count mismatches foreach (var paramProp in asset.inputs) diff --git a/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphAsset.cs b/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphAsset.cs index 4d489b88589..3f478efacf1 100644 --- a/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphAsset.cs +++ b/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphAsset.cs @@ -27,6 +27,7 @@ class SubGraphData : JsonObject public List> keywords = new List>(); public List> nodeProperties = new List>(); public List> outputs = new List>(); + public List> unsupportedTargets = new List>(); } class SubGraphAsset : ScriptableObject, ISerializationCallbackReceiver @@ -66,6 +67,8 @@ class SubGraphAsset : ScriptableObject, ISerializationCallbackReceiver public DataValueEnumerable outputs => m_SubGraphData.outputs.SelectValue(); + public DataValueEnumerable unsupportedTargets => m_SubGraphData.unsupportedTargets.SelectValue(); + public List children = new List(); public List descendents = new List(); @@ -76,7 +79,7 @@ class SubGraphAsset : ScriptableObject, ISerializationCallbackReceiver public ConcretePrecision outputPrecision; - public void WriteData(IEnumerable inputs, IEnumerable keywords, IEnumerable nodeProperties, IEnumerable outputs) + public void WriteData(IEnumerable inputs, IEnumerable keywords, IEnumerable nodeProperties, IEnumerable outputs, IEnumerable unsupportedTargets) { if(m_SubGraphData == null) { @@ -86,6 +89,7 @@ public void WriteData(IEnumerable inputs, IEnumerable inputs, IEnumerable s_ValidSlotTypes = new List() @@ -108,19 +108,12 @@ protected override void OnSlotsChanged() public int AddSlot(ConcreteSlotValueType concreteValueType) { var index = this.GetInputSlots().Count() + 1; - name = NodeUtils.GetDuplicateSafeNameForSlot(this, index, "Out_" + concreteValueType.ToString()); + var name = NodeUtils.GetDuplicateSafeNameForSlot(this, index, "Out_" + concreteValueType.ToString()); AddSlot(MaterialSlot.CreateMaterialSlot(concreteValueType.ToSlotValueType(), index, name, NodeUtils.GetHLSLSafeName(name), SlotType.Input, Vector4.zero)); return index; } - public VisualElement CreateSettingsElement() - { - PropertySheet ps = new PropertySheet(); - ps.Add(new ReorderableSlotListView(this, SlotType.Input)); - return ps; - } - public override bool canDeleteNode => false; public override bool canCopyNode => false; diff --git a/com.unity.shadergraph/Editor/Data/Util/GraphUtil.cs b/com.unity.shadergraph/Editor/Data/Util/GraphUtil.cs index 2489aedfb07..691ff3894df 100644 --- a/com.unity.shadergraph/Editor/Data/Util/GraphUtil.cs +++ b/com.unity.shadergraph/Editor/Data/Util/GraphUtil.cs @@ -102,18 +102,26 @@ public PreprocessorIf(string conditional) class NewGraphAction : EndNameEditAction { - AbstractMaterialNode m_Node; - public AbstractMaterialNode node + Target[] m_Targets; + public Target[] targets { - get { return m_Node; } - set { m_Node = value; } + get => m_Targets; + set => m_Targets = value; + } + + BlockFieldDescriptor[] m_Blocks; + public BlockFieldDescriptor[] blocks + { + get => m_Blocks; + set => m_Blocks = value; } public override void Action(int instanceId, string pathName, string resourceFile) { var graph = new GraphData(); - graph.AddNode(node); - graph.outputNode = node; + graph.AddContexts(); + graph.InitializeOutputs(m_Targets, m_Blocks); + graph.path = "Shader Graphs"; FileUtilities.WriteShaderGraphToDisk(pathName, graph); AssetDatabase.Refresh(); @@ -143,41 +151,40 @@ internal static string ConvertCamelCase(string text, bool preserveAcronyms) return newText.ToString(); } - public static void CreateNewGraph(AbstractMaterialNode node) + public static void CreateNewGraph() { var graphItem = ScriptableObject.CreateInstance(); - graphItem.node = node; + graphItem.targets = null; ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, graphItem, string.Format("New Shader Graph.{0}", ShaderGraphImporter.Extension), null, null); } - public static Type GetOutputNodeType(string path) + public static void CreateNewGraphWithOutputs(Target[] targets, BlockFieldDescriptor[] blockDescriptors) { - ShaderGraphMetadata metadata = null; - foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(path)) - { - if (asset is ShaderGraphMetadata metadataAsset) - { - metadata = metadataAsset; - break; - } - } + var graphItem = ScriptableObject.CreateInstance(); + graphItem.targets = targets; + graphItem.blocks = blockDescriptors; + ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, graphItem, + string.Format("New Shader Graph.{0}", ShaderGraphImporter.Extension), null, null); + } - if (metadata == null) - { - return null; - } + public static bool TryGetMetadataOfType(this Shader shader, out T obj) where T : ScriptableObject + { + obj = null; + if(!shader.IsShaderGraph()) + return false; - var outputNodeTypeName = metadata.outputNodeTypeName; - foreach (var type in TypeCache.GetTypesDerivedFrom()) + var path = AssetDatabase.GetAssetPath(shader); + foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(path)) { - if (type.FullName == outputNodeTypeName) + if (asset is T metadataAsset) { - return type; + obj = metadataAsset; + return true; } } - return null; + return false; } public static bool IsShaderGraph(this Shader shader) @@ -353,25 +360,6 @@ public static void OpenFile(string path) } } - public static string CurrentPipelinePreferredShaderGUI(IMasterNode masterNode) - { - foreach (var target in (masterNode as AbstractMaterialNode).owner.validTargets) - { - if (target.IsPipelineCompatible(GraphicsSettings.currentRenderPipeline)) - { - var context = new TargetSetupContext(); - context.SetMasterNode(masterNode); - target.Setup(ref context); - - var defaultShaderGUI = context.defaultShaderGUI; - if (!string.IsNullOrEmpty(defaultShaderGUI)) - return defaultShaderGUI; - } - } - - return null; - } - // // Find all nodes of the given type downstream from the given node // Returns a unique list. So even if a node can be reached through different paths it will be present only once. diff --git a/com.unity.shadergraph/Editor/Data/Util/SerializationHelper.cs b/com.unity.shadergraph/Editor/Data/Util/SerializationHelper.cs index 9ea607c16f1..d73226e75d5 100644 --- a/com.unity.shadergraph/Editor/Data/Util/SerializationHelper.cs +++ b/com.unity.shadergraph/Editor/Data/Util/SerializationHelper.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using System.Reflection; +using UnityEditor.ShaderGraph.Serialization; using UnityEngine; namespace UnityEditor.Graphing @@ -64,15 +65,20 @@ static Type GetTypeFromSerializedString(TypeSerializationInfo typeInfo) public static JSONSerializedElement Serialize(T item) { + if(item is JsonObject jsonObject) + return new JSONSerializedElement() { JSONnodeData = jsonObject.Serialize() }; + if (item == null) throw new ArgumentNullException("item", "Can not serialize null element"); + //check if unknownnode type - if so, return saved metadata + //unknown node type will need onbeforeserialize to set guid and edges and all the things var typeInfo = GetTypeSerializableAsString(item.GetType()); var data = JsonUtility.ToJson(item, true); if (string.IsNullOrEmpty(data)) throw new ArgumentException(string.Format("Can not serialize {0}", item)); - ; + return new JSONSerializedElement { @@ -91,6 +97,24 @@ static TypeSerializationInfo DoTypeRemap(TypeSerializationInfo info, Dictionary< public static T Deserialize(JSONSerializedElement item, Dictionary remapper, params object[] constructorArgs) where T : class { + T instance; + if (typeof(T) == typeof(JsonObject) || typeof(T).IsSubclassOf(typeof(JsonObject))) + { + try + { + var culture = CultureInfo.CurrentCulture; + var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + instance = Activator.CreateInstance(typeof(T), flags, null, constructorArgs, culture) as T; + } + catch (Exception e) + { + throw new Exception(string.Format("Could not construct instance of: {0}", typeof(T)), e); + } + + MultiJson.Deserialize(instance as JsonObject, item.JSONnodeData); + return instance; + } + if (!item.typeInfo.IsValid() || string.IsNullOrEmpty(item.JSONnodeData)) throw new ArgumentException(string.Format("Can not deserialize {0}, it is invalid", item)); @@ -101,10 +125,12 @@ public static T Deserialize(JSONSerializedElement item, Dictionary(JSONSerializedElement item, Dictionary(evt => m_inspectorUpdateTrigger()); + } } void ChangeExposedField(bool newValue) @@ -170,7 +167,7 @@ void MarkNodesAsDirty(bool triggerPropertyViewUpdate = false, ModificationScope { DirtyNodes(modificationScope); if(triggerPropertyViewUpdate) - m_propertyViewUpdateTrigger(); + m_inspectorUpdateTrigger(); } void ChangePropertyValue(object newValue) diff --git a/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs b/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs index ac8fcaba640..819566b47a1 100644 --- a/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs +++ b/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs @@ -19,6 +19,7 @@ class BlackboardProvider public const int k_PropertySectionIndex = 0; public const int k_KeywordSectionIndex = 1; + const string k_styleName = "Blackboard"; public Blackboard blackboard { get; private set; } Label m_PathLabel; @@ -49,6 +50,9 @@ public BlackboardProvider(GraphData graph) moveItemRequested = MoveItemRequested }; + var styleSheet = Resources.Load($"Styles/{k_styleName}"); + blackboard.styleSheets.Add(styleSheet); + m_PathLabel = blackboard.hierarchy.ElementAt(0).Q