浏览代码

Merge pull request #92 from Unity-Technologies/pass-architecture

Pass architecture
/main
GitHub 7 年前
当前提交
81859b60
共有 39 个文件被更改,包括 1072 次插入951 次删除
  1. 46
      MaterialGraphProject/Assets/GraphFramework/SerializableGraph/Editor/Implementation/NodeUtils.cs
  2. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/AssetCallbacks/CreateShaderGraph.cs
  3. 41
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/AbstractMaterialGraph.cs
  4. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraph.cs
  5. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/IMasterNode.cs
  6. 13
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/MasterNode.cs
  7. 13
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/LayeredShaderGraph.cs
  8. 48
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/SurfaceMaterialOptions.cs
  9. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/StandardNodeEditorView.cs
  10. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/PreviewManager.cs
  11. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/GraphEditorView.cs
  12. 108
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template
  13. 281
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs
  14. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs.meta
  15. 208
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs
  16. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs.meta
  17. 163
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs
  18. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs.meta
  19. 79
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/UnlitMasterNode.cs
  20. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/UnlitMasterNode.cs.meta
  21. 40
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template
  22. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template.meta
  23. 145
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template
  24. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightPBRMasterNode.cs.meta
  25. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightMetallicMasterNode.cs.meta
  26. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightSpecularMasterNode.cs.meta
  27. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightUnlitMasterNode.cs.meta
  28. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightMasterNode.cs.meta
  29. 57
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightPBRMasterNode.cs
  30. 71
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightUnlitMasterNode.cs
  31. 126
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightMasterNode.cs
  32. 84
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightMetallicMasterNode.cs
  33. 79
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightSpecularMasterNode.cs
  34. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/MasterRemapNode.cs.meta
  35. 101
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/MasterRemapNode.cs
  36. 180
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightSubshaderPBR.template
  37. 0
      /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template.meta
  38. 0
      /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template
  39. 0
      /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template.meta

46
MaterialGraphProject/Assets/GraphFramework/SerializableGraph/Editor/Implementation/NodeUtils.cs


if (node == null)
return;
using (var stackDisposable = StackPool<INode>.GetDisposable())
using (var queueDisposable = QueuePool<INode>.GetDisposable())
{
var stack = stackDisposable.value;
var queue = queueDisposable.value;
queue.Enqueue(node);
// already added this node
if (nodeList.Contains(node))
return;
while (queue.Any())
{
var fromNode = queue.Dequeue();
// already added this node
if (nodeList.Contains(fromNode))
continue;
foreach (var slot in fromNode.GetInputSlots<ISlot>())
{
if (slotIds != null && !slotIds.Contains(slot.id))
continue;
var ids = node.GetInputSlots<ISlot>().Select(x => x.id);
if (slotIds != null)
ids = node.GetInputSlots<ISlot>().Where(x => slotIds.Contains(x.id)).Select(x => x.id);
foreach (var edge in fromNode.owner.GetEdges(fromNode.GetSlotReference(slot.id)))
{
var outputNode = fromNode.owner.GetNodeFromGuid(edge.outputSlot.nodeGuid);
queue.Enqueue(outputNode);
stack.Push(outputNode);
}
}
foreach (var slot in ids)
{
foreach (var edge in node.owner.GetEdges(node.GetSlotReference(slot)))
{
var outputNode = node.owner.GetNodeFromGuid(edge.outputSlot.nodeGuid);
DepthFirstCollectNodesFromNode(nodeList, outputNode);
}
while (stack.Any())
nodeList.Add(stack.Pop());
if (includeSelf == IncludeSelf.Include)
nodeList.Add(node);
}
if (includeSelf == IncludeSelf.Include)
nodeList.Add(node);
}
public static void CollectNodesNodeFeedsInto(List<INode> nodeList, INode node, IncludeSelf includeSelf = IncludeSelf.Include)

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/AssetCallbacks/CreateShaderGraph.cs


public override void Action(int instanceId, string pathName, string resourceFile)
{
var graph = new ShaderGraph.MaterialGraph();
graph.AddNode(new LightweightMetallicMasterNode());
//graph.AddNode(new LightweightMetallicMasterNode());
File.WriteAllText(pathName, EditorJsonUtility.ToJson(graph));
AssetDatabase.Refresh();
}

41
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/AbstractMaterialGraph.cs


base.OnAfterDeserialize();
}
protected static ShaderGraphRequirements GetRequirements(List<INode> nodes)
internal static ShaderGraphRequirements GetRequirements(List<INode> nodes)
{
NeededCoordinateSpace requiresNormal = nodes.OfType<IMayRequireNormal>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal());
NeededCoordinateSpace requiresBitangent = nodes.OfType<IMayRequireBitangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresBitangent());

FloatShaderProperty outputIdProperty;
return GetShader(node, GenerationMode.Preview, string.Format("hidden/preview/{0}", node.GetVariableNameForNode()), out configuredTextures, out previewMode, out outputIdProperty);
}
public string GetUberPreviewShader(Dictionary<Guid, int> ids, out FloatShaderProperty outputIdProperty)
{
List<PropertyCollector.TextureInfo> configuredTextures;

protected static void GenerateSurfaceDescriptionStruct(ShaderGenerator surfaceDescriptionStruct, List<MaterialSlot> slots, bool isMaster)
internal static void GenerateSurfaceDescriptionStruct(ShaderGenerator surfaceDescriptionStruct, List<MaterialSlot> slots, bool isMaster)
{
surfaceDescriptionStruct.AddShaderChunk("struct SurfaceDescription{", false);
surfaceDescriptionStruct.Indent();

surfaceDescriptionStruct.AddShaderChunk(string.Format("{0} {1};", AbstractMaterialNode.ConvertConcreteSlotValueTypeToString(AbstractMaterialNode.OutputPrecision.@float, slot.concreteValueType), AbstractMaterialNode.GetHLSLSafeName(slot.shaderOutputName)), false);
surfaceDescriptionStruct.Deindent();
surfaceDescriptionStruct.AddShaderChunk("};", false);
surfaceDescriptionStruct.AddShaderChunk("void ScaleSurfaceDescription(inout SurfaceDescription surface, float scale){", false);
surfaceDescriptionStruct.Indent();
foreach (var slot in slots)
surfaceDescriptionStruct.AddShaderChunk(string.Format("surface.{0} = scale * surface.{0};", AbstractMaterialNode.GetHLSLSafeName(slot.shaderOutputName)), false);
surfaceDescriptionStruct.Deindent();
surfaceDescriptionStruct.AddShaderChunk("};", false);
surfaceDescriptionStruct.AddShaderChunk("void AddSurfaceDescription(inout SurfaceDescription base, in SurfaceDescription add){", false);
surfaceDescriptionStruct.Indent();
foreach (var slot in slots)
surfaceDescriptionStruct.AddShaderChunk(string.Format("base.{0} = base.{0} + add.{0};", AbstractMaterialNode.GetHLSLSafeName(slot.shaderOutputName)), false);
}
else
{

surfaceDescriptionStruct.AddShaderChunk("};", false);
}
protected static void GenerateSurfaceDescription(
internal static void GenerateSurfaceDescription(
List<INode> activeNodeList,
AbstractMaterialNode masterNode,
AbstractMaterialGraph graph,

string functionName = "PopulateSurfaceData",
string surfaceDescriptionName = "SurfaceDescription",
FloatShaderProperty outputIdProperty = null,
Dictionary<Guid, int> ids = null)
Dictionary<Guid, int> ids = null,
IEnumerable<MaterialSlot> slots = null)
{
if (graph == null)
return;

{
if (masterNode is IMasterNode)
{
foreach (var input in masterNode.GetInputSlots<MaterialSlot>())
var usedSlots = slots ?? masterNode.GetInputSlots<MaterialSlot>();
foreach (var input in usedSlots)
{
var foundEdges = graph.GetEdges(input.slotReference).ToArray();
if (foundEdges.Any())

};
if (isUber)
shaderProperties.AddShaderProperty(outputIdProperty);
GenerateSurfaceDescription(
activeNodeList,
node,

finalShader.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);
finalShader.AddShaderChunk("ENDCG", false);
var masterNode = node as IMasterNode;
if (node != null && masterNode != null)
{
var subShaders = masterNode.GetSubshader(requirements, null);
foreach (var ss in subShaders)
finalShader.AddShaderChunk(ss, false);
}
else
{
finalShader.AddShaderChunk(ShaderGenerator.GetPreviewSubShader(node, requirements), false);
}
finalShader.AddShaderChunk(ShaderGenerator.GetPreviewSubShader(node, requirements), false);
ListPool<INode>.Release(activeNodeList);
finalShader.Deindent();

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraph.cs


public string GetShader(string name, GenerationMode mode, out List<PropertyCollector.TextureInfo> configuredTextures)
{
PreviewMode pmode;
FloatShaderProperty outputIdProperty;
return base.GetShader(masterNode as AbstractMaterialNode, mode, name, out configuredTextures, out pmode, out outputIdProperty);
return masterNode.GetShader(mode, name, out configuredTextures);
}
public void LoadedFromDisk()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/IMasterNode.cs


public interface IMasterNode
{
SurfaceMaterialOptions options { get; }
IEnumerable<string> GetSubshader(ShaderGraphRequirements graphRequirements, MasterRemapGraph remapper);
string GetShader(GenerationMode mode, string name, out List<PropertyCollector.TextureInfo> configuredTextures);
}
}

13
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/MasterNode.cs


[SerializeField]
protected SurfaceMaterialOptions m_MaterialOptions = new SurfaceMaterialOptions();
public MasterNode()
{
name = "MasterNode";
UpdateNodeAfterDeserialization();
}
public override bool hasPreview
{
get { return true; }

get { return PreviewMode.Preview3D; }
}
public virtual ShaderGraphRequirements GetNodeSpecificRequirements()
{
return ShaderGraphRequirements.none;
}
public SurfaceMaterialOptions options
{
get { return m_MaterialOptions; }

public abstract IEnumerable<string> GetSubshader(ShaderGraphRequirements graphRequirements, MasterRemapGraph remapper);
public abstract string GetShader(GenerationMode mode, string name, out List<PropertyCollector.TextureInfo> configuredTextures);
}
}

13
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/LayeredShaderGraph.cs


var masterNode = baseGraph.masterNode;
GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, ((AbstractMaterialNode) masterNode).GetInputSlots<MaterialSlot>().ToList(), true);
foreach (var layer in layerMap)
/* foreach (var layer in layerMap)
{
activeNodes.Clear();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodes, layer.Value.masterNode as AbstractMaterialNode);

requirements,
mode,
LayerToFunctionName(layer.Key));
}
}*/
surfaceDescriptionStruct.AddShaderChunk("struct WeightsSurfaceDescription{", false);
surfaceDescriptionStruct.Indent();

activeNodes.Clear();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodes, outputNode);
GenerateSurfaceDescription(
/*GenerateSurfaceDescription(
activeNodes,
outputNode,
this,

mode,
"PopulateWeightsGraph",
"WeightsSurfaceDescription");
*/
string functionName = "PopulateSurfaceData";
string surfaceDescriptionName = "SurfaceDescription";

if (masterNode != null)
{
var subShaders = masterNode.GetSubshader(requirements, null);
foreach (var ss in subShaders)
finalShader.AddShaderChunk(ss, false);
//var subShaders = masterNode.GetSubshader(requirements, null);
// foreach (var ss in subShaders)
// finalShader.AddShaderChunk(ss, false);
}
finalShader.Deindent();

48
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/SurfaceMaterialOptions.cs


private RenderType m_RenderType = RenderType.Opaque;
[SerializeField]
private bool m_ShadowPass;
[SerializeField]
private bool m_FullForwardShadows;
[SerializeField]
private bool m_NoAmbient;
[SerializeField]
private bool m_NoVertexLights;
[SerializeField]
private bool m_NoLightmaps;
[SerializeField]
private bool m_NoDirLightmap;
[SerializeField]
private bool m_NoForwardAdd;
[SerializeField]
private bool m_ApproxView;
[SerializeField]
private bool m_HalfAsView;
[SerializeField]
[SerializeField]
private bool m_Expanded;
public void Init()
{

zWrite = ZWrite.On;
renderQueue = RenderQueue.Geometry;
renderType = RenderType.Opaque;
shadowPass = false;
fullForwardShadows = false;
noAmbient = false;
noVertexLights = false;
noLightmaps = false;
noDirLightmap = false;
noForwardAdd = false;
approxView = false;
halfAsView = false;
lod = 200;
}

public ZWrite zWrite { get { return m_ZWrite; } set { m_ZWrite = value; } }
public RenderQueue renderQueue { get { return m_RenderQueue; } set { m_RenderQueue = value; } }
public RenderType renderType { get { return m_RenderType; } set { m_RenderType = value; } }
public bool shadowPass { get { return m_ShadowPass; } set { m_ShadowPass = value; } }
public bool fullForwardShadows { get { return m_FullForwardShadows; } set { m_FullForwardShadows = value; } }
public bool noAmbient { get { return m_NoAmbient; } set { m_NoAmbient = value; } }
public bool noVertexLights { get { return m_NoVertexLights; } set { m_NoVertexLights = value; } }
public bool noLightmaps { get { return m_NoLightmaps; } set { m_NoLightmaps = value; } }
public bool noDirLightmap { get { return m_NoDirLightmap; } set { m_NoDirLightmap = value; } }
public bool noForwardAdd { get { return m_NoForwardAdd; } set { m_NoForwardAdd = value; } }
public bool approxView { get { return m_ApproxView; } set { m_ApproxView = value; } }
public bool halfAsView { get { return m_HalfAsView; } set { m_HalfAsView = value; } }
public int lod { get { return m_LOD; } set { m_LOD = value; } }
}
}

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/StandardNodeEditorView.cs


using System.Linq;
using UnityEditor.Graphing.Util;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph.Drawing.Inspector
{

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/PreviewManager.cs


else
{
PreviewMode mode;
shaderData.shaderString = m_Graph.GetPreviewShader(node, out mode);
if (node is IMasterNode)
{
List<PropertyCollector.TextureInfo> configuredTextures;
shaderData.shaderString = ((IMasterNode)node).GetShader(GenerationMode.Preview, node.name, out configuredTextures);
}
else
shaderData.shaderString = m_Graph.GetPreviewShader(node, out mode);
}
File.WriteAllText(Application.dataPath + "/../GeneratedShader.shader", (shaderData.shaderString ?? "null").Replace("UnityEngine.MaterialGraph", "Generated"));

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/GraphEditorView.cs


var textureInfo = new List<PropertyCollector.TextureInfo>();
PreviewMode previewMode;
FloatShaderProperty outputIdProperty;
string shader = graph.GetShader(copyFromNode, GenerationMode.ForReals, assetName, out textureInfo, out previewMode, out outputIdProperty);
GUIUtility.systemCopyBuffer = shader;
if (copyFromNode is MasterNode)
{
var shader = ((MasterNode)copyFromNode).GetShader(GenerationMode.ForReals, copyFromNode.name, out textureInfo);
GUIUtility.systemCopyBuffer = shader;
}
else
{
string shader = graph.GetShader(copyFromNode, GenerationMode.ForReals, assetName, out textureInfo, out previewMode, out outputIdProperty);
GUIUtility.systemCopyBuffer = shader;
}
}
));

108
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template


SubShader
Pass
Tags{"RenderType" = "Opaque" "IgnoreProjectors" = "True" "RenderPipeline" = "LightweightPipeline"}
LOD ${LOD}
Tags{"LightMode" = "LightweightForward"}
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
CGPROGRAM
#pragma target 3.0
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile_fog
#pragma multi_compile_instancing
Pass
{
Tags{"LightMode" = "LightweightForward"}
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
CGPROGRAM
#pragma target 3.0
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag
#pragma glsl
#pragma debug
#pragma vertex vert
#pragma fragment frag
#pragma glsl
#pragma debug
#include "UnityCG.cginc"
#include "UnityCG.cginc"
${Defines}
${Defines}
${Graph}
struct GraphVertexOutput
{
float4 position : POSITION;
${Interpolators}
UNITY_VERTEX_OUTPUT_STEREO
};
struct GraphVertexOutput
{
float4 position : POSITION;
${Interpolators}
UNITY_VERTEX_OUTPUT_STEREO
};
GraphVertexOutput vert (GraphVertexInput v)
{
v = PopulateVertexData(v);
UNITY_SETUP_INSTANCE_ID(v);
GraphVertexOutput vert (GraphVertexInput v)
{
v = PopulateVertexData(v);
UNITY_SETUP_INSTANCE_ID(v);
GraphVertexOutput o;
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.position = UnityObjectToClipPos(v.vertex);
${VertexShader}
return o;
}
GraphVertexOutput o;
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.position = UnityObjectToClipPos(v.vertex);
${VertexShader}
return o;
}
fixed4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}
SurfaceInputs surfaceInput;
${SurfaceInputs}
fixed4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}
SurfaceInputs surfaceInput;
${SurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float3 Color = 0;
float3 Alpha = 0;
${SurfaceOutputRemap}
#ifdef _ALPHABLEND_ON
return fixed4(Color, Alpha);
#else
return fixed4(Color, 1.0);
#endif
}
ENDCG
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float3 Color = 0;
float3 Alpha = 0;
${SurfaceOutputRemap}
return fixed4(Color, Alpha);
ENDCG
}

281
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
public class LightWeightPBRSubShader
{
Pass m_ForwardPassMetallic = new Pass()
{
Name = "LightweightForward",
PixelShaderSlots = new List<int>()
{
PBRMasterNode.AlbedoSlotId,
PBRMasterNode.NormalSlotId,
PBRMasterNode.EmissionSlotId,
PBRMasterNode.MetallicSlotId,
PBRMasterNode.SmoothnessSlotId,
PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId
}
};
struct Pass
{
public string Name;
public List<int> VertexShaderSlots;
public List<int> PixelShaderSlots;
}
Pass m_ForwardPassSpecular = new Pass()
{
Name = "LightweightForward",
PixelShaderSlots = new List<int>()
{
PBRMasterNode.AlbedoSlotId,
PBRMasterNode.NormalSlotId,
PBRMasterNode.EmissionSlotId,
PBRMasterNode.SpecularSlotId,
PBRMasterNode.SmoothnessSlotId,
PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId
}
};
private static string GetShaderPassFromTemplate(string template, PBRMasterNode masterNode, Pass pass, GenerationMode mode)
{
var surfaceVertexShader = new ShaderGenerator();
var surfaceDescriptionFunction = new ShaderGenerator();
var surfaceDescriptionStruct = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var surfaceInputs = new ShaderGenerator();
var shaderProperties = new PropertyCollector();
var graphVertexInput = @"
struct GraphVertexInput
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float4 color : COLOR;
float4 texcoord0 : TEXCOORD0;
float4 lightmapUV : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};";
surfaceInputs.AddShaderChunk("struct SurfaceInputs{", false);
surfaceInputs.Indent();
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
var requirements = AbstractMaterialGraph.GetRequirements(activeNodeList);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresNormal, InterpolatorType.Normal, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresTangent, InterpolatorType.Tangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresBitangent, InterpolatorType.BiTangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresViewDir, InterpolatorType.ViewDirection, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresPosition, InterpolatorType.Position, surfaceInputs);
if (requirements.requiresVertexColor)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.VertexColor), false);
if (requirements.requiresScreenPosition)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.ScreenPosition), false);
foreach (var channel in requirements.requiresMeshUVs.Distinct())
surfaceInputs.AddShaderChunk(string.Format("half4 {0};", channel.GetUVName()), false);
surfaceInputs.Deindent();
surfaceInputs.AddShaderChunk("};", false);
surfaceVertexShader.AddShaderChunk("GraphVertexInput PopulateVertexData(GraphVertexInput v){", false);
surfaceVertexShader.Indent();
surfaceVertexShader.AddShaderChunk("return v;", false);
surfaceVertexShader.Deindent();
surfaceVertexShader.AddShaderChunk("}", false);
var slots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
slots.Add(masterNode.FindSlot<MaterialSlot>(id));
AbstractMaterialGraph.GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, slots, true);
var usedSlots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
usedSlots.Add(masterNode.FindSlot<MaterialSlot>(id));
AbstractMaterialGraph.GenerateSurfaceDescription(
activeNodeList,
masterNode,
masterNode.owner as AbstractMaterialGraph,
surfaceDescriptionFunction,
shaderFunctionVisitor,
shaderProperties,
requirements,
mode,
"PopulateSurfaceData",
"SurfaceDescription",
null,
null,
usedSlots);
var graph = new ShaderGenerator();
graph.AddShaderChunk(shaderFunctionVisitor.GetShaderString(2), false);
graph.AddShaderChunk(graphVertexInput, false);
graph.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionStruct.GetShaderString(2), false);
graph.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
graph.AddShaderChunk(surfaceVertexShader.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);
var tagsVisitor = new ShaderGenerator();
var blendingVisitor = new ShaderGenerator();
var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
var materialOptions = new SurfaceMaterialOptions();
switch (masterNode.alphaMode)
{
case PBRMasterNode.AlphaMode.Overwrite:
case PBRMasterNode.AlphaMode.Clip:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.Zero;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.On;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Geometry;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Opaque;
break;
case PBRMasterNode.AlphaMode.AlphaBlend:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.SrcAlpha;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.OneMinusSrcAlpha;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
case PBRMasterNode.AlphaMode.AdditiveBlend:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
}
materialOptions.GetTags(tagsVisitor);
materialOptions.GetBlend(blendingVisitor);
materialOptions.GetCull(cullingVisitor);
materialOptions.GetDepthTest(zTestVisitor);
materialOptions.GetDepthWrite(zWriteVisitor);
var interpolators = new ShaderGenerator();
var localVertexShader = new ShaderGenerator();
var localPixelShader = new ShaderGenerator();
var localSurfaceInputs = new ShaderGenerator();
var surfaceOutputRemap = new ShaderGenerator();
var reqs = ShaderGraphRequirements.none;
reqs.requiresNormal |= NeededCoordinateSpace.World;
reqs.requiresTangent |= NeededCoordinateSpace.World;
reqs.requiresBitangent |= NeededCoordinateSpace.World;
reqs.requiresPosition |= NeededCoordinateSpace.World;
reqs.requiresViewDir |= NeededCoordinateSpace.World;
ShaderGenerator.GenerateStandardTransforms(
3,
10,
interpolators,
localVertexShader,
localPixelShader,
localSurfaceInputs,
requirements,
reqs,
CoordinateSpace.World);
ShaderGenerator defines = new ShaderGenerator();
defines.AddShaderChunk("#define _GLOSSYREFLECTIONS_ON", true);
defines.AddShaderChunk("#define _SPECULARHIGHLIGHTS_ON", true);
if (masterNode.IsSlotConnected(PBRMasterNode.NormalSlotId))
defines.AddShaderChunk("#define _NORMALMAP 1", true);
if (masterNode.model == PBRMasterNode.Model.Metallic)
defines.AddShaderChunk("#define _METALLIC_SETUP 1", true);
switch (masterNode.alphaMode)
{
case PBRMasterNode.AlphaMode.AlphaBlend:
case PBRMasterNode.AlphaMode.AdditiveBlend:
defines.AddShaderChunk("#define _AlphaOut 1", true);
break;
case PBRMasterNode.AlphaMode.Clip:
defines.AddShaderChunk("#define _AlphaClip 1", true);
break;
}
var templateLocation = ShaderGenerator.GetTemplatePath(template);
foreach (var slot in usedSlots)
{
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
}
if (!File.Exists(templateLocation))
return string.Empty;
var subShaderTemplate = File.ReadAllText(templateLocation);
var resultPass = subShaderTemplate.Replace("${Defines}", defines.GetShaderString(3));
resultPass = resultPass.Replace("${Graph}", graph.GetShaderString(3));
resultPass = resultPass.Replace("${Interpolators}", interpolators.GetShaderString(3));
resultPass = resultPass.Replace("${VertexShader}", localVertexShader.GetShaderString(3));
resultPass = resultPass.Replace("${LocalPixelShader}", localPixelShader.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceInputs}", localSurfaceInputs.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultPass = resultPass.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${LOD}", "" + materialOptions.lod);
return resultPass;
}
public IEnumerable<string> GetSubshader(PBRMasterNode masterNode, GenerationMode mode)
{
var subShader = new ShaderGenerator();
subShader.AddShaderChunk("SubShader", true);
subShader.AddShaderChunk("{", true);
subShader.Indent();
subShader.AddShaderChunk("Tags{ \"RenderPipeline\" = \"LightweightPipeline\"}", true);
subShader.AddShaderChunk(
GetShaderPassFromTemplate(
"lightweightPBRForwardPass.template",
masterNode,
masterNode.model == PBRMasterNode.Model.Metallic ? m_ForwardPassMetallic : m_ForwardPassSpecular,
mode),
true);
var extraPassesTemplateLocation = ShaderGenerator.GetTemplatePath("lightweightPBRExtraPasses.template");
if (File.Exists(extraPassesTemplateLocation))
subShader.AddShaderChunk(File.ReadAllText(extraPassesTemplateLocation), true);
subShader.Deindent();
subShader.AddShaderChunk("}", true);
return new[] { subShader.GetShaderString(0) };
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs.meta


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

208
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs


using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
public class LightWeightUnlitSubShader
{
Pass m_UnlitPass = new Pass()
{
Name = "Unlit",
PixelShaderSlots = new List<int>()
{
UnlitMasterNode.ColorSlotId,
UnlitMasterNode.AlphaSlotId
}
};
struct Pass
{
public string Name;
public List<int> VertexShaderSlots;
public List<int> PixelShaderSlots;
}
private static string GetShaderPassFromTemplate(string template, UnlitMasterNode masterNode, Pass pass, GenerationMode mode)
{
var surfaceVertexShader = new ShaderGenerator();
var surfaceDescriptionFunction = new ShaderGenerator();
var surfaceDescriptionStruct = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var surfaceInputs = new ShaderGenerator();
var shaderProperties = new PropertyCollector();
var graphVertexInput = @"
struct GraphVertexInput
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float4 color : COLOR;
float4 texcoord0 : TEXCOORD0;
float4 lightmapUV : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};";
surfaceInputs.AddShaderChunk("struct SurfaceInputs{", false);
surfaceInputs.Indent();
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
var requirements = AbstractMaterialGraph.GetRequirements(activeNodeList);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresNormal, InterpolatorType.Normal, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresTangent, InterpolatorType.Tangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresBitangent, InterpolatorType.BiTangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresViewDir, InterpolatorType.ViewDirection, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresPosition, InterpolatorType.Position, surfaceInputs);
if (requirements.requiresVertexColor)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.VertexColor), false);
if (requirements.requiresScreenPosition)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.ScreenPosition), false);
foreach (var channel in requirements.requiresMeshUVs.Distinct())
surfaceInputs.AddShaderChunk(string.Format("half4 {0};", channel.GetUVName()), false);
surfaceInputs.Deindent();
surfaceInputs.AddShaderChunk("};", false);
surfaceVertexShader.AddShaderChunk("GraphVertexInput PopulateVertexData(GraphVertexInput v){", false);
surfaceVertexShader.Indent();
surfaceVertexShader.AddShaderChunk("return v;", false);
surfaceVertexShader.Deindent();
surfaceVertexShader.AddShaderChunk("}", false);
var slots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
{
var slot = masterNode.FindSlot<MaterialSlot>(id);
if (slot != null)
slots.Add(slot);
}
AbstractMaterialGraph.GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, slots, true);
var usedSlots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
usedSlots.Add(masterNode.FindSlot<MaterialSlot>(id));
AbstractMaterialGraph.GenerateSurfaceDescription(
activeNodeList,
masterNode,
masterNode.owner as AbstractMaterialGraph,
surfaceDescriptionFunction,
shaderFunctionVisitor,
shaderProperties,
requirements,
mode,
"PopulateSurfaceData",
"SurfaceDescription",
null,
null,
usedSlots);
var graph = new ShaderGenerator();
graph.AddShaderChunk(shaderFunctionVisitor.GetShaderString(2), false);
graph.AddShaderChunk(graphVertexInput, false);
graph.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionStruct.GetShaderString(2), false);
graph.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
graph.AddShaderChunk(surfaceVertexShader.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);
var tagsVisitor = new ShaderGenerator();
var blendingVisitor = new ShaderGenerator();
var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
var materialOptions = new SurfaceMaterialOptions();
materialOptions.GetTags(tagsVisitor);
materialOptions.GetBlend(blendingVisitor);
materialOptions.GetCull(cullingVisitor);
materialOptions.GetDepthTest(zTestVisitor);
materialOptions.GetDepthWrite(zWriteVisitor);
var interpolators = new ShaderGenerator();
var localVertexShader = new ShaderGenerator();
var localPixelShader = new ShaderGenerator();
var localSurfaceInputs = new ShaderGenerator();
var surfaceOutputRemap = new ShaderGenerator();
var reqs = ShaderGraphRequirements.none;
reqs.requiresNormal |= NeededCoordinateSpace.World;
reqs.requiresTangent |= NeededCoordinateSpace.World;
reqs.requiresBitangent |= NeededCoordinateSpace.World;
reqs.requiresPosition |= NeededCoordinateSpace.World;
reqs.requiresViewDir |= NeededCoordinateSpace.World;
ShaderGenerator.GenerateStandardTransforms(
3,
10,
interpolators,
localVertexShader,
localPixelShader,
localSurfaceInputs,
requirements,
reqs,
CoordinateSpace.World);
ShaderGenerator defines = new ShaderGenerator();
var templateLocation = ShaderGenerator.GetTemplatePath(template);
foreach (var slot in usedSlots)
{
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
}
if (!File.Exists(templateLocation))
return string.Empty;
var subShaderTemplate = File.ReadAllText(templateLocation);
var resultPass = subShaderTemplate.Replace("${Defines}", defines.GetShaderString(3));
resultPass = resultPass.Replace("${Graph}", graph.GetShaderString(3));
resultPass = resultPass.Replace("${Interpolators}", interpolators.GetShaderString(3));
resultPass = resultPass.Replace("${VertexShader}", localVertexShader.GetShaderString(3));
resultPass = resultPass.Replace("${LocalPixelShader}", localPixelShader.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceInputs}", localSurfaceInputs.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultPass = resultPass.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${LOD}", "" + materialOptions.lod);
return resultPass;
}
public IEnumerable<string> GetSubshader(UnlitMasterNode masterNode, GenerationMode mode)
{
var subShader = new ShaderGenerator();
subShader.AddShaderChunk("SubShader", true);
subShader.AddShaderChunk("{", true);
subShader.Indent();
subShader.AddShaderChunk("Tags{ \"RenderType\" = \"Opaque\" \"RenderPipeline\" = \"LightweightPipeline\"}", true);
subShader.AddShaderChunk(
GetShaderPassFromTemplate(
"lightweightUnlitPass.template",
masterNode,
m_UnlitPass,
mode),
true);
subShader.Deindent();
subShader.AddShaderChunk("}", true);
return new[] { subShader.GetShaderString(0) };
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs.meta


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

163
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[Title("Master/PBR")]
public class PBRMasterNode : MasterNode
{
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 VertexOffsetName = "VertexPosition";
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 enum Model
{
Specular,
Metallic
}
public enum AlphaMode
{
Overwrite,
AlphaBlend,
AdditiveBlend,
Clip
}
[SerializeField]
private Model m_Model = Model.Metallic;
[EnumControl("")]
public Model model
{
get { return m_Model; }
set
{
if (m_Model == value)
return;
m_Model = value;
UpdateNodeAfterDeserialization();
if (onModified != null)
{
onModified(this, ModificationScope.Topological);
}
}
}
[SerializeField]
private AlphaMode m_AlphaMode;
[EnumControl("")]
public AlphaMode alphaMode
{
get { return m_AlphaMode; }
set
{
if (m_AlphaMode == value)
return;
m_AlphaMode = value;
if (onModified != null)
{
onModified(this, ModificationScope.Graph);
}
}
}
public PBRMasterNode()
{
UpdateNodeAfterDeserialization();
}
public bool IsSlotConnected(int slotId)
{
var slot = FindSlot<MaterialSlot>(slotId);
return slot != null && owner.GetEdges(slot.slotReference).Any();
}
public sealed override void UpdateNodeAfterDeserialization()
{
name = "PBR Master";
AddSlot(new Vector3MaterialSlot(AlbedoSlotId, AlbedoSlotName, AlbedoSlotName, SlotType.Input, new Vector4(0.5f, 0.5f, 0.5f), ShaderStage.Fragment));
AddSlot(new Vector3MaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, SlotType.Input, new Vector3(0, 0, 1), ShaderStage.Fragment));
AddSlot(new Vector3MaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Vector3.zero, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, 0, ShaderStage.Fragment));
AddSlot(new Vector3MaterialSlot(SpecularSlotId, SpecularSlotName, SpecularSlotName, SlotType.Input, Vector3.zero, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input, 1f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1f, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
model == Model.Metallic ? MetallicSlotId : SpecularSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId
});
}
public override string GetShader(GenerationMode mode, string outputName, out List<PropertyCollector.TextureInfo> configuredTextures)
{
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, this);
var shaderProperties = new PropertyCollector();
var abstractMaterialGraph = owner as AbstractMaterialGraph;
if (abstractMaterialGraph != null)
abstractMaterialGraph.CollectShaderProperties(shaderProperties, mode);
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
activeNode.CollectShaderProperties(shaderProperties, mode);
var finalShader = new ShaderGenerator();
finalShader.AddShaderChunk(string.Format(@"Shader ""{0}""", outputName), false);
finalShader.AddShaderChunk("{", false);
finalShader.Indent();
finalShader.AddShaderChunk("Properties", false);
finalShader.AddShaderChunk("{", false);
finalShader.Indent();
finalShader.AddShaderChunk(shaderProperties.GetPropertiesBlock(2), false);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
var lwSub = new LightWeightPBRSubShader();
foreach (var subshader in lwSub.GetSubshader(this, mode))
finalShader.AddShaderChunk(subshader, true);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
configuredTextures = shaderProperties.GetConfiguredTexutres();
return finalShader.GetShaderString(0);
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs.meta


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

79
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/UnlitMasterNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[Title("Master/Unlit")]
public class UnlitMasterNode : MasterNode
{
public const string ColorSlotName = "Color";
public const string AlphaSlotName = "Alpha";
public const string VertexOffsetName = "VertexPosition";
public const int ColorSlotId = 0;
public const int AlphaSlotId = 7;
public UnlitMasterNode()
{
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
name = "Unlit Master";
AddSlot(new Vector3MaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, new Vector3(0.5f, 0.5f, 0.5f), ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
ColorSlotId,
AlphaSlotId
});
}
public override string GetShader(GenerationMode mode, string outputName, out List<PropertyCollector.TextureInfo> configuredTextures)
{
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, this);
var shaderProperties = new PropertyCollector();
var abstractMaterialGraph = owner as AbstractMaterialGraph;
if (abstractMaterialGraph != null)
abstractMaterialGraph.CollectShaderProperties(shaderProperties, mode);
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
activeNode.CollectShaderProperties(shaderProperties, mode);
var finalShader = new ShaderGenerator();
finalShader.AddShaderChunk(string.Format(@"Shader ""{0}""", outputName), false);
finalShader.AddShaderChunk("{", false);
finalShader.Indent();
finalShader.AddShaderChunk("Properties", false);
finalShader.AddShaderChunk("{", false);
finalShader.Indent();
finalShader.AddShaderChunk(shaderProperties.GetPropertiesBlock(2), false);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
var lwSub = new LightWeightUnlitSubShader();
foreach (var subshader in lwSub.GetSubshader(this, mode))
finalShader.AddShaderChunk(subshader, true);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
configuredTextures = shaderProperties.GetConfiguredTexutres();
return finalShader.GetShaderString(0);
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/UnlitMasterNode.cs.meta


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

40
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template


Pass
{
Tags{"Lightmode" = "ShadowCaster"}
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "UnityCG.cginc"
#include "LightweightPassShadow.cginc"
ENDCG
}
Pass
{
Tags{"Lightmode" = "DepthOnly"}
ZWrite On
CGPROGRAM
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return UnityObjectToClipPos(pos);
}
half4 frag() : SV_TARGET
{
return 0;
}
ENDCG
}

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template.meta


fileFormatVersion: 2
guid: 5fa0a7ad9ac73b34691439e5cf40a1c3
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

145
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template


Pass
{
Tags{"LightMode" = "LightweightForward"}
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
CGPROGRAM
#pragma target 3.0
#pragma multi_compile _MAIN_DIRECTIONAL_LIGHT _MAIN_SPOT_LIGHT _MAIN_POINT_LIGHT
#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ _HARD_SHADOWS _SOFT_SHADOWS _HARD_SHADOWS_CASCADES _SOFT_SHADOWS_CASCADES
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag
#pragma glsl
#pragma debug
${Defines}
#include "LightweightLighting.cginc"
${Graph}
struct GraphVertexOutput
{
float4 position : POSITION;
float4 lwCustom : TEXCOORD0;
float4 fogCoord : TEXCOORD1; // x: fogCoord, yzw: vertexColor
${Interpolators}
UNITY_VERTEX_OUTPUT_STEREO
};
GraphVertexOutput vert (GraphVertexInput v)
{
v = PopulateVertexData(v);
UNITY_SETUP_INSTANCE_ID(v);
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.position = UnityObjectToClipPos(v.vertex);
${VertexShader}
#ifdef LIGHTMAP_ON
o.lwCustom.zw = v.lightmapUV * unity_LightmapST.xy + unity_LightmapST.zw;
#endif
float3 lwWNormal = normalize(UnityObjectToWorldNormal(v.normal));
float3 lwWorldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
// TODO: change to only support point lights per vertex. This will greatly simplify shader ALU
#if defined(_VERTEX_LIGHTS) && defined(_MULTIPLE_LIGHTS)
half3 diffuse = half3(1.0, 1.0, 1.0);
// pixel lights shaded = min(pixelLights, perObjectLights)
// vertex lights shaded = min(vertexLights, perObjectLights) - pixel lights shaded
// Therefore vertexStartIndex = pixelLightCount; vertexEndIndex = min(vertexLights, perObjectLights)
int vertexLightStart = min(globalLightCount.x, unity_LightIndicesOffsetAndCount.y);
int vertexLightEnd = min(globalLightCount.y, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = vertexLightStart; lightIter < vertexLightEnd; ++lightIter)
{
int lightIndex = unity_4LightIndices0[lightIter];
LightInput lightInput;
INITIALIZE_LIGHT(lightInput, lightIndex);
half3 lightDirection;
half atten = ComputeLightAttenuationVertex(lightInput, lwWNormal, lwWorldPos, lightDirection);
o.fogCoord.yzw += LightingLambert(diffuse, lightDirection, lwWNormal, atten);
}
#endif
#if defined(_LIGHT_PROBES_ON) && !defined(LIGHTMAP_ON)
o.fogCoord.yzw += max(half3(0, 0, 0), ShadeSH9(half4(lwWNormal, 1)));
#endif
UNITY_TRANSFER_FOG(o, o.position);
return o;
}
fixed4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}
SurfaceInputs surfaceInput = (SurfaceInputs)0;
${SurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float3 Albedo = float3(0.5, 0.5, 0.5);
float3 Specular = float3(0, 0, 0);
float Metallic = 0;
float3 Normal = float3(0, 0, 1);
float3 Emission = 0;
float Smoothness = 0.5;
float Occlusion = 1;
float Alpha = 1;
${SurfaceOutputRemap}
#if defined(UNITY_COLORSPACE_GAMMA)
Albedo = Albedo * Albedo;
Emission = Emission * Emission;
#endif
half4 result = LightweightFragmentPBR(
IN.lwCustom,
WorldSpacePosition,
WorldSpaceNormal,
WorldSpaceTangent,
WorldSpaceBiTangent,
WorldSpaceViewDirection,
IN.fogCoord.x,
Albedo,
Metallic,
Specular,
Smoothness,
Normal,
Occlusion,
Emission,
Alpha);
#if _AlphaOut
result.a = Alpha;
#else
result.a = 1;
#endif
#if _AlphaClip
clip(Alpha - 0.01);
#endif
return result;
}
ENDCG
}

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightPBRMasterNode.cs.meta


fileFormatVersion: 2
guid: 1ac259924f8784a4aa1eb5e9e556b08d
timeCreated: 1478188276
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightMetallicMasterNode.cs.meta


fileFormatVersion: 2
guid: 4b9e77744d433de4186738959cadcfca
timeCreated: 1478188276
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightSpecularMasterNode.cs.meta


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

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightUnlitMasterNode.cs.meta


fileFormatVersion: 2
guid: 19892eaf92f3e2e49928945f6da04525
timeCreated: 1478188276
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightMasterNode.cs.meta


fileFormatVersion: 2
guid: 72c867ea29464bec864ea612e2bcecd3
timeCreated: 1505799928

57
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightPBRMasterNode.cs


using System;
using System.Linq;
namespace UnityEditor.ShaderGraph
{
[Serializable]
public abstract class AbstractLightweightPBRMasterNode : AbstractLightweightMasterNode
{
public const string AlbedoSlotName = "Albedo";
public const string NormalSlotName = "Normal";
public const string EmissionSlotName = "Emission";
public const string SmoothnessSlotName = "Smoothness";
public const string OcclusionSlotName = "Occlusion";
public const string AlphaSlotName = "Alpha";
public const string VertexOffsetName = "VertexPosition";
public const int AlbedoSlotId = 0;
public const int NormalSlotId = 1;
public const int EmissionSlotId = 3;
public const int SmoothnessSlotId = 4;
public const int OcclusionSlotId = 5;
public const int AlphaSlotId = 6;
protected override void GetLightweightDefinesAndRemap(ShaderGenerator defines, ShaderGenerator surfaceOutputRemap, MasterRemapGraph remapper)
{
base.GetLightweightDefinesAndRemap(defines, surfaceOutputRemap, remapper);
defines.AddShaderChunk("#define _GLOSSYREFLECTIONS_ON", true);
defines.AddShaderChunk("#define _SPECULARHIGHLIGHTS_ON", true);
if(IsNormalMapConnected())
defines.AddShaderChunk("#define _NORMALMAP 1", true);
}
protected override int GetInterpolatorStartIndex()
{
return 2;
}
public override ShaderGraphRequirements GetNodeSpecificRequirements()
{
var reqs = ShaderGraphRequirements.none;
reqs.requiresNormal |= NeededCoordinateSpace.World;
reqs.requiresTangent |= NeededCoordinateSpace.World;
reqs.requiresBitangent |= NeededCoordinateSpace.World;
reqs.requiresPosition |= NeededCoordinateSpace.World;
reqs.requiresViewDir |= NeededCoordinateSpace.World;
return base.GetNodeSpecificRequirements().Union(reqs);
}
bool IsNormalMapConnected()
{
var nm = FindSlot<MaterialSlot>(NormalSlotId);
return owner.GetEdges(nm.slotReference).Any();
}
}
}

71
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightUnlitMasterNode.cs


using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[Title("Master/Lightweight/Unlit")]
public class LightweightUnlitMasterNode : AbstractLightweightMasterNode
{
public const string ColorSlotName = "Color";
public const string AlphaSlotName = "Alpha";
public const int ColorSlotId = 0;
public const int AlphaSlotId = 1;
public LightweightUnlitMasterNode()
{
name = "LightweightUnlitMasterNode";
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector3MaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, Vector3.zero, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 0, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
ColorSlotId,
AlphaSlotId
});
}
protected override IEnumerable<int> masterSurfaceInputs
{
get
{
return new[]
{
ColorSlotId,
AlphaSlotId,
};
}
}
protected override IEnumerable<int> masterVertexInputs
{
get
{
return new int[]
{
};
}
}
protected override string GetTemplateName()
{
return "lightweightSubshaderUnlit.template";
}
protected override int GetInterpolatorStartIndex()
{
return 0;
}
}
}

126
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightMasterNode.cs


using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
public abstract class AbstractLightweightMasterNode : MasterNode
{
private const int kMaxInterpolators = 8;
protected abstract IEnumerable<int> masterSurfaceInputs { get; }
protected abstract IEnumerable<int> masterVertexInputs { get; }
protected abstract string GetTemplateName();
protected virtual void GetLightweightDefinesAndRemap(ShaderGenerator defines, ShaderGenerator surfaceOutputRemap, MasterRemapGraph remapper)
{
// Step 1: no remapper, working with raw master node..
if (remapper == null)
{
foreach (var slot in GetInputSlots<MaterialSlot>())
{
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
}
}
// Step 2: remapper present... complex workflow time
else
{
surfaceOutputRemap.AddShaderChunk("{", false);
surfaceOutputRemap.Indent();
foreach (var prop in remapper.properties)
{
surfaceOutputRemap.AddShaderChunk(prop.GetInlinePropertyDeclarationString(), true);
surfaceOutputRemap.AddShaderChunk(string.Format("{0} = surf.{0};", prop.referenceName), true);
}
List<INode> nodes = new List<INode>();
NodeUtils.DepthFirstCollectNodesFromNode(nodes, this, NodeUtils.IncludeSelf.Exclude);
foreach (var activeNode in nodes.OfType<AbstractMaterialNode>())
{
if (activeNode is IGeneratesBodyCode)
(activeNode as IGeneratesBodyCode).GenerateNodeCode(surfaceOutputRemap, GenerationMode.ForReals);
}
foreach (var input in GetInputSlots<MaterialSlot>())
{
foreach (var edge in owner.GetEdges(input.slotReference))
{
var outputRef = edge.outputSlot;
var fromNode = owner.GetNodeFromGuid<AbstractMaterialNode>(outputRef.nodeGuid);
if (fromNode == null)
continue;
surfaceOutputRemap.AddShaderChunk(
string.Format("{0} = {1};", input.shaderOutputName,
fromNode.GetVariableNameForSlot(outputRef.slotId)), true);
}
}
surfaceOutputRemap.Deindent();
surfaceOutputRemap.AddShaderChunk("}", false);
}
}
public override IEnumerable<string> GetSubshader(ShaderGraphRequirements graphRequirements, MasterRemapGraph remapper)
{
var tagsVisitor = new ShaderGenerator();
var blendingVisitor = new ShaderGenerator();
var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
m_MaterialOptions.GetTags(tagsVisitor);
m_MaterialOptions.GetBlend(blendingVisitor);
m_MaterialOptions.GetCull(cullingVisitor);
m_MaterialOptions.GetDepthTest(zTestVisitor);
m_MaterialOptions.GetDepthWrite(zWriteVisitor);
var interpolators = new ShaderGenerator();
var vertexShader = new ShaderGenerator();
var localPixelShader = new ShaderGenerator();
var surfaceInputs = new ShaderGenerator();
ShaderGenerator.GenerateStandardTransforms(
GetInterpolatorStartIndex(),
10,
interpolators,
vertexShader,
localPixelShader,
surfaceInputs,
graphRequirements,
GetNodeSpecificRequirements(),
CoordinateSpace.World);
ShaderGenerator defines = new ShaderGenerator();
ShaderGenerator surfaceOutputRemap = new ShaderGenerator();
GetLightweightDefinesAndRemap(defines, surfaceOutputRemap, remapper);
var templateLocation = ShaderGenerator.GetTemplatePath(GetTemplateName());
if (!File.Exists(templateLocation))
return new string[] {};
var subShaderTemplate = File.ReadAllText(templateLocation);
var resultShader = subShaderTemplate.Replace("${Defines}", defines.GetShaderString(3));
resultShader = resultShader.Replace("${Interpolators}", interpolators.GetShaderString(3));
resultShader = resultShader.Replace("${VertexShader}", vertexShader.GetShaderString(3));
resultShader = resultShader.Replace("${LocalPixelShader}", localPixelShader.GetShaderString(3));
resultShader = resultShader.Replace("${SurfaceInputs}", surfaceInputs.GetShaderString(3));
resultShader = resultShader.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultShader = resultShader.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${LOD}", "" + m_MaterialOptions.lod);
return new[] {resultShader};
}
protected abstract int GetInterpolatorStartIndex();
}
}

84
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightMetallicMasterNode.cs


using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[Title("Master/Lightweight/PBR Metallic")]
public class LightweightMetallicMasterNode : AbstractLightweightPBRMasterNode
{
public const string MetallicSlotName = "Metallic";
public const int MetallicSlotId = 2;
public LightweightMetallicMasterNode()
{
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
name = "LW Metallic Master";
AddSlot(new Vector3MaterialSlot(AlbedoSlotId, AlbedoSlotName, AlbedoSlotName, SlotType.Input, new Vector4(0.5f, 0.5f, 0.5f), ShaderStage.Fragment));
AddSlot(new Vector3MaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, SlotType.Input, new Vector3(0,0,1), ShaderStage.Fragment));
AddSlot(new Vector3MaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Vector3.zero, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input,0, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input, 1f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 0, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
MetallicSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId
});
}
protected override string GetTemplateName()
{
return "lightweightSubshaderPBR.template";
}
protected override void GetLightweightDefinesAndRemap(ShaderGenerator defines, ShaderGenerator surfaceOutputRemap, MasterRemapGraph remapper)
{
base.GetLightweightDefinesAndRemap(defines, surfaceOutputRemap, remapper);
defines.AddShaderChunk("#define _METALLIC_SETUP 1", true);
}
protected override IEnumerable<int> masterSurfaceInputs
{
get
{
return new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
MetallicSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
};
}
}
protected override IEnumerable<int> masterVertexInputs
{
get
{
return new int[]
{
};
}
}
}
}

79
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightSpecularMasterNode.cs


using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[Title("Master/Lightweight/PBR Specular")]
public class LightweightSpecularMasterNode : AbstractLightweightPBRMasterNode
{
public const string SpecularSlotName = "Specular";
public const int SpecularSlotId = 2;
public const string WorkflowName = "Specular";
public LightweightSpecularMasterNode()
{
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
name = "LW Specular Master";
AddSlot(new Vector3MaterialSlot(AlbedoSlotId, AlbedoSlotName, AlbedoSlotName, SlotType.Input, new Vector3(0.5f, 0.5f, 0.5f), ShaderStage.Fragment));
AddSlot(new Vector3MaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, SlotType.Input, new Vector3(0,0,1), ShaderStage.Fragment));
AddSlot(new Vector3MaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Vector3.zero, ShaderStage.Fragment));
AddSlot(new Vector3MaterialSlot(SpecularSlotId, SpecularSlotName, SpecularSlotName, SlotType.Input, Vector3.zero, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input,0, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
SpecularSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId
});
}
protected override string GetTemplateName()
{
return "lightweightSubshaderPBR.template";
}
protected override IEnumerable<int> masterSurfaceInputs
{
get
{
return new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
SpecularSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
};
}
}
protected override IEnumerable<int> masterVertexInputs
{
get
{
return new int[]
{
};
}
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/MasterRemapNode.cs.meta


fileFormatVersion: 2
guid: 861139fc6f60415cae2eb9a9625aaeb8
timeCreated: 1506873607

101
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/MasterRemapNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Title("Master/Remap-Node")]
public class MasterRemapNode : AbstractSubGraphNode, IMasterNode
{
[SerializeField]
protected SurfaceMaterialOptions m_MaterialOptions = new SurfaceMaterialOptions();
public SurfaceMaterialOptions options
{
get { return m_MaterialOptions; }
}
public override PreviewMode previewMode
{
get { return PreviewMode.Preview3D; }
}
[SerializeField]
private string m_SerializedRemapGraph = string.Empty;
[Serializable]
private class RemapGraphHelper
{
public MasterRemapGraphAsset remapGraph;
}
protected override AbstractSubGraph referencedGraph
{
get
{
if (remapGraphAsset == null)
return null;
return remapGraphAsset.remapGraph;
}
}
#if UNITY_EDITOR
[ObjectControl("Remap")]
public MasterRemapGraphAsset remapGraphAsset
{
get
{
if (string.IsNullOrEmpty(m_SerializedRemapGraph))
return null;
var helper = new RemapGraphHelper();
EditorJsonUtility.FromJsonOverwrite(m_SerializedRemapGraph, helper);
return helper.remapGraph;
}
set
{
if (remapGraphAsset == value)
return;
var helper = new RemapGraphHelper();
helper.remapGraph = value;
m_SerializedRemapGraph = EditorJsonUtility.ToJson(helper, true);
UpdateSlots();
if (onModified != null)
onModified(this, ModificationScope.Topological);
}
}
#else
public MaterialSubGraphAsset subGraphAsset {get; set; }
#endif
public MasterRemapNode()
{
name = "RemapMaster";
}
public IEnumerable<string> GetSubshader(ShaderGraphRequirements graphRequirements, MasterRemapGraph remapper)
{
if (referencedGraph == null)
return new string[]{};
var masterNodes = referencedGraph.activeNodes.OfType<IMasterNode>().ToList();
if (masterNodes.Count == 0)
return new string[]{};
var results = new List<string>();
foreach (var master in masterNodes)
results.AddRange(master.GetSubshader(graphRequirements, referencedGraph as MasterRemapGraph));
return results;
}
}
}

180
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightSubshaderPBR.template


SubShader
{
Tags{"RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline"}
LOD ${LOD}
Pass
{
Tags{"LightMode" = "LightweightForward"}
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
CGPROGRAM
#pragma target 3.0
#pragma multi_compile _MAIN_DIRECTIONAL_LIGHT _MAIN_SPOT_LIGHT _MAIN_POINT_LIGHT
#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ _HARD_SHADOWS _SOFT_SHADOWS _HARD_SHADOWS_CASCADES _SOFT_SHADOWS_CASCADES
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag
#pragma glsl
#pragma debug
${Defines}
#include "LightweightLighting.cginc"
struct GraphVertexOutput
{
float4 position : POSITION;
float4 lwCustom : TEXCOORD0;
float4 fogCoord : TEXCOORD1; // x: fogCoord, yzw: vertexColor
${Interpolators}
UNITY_VERTEX_OUTPUT_STEREO
};
GraphVertexOutput vert (GraphVertexInput v)
{
v = PopulateVertexData(v);
UNITY_SETUP_INSTANCE_ID(v);
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.position = UnityObjectToClipPos(v.vertex);
${VertexShader}
#ifdef LIGHTMAP_ON
o.lwCustom.zw = v.lightmapUV * unity_LightmapST.xy + unity_LightmapST.zw;
#endif
float3 lwWNormal = normalize(UnityObjectToWorldNormal(v.normal));
float3 lwWorldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
// TODO: change to only support point lights per vertex. This will greatly simplify shader ALU
#if defined(_VERTEX_LIGHTS) && defined(_MULTIPLE_LIGHTS)
half3 diffuse = half3(1.0, 1.0, 1.0);
// pixel lights shaded = min(pixelLights, perObjectLights)
// vertex lights shaded = min(vertexLights, perObjectLights) - pixel lights shaded
// Therefore vertexStartIndex = pixelLightCount; vertexEndIndex = min(vertexLights, perObjectLights)
int vertexLightStart = min(globalLightCount.x, unity_LightIndicesOffsetAndCount.y);
int vertexLightEnd = min(globalLightCount.y, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = vertexLightStart; lightIter < vertexLightEnd; ++lightIter)
{
int lightIndex = unity_4LightIndices0[lightIter];
LightInput lightInput;
INITIALIZE_LIGHT(lightInput, lightIndex);
half3 lightDirection;
half atten = ComputeLightAttenuationVertex(lightInput, lwWNormal, lwWorldPos, lightDirection);
o.fogCoord.yzw += LightingLambert(diffuse, lightDirection, lwWNormal, atten);
}
#endif
#if defined(_LIGHT_PROBES_ON) && !defined(LIGHTMAP_ON)
o.fogCoord.yzw += max(half3(0, 0, 0), ShadeSH9(half4(lwWNormal, 1)));
#endif
UNITY_TRANSFER_FOG(o, o.position);
return o;
}
fixed4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}
SurfaceInputs surfaceInput = (SurfaceInputs)0;
${SurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float3 Albedo = float3(0.5, 0.5, 0.5);
float3 Specular = float3(0, 0, 0);
float Metallic = 0;
float3 Normal = float3(0, 0, 1);
float3 Emission = 0;
float Smoothness = 0.5;
float Occlusion = 1;
float Alpha = 1;
${SurfaceOutputRemap}
#if defined(UNITY_COLORSPACE_GAMMA)
Albedo = Albedo * Albedo;
Emission = Emission * Emission;
#endif
return LightweightFragmentPBR(
IN.lwCustom,
WorldSpacePosition,
WorldSpaceNormal,
WorldSpaceTangent,
WorldSpaceBiTangent,
WorldSpaceViewDirection,
IN.fogCoord.x,
Albedo,
Metallic,
Specular,
Smoothness,
Normal,
Occlusion,
Emission,
Alpha);
}
ENDCG
}
Pass
{
Tags{"Lightmode" = "ShadowCaster"}
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "UnityCG.cginc"
#include "LightweightPassShadow.cginc"
ENDCG
}
Pass
{
Tags{"Lightmode" = "DepthOnly"}
ZWrite On
CGPROGRAM
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return UnityObjectToClipPos(pos);
}
half4 frag() : SV_TARGET
{
return 0;
}
ENDCG
}
}

/MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightSubshaderUnlit.template.meta → /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template.meta

/MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightSubshaderUnlit.template → /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template

/MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightSubshaderPBR.template.meta → /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template.meta

正在加载...
取消
保存