浏览代码

Merge pull request #67 from stramit/refactor-properties

Refactor properties
/main
GitHub 7 年前
当前提交
5f6271d2
共有 135 个文件被更改,包括 1999 次插入870 次删除
  1. 6
      MaterialGraphProject/Assets/NewNodes/Editor/ToggleNodePresenter.cs
  2. 19
      MaterialGraphProject/Assets/NewNodes/Keep/ConstantsNode.cs
  3. 9
      MaterialGraphProject/Assets/NewNodes/Keep/HeightToNormalNode.cs
  4. 2
      MaterialGraphProject/Assets/NewNodes/Keep/LightProbeNode.cs
  5. 10
      MaterialGraphProject/Assets/NewNodes/Keep/ParallaxNode.cs
  6. 4
      MaterialGraphProject/Assets/NewNodes/Keep/ReflectionProbeNode.cs
  7. 58
      MaterialGraphProject/Assets/NewNodes/Keep/SamplerStateNode.cs
  8. 6
      MaterialGraphProject/Assets/NewNodes/Keep/TangentToWorldNode.cs
  9. 12
      MaterialGraphProject/Assets/NewNodes/Keep/TransformNode.cs
  10. 6
      MaterialGraphProject/Assets/NewNodes/Kill/MultiLayerParallaxNode.cs
  11. 6
      MaterialGraphProject/Assets/NewNodes/Kill/POMNode.cs
  12. 2
      MaterialGraphProject/Assets/NewNodes/Kill/SphericalIndentationNode.cs
  13. 4
      MaterialGraphProject/Assets/NewNodes/Kill/ToggleNode.cs
  14. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/AssetCallbacks/CreateShaderGraph.cs
  15. 59
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/AbstractMaterialGraphEditWindow.cs
  16. 24
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/GraphInspectorPresenter.cs
  17. 15
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/GraphInspectorPresenter.cs.meta
  18. 122
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/GraphInspectorView.cs
  19. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/SurfaceMasterNodeEditorView.cs
  20. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/NodeInspectors/PropertyNodeInspector.cs
  21. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/NodeInspectors/SurfaceMasterNodeInspector.cs
  22. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/GraphEditorPresenter.cs
  23. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/MaterialGraphPresenter.cs
  24. 1
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/ColorNodePresenter.cs
  25. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/CubemapNodePresenter.cs
  26. 32
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/MasterNodePresenter.cs
  27. 10
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/SamplerStateNodePresenter.cs
  28. 31
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/SurfaceMasterNodePresenter.cs
  29. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/TextureAssetNodePresenter.cs
  30. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/TextureLODNodePresenter.cs
  31. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/TextureSamplerNodePresenter.cs
  32. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/Vector1NodePresenter.cs
  33. 19
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/PropertyNodePresenter.cs
  34. 26
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/PreviewSystem.cs
  35. 9
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Importers/ShaderGraphImporter.cs
  36. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/IntegrationTests/PropertyNodeTests.cs
  37. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/IntegrationTests/ShaderGenerationTest.cs
  38. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/AbstractMaterialGraphTests.cs
  39. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/MaterialNodeTests.cs
  40. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/MaterialSlotTests.cs
  41. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/PixelShaderNodeTests.cs
  42. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/PropertyChunkTests.cs
  43. 18
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/PropertyGeneratorTests.cs
  44. 10
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/PropertyNodeTests.cs
  45. 353
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/AbstractMaterialGraph.cs
  46. 51
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/MaterialGraph.cs
  47. 55
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/MaterialSlot.cs
  48. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Interfaces/IGenerateProperties.cs
  49. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Interfaces/IMasterNode.cs
  50. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Interfaces/IMayRequireNormal.cs
  51. 14
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/LightweightPipeline/AbstractLightweightPBRMasterNode.cs
  52. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/LightweightPipeline/LightweightFastBlinnMasterNode.cs
  53. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/LightweightPipeline/LightweightMetallicMasterNode.cs
  54. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/LightweightPipeline/LightweightSpecularMasterNode.cs
  55. 10
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/LightweightPipeline/LightweightUnlitMasterNode.cs
  56. 16
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/AbstractMaterialNode.cs
  57. 156
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/HLSLNode.cs
  58. 45
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/ColorNode.cs
  59. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Geometry/WorldSpaceBitangentNode.cs
  60. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Geometry/WorldSpacePositionNode.cs
  61. 14
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Geometry/WorldSpaceTangentNode.cs
  62. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Matrix/Matrix2Node.cs
  63. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Texture/CubemapNode.cs
  64. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Texture/TextureLODNode.cs
  65. 74
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Vector/Vector1Node.cs
  66. 52
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Vector/Vector2Node.cs
  67. 53
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Vector/Vector3Node.cs
  68. 48
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Vector/Vector4Node.cs
  69. 245
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/PropertyNode.cs
  70. 13
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SubGraph/SubGraph.cs
  71. 41
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SubGraph/SubGraphInputNode.cs
  72. 76
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SubGraph/SubGraphNode.cs
  73. 16
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SurfaceModel/AbstractSurfaceMasterNode.cs
  74. 16
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SurfaceModel/ExportTextureMasterNode.cs
  75. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SurfaceModel/MetallicMasterNode.cs
  76. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SurfaceModel/SpecularMasterNode.cs
  77. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Util/CubemapPropertyChunk.cs
  78. 322
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Util/ShaderGenerator.cs
  79. 10
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Util/TextureType.cs
  80. 87
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/AbstractShaderProperty.cs
  81. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/AbstractShaderProperty.cs.meta
  82. 67
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/ColorShaderProperty.cs
  83. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/ColorShaderProperty.cs.meta
  84. 54
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/FloatShaderProperty.cs
  85. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/FloatShaderProperty.cs.meta
  86. 17
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/IShaderProperty.cs
  87. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/IShaderProperty.cs.meta
  88. 34
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/SamplerStateShaderProperty.cs
  89. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/SamplerStateShaderProperty.cs.meta
  90. 44
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/SerializableTexture.cs
  91. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/SerializableTexture.cs.meta
  92. 25
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/ShaderGraphRequirements.cs
  93. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/ShaderGraphRequirements.cs.meta
  94. 45
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/TextureSamplerState.cs
  95. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/TextureSamplerState.cs.meta
  96. 61
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/TextureShaderProperty.cs
  97. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/TextureShaderProperty.cs.meta
  98. 24
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/Vector2ShaderProperty.cs
  99. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/Vector2ShaderProperty.cs.meta
  100. 23
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/Vector3ShaderProperty.cs

6
MaterialGraphProject/Assets/NewNodes/Editor/ToggleNodePresenter.cs


namespace UnityEditor.MaterialGraph.Drawing
{
[Serializable]
/>an class="p">* [Serializable]
class ToggleNodeControlPresenter : GraphControlPresenter
{
public override void OnGUIHandler()

{
return EditorGUIUtility.singleLineHeight + 2 * EditorGUIUtility.standardVerticalSpacing;
}
*/
*
public override float GetHeight()
{
return 2 * (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing) + EditorGUIUtility.standardVerticalSpacing;

instance.Initialize(node);
return new List<GraphControlPresenter> { instance };
}
}
}*/
}

19
MaterialGraphProject/Assets/NewNodes/Keep/ConstantsNode.cs


namespace UnityEngine.MaterialGraph
{
[Title("Math/Constants")]
public class ConstantsNode : PropertyNode, IGeneratesBodyCode
public class ConstantsNode : AbstractMaterialNode, IGeneratesBodyCode
{
static Dictionary<ConstantType, float> m_constantList = new Dictionary<ConstantType, float>
{

RemoveSlotsNameNotMatching(new[] { kOutputSlotId });
}
public override PropertyType propertyType
{
get { return PropertyType.Float; }
}
public override PreviewProperty GetPreviewProperty()
{
return new PreviewProperty
{
m_Name = propertyName,
m_PropType = PropertyType.Float,
m_Float = m_constantList[constant]
};
}
visitor.AddShaderChunk(precision + " " + propertyName + " = " + m_constantList[constant] + ";", true);
visitor.AddShaderChunk(precision + " " + GetVariableNameForNode() + " = " + m_constantList[constant] + ";", true);
}
}
}

9
MaterialGraphProject/Assets/NewNodes/Keep/HeightToNormalNode.cs


}
";
}
public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
base.GeneratePropertyUsages(visitor, generationMode);
visitor.AddShaderChunk("#ifdef UNITY_COMPILER_HLSL", false);
visitor.AddShaderChunk("SamplerState my_linear_repeat_sampler;", false);
visitor.AddShaderChunk("#endif", false);
}
}
}

2
MaterialGraphProject/Assets/NewNodes/Keep/LightProbeNode.cs


}
static string Unity_LightProbe(
[Slot(0, Binding.Normal)] Vector3 worldSpaceNormal,
[Slot(0, Binding.WorldSpaceNormal)] Vector3 worldSpaceNormal,
[Slot(1, Binding.None)] out Vector4 color)
{
color = Vector4.one;

10
MaterialGraphProject/Assets/NewNodes/Keep/ParallaxNode.cs


namespace UnityEngine.MaterialGraph
{
interface IMayRequireViewDirectionTangentSpace
{
bool RequiresViewDirectionTangentSpace();
}
public class ParallaxNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireMeshUV, IMayRequireViewDirectionTangentSpace
public class ParallaxNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireMeshUV, IMayRequireViewDirection
{
protected const string kInputSlot1ShaderName = "Depth";
protected const string kOutputSlotShaderName = "UV";

return channel == UVChannel.uv0;
}
public bool RequiresViewDirectionTangentSpace()
public NeededCoordinateSpace RequiresViewDirection()
return true;
return NeededCoordinateSpace.Tangent;
}
}
}

4
MaterialGraphProject/Assets/NewNodes/Keep/ReflectionProbeNode.cs


}
static string Unity_ReflectionProbe(
[Slot(0, Binding.ViewDirection)] Vector3 viewDirection,
[Slot(1, Binding.Normal)] Vector3 worldSpaceNormal,
[Slot(0, Binding.ObjectSpaceNormal)] Vector3 viewDirection,
[Slot(1, Binding.ObjectSpaceViewDirection)] Vector3 worldSpaceNormal,
[Slot(2, Binding.None)] Vector1 lod,
[Slot(3, Binding.None)] out Vector4 color)
{

58
MaterialGraphProject/Assets/NewNodes/Keep/SamplerStateNode.cs


using System.Collections.Generic;
using UnityEngine.MaterialGraph;
using System;
using UnityEngine.Graphing;
namespace UnityEngine.MaterialGraph

{
public enum FilterMode
{
Linear,
Point
}
public enum WrapMode
{
Repeat,
Clamp
}
static Dictionary<FilterMode, string> filterMode = new Dictionary<FilterMode, string>
{
{FilterMode.Linear, "_linear"},
{FilterMode.Point, "_point"},
};
static Dictionary<WrapMode, string> wrapMode = new Dictionary<WrapMode, string>
{
{WrapMode.Repeat, "_repeat"},
{WrapMode.Clamp, "_clamp"},
};
private FilterMode m_filter = FilterMode.Linear;
private TextureSamplerState.FilterMode m_filter = TextureSamplerState.FilterMode.Linear;
public FilterMode filter
public TextureSamplerState.FilterMode filter
{
get { return m_filter; }
set

}
[SerializeField]
private WrapMode m_wrap = WrapMode.Repeat;
private TextureSamplerState.WrapMode m_wrap = TextureSamplerState.WrapMode.Repeat;
public WrapMode wrap
public TextureSamplerState.WrapMode wrap
{
get { return m_wrap; }
set

return GetVariableNameForNode();
}
public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
var decl = string.Format(@"
#ifdef UNITY_COMPILER_HLSL
SamplerState {0};
#endif", GetVariableNameForNode());
visitor.AddShaderChunk(decl, true);
properties.AddShaderProperty(new SamplerStateShaderProperty()
{
name = GetVariableNameForNode(),
generatePropertyBlock = false,
value = new TextureSamplerState()
{
filter = m_filter,
wrap = m_wrap
}
});
return base.GetVariableNameForNode() + filterMode[filter] + wrapMode[wrap] + "_sampler";
string ss = name + "_"
+ Enum.GetName(typeof(TextureSamplerState.FilterMode), filter) + "_"
+ Enum.GetName(typeof(TextureSamplerState.WrapMode), wrap) + "_sampler;";
return ss;
}
}
}

6
MaterialGraphProject/Assets/NewNodes/Keep/TangentToWorldNode.cs


static string Unity_TangentToWorld(
[Slot(0, Binding.None)] Vector3 inVector,
[Slot(1, Binding.None)] out Vector3 result,
[Slot(2, Binding.Tangent)] Vector3 tangent,
[Slot(3, Binding.Bitangent)] Vector3 biTangent,
[Slot(4, Binding.Normal)] Vector3 normal)
[Slot(2, Binding.WorldSpaceTangent)] Vector3 tangent,
[Slot(3, Binding.WorldSpaceBitangent)] Vector3 biTangent,
[Slot(4, Binding.WorldSpaceNormal)] Vector3 normal)
{
result = Vector3.zero;
return

12
MaterialGraphProject/Assets/NewNodes/Keep/TransformNode.cs


get { return ConvertConcreteSlotValueTypeToString(FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType); }
}
public bool RequiresTangent()
public NeededCoordinateSpace RequiresTangent()
return true;
return NeededCoordinateSpace.World;
public bool RequiresBitangent()
public NeededCoordinateSpace RequiresBitangent()
return true;
return NeededCoordinateSpace.World;
public bool RequiresNormal()
public NeededCoordinateSpace RequiresNormal()
return true;
return NeededCoordinateSpace.World;
}
}
}

6
MaterialGraphProject/Assets/NewNodes/Kill/MultiLayerParallaxNode.cs


namespace UnityEngine.MaterialGraph
{
[Title("UV/MultiLayerParallax")]
public class MultiLayerParallaxNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireMeshUV, IMayRequireViewDirectionTangentSpace
public class MultiLayerParallaxNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireMeshUV, IMayRequireViewDirection
{
protected const string kInputDepthShaderName = "Depth";
protected const string kInputFadeRateShaderName = "FadeRate";

return channel == UVChannel.uv0;
}
public bool RequiresViewDirectionTangentSpace()
public NeededCoordinateSpace RequiresViewDirection()
return true;
return NeededCoordinateSpace.Tangent;
}
}
}

6
MaterialGraphProject/Assets/NewNodes/Kill/POMNode.cs


[Slot(1, Binding.None)] Texture2D tex,
[Slot(2, Binding.None)] Vector1 heightScale,
[Slot(3, Binding.MeshUV0)] Vector2 UVs,
[Slot(4, Binding.ViewDirectionTangentSpace)] Vector3 viewTangentSpace,
[Slot(5, Binding.Normal)] Vector3 worldSpaceNormal,
[Slot(6, Binding.ViewDirection)] Vector3 worldSpaceViewDirection,
[Slot(4, Binding.TangentSpaceViewDirection)] Vector3 viewTangentSpace,
[Slot(5, Binding.WorldSpaceNormal)] Vector3 worldSpaceNormal,
[Slot(6, Binding.WorldSpaceViewDirection)] Vector3 worldSpaceViewDirection,
[Slot(7, Binding.None)] out Vector2 result)
{
result = Vector2.zero;

2
MaterialGraphProject/Assets/NewNodes/Kill/SphericalIndentationNode.cs


[Slot(3, Binding.None, 1f, 1f, 1f, 1f)] Vector1 radius,
[Slot(4, Binding.None)] out Vector3 resultUV,
[Slot(5, Binding.None)] out Vector3 resultNormal,
[Slot(6, Binding.ViewDirectionTangentSpace, true)] Vector3 tangentSpaceViewDirection)
[Slot(6, Binding.TangentSpaceViewDirection, true)] Vector3 tangentSpaceViewDirection)
{
resultUV = Vector3.zero;
resultNormal = Vector3.up;

4
MaterialGraphProject/Assets/NewNodes/Kill/ToggleNode.cs


namespace UnityEngine.MaterialGraph
{
[Title("Input/Toggle")]
/* [Title("Input/Toggle")]
public class ToggleNode : PropertyNode, IGeneratesBodyCode
{
[SerializeField]

m_Float = value ? 1f : 0f
};
}
}
}*/
}

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


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

59
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/AbstractMaterialGraphEditWindow.cs


void Show();
void Focus();
Object selected { get; }
Object selected { get; set; }
public abstract class HelperMaterialGraphEditWindow : EditorWindow, IMaterialGraphEditWindow
{
public abstract AbstractMaterialGraph GetMaterialGraph();
public abstract void PingAsset();
public abstract void UpdateAsset();
public abstract void ToggleRequiresTime();
public abstract void ToSubGraph();
public abstract Object selected { get; set; }
public abstract void ChangeSelection(Object newSelection);
}
{}
{
public override AbstractMaterialGraph GetMaterialGraph()
{
return inMemoryAsset;
}
}
{}
{
public override AbstractMaterialGraph GetMaterialGraph()
{
return inMemoryAsset;
}
}
public abstract class AbstractMaterialGraphEditWindow<TGraphType> : EditorWindow, IMaterialGraphEditWindow where TGraphType : AbstractMaterialGraph
public abstract class AbstractMaterialGraphEditWindow<TGraphType> : HelperMaterialGraphEditWindow where TGraphType : AbstractMaterialGraph
{
public static bool allowAlwaysRepaint = true;

TGraphType m_InMemoryAsset;
GraphEditorView m_GraphEditorView;
GraphEditorView graphEditorView
{
get { return m_GraphEditorView; }

}
}
public TGraphType inMemoryAsset
protected TGraphType inMemoryAsset
public Object selected
public override Object selected
{
get { return m_Selected; }
set { m_Selected = value; }

}
}
public void PingAsset()
public override void PingAsset()
public void UpdateAsset()
public override void UpdateAsset()
{
if (selected != null && inMemoryAsset != null)
{

}
}
public void ToSubGraph()
public override void ToSubGraph()
{
string path = EditorUtility.SaveFilePanelInProject("Save subgraph", "New SubGraph", "ShaderSubGraph", "");
path = path.Replace(Application.dataPath, "Assets");

if (graph == null)
return;
var masterNode = graph.masterNode;
if (masterNode == null)
return;
List<PropertyGenerator.TextureInfo> configuredTextures;
masterNode.GetFullShader(GenerationMode.ForReals, Path.GetFileNameWithoutExtension(path), out configuredTextures);
List<PropertyCollector.TextureInfo> configuredTextures;
graph.GetShader(Path.GetFileNameWithoutExtension(path), out configuredTextures);
var shaderImporter = AssetImporter.GetAtPath(path) as ShaderImporter;
if (shaderImporter == null)

var textures = new List<Texture>();
foreach (var textureInfo in configuredTextures.Where(
x => x.modifiable == TexturePropertyChunk.ModifiableState.Modifiable))
foreach (var textureInfo in configuredTextures.Where(x => x.modifiable))
{
var texture = EditorUtility.InstanceIDToObject(textureInfo.textureId) as Texture;
if (texture == null)

textureNames.Clear();
textures.Clear();
foreach (var textureInfo in configuredTextures.Where(
x => x.modifiable == TexturePropertyChunk.ModifiableState.NonModifiable))
foreach (var textureInfo in configuredTextures.Where(x => !x.modifiable))
{
var texture = EditorUtility.InstanceIDToObject(textureInfo.textureId) as Texture;
if (texture == null)

AssetDatabase.ImportAsset(path);
}
public virtual void ToggleRequiresTime()
public override void ToggleRequiresTime()
public void ChangeSelection(Object newSelection)
public override void ChangeSelection(Object newSelection)
{
if (!EditorUtility.IsPersistent(newSelection))
return;

24
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/GraphInspectorPresenter.cs


{
PreviewData m_PreviewHandle;
public IGraph graph { get; set; }
[SerializeField]
private int m_Version;
[Flags]
public enum ChangeType

public OnChange onChange;
public void Initialize(string assetName, IGraph graph, PreviewSystem previewSystem)
[SerializeField]
private HelperMaterialGraphEditWindow m_Owner;
public AbstractMaterialGraph graph
var masterNode = graph.GetNodes<AbstractMasterNode>().FirstOrDefault();
get { return m_Owner.GetMaterialGraph(); }
}
public void Dirty()
{
m_Version++;
}
public void Initialize(string assetName, PreviewSystem previewSystem, HelperMaterialGraphEditWindow window)
{
m_Owner = window;
var masterNode = graph.GetNodes<MasterNode>().FirstOrDefault();
this.graph = graph;
this.assetName = assetName;
selectedNodes = new List<INode>();

15
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/GraphInspectorPresenter.cs.meta


fileFormatVersion: 2
guid: 215d826e4a644dc0bde2fa9ba68f4096
timeCreated: 1502956093
fileFormatVersion: 2
guid: d8c67032914554203be73439532c83b8
timeCreated: 1502956093
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

122
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/GraphInspectorView.cs


using UnityEditor.Graphing.Util;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Graphing;
using UnityEngine.Experimental.UIElements.StyleEnums;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEngine.Graphing;
using UnityEngine.MaterialGraph;
using Object = UnityEngine.Object;

int m_SelectionHash;
VisualElement m_Title;
VisualElement m_PropertiesContainer;
VisualElement m_ContentContainer;
AbstractNodeEditorView m_EditorView;

}
Add(topContainer);
ReaddProps();
var bottomContainer = new VisualElement { name = "bottom" };
{
m_Preview = new Image { name = "preview", image = Texture2D.blackTexture};

// - SubGraphOutputNode
m_TypeMapper = new TypeMapper(typeof(INode), typeof(AbstractNodeEditorView), typeof(StandardNodeEditorView))
{
{ typeof(AbstractSurfaceMasterNode), typeof(SurfaceMasterNodeEditorView) }
// { typeof(AbstractSurfaceMasterNode), typeof(SurfaceMasterNodeEditorView) }
};
}
private void ReaddProps()
{
if (m_PropertiesContainer != null)
Remove(m_PropertiesContainer);
m_PropertiesContainer = new VisualElement()
{
new IMGUIContainer(OnGuiHandler)
m_PropertiesContainer.style.flexDirection = StyleValue<FlexDirection>.Create(FlexDirection.Column);
Add(m_PropertiesContainer);
}
private void OnGuiHandler()
{
if (m_Presenter == null)
return;
if (GUILayout.Button("Add Property"))
{
var gm = new GenericMenu();
gm.AddItem(new GUIContent("Float"), false, () =>
{
m_Presenter.graph.AddShaderProperty(new FloatShaderProperty());
ReaddProps();
});
gm.AddItem(new GUIContent("Vector2"), false, () =>
{
m_Presenter.graph.AddShaderProperty(new Vector2ShaderProperty());
ReaddProps();
});
gm.AddItem(new GUIContent("Vector3"), false, () =>
{
m_Presenter.graph.AddShaderProperty(new Vector3ShaderProperty());
ReaddProps();
});
gm.AddItem(new GUIContent("Vector4"), false, () =>
{
m_Presenter.graph.AddShaderProperty(new Vector4ShaderProperty());
ReaddProps();
});
gm.AddItem(new GUIContent("Color"), false, () =>
{
m_Presenter.graph.AddShaderProperty(new ColorShaderProperty());
ReaddProps();
});
gm.AddItem(new GUIContent("Texture"), false, () =>
{
m_Presenter.graph.AddShaderProperty(new TextureShaderProperty());
ReaddProps();
});
gm.ShowAsContext();
}
EditorGUI.BeginChangeCheck();
foreach (var property in m_Presenter.graph.properties.ToArray())
{
property.name = EditorGUILayout.DelayedTextField("Name", property.name);
property.description = EditorGUILayout.DelayedTextField("Description", property.description);
if (property is FloatShaderProperty)
{
var fProp = property as FloatShaderProperty;
fProp.value = EditorGUILayout.FloatField("Value", fProp.value);
}
else if (property is Vector2ShaderProperty)
{
var fProp = property as Vector2ShaderProperty;
fProp.value = EditorGUILayout.Vector2Field("Value", fProp.value);
}
else if (property is Vector3ShaderProperty)
{
var fProp = property as Vector3ShaderProperty;
fProp.value = EditorGUILayout.Vector3Field("Value", fProp.value);
}
else if (property is Vector4ShaderProperty)
{
var fProp = property as Vector4ShaderProperty;
fProp.value = EditorGUILayout.Vector4Field("Value", fProp.value);
}
else if (property is ColorShaderProperty)
{
var fProp = property as ColorShaderProperty;
fProp.value = EditorGUILayout.ColorField("Value", fProp.value);
}
else if (property is TextureShaderProperty)
{
var fProp = property as TextureShaderProperty;
fProp.value.texture = EditorGUILayout.MiniThumbnailObjectField(new GUIContent("Texture"), fProp.value.texture, typeof(Texture), null) as Texture;
}
if (GUILayout.Button("Remove"))
{
m_Presenter.graph.RemoveShaderProperty(property.guid);
}
EditorGUILayout.Separator();
}
if (EditorGUI.EndChangeCheck())
{
foreach (var node in m_Presenter.graph.GetNodes<PropertyNode>())
node.onModified(node, ModificationScope.Node);
}
}
public void OnChange(GraphInspectorPresenter.ChangeType changeType)

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/SurfaceMasterNodeEditorView.cs


namespace UnityEditor.MaterialGraph.Drawing.Inspector
{
public class SurfaceMasterNodeEditorView : AbstractNodeEditorView
/* public class SurfaceMasterNodeEditorView : AbstractNodeEditorView
{
NodeEditorHeaderView m_HeaderView;
AbstractSurfaceMasterNode m_Node;

m_HeaderView.title = m_Node.name;
Dirty(ChangeType.Repaint);
}
}
}*/
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/NodeInspectors/PropertyNodeInspector.cs


EditorGUI.BeginChangeCheck();
//propertyNode.name = EditorGUILayout.TextField ("Name", propertyNode.name);
propertyNode.description = EditorGUILayout.TextField("Description", propertyNode.description);
//propertyNode.description = EditorGUILayout.TextField("Description", propertyNode.description);
if (EditorGUI.EndChangeCheck())
node.onModified(node, ModificationScope.Node);

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/NodeInspectors/SurfaceMasterNodeInspector.cs


{
public class SurfaceMasterNodeInspector : BasicNodeInspector
{
public override void OnInspectorGUI()
/* public override void OnInspectorGUI()
{
base.OnInspectorGUI();

if (EditorGUI.EndChangeCheck())
node.onModified(node, ModificationScope.Node);
}
}*/
}
}

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/GraphEditorPresenter.cs


using System;
using System;
using UnityEngine.MaterialGraph;
namespace UnityEditor.MaterialGraph.Drawing
{

set { m_GraphInspectorPresenter = value; }
}
public void Initialize(IGraph graph, IMaterialGraphEditWindow container, string assetName)
public void Initialize(AbstractMaterialGraph graph, HelperMaterialGraphEditWindow container, string assetName)
{
m_PreviewSystem = new PreviewSystem(graph);

m_GraphInspectorPresenter = CreateInstance<GraphInspectorPresenter>();
m_GraphInspectorPresenter.Initialize(assetName, graph, m_PreviewSystem);
m_GraphInspectorPresenter.Initialize(assetName, m_PreviewSystem, container);
m_GraphPresenter = CreateInstance<MaterialGraphPresenter>();
m_GraphPresenter.Initialize(graph, container, m_PreviewSystem);

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/MaterialGraphPresenter.cs


//typeMapper[typeof(TextureNode)] = typeof(TextureNodePresenter);
//typeMapper[typeof(SamplerAssetNode)] = typeof(SamplerAssetNodePresenter);
//typeMapper[typeof(TextureSamplerNode)] = typeof(TextureSamplerNodePresenter);
typeMapper[typeof(Texture2DNode)] = typeof(TextureAssetNodePresenter);
typeMapper[typeof(TextureLODNode)] = typeof(TextureLODNodePresenter);
// typeMapper[typeof(Texture2DNode)] = typeof(TextureAssetNodePresenter);
// typeMapper[typeof(TextureLODNode)] = typeof(TextureLODNodePresenter);
typeMapper[typeof(CubemapNode)] = typeof(CubeNodePresenter);
typeMapper[typeof(ToggleNode)] = typeof(ToggleNodePresenter);
// typeMapper[typeof(CubemapNode)] = typeof(CubeNodePresenter);
// typeMapper[typeof(ToggleNode)] = typeof(ToggleNodePresenter);
typeMapper[typeof(PropertyNode)] = typeof(PropertyNodePresenter);
/* typeMapper[typeof(ScaleOffsetNode)] = typeof(AnyNodePresenter); // anything derived from AnyNode should use the AnyNodePresenter
typeMapper[typeof(RadialShearNode)] = typeof(AnyNodePresenter); // anything derived from AnyNode should use the AnyNodePresenter
typeMapper[typeof(SphereWarpNode)] = typeof(AnyNodePresenter); // anything derived from AnyNode should use the AnyNodePresenter

// typeMapper[typeof(RemapMasterNode)] = typeof(RemapMasterNodePresenter);
// typeMapper[typeof(MasterRemapInputNode)] = typeof(RemapInputNodePresenter);
typeMapper[typeof(AbstractSubGraphIONode)] = typeof(SubgraphIONodePresenter);
typeMapper[typeof(AbstractSurfaceMasterNode)] = typeof(SurfaceMasterNodePresenter);
// typeMapper[typeof(AbstractSurfaceMasterNode)] = typeof(SurfaceMasterNodePresenter);
typeMapper[typeof(LevelsNode)] = typeof(LevelsNodePresenter);
typeMapper[typeof(ConstantsNode)] = typeof(ConstantsNodePresenter);

1
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/ColorNodePresenter.cs


if (cNode == null)
return;
cNode.exposedState = (PropertyNode.ExposedState)EditorGUILayout.EnumPopup(new GUIContent("Exposed"), cNode.exposedState);
cNode.color = EditorGUILayout.ColorField(new GUIContent("Color"), cNode.color, true, true, cNode.HDR, new ColorPickerHDRConfig(0f, 8f, 0.125f, 3f));
cNode.HDR = EditorGUILayout.Toggle("HDR", cNode.HDR);
}

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/CubemapNodePresenter.cs


namespace UnityEditor.MaterialGraph.Drawing
{
class CubeContolPresenter : GraphControlPresenter
/* class CubeContolPresenter : GraphControlPresenter
{
//private string[] m_TextureTypeNames;
//private string[] textureTypeNames

m_TextureTypeNames = Enum.GetNames(typeof(TextureType));
return m_TextureTypeNames;
}
}*/
}*
public override void OnGUIHandler()
{

instance.Initialize(node);
return new List<GraphControlPresenter> { instance };
}
}
}*/
}

32
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/MasterNodePresenter.cs


namespace UnityEditor.MaterialGraph.Drawing
{
class MasterNodeControlPresenter : GraphControlPresenter
{
public override void OnGUIHandler()
{
base.OnGUIHandler();
var masterNode = node as AbstractMasterNode;
if (masterNode == null || !masterNode.canBeActiveMaster)
return;
using (new EditorGUI.DisabledScope(masterNode.isActiveMaster))
masterNode.isActiveMaster |= GUILayout.Button("Set active");
}
public override float GetHeight()
{
var masterNode = node as AbstractMasterNode;
if (masterNode == null || !masterNode.canBeActiveMaster)
return 0f;
return EditorGUIUtility.singleLineHeight + 3 * EditorGUIUtility.standardVerticalSpacing;
}
}
[Serializable]
public class MasterNodePresenter : MaterialNodePresenter
{
protected override IEnumerable<GraphControlPresenter> GetControlData()
{
var instance = CreateInstance<MasterNodeControlPresenter>();
instance.Initialize(node);
return new List<GraphControlPresenter> { instance };
}
}
}

10
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/SamplerStateNodePresenter.cs


get
{
if (samplerFilterMode == null)
samplerFilterMode = Enum.GetNames(typeof(SamplerStateNode.FilterMode));
samplerFilterMode = Enum.GetNames(typeof(TextureSamplerState.FilterMode));
return samplerFilterMode;
}
}

get
{
if (samplerWrapMode == null)
samplerWrapMode = Enum.GetNames(typeof(SamplerStateNode.WrapMode));
samplerWrapMode = Enum.GetNames(typeof(TextureSamplerState.WrapMode));
return samplerWrapMode;
}
}

base.OnGUIHandler();
var cNode = node as UnityEngine.MaterialGraph.SamplerStateNode;
var cNode = node as SamplerStateNode;
cNode.filter = (SamplerStateNode.FilterMode)EditorGUILayout.Popup((int)cNode.filter, _samplerFilterMode, EditorStyles.popup);
cNode.wrap = (SamplerStateNode.WrapMode)EditorGUILayout.Popup((int)cNode.wrap, _samplerWrapMode, EditorStyles.popup);
cNode.filter = (TextureSamplerState.FilterMode)EditorGUILayout.Popup((int)cNode.filter, _samplerFilterMode, EditorStyles.popup);
cNode.wrap = (TextureSamplerState.WrapMode)EditorGUILayout.Popup((int)cNode.wrap, _samplerWrapMode, EditorStyles.popup);
}
public override float GetHeight()

31
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/SurfaceMasterNodePresenter.cs


namespace UnityEditor.MaterialGraph.Drawing
{
[Serializable]
class SurfaceMasterContolPresenter : GraphControlPresenter
{
public override void OnGUIHandler()
{
base.OnGUIHandler();
var cNode = node as AbstractSurfaceMasterNode;
if (cNode == null)
return;
cNode.options.lod = EditorGUILayout.IntField("LOD", cNode.options.lod);
}
public override float GetHeight()
{
return EditorGUIUtility.singleLineHeight + 2 * EditorGUIUtility.standardVerticalSpacing;
}
}
[Serializable]
public class SurfaceMasterNodePresenter : MasterNodePresenter
{
protected override IEnumerable<GraphControlPresenter> GetControlData()
{
var instance = CreateInstance<SurfaceMasterContolPresenter>();
instance.Initialize(node);
var controls = new List<GraphControlPresenter>(base.GetControlData());
controls.Add(instance);
return controls;
}
}
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/TextureAssetNodePresenter.cs


namespace UnityEditor.MaterialGraph.Drawing
{
class TextureAssetContolPresenter : GraphControlPresenter
/* class TextureAssetContolPresenter : GraphControlPresenter
{
private string[] m_TextureTypeNames;
private string[] textureTypeNames

instance.Initialize(node);
return new List<GraphControlPresenter> { instance };
}
}
}*/
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/TextureLODNodePresenter.cs


namespace UnityEditor.MaterialGraph.Drawing
{
class TextureLODContolPresenter : GraphControlPresenter
/* class TextureLODContolPresenter : GraphControlPresenter
{
private string[] m_TextureTypeNames;
private string[] textureTypeNames

instance.Initialize(node);
return new List<GraphControlPresenter> { instance };
}
}
}*/
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/TextureSamplerNodePresenter.cs


namespace UnityEditor.MaterialGraph.Drawing
{
/*
class TextureSamplerContolPresenter : GraphControlPresenter
{
private string[] m_TextureTypeNames;

instance.Initialize(node);
return new List<GraphControlPresenter> { instance };
}
}
}*/
}

5
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/Nodes/Vector1NodePresenter.cs


if (tNode == null)
return;
tNode.value = EditorGUILayout.FloatField("Value:", tNode.value);
/*
tNode.floatType = (FloatPropertyChunk.FloatType)EditorGUILayout.EnumPopup("Float", tNode.floatType);

toggleState = EditorGUILayout.Toggle(toggleState);
tNode.value = toggleState == true ? 1f : 0f;
break;
}
}*/
}
public override float GetHeight()

19
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/PropertyNodePresenter.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Experimental.UIElements.GraphView;
using UnityEngine;
using UnityEngine.MaterialGraph;

{
base.OnGUIHandler();
var tNode = node as UnityEngine.MaterialGraph.PropertyNode;
var tNode = node as PropertyNode;
tNode.exposedState = (PropertyNode.ExposedState)EditorGUILayout.EnumPopup(new GUIContent("Exposed"), tNode.exposedState);
var graph = node.owner as AbstractMaterialGraph;
var currentGUID = tNode.propertyGuid;
var properties = graph.properties.ToList();
var propertiesGUID = properties.Select(x => x.guid).ToList();
var currentSelectedIndex = propertiesGUID.IndexOf(currentGUID);
var newIndex = EditorGUILayout.Popup("Property", currentSelectedIndex, properties.Select(x => x.name).ToArray());
if (newIndex != currentSelectedIndex)
tNode.propertyGuid = propertiesGUID[newIndex];
return (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing) + EditorGUIUtility.standardVerticalSpacing;
return (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing) * 2 + EditorGUIUtility.standardVerticalSpacing;
public abstract class PropertyNodePresenter : MaterialNodePresenter
public class PropertyNodePresenter : MaterialNodePresenter
{
protected override IEnumerable<GraphControlPresenter> GetControlData()
{

26
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/PreviewSystem.cs


{
public class PreviewSystem : IDisposable
{
IGraph m_Graph;
AbstractMaterialGraph m_Graph;
Dictionary<Guid, PreviewData> m_Previews = new Dictionary<Guid, PreviewData>();
HashSet<Guid> m_DirtyPreviews = new HashSet<Guid>();
HashSet<Guid> m_DirtyShaders = new HashSet<Guid>();

MaterialGraphPreviewGenerator m_PreviewGenerator = new MaterialGraphPreviewGenerator();
Texture2D m_ErrorTexture;
public PreviewSystem(IGraph graph)
public PreviewSystem(AbstractMaterialGraph graph)
{
m_Graph = graph;
m_PreviewMaterial = new Material(Shader.Find("Unlit/Color")) { hideFlags = HideFlags.HideInHierarchy };

{
var node = m_Graph.GetNodeFromGuid<AbstractMaterialNode>(nodeGuid);
node.CollectPreviewMaterialProperties(m_PreviewProperties);
foreach (var prop in m_Graph.properties)
m_PreviewProperties.Add(prop.GetPreviewMaterialProperty());
foreach (var previewProperty in m_PreviewProperties)
{
if (previewProperty.m_PropType == PropertyType.Texture && previewProperty.m_Texture != null)

}
var node = m_Graph.GetNodeFromGuid(nodeGuid);
m_PreviewMaterial.shader = previewData.shader;
m_PreviewGenerator.DoRenderPreview(previewData.renderTexture, m_PreviewMaterial, previewData.previewMode, node is IMasterNode, time, m_PreviewPropertyBlock);
m_PreviewGenerator.DoRenderPreview(previewData.renderTexture, m_PreviewMaterial, previewData.previewMode, node is MasterNode, time, m_PreviewPropertyBlock);
previewData.texture = previewData.renderTexture;
}

if (!m_Previews.TryGetValue(nodeGuid, out previewData))
return;
if (node is IMasterNode)
if (node is MasterNode && node.owner is UnityEngine.MaterialGraph.MaterialGraph)
var masterNode = (IMasterNode)node;
List<PropertyGenerator.TextureInfo> defaultTextures;
previewData.shaderString = masterNode.GetFullShader(GenerationMode.Preview, node.guid + "_preview", out defaultTextures);
var masterNode = (MasterNode)node;
var materialGraph = (UnityEngine.MaterialGraph.MaterialGraph) node.owner;
List<PropertyCollector.TextureInfo> defaultTextures;
previewData.shaderString = materialGraph.GetShader(node.guid + "_preview", out defaultTextures);
previewData.previewMode = masterNode.has3DPreview() ? PreviewMode.Preview3D : PreviewMode.Preview2D;
}
else if (!node.hasPreview || NodeUtils.FindEffectiveShaderStage(node, true) == ShaderStage.Vertex)

else
{
PreviewMode previewMode;
previewData.shaderString = ShaderGenerator.GeneratePreviewShader(node, out previewMode);
previewData.previewMode = previewMode;
List<PropertyCollector.TextureInfo> defaultTextures;
PreviewMode mode;
previewData.shaderString = m_Graph.GetPreviewShader(node, out mode);
previewData.previewMode = mode;
}
// Debug output

9
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Importers/ShaderGraphImporter.cs


var textGraph = File.ReadAllText(path, Encoding.UTF8);
var graph = JsonUtility.FromJson<MaterialGraph>(textGraph);
IMasterNode masterNode = graph.masterNode;
if (masterNode == null)
return null;
List<PropertyGenerator.TextureInfo> configuredTextures;
var shaderString = masterNode.GetFullShader(GenerationMode.ForReals, string.Format("graphs/{0}", name), out configuredTextures);
List<PropertyCollector.TextureInfo> configuredTextures;
var shaderString = graph.GetShader(string.Format("graphs/{0}", name), out configuredTextures);
Debug.Log(shaderString);
return shaderString;
}
catch (Exception)

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/IntegrationTests/PropertyNodeTests.cs


namespace UnityEditor.MaterialGraph.IntegrationTests
{
[TestFixture]
/*[TestFixture]
public class PropertyNodeTests
{
private UnityEngine.MaterialGraph.MaterialGraph m_Graph;

m_TextureNode.GeneratePropertyUsages(generator, GenerationMode.ForReals);
Assert.AreEqual(expected, generator.GetShaderString(0));
}
}
}*/
}

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/IntegrationTests/ShaderGenerationTest.cs


//Assert.IsNotNull(materialGraph);
// Generate the shader
List<PropertyGenerator.TextureInfo> configuredTextures;
var shaderString =
graph.masterNode.GetFullShader(GenerationMode.ForReals, Path.GetFileNameWithoutExtension(filePath), out configuredTextures);
List<PropertyCollector.TextureInfo> configuredTextures = new List<PropertyCollector.TextureInfo>();
var shaderString = String.Empty;
//graph.masterNode.GetFullShader(GenerationMode.ForReals, Path.GetFileNameWithoutExtension(filePath), out configuredTextures);
var rootPath = Directory.GetParent(Directory.GetParent(Application.dataPath).ToString());
var shaderTemplatePath = Path.Combine(rootPath.ToString(), "ShaderTemplates");

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/AbstractMaterialGraphTests.cs


Assert.AreEqual(node, graph.GetNodeFromGuid<TestableMNode>(node.guid));
}
[Test]
/* [Test]
public void TestCreatePixelShaderGraphWorks()
{
var graph = new UnityEngine.MaterialGraph.MaterialGraph();

graph.AddNode(psn2);
Assert.AreEqual(0, graph.edges.Count());
Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count());
}
}*/
}
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/MaterialNodeTests.cs


Assert.AreEqual(expected, result);
}
[Test]
/>an class="p">* [Test]
public void NodeGenerateCorrectPreviewPropertyUsages()
{
string expected = string.Format("{0} {1};{2}", AbstractMaterialNode.OutputPrecision.@fixed, m_NodeA.GetVariableNameForSlot(TestNode.V1In), Environment.NewLine);

m_NodeA.precision = AbstractMaterialNode.OutputPrecision.half;
m_NodeA.GeneratePropertyUsages(visitor, GenerationMode.Preview);
Assert.AreEqual(expected, visitor.GetShaderString(0));
}
}*/
}
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/MaterialSlotTests.cs


Assert.AreEqual(SlotValueType.Vector3, slot.valueType);
}
[Test]
/* [Test]
public void MaterialSlotCanGeneratePropertyUsagesForPreview()
{
string expected = string.Format("{0} {1};{2}", m_NodeA.precision, m_NodeA.GetVariableNameForSlot(TestNode.V1In), Environment.NewLine);

slot.GeneratePropertyUsages(visitor, GenerationMode.Preview);
Assert.AreEqual(expected, visitor.GetShaderString(0));
}
}*/
[Test]
public void MaterialSlotReturnsValidDefaultValue()

Assert.AreEqual("half4 (6,6,6,1)", result);
}
[Test]
/* [Test]
}
}*/
}
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/PixelShaderNodeTests.cs


[TestFixture]
public class PixelShaderNodeTests
{
private UnityEngine.MaterialGraph.MaterialGraph m_Graph;
/* private UnityEngine.MaterialGraph.MaterialGraph m_Graph;
private Vector1Node m_InputOne;
private AbsoluteNode m_Abs;
private MetallicMasterNode m_PixelNode;

//m_Graph.Connect(m_Abs.GetSlotReference(Function1Input.OutputSlotId), m_PixelNode.GetSlotReference(AbstractSurfaceMasterNode.AlbedoSlotId));
}
/* [Test]
[Test]
public void TestNodeGeneratesCorrectNodeCode()
{
string expected = string.Format("half {0} = 0.2;" + Environment.NewLine

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/PropertyChunkTests.cs


namespace UnityEditor.MaterialGraph.UnitTests
{
[TestFixture]
/>an class="p">* [TestFixture]
public class PropertyChunkTests
{
class TestPropertyChunch : PropertyChunk

Assert.AreEqual(TexturePropertyChunk.ModifiableState.NonModifiable, chunk.modifiableState);
Assert.AreEqual(PropertyChunk.HideState.Hidden, chunk.hideState);
}
}
}*/
}

18
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/PropertyGeneratorTests.cs


private const string kPropertyName = "ThePropertyName";
private const string kPropertyDescription = "ThePropertyDescription";
[Test]
/>an class="p">* [Test]
var generator = new PropertyGenerator();
var generator = new PropertyCollector();
Assert.AreNotEqual(string.Empty, generator.GetShaderString(0));
Assert.AreNotEqual(string.Empty, generator.GetPropertiesBlock(0));
}
[Test]

var generator = new PropertyGenerator();
var generator = new PropertyCollector();
Assert.AreEqual(0, generator.GetShaderString(0).Count(x => x == '\t'));
Assert.AreEqual(1, generator.GetShaderString(1).Count(x => x == '\t'));
Assert.AreEqual(2, generator.GetShaderString(2).Count(x => x == '\t'));
Assert.AreEqual(0, generator.GetPropertiesBlock(0).Count(x => x == '\t'));
Assert.AreEqual(1, generator.GetPropertiesBlock(1).Count(x => x == '\t'));
Assert.AreEqual(2, generator.GetPropertiesBlock(2).Count(x => x == '\t'));
}
[Test]

var generator = new PropertyGenerator();
var generator = new PropertyCollector();
generator.AddShaderProperty(chunk);
var infos = generator.GetConfiguredTexutres();

Assert.AreEqual(TexturePropertyChunk.ModifiableState.Modifiable, infos[0].modifiable);
}
}*/
}
}

10
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/PropertyNodeTests.cs


namespace UnityEditor.MaterialGraph.UnitTests
{
[TestFixture]
/* [TestFixture]
public class PropertyNodeTests
{
private class TestPropertyNode : PropertyNode

private Vector3Node m_Vector3Node;
private Vector4Node m_Vector4Node;
private ColorNode m_ColorNode;
private Texture2DNode m_TextureNode;
// private Texture2DNode m_TextureNode;
private TestPropertyNode m_PropertyNode;
private const string kPropertyName = "PropertyName";

m_Vector3Node = new Vector3Node();
m_Vector4Node = new Vector4Node();
m_ColorNode = new ColorNode();
m_TextureNode = new Texture2DNode();
// m_TextureNode = new Texture2DNode();
m_PropertyNode = new TestPropertyNode();
m_Graph.AddNode(m_Vector1Node);

m_Vector2Node.ValidateNode();
Assert.IsFalse(m_Vector1Node.hasError);
Assert.IsFalse(m_Vector2Node.hasError);
}*/
}*
[Test]
public void TestPropertyExposedOnSubgraphReturnsFalse()

m_ColorNode.GeneratePropertyUsages(generator, GenerationMode.ForReals);
Assert.AreEqual(expected, generator.GetShaderString(0));
}
}
}*/
}

353
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/AbstractMaterialGraph.cs


using System;
using System.Collections.Generic;
using System.Linq;
public abstract class AbstractMaterialGraph : SerializableGraph
public abstract class AbstractMaterialGraph : SerializableGraph, IGenerateProperties
[NonSerialized] private List<IShaderProperty> m_Properties = new List<IShaderProperty>();
[SerializeField] private List<SerializationHelper.JSONSerializedElement> m_SerializedProperties = new List<SerializationHelper.JSONSerializedElement>();
public IEnumerable<IShaderProperty> properties
{
get { return m_Properties; }
}
public override void AddNode(INode node)
{
if (node is AbstractMaterialNode)

}
}
public void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
{
foreach (var prop in properties)
collector.AddShaderProperty(prop);
}
public void AddShaderProperty(IShaderProperty property)
{
if (property == null)
return;
if (m_Properties.Contains(property))
return;
m_Properties.Add(property);
}
public void RemoveShaderProperty(Guid guid)
{
m_Properties.RemoveAll(x => x.guid == guid);
}
public override Dictionary<SerializationHelper.TypeSerializationInfo, SerializationHelper.TypeSerializationInfo> GetLegacyTypeRemapping()
{
var result = base.GetLegacyTypeRemapping();

assemblyName = "Assembly-CSharp"
};
result[viewNode] = SerializationHelper.GetTypeSerializableAsString(typeof(WorldSpaceViewDirectionNode));
result[viewNode] = SerializationHelper.GetTypeSerializableAsString(typeof(ViewDirectionNode));
var normalNode = new SerializationHelper.TypeSerializationInfo
{

result[normalNode] = SerializationHelper.GetTypeSerializableAsString(typeof(WorldSpaceNormalNode));
result[normalNode] = SerializationHelper.GetTypeSerializableAsString(typeof(NormalNode));
var worldPosNode = new SerializationHelper.TypeSerializationInfo
{

return result;
}
public override void OnBeforeSerialize()
{
base.OnBeforeSerialize();
m_SerializedProperties = SerializationHelper.Serialize<IShaderProperty>(m_Properties);
}
public override void OnAfterDeserialize()
{
// have to deserialize 'globals' before nodes
m_Properties = SerializationHelper.Deserialize<IShaderProperty>(m_SerializedProperties, null);
base.OnAfterDeserialize();
}
private static ShaderGraphRequirements GetRequierments(AbstractMaterialNode nodeForRequirements)
{
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, nodeForRequirements);
NeededCoordinateSpace requiresNormal = activeNodeList.OfType<IMayRequireNormal>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal());
NeededCoordinateSpace requiresBitangent = activeNodeList.OfType<IMayRequireBitangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresBitangent());
NeededCoordinateSpace requiresTangent = activeNodeList.OfType<IMayRequireTangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresTangent());
NeededCoordinateSpace requiresViewDir = activeNodeList.OfType<IMayRequireViewDirection>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresViewDirection());
NeededCoordinateSpace requiresPosition = activeNodeList.OfType<IMayRequirePosition>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresPosition());
bool requiresScreenPosition = activeNodeList.OfType<IMayRequireScreenPosition>().Any(x => x.RequiresScreenPosition());
bool requiresVertexColor = activeNodeList.OfType<IMayRequireVertexColor>().Any(x => x.RequiresVertexColor());
var meshUV = new List<UVChannel>();
for (int uvIndex = 0; uvIndex < ShaderGeneratorNames.UVCount; ++uvIndex)
{
var channel = (UVChannel)uvIndex;
if (activeNodeList.OfType<IMayRequireMeshUV>().Any(x => x.RequiresMeshUV(channel)))
meshUV.Add(channel);
}
// if anything needs tangentspace we have make
// sure to have our othonormal basis!
var compoundSpaces = requiresBitangent | requiresNormal | requiresPosition
| requiresTangent | requiresViewDir | requiresPosition
| requiresNormal;
var needsTangentSpace = (compoundSpaces & NeededCoordinateSpace.Tangent) > 0;
if (needsTangentSpace)
{
requiresBitangent |= NeededCoordinateSpace.Object;
requiresNormal |= NeededCoordinateSpace.Object;
requiresTangent |= NeededCoordinateSpace.Object;
}
var reqs = new ShaderGraphRequirements()
{
requiresNormal = requiresNormal,
requiresBitangent = requiresBitangent,
requiresTangent = requiresTangent,
requiresViewDir = requiresViewDir,
requiresPosition = requiresPosition,
requiresScreenPosition = requiresScreenPosition,
requiresVertexColor = requiresVertexColor,
requiresMeshUVs = meshUV
};
ListPool<INode>.Release(activeNodeList);
return reqs;
}
private static void GenerateSpaceTranslationSurfaceInputs(
NeededCoordinateSpace neededSpaces,
ShaderGenerator surfaceInputs,
string objectSpaceName,
string viewSpaceName,
string worldSpaceName,
string tangentSpaceName)
{
if ((neededSpaces & NeededCoordinateSpace.Object) > 0)
surfaceInputs.AddShaderChunk(string.Format("float3 {0};", objectSpaceName), false);
if ((neededSpaces & NeededCoordinateSpace.World) > 0)
surfaceInputs.AddShaderChunk(string.Format("float3 {0};", worldSpaceName), false);
if ((neededSpaces & NeededCoordinateSpace.View) > 0)
surfaceInputs.AddShaderChunk(string.Format("float3 {0};", viewSpaceName), false);
if ((neededSpaces & NeededCoordinateSpace.Tangent) > 0)
surfaceInputs.AddShaderChunk(string.Format("float3 {0};", tangentSpaceName), false);
}
public string GetPreviewShader(AbstractMaterialNode node, out PreviewMode previewMode)
{
List<PropertyCollector.TextureInfo> configuredTextures;
return GetShader(node, GenerationMode.Preview, string.Format("hidden/preview/{0}", node.GetVariableNameForNode()), out configuredTextures, out previewMode);
}
protected string GetShader(AbstractMaterialNode node, GenerationMode mode, string name, out List<PropertyCollector.TextureInfo> configuredTextures, out PreviewMode previewMode)
{
var vertexShader = new ShaderGenerator();
var pixelShader = new ShaderGenerator();
var surfaceDescription = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var surfaceInputs = new ShaderGenerator();
var graphVertexInput = @"
struct GraphVertexInput
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float4 texcoord : TEXCOORD0;
float4 lightmapUV : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};";
surfaceInputs.AddShaderChunk("struct SurfaceInputs{", false);
surfaceInputs.Indent();
var requirements = GetRequierments(node);
GenerateSpaceTranslationSurfaceInputs(requirements.requiresNormal, surfaceInputs,
ShaderGeneratorNames.ObjectSpaceNormal, ShaderGeneratorNames.ViewSpaceNormal,
ShaderGeneratorNames.WorldSpaceNormal, ShaderGeneratorNames.TangentSpaceNormal);
GenerateSpaceTranslationSurfaceInputs(requirements.requiresTangent, surfaceInputs,
ShaderGeneratorNames.ObjectSpaceTangent, ShaderGeneratorNames.ViewSpaceTangent,
ShaderGeneratorNames.WorldSpaceTangent, ShaderGeneratorNames.TangentSpaceTangent);
GenerateSpaceTranslationSurfaceInputs(requirements.requiresBitangent, surfaceInputs,
ShaderGeneratorNames.ObjectSpaceBiTangent, ShaderGeneratorNames.ViewSpaceBiTangent,
ShaderGeneratorNames.WorldSpaceSpaceBiTangent, ShaderGeneratorNames.TangentSpaceBiTangent);
GenerateSpaceTranslationSurfaceInputs(requirements.requiresViewDir, surfaceInputs,
ShaderGeneratorNames.ObjectSpaceViewDirection, ShaderGeneratorNames.ViewSpaceViewDirection,
ShaderGeneratorNames.WorldSpaceViewDirection, ShaderGeneratorNames.TangentSpaceViewDirection);
GenerateSpaceTranslationSurfaceInputs(requirements.requiresPosition, surfaceInputs,
ShaderGeneratorNames.ObjectSpacePosition, ShaderGeneratorNames.ViewSpacePosition,
ShaderGeneratorNames.WorldSpacePosition, ShaderGeneratorNames.TangentSpacePosition);
if (requirements.requiresVertexColor)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.VertexColor), false);
if (requirements.requiresScreenPosition)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.ScreenPosition), false);
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, node);
previewMode = PreviewMode.Preview2D;
foreach (var pNode in activeNodeList.OfType<AbstractMaterialNode>())
{
if (pNode.previewMode == PreviewMode.Preview3D)
{
previewMode = PreviewMode.Preview3D;
break;
}
}
foreach (var channel in requirements.requiresMeshUVs.Distinct())
surfaceInputs.AddShaderChunk(string.Format("half4 {0};", channel.GetUVName()), false);
surfaceInputs.Deindent();
surfaceInputs.AddShaderChunk("};", false);
vertexShader.AddShaderChunk("GraphVertexInput PopulateVertexData(GraphVertexInput v){", false);
vertexShader.Indent();
vertexShader.AddShaderChunk("return v;", false);
vertexShader.Deindent();
vertexShader.AddShaderChunk("}", false);
surfaceDescription.AddShaderChunk("struct SurfaceDescription{", false);
surfaceDescription.Indent();
if (mode == GenerationMode.Preview)
{
foreach (var slot in node.GetOutputSlots<MaterialSlot>())
surfaceDescription.AddShaderChunk(AbstractMaterialNode.ConvertConcreteSlotValueTypeToString(AbstractMaterialNode.OutputPrecision.@float, slot.concreteValueType) + " " + node.GetVariableNameForSlot(slot.id) + ";", false);
}
else
{
foreach (var slot in node.GetInputSlots<MaterialSlot>())
surfaceDescription.AddShaderChunk(AbstractMaterialNode.ConvertConcreteSlotValueTypeToString(AbstractMaterialNode.OutputPrecision.@float, slot.concreteValueType) + " " + slot.shaderOutputName + ";", false);
}
surfaceDescription.Deindent();
surfaceDescription.AddShaderChunk("};", false);
pixelShader.AddShaderChunk("SurfaceDescription PopulateSurfaceData(SurfaceInputs IN) {", false);
pixelShader.Indent();
if ((requirements.requiresNormal & NeededCoordinateSpace.Object) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.ObjectSpaceNormal), false);
if ((requirements.requiresNormal & NeededCoordinateSpace.View) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.ViewSpaceNormal), false);
if ((requirements.requiresNormal & NeededCoordinateSpace.World) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.WorldSpaceNormal), false);
if ((requirements.requiresNormal & NeededCoordinateSpace.Tangent) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.TangentSpaceNormal), false);
if ((requirements.requiresTangent & NeededCoordinateSpace.Object) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.ObjectSpaceTangent), false);
if ((requirements.requiresTangent & NeededCoordinateSpace.View) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.ViewSpaceTangent), false);
if ((requirements.requiresTangent & NeededCoordinateSpace.World) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.WorldSpaceTangent), false);
if ((requirements.requiresTangent & NeededCoordinateSpace.Tangent) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.TangentSpaceTangent), false);
if ((requirements.requiresBitangent & NeededCoordinateSpace.Object) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.ObjectSpaceBiTangent), false);
if ((requirements.requiresBitangent & NeededCoordinateSpace.View) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.ViewSpaceBiTangent), false);
if ((requirements.requiresBitangent & NeededCoordinateSpace.World) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.WorldSpaceSpaceBiTangent), false);
if ((requirements.requiresBitangent & NeededCoordinateSpace.Tangent) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.TangentSpaceBiTangent), false);
if ((requirements.requiresViewDir & NeededCoordinateSpace.Object) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.ObjectSpaceViewDirection), false);
if ((requirements.requiresViewDir & NeededCoordinateSpace.View) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.ViewSpaceViewDirection), false);
if ((requirements.requiresViewDir & NeededCoordinateSpace.World) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.WorldSpaceViewDirection), false);
if ((requirements.requiresViewDir & NeededCoordinateSpace.Tangent) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.TangentSpaceViewDirection), false);
if ((requirements.requiresPosition & NeededCoordinateSpace.Object) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.ObjectSpacePosition), false);
if ((requirements.requiresPosition & NeededCoordinateSpace.View) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.ViewSpacePosition), false);
if ((requirements.requiresPosition & NeededCoordinateSpace.World) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.WorldSpacePosition), false);
if ((requirements.requiresPosition & NeededCoordinateSpace.Tangent) > 0)
pixelShader.AddShaderChunk(string.Format("float3 {0} = IN.{0};", ShaderGeneratorNames.TangentSpacePosition), false);
if (requirements.requiresScreenPosition)
pixelShader.AddShaderChunk(string.Format("float4 {0} = IN.{0};", ShaderGeneratorNames.ScreenPosition), false);
if (requirements.requiresVertexColor)
pixelShader.AddShaderChunk(string.Format("float4 {0} = IN.{0};", ShaderGeneratorNames.VertexColor), false);
foreach (var channel in requirements.requiresMeshUVs.Distinct())
pixelShader.AddShaderChunk(string.Format("half4 {0} = IN.{0};", channel.GetUVName()), false);
var shaderProperties = new PropertyCollector();
CollectShaderProperties(shaderProperties, mode);
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
{
if (activeNode is IGeneratesFunction)
(activeNode as IGeneratesFunction).GenerateNodeFunction(shaderFunctionVisitor, mode);
if (activeNode is IGeneratesBodyCode)
(activeNode as IGeneratesBodyCode).GenerateNodeCode(pixelShader, mode);
activeNode.CollectShaderProperties(shaderProperties, mode);
}
pixelShader.AddShaderChunk("SurfaceDescription surface;", false);
if (mode == GenerationMode.Preview)
{
foreach (var slot in node.GetOutputSlots<MaterialSlot>())
pixelShader.AddShaderChunk(string.Format("surface.{0} = {0};", node.GetVariableNameForSlot(slot.id)), true);
}
else
{
foreach (var input in node.GetInputSlots<MaterialSlot>())
{
foreach (var edge in GetEdges(input.slotReference))
{
var outputRef = edge.outputSlot;
var fromNode = GetNodeFromGuid<AbstractMaterialNode>(outputRef.nodeGuid);
if (fromNode == null)
continue;
var remapper = fromNode as INodeGroupRemapper;
if (remapper != null && !remapper.IsValidSlotConnection(outputRef.slotId))
continue;
pixelShader.AddShaderChunk(string.Format("surface.{0} = {1};", input.shaderOutputName, fromNode.GetVariableNameForSlot(outputRef.slotId)), true);
}
}
}
pixelShader.AddShaderChunk("return surface;", false);
pixelShader.Deindent();
pixelShader.AddShaderChunk("}", false);
ListPool<INode>.Release(activeNodeList);
var finalShader = new ShaderGenerator();
finalShader.AddShaderChunk(string.Format(@"Shader ""{0}""", name), 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);
finalShader.AddShaderChunk("CGINCLUDE", false);
finalShader.AddShaderChunk("#include \"UnityCG.cginc\"", false);
finalShader.AddShaderChunk(shaderFunctionVisitor.GetShaderString(2), false);
finalShader.AddShaderChunk(graphVertexInput, false);
finalShader.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
finalShader.AddShaderChunk(surfaceDescription.GetShaderString(2), false);
finalShader.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
finalShader.AddShaderChunk(vertexShader.GetShaderString(2), false);
finalShader.AddShaderChunk(pixelShader.GetShaderString(2), false);
finalShader.AddShaderChunk("ENDCG", false);
if (mode == GenerationMode.Preview)
finalShader.AddShaderChunk(ShaderGenerator.GetPreviewSubShader(node, requirements), false);
else
{
var master = (MasterNode) node;
finalShader.AddShaderChunk(master.GetSubShader(requirements), false);
}
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
configuredTextures = shaderProperties.GetConfiguredTexutres();
return finalShader.GetShaderString(0);
}
}
}

51
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/MaterialGraph.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Graphing;

public class MaterialGraph : AbstractMaterialGraph
{
[NonSerialized]
private Guid m_ActiveMasterNodeGUID;
[SerializeField]
private string m_ActiveMasterNodeGUIDSerialized;
public MaterialGraph()
public MasterNode masterNode
m_ActiveMasterNodeGUID = Guid.NewGuid();
get { return GetNodes<MasterNode>().FirstOrDefault(); }
public IMasterNode masterNode
public string GetShader(string name, out List<PropertyCollector.TextureInfo> configuredTextures)
get
{
var found = GetNodeFromGuid(m_ActiveMasterNodeGUID) as IMasterNode;
if (found != null)
return found;
return GetNodes<IMasterNode>().FirstOrDefault();
}
set
{
var previousMaster = masterNode;
if (value == null)
m_ActiveMasterNodeGUID = Guid.NewGuid();
else
m_ActiveMasterNodeGUID = value.guid;
masterNode.onModified(masterNode, ModificationScope.Node);
previousMaster.onModified(previousMaster, ModificationScope.Node);
}
PreviewMode mode;
return GetShader(masterNode, GenerationMode.ForReals, name, out configuredTextures, out mode);
public override void OnBeforeSerialize()
{
base.OnBeforeSerialize();
m_ActiveMasterNodeGUIDSerialized = m_ActiveMasterNodeGUID.ToString();
}
public override void OnAfterDeserialize()
{
base.OnAfterDeserialize();
if (!string.IsNullOrEmpty(m_ActiveMasterNodeGUIDSerialized))
m_ActiveMasterNodeGUID = new Guid(m_ActiveMasterNodeGUIDSerialized);
else
m_ActiveMasterNodeGUID = Guid.NewGuid();
}
}
}

55
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/MaterialSlot.cs


using System;
using System.Collections.Generic;
using UnityEngine.Graphing;
namespace UnityEngine.MaterialGraph

set { m_ShaderStage = value; }
}
public void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
if (!generationMode.IsPreview())
return;
if (concreteValueType == ConcreteSlotValueType.SamplerState ||
concreteValueType == ConcreteSlotValueType.Texture2D)
return;
var matOwner = owner as AbstractMaterialNode;
if (matOwner == null)
throw new Exception(string.Format("Slot {0} either has no owner, or the owner is not a {1}", this, typeof(AbstractMaterialNode)));
visitor.AddShaderChunk(AbstractMaterialNode.ConvertConcreteSlotValueTypeToString(matOwner.precision, concreteValueType) + " " + matOwner.GetVariableNameForSlot(id) + ";", true);
}
public bool IsCompatibleWithInputSlotType(SlotValueType inputType)
{
switch (valueType)

default:
return "error";
}
}
public void AddProperty(PropertyCollector properties, GenerationMode generationMode)
{
if (!generationMode.IsPreview())
return;
if (concreteValueType == ConcreteSlotValueType.SamplerState ||
concreteValueType == ConcreteSlotValueType.Texture2D)
return;
var matOwner = owner as AbstractMaterialNode;
if (matOwner == null)
throw new Exception(string.Format("Slot {0} either has no owner, or the owner is not a {1}", this, typeof(AbstractMaterialNode)));
IShaderProperty property;
switch (concreteValueType)
{
case ConcreteSlotValueType.Vector4:
property = new Vector4ShaderProperty();
break;
case ConcreteSlotValueType.Vector3:
property = new Vector3ShaderProperty();
break;
case ConcreteSlotValueType.Vector2:
property = new Vector2ShaderProperty();
break;
case ConcreteSlotValueType.Vector1:
property = new FloatShaderProperty();
break;
default:
throw new ArgumentOutOfRangeException();
}
property.name = matOwner.GetVariableNameForSlot(id);
property.generatePropertyBlock = false;
properties.AddShaderProperty(property);
}
}
}

5
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Interfaces/IGenerateProperties.cs


using System.Collections.Generic;
void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode);
void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode);
void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode);
}
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Interfaces/IMasterNode.cs


namespace UnityEngine.MaterialGraph
{
public interface IMasterNode : INode
/* public interface IMasterNode : INode
{
string GetFullShader(GenerationMode mode, string name, out List<PropertyGenerator.TextureInfo> configuredTextures);

bool has3DPreview();
}
}*/
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Interfaces/IMayRequireNormal.cs


{
public interface IMayRequireNormal
{
bool RequiresNormal();
NeededCoordinateSpace RequiresNormal();
}
}

14
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/LightweightPipeline/AbstractLightweightPBRMasterNode.cs


namespace UnityEngine.MaterialGraph
{
[Serializable]
/*[Serializable]
public abstract class AbstractLightweightPBRMasterNode : AbstractMasterNode
{
public const string AlbedoSlotName = "Albedo";

resultShader = resultShader.Replace("${LOD}", "" + m_MaterialOptions.lod);
resultShader = resultShader.Replace("${Defines}", definesVisitor.GetShaderString(2));
return resultShader;
}

int vertInputIndex = 2;
int vertOutputIndex = 5;
// always add everything because why not.
// always add everything because why not.
shaderInputVisitor.AddShaderChunk("float2 lightmapUV : TEXCOORD1;", true);*/
shaderInputVisitor.AddShaderChunk("float2 lightmapUV : TEXCOORD1;", true);*
shaderInputVisitor.AddShaderChunk("half4 texcoord1 : TEXCOORD1;", true);

shaderOutputVisitor.AddShaderChunk("half4 fogCoord : TEXCOORD2; \\", true);
shaderOutputVisitor.AddShaderChunk("half3 normal : TEXCOORD3; \\", true);
shaderOutputVisitor.AddShaderChunk("half4 meshUV0 : TEXCOORD4; \\", true);
shaderOutputVisitor.AddShaderChunk("float4 hpos : SV_POSITION; \\", true);*/
shaderOutputVisitor.AddShaderChunk("float4 hpos : SV_POSITION; \\", true);*
bool requiresBitangent = activeNodeList.OfType<IMayRequireBitangent>().Any(x => x.RequiresBitangent());
bool requiresTangent = activeNodeList.OfType<IMayRequireTangent>().Any(x => x.RequiresTangent());

}
}
}
}
}*/
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/LightweightPipeline/LightweightFastBlinnMasterNode.cs


namespace UnityEngine.MaterialGraph
{
[Serializable]
/* [Serializable]
[Title("Master/Lightweight/Fast Blinn")]
public class LightweightFastBlinnMasterNode : AbstractMasterNode
{

resultShader = resultShader.Replace("${LOD}", "" + m_MaterialOptions.lod);
resultShader = resultShader.Replace("${Defines}", definesVisitor.GetShaderString(2));
return resultShader;
}

}
}
}
}
}*/
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/LightweightPipeline/LightweightMetallicMasterNode.cs


namespace UnityEngine.MaterialGraph
{
[Serializable]
/* [Serializable]
[Title("Master/Lightweight/PBR Metallic")]
public class LightweightMetallicMasterNode : AbstractLightweightPBRMasterNode
{

{
return WorkflowName;
}
}
}*/
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/LightweightPipeline/LightweightSpecularMasterNode.cs


namespace UnityEngine.MaterialGraph
{
[Serializable]
/>an class="p">* [Serializable]
[Title("Master/Lightweight/PBR Specular")]
public class LightweightSpecularMasterNode : AbstractLightweightPBRMasterNode
{

{
return WorkflowName;
}
}
}*/
}

10
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/LightweightPipeline/LightweightUnlitMasterNode.cs


namespace UnityEngine.MaterialGraph
{
[Serializable]
/* [Serializable]
[Title("Master/Lightweight/Unlit")]
public class LightweightUnlitMasterNode : AbstractMasterNode
{

resultShader = resultShader.Replace("${LOD}", "" + m_MaterialOptions.lod);
resultShader = resultShader.Replace("${Defines}", definesVisitor.GetShaderString(2));
}
public override string GetFullShader(GenerationMode mode, string name, out List<PropertyGenerator.TextureInfo> configuredTextures)

}
}
}
}
}*/
}

16
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/AbstractMaterialNode.cs


version = 0;
}
public virtual void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
{}
public virtual void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
public virtual void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
{
if (!generateDefaultInputs)
return;

if (edges.Any())
continue;
inputSlot.GeneratePropertyUsages(visitor, generationMode);
inputSlot.AddProperty(properties, generationMode);
}
}

return PropertyType.Vector4;
}
}
/*
public virtual bool DrawSlotDefaultInput(Rect rect, MaterialSlot inputSlot)
{
var inputSlotType = inputSlot.concreteValueType;
return inputSlot.OnGUI(rect, inputSlotType);
}
*/
public virtual void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{

156
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/HLSLNode.cs


, IMayRequireMeshUV
, IMayRequireScreenPosition
, IMayRequireViewDirection
, IMayRequireWorldPosition
, IMayRequirePosition
, IMayRequireViewDirectionTangentSpace
{
[NonSerialized]
private List<SlotAttribute> m_Slots = new List<SlotAttribute>();

protected enum Binding
{
None,
Normal,
Tangent,
Bitangent,
ObjectSpaceNormal,
ObjectSpaceTangent,
ObjectSpaceBitangent,
ObjectSpacePosition,
ViewSpaceNormal,
ViewSpaceTangent,
ViewSpaceBitangent,
ViewSpacePosition,
WorldSpaceNormal,
WorldSpaceTangent,
WorldSpaceBitangent,
WorldSpacePosition,
TangentSpaceNormal,
TangentSpaceTangent,
TangentSpaceBitangent,
TangentSpacePosition,
ViewDirection,
WorldPosition,
ObjectSpaceViewDirection,
ViewSpaceViewDirection,
WorldSpaceViewDirection,
TangentSpaceViewDirection,
ViewDirectionTangentSpace
}
private static string BindChannelToShaderName(Binding channel)

case Binding.None:
return "ERROR!";
case Binding.Normal:
case Binding.ObjectSpaceNormal:
return ShaderGeneratorNames.ObjectSpaceNormal;
case Binding.ObjectSpaceTangent:
return ShaderGeneratorNames.ObjectSpaceTangent;
case Binding.ObjectSpaceBitangent:
return ShaderGeneratorNames.ObjectSpaceBiTangent;
case Binding.ObjectSpacePosition:
return ShaderGeneratorNames.ObjectSpacePosition;
case Binding.ViewSpaceNormal:
return ShaderGeneratorNames.ViewSpaceNormal;
case Binding.ViewSpaceTangent:
return ShaderGeneratorNames.ViewSpaceTangent;
case Binding.ViewSpaceBitangent:
return ShaderGeneratorNames.ViewSpaceBiTangent;
case Binding.ViewSpacePosition:
return ShaderGeneratorNames.ViewSpacePosition;
case Binding.WorldSpaceNormal:
case Binding.Tangent:
case Binding.WorldSpaceTangent:
case Binding.Bitangent:
return ShaderGeneratorNames.WorldSpaceBitangent;
case Binding.WorldSpaceBitangent:
return ShaderGeneratorNames.WorldSpaceSpaceBiTangent;
case Binding.WorldSpacePosition:
return ShaderGeneratorNames.WorldSpacePosition;
case Binding.TangentSpaceNormal:
return ShaderGeneratorNames.TangentSpaceNormal;
case Binding.TangentSpaceTangent:
return ShaderGeneratorNames.TangentSpaceTangent;
case Binding.TangentSpaceBitangent:
return ShaderGeneratorNames.TangentSpaceBiTangent;
case Binding.TangentSpacePosition:
return ShaderGeneratorNames.TangentSpacePosition;
return ShaderGeneratorNames.GetUVName(UVChannel.uv0);
return UVChannel.uv0.GetUVName();
return ShaderGeneratorNames.GetUVName(UVChannel.uv1);
return UVChannel.uv1.GetUVName();
return ShaderGeneratorNames.GetUVName(UVChannel.uv2);
return UVChannel.uv2.GetUVName();
return ShaderGeneratorNames.GetUVName(UVChannel.uv3);
return UVChannel.uv3.GetUVName();
case Binding.ViewDirection:
case Binding.ObjectSpaceViewDirection:
return ShaderGeneratorNames.ObjectSpaceViewDirection;
case Binding.ViewSpaceViewDirection:
return ShaderGeneratorNames.ViewSpaceViewDirection;
case Binding.WorldSpaceViewDirection:
case Binding.WorldPosition:
return ShaderGeneratorNames.WorldSpacePosition;
case Binding.TangentSpaceViewDirection:
return ShaderGeneratorNames.TangentSpaceViewDirection;
case Binding.ViewDirectionTangentSpace:
return ShaderGeneratorNames.TangentSpaceViewDirection;
default:
throw new ArgumentOutOfRangeException("channel", channel, null);
}

return attrs.FirstOrDefault();
}
public bool RequiresNormal()
public NeededCoordinateSpace RequiresNormal()
return NodeRequiresBinding(Binding.Normal);
var binding = NeededCoordinateSpace.None;
if (NodeRequiresBinding(Binding.ObjectSpaceNormal))
binding |= NeededCoordinateSpace.Object;
if (NodeRequiresBinding(Binding.ViewSpaceNormal))
binding |= NeededCoordinateSpace.View;
if (NodeRequiresBinding(Binding.WorldSpaceNormal))
binding |= NeededCoordinateSpace.World;
if (NodeRequiresBinding(Binding.TangentSpaceNormal))
binding |= NeededCoordinateSpace.Tangent;
return binding;
}
public bool RequiresMeshUV(UVChannel channel)

return NodeRequiresBinding(Binding.ScreenPosition);
}
public bool RequiresViewDirection()
public NeededCoordinateSpace RequiresViewDirection()
return NodeRequiresBinding(Binding.ViewDirection);
var binding = NeededCoordinateSpace.None;
if (NodeRequiresBinding(Binding.ObjectSpaceViewDirection))
binding |= NeededCoordinateSpace.Object;
if (NodeRequiresBinding(Binding.ViewSpaceViewDirection))
binding |= NeededCoordinateSpace.View;
if (NodeRequiresBinding(Binding.WorldSpaceViewDirection))
binding |= NeededCoordinateSpace.World;
if (NodeRequiresBinding(Binding.TangentSpaceNormal))
binding |= NeededCoordinateSpace.Tangent;
return binding;
public bool RequiresViewDirectionTangentSpace()
public NeededCoordinateSpace RequiresPosition()
return NodeRequiresBinding(Binding.ViewDirectionTangentSpace);
}
var binding = NeededCoordinateSpace.None;
if (NodeRequiresBinding(Binding.ObjectSpacePosition))
binding |= NeededCoordinateSpace.Object;
if (NodeRequiresBinding(Binding.ViewSpacePosition))
binding |= NeededCoordinateSpace.View;
if (NodeRequiresBinding(Binding.WorldSpacePosition))
binding |= NeededCoordinateSpace.World;
if (NodeRequiresBinding(Binding.TangentSpacePosition))
binding |= NeededCoordinateSpace.Tangent;
public bool RequiresWorldPosition()
{
return NodeRequiresBinding(Binding.WorldPosition);
return binding;
public bool RequiresTangent()
public NeededCoordinateSpace RequiresTangent()
return NodeRequiresBinding(Binding.Tangent);
var binding = NeededCoordinateSpace.None;
if (NodeRequiresBinding(Binding.ObjectSpaceTangent))
binding |= NeededCoordinateSpace.Object;
if (NodeRequiresBinding(Binding.ViewSpaceTangent))
binding |= NeededCoordinateSpace.View;
if (NodeRequiresBinding(Binding.WorldSpaceTangent))
binding |= NeededCoordinateSpace.World;
if (NodeRequiresBinding(Binding.TangentSpaceTangent))
binding |= NeededCoordinateSpace.Tangent;
return binding;
public bool RequiresBitangent()
public NeededCoordinateSpace RequiresBitangent()
return NodeRequiresBinding(Binding.Bitangent);
var binding = NeededCoordinateSpace.None;
if (NodeRequiresBinding(Binding.ObjectSpaceBitangent))
binding |= NeededCoordinateSpace.Object;
if (NodeRequiresBinding(Binding.ViewSpaceBitangent))
binding |= NeededCoordinateSpace.View;
if (NodeRequiresBinding(Binding.WorldSpaceBitangent))
binding |= NeededCoordinateSpace.World;
if (NodeRequiresBinding(Binding.TangentSpaceBitangent))
binding |= NeededCoordinateSpace.Tangent;
return binding;
}
public bool RequiresVertexColor()

45
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/ColorNode.cs


using System.Collections.Generic;
public class ColorNode : PropertyNode, IGeneratesBodyCode
public class ColorNode : AbstractMaterialNode, IGeneratesBodyCode
{
[SerializeField]
private bool m_HDR;

RemoveSlotsNameNotMatching(new[] { kOutputSlotId });
}
public override PropertyType propertyType
{
get { return PropertyType.Color; }
}
public Color color
{
get { return m_Color; }

}
}
public override void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
if (exposedState == ExposedState.Exposed)
visitor.AddShaderProperty(new ColorPropertyChunk(propertyName, description, color, m_HDR ? ColorPropertyChunk.ColorType.HDR : ColorPropertyChunk.ColorType.Default , PropertyChunk.HideState.Visible));
}
if (!generationMode.IsPreview())
return;
public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
visitor.AddShaderChunk(precision + "4 " + propertyName + ";", true);
properties.AddShaderProperty(new ColorShaderProperty()
{
name = GetVariableNameForNode(),
generatePropertyBlock = false,
value = color,
HDR = HDR
});
// we only need to generate node code if we are using a constant... otherwise we can just refer to the property :)
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
if (generationMode.IsPreview())
visitor.AddShaderChunk(precision + "4 " + propertyName + " = " + precision + "4 (" + color.r + ", " + color.g + ", " + color.b + ", " + color.a + ");", true);
visitor.AddShaderChunk(precision + "4 " + GetVariableNameForNode() + " = " + precision + "4 (" + color.r + ", " + color.g + ", " + color.b + ", " + color.a + ");", true);
public override PreviewProperty GetPreviewProperty()
public override string GetVariableNameForSlot(int slotId)
return new PreviewProperty
return GetVariableNameForNode();
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
properties.Add(new PreviewProperty
m_Name = propertyName,
m_Name = GetVariableNameForNode(),
};
});
}
}
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Geometry/WorldSpaceBitangentNode.cs


{
public interface IMayRequireBitangent
{
bool RequiresBitangent();
NeededCoordinateSpace RequiresBitangent();
[Title("Input/Geometry/World Bitangent")]
/* [Title("Input/Geometry/World Bitangent")]
public class WorldSpaceBitangentNode : AbstractMaterialNode, IMayRequireBitangent
{
public const int kOutputSlotId = 0;

public override string GetVariableNameForSlot(int slotId)
{
return ShaderGeneratorNames.WorldSpaceBitangent;
return ShaderGeneratorNames.BiTangent;
}
public bool RequiresBitangent()

}
}*/
}

12
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Geometry/WorldSpacePositionNode.cs


namespace UnityEngine.MaterialGraph
{
interface IMayRequireWorldPosition
interface IMayRequirePosition
bool RequiresWorldPosition();
NeededCoordinateSpace RequiresPosition();
public class WorldSpacePositionNode : AbstractMaterialNode, IMayRequireWorldPosition
public class WorldSpacePositionNode : AbstractMaterialNode, IMayRequirePosition
{
private const int kOutputSlotId = 0;

public WorldSpacePositionNode()
{
name = "WorldSpacePosition";
name = "Position";
UpdateNodeAfterDeserialization();
}

return ShaderGeneratorNames.WorldSpacePosition;
}
public bool RequiresWorldPosition()
public NeededCoordinateSpace RequiresPosition()
return true;
return NeededCoordinateSpace.World;
}
}
}

14
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Geometry/WorldSpaceTangentNode.cs


{
public interface IMayRequireTangent
{
bool RequiresTangent();
NeededCoordinateSpace RequiresTangent();
public class WorldSpaceTangentNode : AbstractMaterialNode, IMayRequireTangent
public class TangentNode : AbstractMaterialNode, IMayRequireTangent
public WorldSpaceTangentNode()
public TangentNode()
name = "WorldTangent";
name = "Tangent";
UpdateNodeAfterDeserialization();
}

public override string GetVariableNameForSlot(int slotId)
{
return ShaderGeneratorNames.WorldSpaceTangent;
return ShaderGeneratorNames.ObjectSpaceTangent;
public bool RequiresTangent()
public NeededCoordinateSpace RequiresTangent()
return true;
return NeededCoordinateSpace.Object;
}
}
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Matrix/Matrix2Node.cs


//if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
// return;
visitor.AddShaderChunk(precision + "2 " + propertyName + " = " + precision + "2x2 (" + m_Value[0].x + ", " + m_Value[0].y + ", " + m_Value[1].x + ", " + m_Value[1].y + ");", true);
visitor.AddShaderChunk(precision + "2 " + name + " = " + precision + "2x2 (" + m_Value[0].x + ", " + m_Value[0].y + ", " + m_Value[1].x + ", " + m_Value[1].y + ");", true);
}
[SerializeField]

4
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Texture/CubemapNode.cs


namespace UnityEngine.MaterialGraph
{
[Title("Input/Texture/Cubemap")]
/* [Title("Input/Texture/Cubemap")]
public class CubemapNode : PropertyNode, IGeneratesBodyCode, IMayRequireViewDirection, IMayRequireNormal
{
protected const string kUVSlotName = "RefVector";

{
return true;
}
}
}*/
}

6
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Texture/TextureLODNode.cs


namespace UnityEngine.MaterialGraph
{
[Title("Input/Texture/TextureLOD")]
/>an class="p">* [Title("Input/Texture/TextureLOD")]
public class TextureLODNode : PropertyNode, IGeneratesBodyCode, IMayRequireMeshUV
{
protected const string kUVSlotName = "UV";

return false;
}
*/
*
public override PreviewProperty GetPreviewProperty()
{

var edges = owner.GetEdges(uvSlot.slotReference).ToList();
return edges.Count == 0;
}
}
}*/
}

74
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Vector/Vector1Node.cs


using System.Collections.Generic;
public class Vector1Node : PropertyNode, IGeneratesBodyCode
public class Vector1Node : AbstractMaterialNode, IGeneratesBodyCode
[SerializeField]
private FloatPropertyChunk.FloatType m_floatType;
/*[SerializeField]
private FloatPropertyChunk.FloatType m_floatType;*/
[SerializeField]
private Vector3 m_rangeValues = new Vector3(0f, 1f, 2f);
// [SerializeField]
//private Vector3 m_rangeValues = new Vector3(0f, 1f, 2f);
public const int OutputSlotId = 0;
private const string kOutputSlotName = "Value";

RemoveSlotsNameNotMatching(new[] { OutputSlotId });
}
public override PropertyType propertyType
{
get { return PropertyType.Float; }
}
public float value
{
get { return m_Value; }

}
}
public FloatPropertyChunk.FloatType floatType
/* public FloatPropertyChunk.FloatType floatType
{
get { return m_floatType; }
set

if (onModified != null)
onModified(this, ModificationScope.Node);
}
}
}*/
public Vector3 rangeValues
/* public Vector3 rangeValues
{
get { return m_rangeValues; }
set

onModified(this, ModificationScope.Node);
}
}
public override void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
*/
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
if (exposedState == ExposedState.Exposed)
{
switch (m_floatType)
{
case FloatPropertyChunk.FloatType.Float:
visitor.AddShaderProperty(new FloatPropertyChunk(propertyName, description, m_Value, PropertyChunk.HideState.Visible));
break;
case FloatPropertyChunk.FloatType.Toggle:
visitor.AddShaderProperty(new FloatPropertyChunk(propertyName, description, m_Value, m_floatType, PropertyChunk.HideState.Visible));
break;
case FloatPropertyChunk.FloatType.Range:
visitor.AddShaderProperty(new FloatPropertyChunk(propertyName, description, m_Value, m_floatType, m_rangeValues, PropertyChunk.HideState.Visible));
break;
case FloatPropertyChunk.FloatType.PowerSlider:
visitor.AddShaderProperty(new FloatPropertyChunk(propertyName, description, m_Value, m_floatType, m_rangeValues, PropertyChunk.HideState.Visible));
break;
}
}
}
if (!generationMode.IsPreview())
return;
public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
visitor.AddShaderChunk(precision + " " + propertyName + ";", true);
properties.AddShaderProperty(new FloatShaderProperty()
{
name = GetVariableNameForNode(),
generatePropertyBlock = false,
value = value
});
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
if (generationMode.IsPreview())
visitor.AddShaderChunk(precision + " " + propertyName + " = " + m_Value + ";", true);
visitor.AddShaderChunk(precision + " " + GetVariableNameForNode() + " = " + m_Value + ";", true);
public override PreviewProperty GetPreviewProperty()
public override string GetVariableNameForSlot(int slotId)
return new PreviewProperty
return GetVariableNameForNode();
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
properties.Add(new PreviewProperty()
m_Name = propertyName,
m_Name = GetVariableNameForNode(),
};
});
}
}
}

52
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Vector/Vector2Node.cs


using System.Collections.Generic;
public class Vector2Node : PropertyNode, IGeneratesBodyCode
public class Vector2Node : AbstractMaterialNode, IGeneratesBodyCode
private const int kOutputSlotId = 0;
private const string kOutputSlotName = "Value";
public const int OutputSlotId = 0;
private const string kOutputSlotName = "Value";
public Vector2Node()
{
name = "Vector2";

public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, SlotValueType.Vector2, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { kOutputSlotId });
}
public override PropertyType propertyType
{
get { return PropertyType.Vector2; }
AddSlot(new MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, SlotValueType.Vector2, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
}
public Vector2 value

}
}
public override void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
if (exposedState == ExposedState.Exposed)
visitor.AddShaderProperty(new VectorPropertyChunk(propertyName, description, m_Value, PropertyChunk.HideState.Visible));
}
if (!generationMode.IsPreview())
return;
public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
visitor.AddShaderChunk(precision + "2 " + propertyName + ";", true);
properties.AddShaderProperty(new Vector2ShaderProperty()
{
name = GetVariableNameForNode(),
generatePropertyBlock = false,
value = value
});
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
if (generationMode.IsPreview())
visitor.AddShaderChunk(precision + "2 " + propertyName + " = " + precision + "2 (" + m_Value.x + ", " + m_Value.y + ");", true);
visitor.AddShaderChunk(precision + " " + GetVariableNameForNode() + " = " + m_Value + ";", true);
public override PreviewProperty GetPreviewProperty()
public override string GetVariableNameForSlot(int slotId)
{
return GetVariableNameForNode();
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
return new PreviewProperty
properties.Add(new PreviewProperty()
m_Name = propertyName,
m_Name = GetVariableNameForNode(),
};
});
}
}
}

53
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Vector/Vector3Node.cs


using System;
using System.Collections.Generic;
public class Vector3Node : PropertyNode, IGeneratesBodyCode
public class Vector3Node : AbstractMaterialNode, IGeneratesBodyCode
private const int kOutputSlotId = 0;
private const string kOutputSlotName = "Value";
public const int OutputSlotId = 0;
private const string kOutputSlotName = "Value";
public Vector3Node()
{
name = "Vector3";

public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, SlotValueType.Vector3, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { kOutputSlotId });
}
public override PropertyType propertyType
{
get { return PropertyType.Vector3; }
AddSlot(new MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, SlotValueType.Vector3, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
}
public Vector3 value

}
}
public override void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
if (exposedState == ExposedState.Exposed)
visitor.AddShaderProperty(new VectorPropertyChunk(propertyName, description, m_Value, PropertyChunk.HideState.Visible));
}
if (!generationMode.IsPreview())
return;
public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
visitor.AddShaderChunk(precision + "3 " + propertyName + ";", true);
properties.AddShaderProperty(new Vector3ShaderProperty()
{
name = GetVariableNameForNode(),
generatePropertyBlock = false,
value = value
});
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
if (generationMode.IsPreview())
visitor.AddShaderChunk(precision + "3 " + propertyName + " = " + precision + "3 (" + m_Value.x + ", " + m_Value.y + ", " + m_Value.z + ");", true);
visitor.AddShaderChunk(precision + " " + GetVariableNameForNode() + " = " + m_Value + ";", true);
public override PreviewProperty GetPreviewProperty()
public override string GetVariableNameForSlot(int slotId)
{
return GetVariableNameForNode();
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
return new PreviewProperty
properties.Add(new PreviewProperty()
m_Name = propertyName,
m_Name = GetVariableNameForNode(),
};
});
}
}
}

48
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Vector/Vector4Node.cs


using System.Collections.Generic;
public class Vector4Node : PropertyNode, IGeneratesBodyCode
public class Vector4Node : AbstractMaterialNode, IGeneratesBodyCode
private const int kOutputSlotId = 0;
public const int OutputSlotId = 0;
private const string kOutputSlotName = "Value";
public Vector4Node()

public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, SlotValueType.Vector4, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { kOutputSlotId });
}
public override PropertyType propertyType
{
get { return PropertyType.Vector4; }
AddSlot(new MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, SlotValueType.Vector4, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
}
public Vector4 value

}
}
public override void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
if (exposedState == ExposedState.Exposed)
visitor.AddShaderProperty(new VectorPropertyChunk(propertyName, description, m_Value, PropertyChunk.HideState.Visible));
}
if (!generationMode.IsPreview())
return;
public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
visitor.AddShaderChunk(precision + "4 " + propertyName + ";", true);
properties.AddShaderProperty(new Vector4ShaderProperty()
{
name = GetVariableNameForNode(),
generatePropertyBlock = false,
value = value
});
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
if (generationMode.IsPreview())
visitor.AddShaderChunk(precision + "4 " + propertyName + " = " + precision + "4 (" + m_Value.x + ", " + m_Value.y + ", " + m_Value.z + ", " + m_Value.w + ");", true);
visitor.AddShaderChunk(precision + " " + GetVariableNameForNode() + " = " + m_Value + ";", true);
public override PreviewProperty GetPreviewProperty()
public override string GetVariableNameForSlot(int slotId)
return new PreviewProperty
return GetVariableNameForNode();
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
properties.Add(new PreviewProperty()
m_Name = propertyName,
m_Name = GetVariableNameForNode(),
};
});
}
}
}

245
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/PropertyNode.cs


using System.Collections.Generic;
using System;
using System.Linq;
public abstract class PropertyNode : AbstractMaterialNode
[Title("Property Node")]
public class PropertyNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequireMeshUV
public enum ExposedState
private Guid m_PropertyGuid;
[SerializeField] private string m_PropertyGuidSerialized;
public const int OutputSlotId = 0;
public const int ROutputSlotId = 1;
public const int GOutputSlotId = 2;
public const int BOutputSlotId = 3;
public const int AOutputSlotId = 4;
public const int TOutputSlotId = 5;
public const int UVInput = 6;
public PropertyNode()
Exposed,
NotExposed
name = "Property";
UpdateNodeAfterDeserialization();
[SerializeField]
private string m_Description = string.Empty;
private void UpdateNode()
{
var graph = owner as AbstractMaterialGraph;
var property = graph.properties.FirstOrDefault(x => x.guid == propertyGuid);
if (property == null)
return;
[SerializeField]
private ExposedState m_Exposed = ExposedState.NotExposed;
if (property is FloatShaderProperty)
{
AddSlot(new MaterialSlot(OutputSlotId, "float", "float", SlotType.Output, SlotValueType.Vector1, Vector4.zero));
RemoveSlotsNameNotMatching(new[] {OutputSlotId});
}
else if (property is Vector2ShaderProperty)
{
AddSlot(new MaterialSlot(OutputSlotId, "V2", "V2", SlotType.Output, SlotValueType.Vector2, Vector4.zero));
RemoveSlotsNameNotMatching(new[] {OutputSlotId});
}
else if (property is Vector3ShaderProperty)
{
AddSlot(new MaterialSlot(OutputSlotId, "V3", "V3", SlotType.Output, SlotValueType.Vector3, Vector4.zero));
RemoveSlotsNameNotMatching(new[] {OutputSlotId});
}
else if (property is Vector4ShaderProperty)
{
AddSlot(new MaterialSlot(OutputSlotId, "V4", "V4", SlotType.Output, SlotValueType.Vector4, Vector4.zero));
RemoveSlotsNameNotMatching(new[] {OutputSlotId});
}
else if (property is ColorShaderProperty)
{
AddSlot(new MaterialSlot(OutputSlotId, "Color", "Color", SlotType.Output, SlotValueType.Vector4, Vector4.zero));
RemoveSlotsNameNotMatching(new[] {OutputSlotId});
}
else if (property is TextureShaderProperty)
{
AddSlot(new MaterialSlot(OutputSlotId, "RGBA", "RGBA", SlotType.Output, SlotValueType.Vector4, Vector4.zero));
AddSlot(new MaterialSlot(ROutputSlotId, "R", "R", SlotType.Output, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(GOutputSlotId, "G", "G", SlotType.Output, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(BOutputSlotId, "B", "B", SlotType.Output, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(AOutputSlotId, "A", "A", SlotType.Output, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(TOutputSlotId, "T", "T", SlotType.Output, SlotValueType.Texture2D, Vector4.zero));
AddSlot(new MaterialSlot(UVInput, "UV", "UV", SlotType.Input, SlotValueType.Vector2, Vector4.zero));
RemoveSlotsNameNotMatching(new[] {OutputSlotId, ROutputSlotId, GOutputSlotId, BOutputSlotId, AOutputSlotId, TOutputSlotId,UVInput});
}
}
public ExposedState exposedState
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
get
var graph = owner as AbstractMaterialGraph;
var property = graph.properties.FirstOrDefault(x => x.guid == propertyGuid);
if (property == null)
return;
if (property is FloatShaderProperty)
{
var result = string.Format("{0} {1} = {2};"
, precision
, GetVariableNameForSlot(OutputSlotId)
, property.name);
visitor.AddShaderChunk(result, true);
}
else if (property is Vector2ShaderProperty)
{
var result = string.Format("{0}2 {1} = {2};"
, precision
, GetVariableNameForSlot(OutputSlotId)
, property.name);
visitor.AddShaderChunk(result, true);
}
else if (property is Vector3ShaderProperty)
if (owner is SubGraph)
return ExposedState.NotExposed;
return m_Exposed;
var result = string.Format("{0}3 {1} = {2};"
, precision
, GetVariableNameForSlot(OutputSlotId)
, property.name);
visitor.AddShaderChunk(result, true);
}
else if (property is Vector4ShaderProperty)
{
var result = string.Format("{0}4 {1} = {2};"
, precision
, GetVariableNameForSlot(OutputSlotId)
, property.name);
visitor.AddShaderChunk(result, true);
}
else if (property is ColorShaderProperty)
{
var result = string.Format("{0}4 {1} = {2};"
, precision
, GetVariableNameForSlot(OutputSlotId)
, property.name);
visitor.AddShaderChunk(result, true);
set
else if (property is TextureShaderProperty)
if (m_Exposed == value)
return;
//UV input slot
var uvSlot = FindInputSlot<MaterialSlot>(UVInput);
var uvName = string.Format("{0}.xy", UVChannel.uv0.GetUVName());
var edgesUV = owner.GetEdges(uvSlot.slotReference);
if (edgesUV.Any())
uvName = GetSlotValue(UVInput, generationMode);
m_Exposed = value;
//Sampler input slot
var result = string.Format("{0}4 {1} = UNITY_SAMPLE_TEX2D({2},{3});"
, precision
, GetVariableNameForSlot(OutputSlotId)
, property.name
, uvName);
visitor.AddShaderChunk(result, true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.r;", precision, GetVariableNameForSlot(ROutputSlotId), GetVariableNameForSlot(OutputSlotId)), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.g;", precision, GetVariableNameForSlot(GOutputSlotId), GetVariableNameForSlot(OutputSlotId)), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.b;", precision, GetVariableNameForSlot(BOutputSlotId), GetVariableNameForSlot(OutputSlotId)), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.a;", precision, GetVariableNameForSlot(AOutputSlotId), GetVariableNameForSlot(OutputSlotId)), true);
public string description
public bool RequiresMeshUV(UVChannel channel)
get
{
return string.IsNullOrEmpty(m_Description) ? name : m_Description;
}
set { m_Description = value; }
if (channel != UVChannel.uv0)
return false;
var uvSlot = FindInputSlot<MaterialSlot>(UVInput);
if (uvSlot == null)
return true;
var edges = owner.GetEdges(uvSlot.slotReference).ToList();
return edges.Count == 0;
public string propertyName
public Guid propertyGuid
get
get { return m_PropertyGuid; }
set
return string.Format("{0}_{1}_Uniform", name, GetVariableNameForNode());
}
}
if (m_PropertyGuid == value)
return;
public abstract PropertyType propertyType { get; }
var graph = owner as AbstractMaterialGraph;
var property = graph.properties.FirstOrDefault(x => x.guid == value);
if (property == null)
return;
m_PropertyGuid = value;
public abstract PreviewProperty GetPreviewProperty();
UpdateNode();
public override string GetVariableNameForSlot(int slotId)
if (onModified != null)
{
onModified(this, ModificationScope.Topological);
}
}
}
public sealed override void UpdateNodeAfterDeserialization()
return propertyName;
base.UpdateNodeAfterDeserialization();
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
public override string GetVariableNameForSlot(int slotId)
base.CollectPreviewMaterialProperties(properties);
properties.Add(GetPreviewProperty());
if (slotId != TOutputSlotId)
return base.GetVariableNameForSlot(slotId);
var graph = owner as AbstractMaterialGraph;
var property = graph.properties.FirstOrDefault(x => x.guid == propertyGuid);
return property.name;
if (exposedState == ExposedState.NotExposed)
return false;
var graph = owner as AbstractMaterialGraph;
var propNodes = owner.GetNodes<PropertyNode>();
foreach (var n in propNodes)
{
if (n == this || n.exposedState == ExposedState.NotExposed)
continue;
if (!graph.properties.Any(x => x.guid == propertyGuid))
return true;
if (n.propertyName == propertyName)
{
return true;
}
}
/*
public override float GetNodeUIHeight(float width)
public override void OnBeforeSerialize()
return 2 * EditorGUIUtility.singleLineHeight;
base.OnBeforeSerialize();
m_PropertyGuidSerialized = m_PropertyGuid.ToString();
public override bool OnGUI()
public override void OnAfterDeserialize()
EditorGUI.BeginChangeCheck();
m_Exposed = EditorGUILayout.Toggle("Exposed Property", m_Exposed);
if (m_Exposed)
m_PropertyName = EditorGUILayout.DelayedTextField("Property Name", m_PropertyName);
var modified = EditorGUI.EndChangeCheck();
if (modified)
{
owner.ValidateGraph();
}
if (m_Exposed)
m_Description = EditorGUILayout.TextField("Description", m_Description);
modified |= base.OnGUI();
return modified;
}*/
base.OnAfterDeserialize();
if (!string.IsNullOrEmpty(m_PropertyGuidSerialized))
m_PropertyGuid = new Guid(m_PropertyGuidSerialized);
}
}
}

13
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SubGraph/SubGraph.cs


}
}
public void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
public void CollectShaderProperties(PropertyCollector visitor, GenerationMode generationMode)
(node as IGenerateProperties).GeneratePropertyBlock(visitor, generationMode);
}
}
public void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
foreach (var node in usedNodes)
{
if (node is IGenerateProperties)
(node as IGenerateProperties).GeneratePropertyUsages(visitor, generationMode);
(node as IGenerateProperties).CollectShaderProperties(visitor, generationMode);
}
}

41
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SubGraph/SubGraphInputNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Graphing;

RemoveSlot(-lastSlotId);
}
public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
if (generationMode == GenerationMode.ForReals)
if (!generationMode.IsPreview())
var outDimension = ConvertConcreteSlotValueTypeToString(slot.concreteValueType);
visitor.AddShaderChunk("float" + outDimension + " " + GetVariableNameForSlot(slot.id) + ";", true);
IShaderProperty property;
switch (slot.concreteValueType)
{
case ConcreteSlotValueType.Vector4:
property = new Vector4ShaderProperty();
break;
case ConcreteSlotValueType.Vector3:
property = new Vector3ShaderProperty();
break;
case ConcreteSlotValueType.Vector2:
property = new Vector2ShaderProperty();
break;
case ConcreteSlotValueType.Vector1:
property = new FloatShaderProperty();
break;
default:
throw new ArgumentOutOfRangeException();
}
property.generatePropertyBlock = false;
properties.AddShaderProperty(property);
}
}

properties.Add
(
new PreviewProperty
{
m_Name = GetVariableNameForSlot(s.id),
m_PropType = ConvertConcreteSlotValueTypeToPropertyType(s.concreteValueType),
m_Vector4 = s.currentValue,
m_Float = s.currentValue.x,
m_Color = s.currentValue
}
{
m_Name = GetVariableNameForSlot(s.id),
m_PropType = ConvertConcreteSlotValueTypeToPropertyType(s.concreteValueType),
m_Vector4 = s.currentValue,
m_Float = s.currentValue.x,
m_Color = s.currentValue
}
);
}
}

76
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SubGraph/SubGraphNode.cs


, IMayRequireMeshUV
, IMayRequireScreenPosition
, IMayRequireViewDirection
, IMayRequireWorldPosition
, IMayRequirePosition
, IMayRequireViewDirectionTangentSpace
, IMayRequireTime
{
[SerializeField]

shaderBodyVisitor.AddShaderChunk(outputString.GetShaderString(0), true);
}
public override void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
{
base.GeneratePropertyBlock(visitor, generationMode);
if (subGraph == null)
return;
subGraph.GeneratePropertyBlock(visitor, GenerationMode.ForReals);
}
public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
public override void CollectShaderProperties(PropertyCollector visitor, GenerationMode generationMode)
base.GeneratePropertyUsages(visitor, generationMode);
base.CollectShaderProperties(visitor, generationMode);
subGraph.GeneratePropertyUsages(visitor, GenerationMode.ForReals);
subGraph.CollectShaderProperties(visitor, GenerationMode.ForReals);
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)

subGraph.GenerateVertexToFragmentBlock(visitor, GenerationMode.ForReals);
}
public bool RequiresNormal()
public NeededCoordinateSpace RequiresNormal()
return false;
return NeededCoordinateSpace.None;
return subGraph.activeNodes.OfType<IMayRequireNormal>().Any(x => x.RequiresNormal());
return subGraph.activeNodes.OfType<IMayRequireNormal>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresNormal();
return mask;
});
}
public bool RequiresMeshUV(UVChannel channel)

return subGraph.activeNodes.OfType<IMayRequireScreenPosition>().Any(x => x.RequiresScreenPosition());
}
public bool RequiresViewDirection()
public NeededCoordinateSpace RequiresViewDirection()
return false;
return NeededCoordinateSpace.None;
return subGraph.activeNodes.OfType<IMayRequireViewDirection>().Any(x => x.RequiresViewDirection());
return subGraph.activeNodes.OfType<IMayRequireViewDirection>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresViewDirection();
return mask;
});
public bool RequiresViewDirectionTangentSpace()
{
if (subGraph == null)
return false;
return subGraph.activeNodes.OfType<IMayRequireViewDirectionTangentSpace>().Any(x => x.RequiresViewDirectionTangentSpace());
}
public bool RequiresWorldPosition()
public NeededCoordinateSpace RequiresPosition()
return false;
return NeededCoordinateSpace.None;
return subGraph.activeNodes.OfType<IMayRequireWorldPosition>().Any(x => x.RequiresWorldPosition());
return subGraph.activeNodes.OfType<IMayRequirePosition>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresPosition();
return mask;
});
public bool RequiresTangent()
public NeededCoordinateSpace RequiresTangent()
return false;
return NeededCoordinateSpace.None;
return subGraph.activeNodes.OfType<IMayRequireTangent>().Any(x => x.RequiresTangent());
return subGraph.activeNodes.OfType<IMayRequireTangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresTangent();
return mask;
});
}
public bool RequiresTime()

return subGraph.activeNodes.OfType<IMayRequireTime>().Any(x => x.RequiresTime());
}
public bool RequiresBitangent()
public NeededCoordinateSpace RequiresBitangent()
return false;
return NeededCoordinateSpace.None;
return subGraph.activeNodes.OfType<IMayRequireBitangent>().Any(x => x.RequiresBitangent());
return subGraph.activeNodes.OfType<IMayRequireBitangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresBitangent();
return mask;
});
}
public bool RequiresVertexColor()

16
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SurfaceModel/AbstractSurfaceMasterNode.cs


namespace UnityEngine.MaterialGraph
{
[Serializable]
public abstract class AbstractSurfaceMasterNode : AbstractMasterNode
/>an class="p">* [Serializable]
public abstract class AbstractSurfaceMasterNode : MasterNode
{
public const string AlbedoSlotName = "Albedo";
public const string NormalSlotName = "Normal";

}
}
public override string GetSubShader(GenerationMode mode, PropertyGenerator shaderPropertiesVisitor)
/ public override string GetSubShader(GenerationMode mode, PropertyCollector shaderPropertiesVisitor)
{
var templateLocation = ShaderGenerator.GetTemplatePath("subshader.template");

return resultShader;
}
public override string GetFullShader(GenerationMode mode, string name, out List<PropertyGenerator.TextureInfo> configuredTextures)
public override string GetFullShader(GenerationMode mode, string name, out List<PropertyCollector.TextureInfo> configuredTextures)
configuredTextures = new List<PropertyGenerator.TextureInfo>();
configuredTextures = new List<PropertyCollector.TextureInfo>();
var shaderPropertiesVisitor = new PropertyGenerator();
var shaderPropertiesVisitor = new PropertyCollector();
resultShader = resultShader.Replace("${ShaderPropertiesHeader}", shaderPropertiesVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ShaderPropertiesHeader}", shaderPropertiesVisitor.GetPropertiesBlock(2));
configuredTextures = shaderPropertiesVisitor.GetConfiguredTexutres();
return Regex.Replace(resultShader, @"\r\n|\n\r|\n|\r", Environment.NewLine);
}

}
}
}
}
}*/
}

16
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SurfaceModel/ExportTextureMasterNode.cs


namespace UnityEngine.MaterialGraph
{
[Serializable]
/>an class="p">* [Serializable]
public class ExportTextureMasterNode : AbstractMasterNode
public class ExportTextureMasterNode : MasterNode
{
public const string ColorSlotName = "Color";
public const int ColorSlotId = 0;

}
}
public override string GetSubShader(GenerationMode mode, PropertyGenerator shaderPropertiesVisitor)
public override string GetSubShader(GenerationMode mode, PropertyCollector shaderPropertiesVisitor)
{
return "";
}

return false;
}
public override string GetFullShader(GenerationMode generationMode, string name, out List<PropertyGenerator.TextureInfo> configuredTextures)
public override string GetFullShader(GenerationMode generationMode, string name, out List<PropertyCollector.TextureInfo> configuredTextures)
{
// figure out what kind of preview we want!
var activeNodeList = ListPool<INode>.Get();

if (!File.Exists(templateLocation))
{
configuredTextures = new List<PropertyGenerator.TextureInfo>();
configuredTextures = new List<PropertyCollector.TextureInfo>();
return string.Empty;
}

var shaderFunctionVisitor = new ShaderGenerator();
var shaderPropertiesVisitor = new PropertyGenerator();
var shaderPropertiesVisitor = new PropertyCollector();
var shaderPropertyUsagesVisitor = new ShaderGenerator();
var shaderInputVisitor = new ShaderGenerator();

ListPool<INode>.Release(activeNodeList);
template = template.Replace("${ShaderName}", name);
template = template.Replace("${ShaderPropertiesHeader}", shaderPropertiesVisitor.GetShaderString(2));
template = template.Replace("${ShaderPropertiesHeader}", shaderPropertiesVisitor.GetPropertiesBlock(2));
template = template.Replace("${ShaderPropertyUsages}", shaderPropertyUsagesVisitor.GetShaderString(3));
template = template.Replace("${ShaderFunctions}", shaderFunctionVisitor.GetShaderString(3));
template = template.Replace("${PixelShaderBody}", shaderBodyVisitor.GetShaderString(4));

configuredTextures = shaderPropertiesVisitor.GetConfiguredTexutres();
return Regex.Replace(template, @"\r\n|\n\r|\n|\r", Environment.NewLine);
}
}
}*/
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SurfaceModel/MetallicMasterNode.cs


namespace UnityEngine.MaterialGraph
{
[Serializable]
/* [Serializable]
[Title("Master/Metallic")]
public class MetallicMasterNode : AbstractSurfaceMasterNode
{

{
return LightFunctionName;
}
}
}*/
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SurfaceModel/SpecularMasterNode.cs


namespace UnityEngine.MaterialGraph
{
[Serializable]
/* [Serializable]
[Title("Master/Specular")]
public class SpecularMasterNode : AbstractSurfaceMasterNode
{

{
return LightFunctionName;
}
}
}*/
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Util/CubemapPropertyChunk.cs


namespace UnityEngine.MaterialGraph
{
public class CubemapPropertyChunk : PropertyChunk
/* public class CubemapPropertyChunk : PropertyChunk
{
public enum ModifiableState
{

return m_Modifiable;
}
}
}
}*/
}

322
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Util/ShaderGenerator.cs


private static string[] UV = {"uv0", "uv1", "uv2", "uv3"};
public static int UVCount = 4;
public const string ObjectSpaceNormal = "objectSpaceNormal";
public const string ViewSpaceNormal = "viewSpaceNormal";
public const string WorldSpaceBitangent = "worldSpaceBitangent";
public const string WorldSpaceTangent = "worldSpaceTangent";
public const string WorldSpacePosition = "worldPosition";
public const string TangentSpaceNormal = "tangentSpaceNormal";
public const string ObjectSpaceBiTangent = "objectSpaceBiTangent";
public const string ViewSpaceBiTangent = "viewSpaceBiTangent";
public const string WorldSpaceSpaceBiTangent = "worldSpaceSpaceBiTangent";
public const string TangentSpaceBiTangent = "TangentSpaceBitangent";
public const string ObjectSpaceTangent = "objectSpaceTangent";
public const string ViewSpaceTangent = "viewSpaceTangent";
public const string WorldSpaceTangent = "worldSpaceSpaceTangent";
public const string TangentSpaceTangent = "tangentSpaceSpaceTangent";
public const string ObjectSpaceViewDirection = "objectSpaceViewDirection";
public const string ViewSpaceViewDirection = "viewSpaceViewDirection";
public const string ObjectSpacePosition = "objectSpacePosition";
public const string ViewSpacePosition = "viewSpaceVPosition";
public const string WorldSpacePosition = "worldSpacePosition";
public const string TangentSpacePosition = "tangentSpacePosition";
public const string ScreenPosition = "screenPosition";
public const string VertexColor = "vertexColor";

return UV[(int)channel];
return UV[(int) channel];
}
}

public static string AdaptNodeOutputForPreview(AbstractMaterialNode node, int outputSlotId)
{
var outputSlot = node.FindOutputSlot<MaterialSlot>(outputSlotId);
var rawOutput = node.GetVariableNameForSlot(outputSlotId);
return AdaptNodeOutputForPreview(node, outputSlotId, rawOutput);
}
public static string AdaptNodeOutputForPreview(AbstractMaterialNode node, int slotId, string variableName)
{
var slot = node.FindSlot<MaterialSlot>(slotId);
if (outputSlot == null)
if (slot == null)
var convertFromType = outputSlot.concreteValueType;
var rawOutput = node.GetVariableNameForSlot(outputSlotId);
var convertFromType = slot.concreteValueType;
return string.Format("half4({0}, {0}, {0}, 1.0)", rawOutput);
return string.Format("half4({0}, {0}, {0}, 1.0)", variableName);
return string.Format("half4({0}.x, {0}.y, 0.0, 1.0)", rawOutput);
return string.Format("half4({0}.x, {0}.y, 0.0, 1.0)", variableName);
return string.Format("half4({0}.x, {0}.y, {0}.z, 1.0)", rawOutput);
return string.Format("half4({0}.x, {0}.y, {0}.z, 1.0)", variableName);
return string.Format("half4({0}.x, {0}.y, {0}.z, 1.0)", rawOutput);
return string.Format("half4({0}.x, {0}.y, {0}.z, 1.0)", variableName);
default:
return kErrorString;
}

get { return m_ShaderChunks.Count; }
}
public static string GeneratePreviewShader(AbstractMaterialNode node, out PreviewMode generatedShaderMode)
public static void GenerateSpaceTranslationPixelShader(
NeededCoordinateSpace neededSpaces,
ShaderGenerator pixelShader,
string objectSpaceName,
string viewSpaceName,
string worldSpaceName,
string tangentSpaceName,
bool isNormal = false)
if (!node.GetOutputSlots<MaterialSlot>().Any())
if ((neededSpaces & NeededCoordinateSpace.Object) > 0)
generatedShaderMode = PreviewMode.Preview2D;
return string.Empty;
pixelShader.AddShaderChunk(string.Format("surfaceInput.{0} = {0};", objectSpaceName), false);
// figure out what kind of preview we want!
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, node);
generatedShaderMode = PreviewMode.Preview2D;
if (activeNodeList.OfType<AbstractMaterialNode>().Any(x => x.previewMode == PreviewMode.Preview3D))
generatedShaderMode = PreviewMode.Preview3D;
string templateLocation = GetTemplatePath("2DPreview.template");
if (!File.Exists(templateLocation))
return null;
string template = File.ReadAllText(templateLocation);
var shaderBodyVisitor = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var shaderPropertiesVisitor = new PropertyGenerator();
var shaderPropertyUsagesVisitor = new ShaderGenerator();
var shaderName = "Hidden/PreviewShader/" + node.GetVariableNameForSlot(node.GetOutputSlots<MaterialSlot>().First().id);
var shaderInputVisitor = new ShaderGenerator();
var vertexShaderBlock = new ShaderGenerator();
// always add color because why not.
shaderInputVisitor.AddShaderChunk("float4 color : COLOR;", true);
vertexShaderBlock.AddShaderChunk("float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;", true);
vertexShaderBlock.AddShaderChunk("float3 viewDir = UnityWorldSpaceViewDir(worldPos);", true);
vertexShaderBlock.AddShaderChunk("float4 screenPos = ComputeScreenPos(UnityObjectToClipPos(v.vertex));", true);
vertexShaderBlock.AddShaderChunk("float3 worldNormal = UnityObjectToWorldNormal(v.normal);", true);
bool requiresBitangent = activeNodeList.OfType<IMayRequireBitangent>().Any(x => x.RequiresBitangent());
bool requiresTangent = activeNodeList.OfType<IMayRequireTangent>().Any(x => x.RequiresTangent());
bool requiresViewDirTangentSpace = activeNodeList.OfType<IMayRequireViewDirectionTangentSpace>().Any(x => x.RequiresViewDirectionTangentSpace());
bool requiresViewDir = activeNodeList.OfType<IMayRequireViewDirection>().Any(x => x.RequiresViewDirection());
bool requiresWorldPos = activeNodeList.OfType<IMayRequireWorldPosition>().Any(x => x.RequiresWorldPosition());
bool requiresNormal = activeNodeList.OfType<IMayRequireNormal>().Any(x => x.RequiresNormal());
bool requiresScreenPosition = activeNodeList.OfType<IMayRequireScreenPosition>().Any(x => x.RequiresScreenPosition());
bool requiresVertexColor = activeNodeList.OfType<IMayRequireVertexColor>().Any(x => x.RequiresVertexColor());
// view directions calculated from world position
if (requiresWorldPos || requiresViewDir || requiresViewDirTangentSpace)
if ((neededSpaces & NeededCoordinateSpace.World) > 0)
shaderInputVisitor.AddShaderChunk("float3 worldPos : TEXCOORD0;", true);
vertexShaderBlock.AddShaderChunk("o.worldPos = worldPos;", true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpacePosition + " = IN.worldPos;", true);
if (isNormal)
pixelShader.AddShaderChunk(string.Format("surfaceInput.{0} = UnityObjectToWorldNormal({1});", worldSpaceName, objectSpaceName), false);
else
pixelShader.AddShaderChunk(string.Format("surfaceInput.{0} = UnityObjectToWorldDir({1});", worldSpaceName, objectSpaceName), false);
if (requiresBitangent || requiresNormal || requiresViewDirTangentSpace)
if ((neededSpaces & NeededCoordinateSpace.View) > 0)
shaderInputVisitor.AddShaderChunk("float3 worldNormal : TEXCOORD1;", true);
vertexShaderBlock.AddShaderChunk("o.worldNormal = worldNormal;", true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceNormal + " = normalize(IN.worldNormal);", true);
pixelShader.AddShaderChunk(string.Format("surfaceInput.{0} = UnityObjectToViewPos({1});", viewSpaceName, objectSpaceName), false);
for (int uvIndex = 0; uvIndex < ShaderGeneratorNames.UVCount; ++uvIndex)
if ((neededSpaces & NeededCoordinateSpace.Tangent) > 0)
var channel = (UVChannel)uvIndex;
if (activeNodeList.OfType<IMayRequireMeshUV>().Any(x => x.RequiresMeshUV(channel)))
{
shaderInputVisitor.AddShaderChunk(string.Format("half4 meshUV{0} : TEXCOORD{1};", uvIndex, (uvIndex + 5)), true);
vertexShaderBlock.AddShaderChunk(string.Format("o.meshUV{0} = v.texcoord{1};", uvIndex, uvIndex == 0 ? "" : uvIndex.ToString()), true);
shaderBodyVisitor.AddShaderChunk(string.Format("half4 {0} = IN.meshUV{1};", channel.GetUVName(), uvIndex), true);
}
pixelShader.AddShaderChunk(string.Format("surfaceInput.{0} = mul(tangentSpaceTransform, {1})", tangentSpaceName, objectSpaceName), false);
}
public static string GetPreviewSubShader(AbstractMaterialNode node, ShaderGraphRequirements shaderGraphRequirements)
{
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, node);
if (requiresViewDir || requiresViewDirTangentSpace)
var interpolators = new ShaderGenerator();
var vertexShader = new ShaderGenerator();
var pixelShader = new ShaderGenerator();
// bitangent needs normal for x product
if (shaderGraphRequirements.requiresNormal > 0 || shaderGraphRequirements.requiresBitangent > 0)
shaderBodyVisitor.AddShaderChunk(
"float3 "
+ ShaderGeneratorNames.WorldSpaceViewDirection
+ " = normalize(UnityWorldSpaceViewDir("
+ ShaderGeneratorNames.WorldSpacePosition
+ "));", true);
interpolators.AddShaderChunk(string.Format("float3 {0} : NORMAL;", ShaderGeneratorNames.ObjectSpaceNormal), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = v.normal;", ShaderGeneratorNames.ObjectSpaceNormal), false);
pixelShader.AddShaderChunk(string.Format("float3 {0} = normalize(IN.{0});", ShaderGeneratorNames.ObjectSpaceNormal), false);
if (requiresScreenPosition)
if (shaderGraphRequirements.requiresTangent > 0 || shaderGraphRequirements.requiresBitangent > 0)
shaderInputVisitor.AddShaderChunk("float4 screenPos : TEXCOORD3;", true);
vertexShaderBlock.AddShaderChunk("o.screenPos = screenPos;", true);
shaderBodyVisitor.AddShaderChunk("half4 " + ShaderGeneratorNames.ScreenPosition + " = IN.screenPos;", true);
interpolators.AddShaderChunk(string.Format("float4 {0} : TANGENT;", ShaderGeneratorNames.ObjectSpaceTangent), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = v.tangent;", ShaderGeneratorNames.ObjectSpaceTangent), false);
pixelShader.AddShaderChunk(string.Format("float4 {0} = IN.{0};", ShaderGeneratorNames.ObjectSpaceTangent), false);
pixelShader.AddShaderChunk(string.Format("float4 {0} = normalize(cross(normalize(IN.{1}), normalize(IN.{2}.xyz)) * IN.{2}.w);",
ShaderGeneratorNames.ObjectSpaceBiTangent,
ShaderGeneratorNames.ObjectSpaceTangent,
ShaderGeneratorNames.ObjectSpaceNormal), false);
if (requiresBitangent || requiresViewDirTangentSpace || requiresTangent)
int interpolatorIndex = 0;
if (shaderGraphRequirements.requiresViewDir > 0)
shaderInputVisitor.AddShaderChunk("float4 worldTangent : TEXCOORD4;", true);
vertexShaderBlock.AddShaderChunk("o.worldTangent = float4(UnityObjectToWorldDir(v.tangent.xyz), v.tangent.w);", true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceTangent + " = normalize(IN.worldTangent.xyz);", true);
interpolators.AddShaderChunk(string.Format("float4 {0} : TEXCOORD{1};", ShaderGeneratorNames.ObjectSpaceViewDirection, interpolatorIndex), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = ObjSpaceViewDir(v.vertex);", ShaderGeneratorNames.ObjectSpaceViewDirection), false);
pixelShader.AddShaderChunk(string.Format("float4 {0} = normalize(IN.{0});", ShaderGeneratorNames.ObjectSpaceViewDirection), false);
interpolatorIndex++;
if (requiresBitangent || requiresViewDirTangentSpace)
if (shaderGraphRequirements.requiresPosition > 0)
shaderBodyVisitor.AddShaderChunk(string.Format("float3 {0} = cross({1}, {2}) * IN.worldTangent.w;", ShaderGeneratorNames.WorldSpaceBitangent, ShaderGeneratorNames.WorldSpaceNormal, ShaderGeneratorNames.WorldSpaceTangent), true);
interpolators.AddShaderChunk(string.Format("float4 {0} : TEXCOORD{1};", ShaderGeneratorNames.ObjectSpacePosition, interpolatorIndex), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = v.vertex;", ShaderGeneratorNames.ObjectSpacePosition), false);
pixelShader.AddShaderChunk(string.Format("float4 {0} = IN.{0};", ShaderGeneratorNames.ObjectSpacePosition), false);
interpolatorIndex++;
if (requiresViewDirTangentSpace)
if (shaderGraphRequirements.NeedsTangentSpace())
shaderBodyVisitor.AddShaderChunk(
"float3 " + ShaderGeneratorNames.TangentSpaceViewDirection + ";", true);
pixelShader.AddShaderChunk(string.Format("float3x3 tangentSpaceTransform = float3x3({0},{1},{2});",
ShaderGeneratorNames.ObjectSpaceTangent, ShaderGeneratorNames.ObjectSpaceBiTangent, ShaderGeneratorNames.ObjectSpaceNormal), false);
}
shaderBodyVisitor.AddShaderChunk(
ShaderGeneratorNames.TangentSpaceViewDirection + ".x = dot(" +
ShaderGeneratorNames.WorldSpaceViewDirection + "," +
ShaderGeneratorNames.WorldSpaceTangent + ");", true);
GenerateSpaceTranslationPixelShader(shaderGraphRequirements.requiresNormal, pixelShader,
ShaderGeneratorNames.ObjectSpaceNormal, ShaderGeneratorNames.ViewSpaceNormal,
ShaderGeneratorNames.WorldSpaceNormal, ShaderGeneratorNames.TangentSpaceNormal);
GenerateSpaceTranslationPixelShader(shaderGraphRequirements.requiresTangent, pixelShader,
ShaderGeneratorNames.ObjectSpaceTangent, ShaderGeneratorNames.ViewSpaceTangent,
ShaderGeneratorNames.WorldSpaceTangent, ShaderGeneratorNames.TangentSpaceTangent);
GenerateSpaceTranslationPixelShader(shaderGraphRequirements.requiresBitangent, pixelShader,
ShaderGeneratorNames.ObjectSpaceBiTangent, ShaderGeneratorNames.ViewSpaceBiTangent,
ShaderGeneratorNames.WorldSpaceSpaceBiTangent, ShaderGeneratorNames.TangentSpaceBiTangent);
GenerateSpaceTranslationPixelShader(shaderGraphRequirements.requiresViewDir, pixelShader,
ShaderGeneratorNames.ObjectSpaceViewDirection, ShaderGeneratorNames.ViewSpaceViewDirection,
ShaderGeneratorNames.WorldSpaceViewDirection, ShaderGeneratorNames.TangentSpaceViewDirection);
shaderBodyVisitor.AddShaderChunk(
ShaderGeneratorNames.TangentSpaceViewDirection + ".y = dot(" +
ShaderGeneratorNames.WorldSpaceViewDirection + "," +
ShaderGeneratorNames.WorldSpaceBitangent + ");", true);
GenerateSpaceTranslationPixelShader(shaderGraphRequirements.requiresPosition, pixelShader,
ShaderGeneratorNames.ObjectSpacePosition, ShaderGeneratorNames.ViewSpacePosition,
ShaderGeneratorNames.WorldSpacePosition, ShaderGeneratorNames.TangentSpacePosition);
shaderBodyVisitor.AddShaderChunk(
ShaderGeneratorNames.TangentSpaceViewDirection + ".z = dot(" +
ShaderGeneratorNames.WorldSpaceViewDirection + "," +
ShaderGeneratorNames.WorldSpaceNormal + ");", true);
if (shaderGraphRequirements.requiresVertexColor)
{
interpolators.AddShaderChunk(string.Format("float4 {0} : COLOR;", ShaderGeneratorNames.VertexColor), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = color", ShaderGeneratorNames.VertexColor), false);
pixelShader.AddShaderChunk(string.Format("surfaceInput.{0} = IN.{0};", ShaderGeneratorNames.VertexColor), false);
if (requiresVertexColor)
if (shaderGraphRequirements.requiresScreenPosition)
vertexShaderBlock.AddShaderChunk("o.color = v.color;", true);
shaderBodyVisitor.AddShaderChunk("float4 " + ShaderGeneratorNames.VertexColor + " = IN.color;", true);
interpolators.AddShaderChunk(string.Format("float4 {0} : TEXCOORD{1};;", ShaderGeneratorNames.ScreenPosition, interpolatorIndex), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = ComputeScreenPos(UnityObjectToClipPos(v.vertex)", ShaderGeneratorNames.ScreenPosition), false);
pixelShader.AddShaderChunk(string.Format("surfaceInput.{0} = IN.{0};", ShaderGeneratorNames.ScreenPosition), false);
interpolatorIndex++;
var generationMode = GenerationMode.Preview;
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
for (int uvIndex = 0; uvIndex < ShaderGeneratorNames.UVCount; ++uvIndex)
if (activeNode is IGeneratesFunction)
(activeNode as IGeneratesFunction).GenerateNodeFunction(shaderFunctionVisitor, generationMode);
if (activeNode is IGeneratesBodyCode)
(activeNode as IGeneratesBodyCode).GenerateNodeCode(shaderBodyVisitor, generationMode);
var channel = (UVChannel) uvIndex;
if (activeNodeList.OfType<IMayRequireMeshUV>().Any(x => x.RequiresMeshUV(channel)))
{
interpolators.AddShaderChunk(string.Format("half4 meshUV{0} : TEXCOORD{1};", uvIndex, interpolatorIndex), false);
vertexShader.AddShaderChunk(string.Format("o.meshUV{0} = v.texcoord{1};", uvIndex, uvIndex == 0 ? "" : uvIndex.ToString()), false);
pixelShader.AddShaderChunk(string.Format("surfaceInput.{0} = IN.meshUV{1};", channel.GetUVName(), uvIndex), false);
interpolatorIndex++;
}
}
activeNode.GeneratePropertyBlock(shaderPropertiesVisitor, generationMode);
activeNode.GeneratePropertyUsages(shaderPropertyUsagesVisitor, generationMode);
var outputs = new ShaderGenerator();
var outputSlot = node.GetOutputSlots<MaterialSlot>().FirstOrDefault();
if (outputSlot != null)
{
var result = string.Format("surf.{0}", node.GetVariableNameForSlot(outputSlot.id));
outputs.AddShaderChunk(string.Format("return {0};", AdaptNodeOutputForPreview(node, outputSlot.id, result)), true);
else
outputs.AddShaderChunk("return 0;", true);
shaderBodyVisitor.AddShaderChunk("return " + AdaptNodeOutputForPreview(node, node.GetOutputSlots<MaterialSlot>().First().id) + ";", true);
var res = subShaderTemplate.Replace("{0}", interpolators.GetShaderString(0));
res = res.Replace("{1}", vertexShader.GetShaderString(0));
res = res.Replace("{2}", pixelShader.GetShaderString(0));
res = res.Replace("{3}", outputs.GetShaderString(0));
return res;
}
ListPool<INode>.Release(activeNodeList);
private const string subShaderTemplate = @"
SubShader
{
Tags { ""RenderType""=""Opaque"" }
LOD 100
template = template.Replace("${ShaderName}", shaderName);
template = template.Replace("${ShaderPropertiesHeader}", shaderPropertiesVisitor.GetShaderString(2));
template = template.Replace("${ShaderPropertyUsages}", shaderPropertyUsagesVisitor.GetShaderString(3));
template = template.Replace("${ShaderInputs}", shaderInputVisitor.GetShaderString(4));
template = template.Replace("${ShaderFunctions}", shaderFunctionVisitor.GetShaderString(3));
template = template.Replace("${VertexShaderBody}", vertexShaderBlock.GetShaderString(4));
template = template.Replace("${PixelShaderBody}", shaderBodyVisitor.GetShaderString(4));
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
string vertexShaderBody = vertexShaderBlock.GetShaderString(4);
if (vertexShaderBody.Length > 0)
{
template = template.Replace("${VertexShaderDecl}", "vertex:vert");
template = template.Replace("${VertexShaderBody}", vertexShaderBody);
}
else
{
template = template.Replace("${VertexShaderDecl}", "");
template = template.Replace("${VertexShaderBody}", vertexShaderBody);
}
#include ""UnityCG.cginc""
return Regex.Replace(template, @"\r\n|\n\r|\n|\r", Environment.NewLine);
struct GraphVertexOutput
{
float4 position : POSITION;
{0}
};
GraphVertexOutput vert (GraphVertexInput v)
{
v = PopulateVertexData(v);
GraphVertexOutput o;
o.position = UnityObjectToClipPos(v.vertex);
{1}
return o;
fixed4 frag (GraphVertexOutput IN) : SV_Target
{
SurfaceInputs surfaceInput;
{2}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
{3}
}
ENDCG
}
}";
}
}

10
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Util/TextureType.cs


namespace UnityEngine.MaterialGraph
{
public enum TextureType
{
White,
Gray,
Black,
Bump
}
}

87
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/AbstractShaderProperty.cs


using System;
namespace UnityEngine.MaterialGraph
{
[Serializable]
public abstract class AbstractShaderProperty<T> : ISerializationCallbackReceiver, IShaderProperty
{
[SerializeField]
private T m_Value;
[SerializeField]
private string m_Description;
[SerializeField]
private string m_Name;
[NonSerialized]
private Guid m_Guid;
[SerializeField]
private string m_GuidSerialized;
[SerializeField]
private bool m_GeneratePropertyBlock = true;
protected AbstractShaderProperty()
{
m_Guid = Guid.NewGuid();
}
public T value
{
get { return m_Value; }
set { m_Value = value; }
}
public string name
{
get
{
if (string.IsNullOrEmpty(m_Name))
return m_Guid.ToString();
return m_Name;
}
set { m_Name = value; }
}
public string description
{
get
{
return string.IsNullOrEmpty(m_Description) ? name : m_Description;
}
set { m_Description = value; }
}
public abstract PropertyType propertyType { get; }
public Guid guid
{
get { return m_Guid; }
}
public bool generatePropertyBlock
{
get { return m_GeneratePropertyBlock; }
set { m_GeneratePropertyBlock = value; }
}
public abstract string GetPropertyBlockString();
public abstract string GetPropertyDeclarationString();
public abstract PreviewProperty GetPreviewMaterialProperty();
public virtual void OnBeforeSerialize()
{
m_GuidSerialized = m_Guid.ToString();
}
public virtual void OnAfterDeserialize()
{
if (!string.IsNullOrEmpty(m_GuidSerialized))
m_Guid = new Guid(m_GuidSerialized);
else
m_Guid = Guid.NewGuid();
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/AbstractShaderProperty.cs.meta


fileFormatVersion: 2
guid: b1411039ed1342fa8efff6fa8a4c179d
timeCreated: 1505346915

67
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/ColorShaderProperty.cs


using System;
using System.Text;
namespace UnityEngine.MaterialGraph
{
[Serializable]
public class ColorShaderProperty : AbstractShaderProperty<Color>
{
[SerializeField]
private bool m_HDR;
public bool HDR
{
get { return m_HDR; }
set
{
if (m_HDR == value)
return;
m_HDR = value;
}
}
public override PropertyType propertyType
{
get { return PropertyType.Color; }
}
public override string GetPropertyBlockString()
{
if (!generatePropertyBlock)
return string.Empty;
var result = new StringBuilder();
if (HDR)
result.Append("[HDR]");
result.Append(name);
result.Append("(\"");
result.Append(description);
result.Append("\", Color) = (");
result.Append(value.r);
result.Append(",");
result.Append(value.g);
result.Append(",");
result.Append(value.b);
result.Append(",");
result.Append(value.a);
result.Append(")");
return result.ToString();
}
public override string GetPropertyDeclarationString()
{
return "float4 " + name + ";";
}
public override PreviewProperty GetPreviewMaterialProperty()
{
return new PreviewProperty
{
m_Name = name,
m_PropType = PropertyType.Color,
m_Color = value
};
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/ColorShaderProperty.cs.meta


fileFormatVersion: 2
guid: 47cf9e64b21b48b09320f42eb82ac3c3
timeCreated: 1505346940

54
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/FloatShaderProperty.cs


using System;
using System.Text;
namespace UnityEngine.MaterialGraph
{
[Serializable]
public class FloatShaderProperty : AbstractShaderProperty<float>
{
public override PropertyType propertyType
{
get { return PropertyType.Float; }
}
public override string GetPropertyBlockString()
{
var result = new StringBuilder();
// if (m_FloatType == FloatPropertyChunk.FloatType.Toggle)
// result.Append("[Toggle]");
// else if (m_FloatType == FloatPropertyChunk.FloatType.PowerSlider)
// result.Append("[PowerSlider(" + m_rangeValues.z + ")]");
result.Append(name);
result.Append("(\"");
result.Append(description);
//if (m_FloatType == FloatPropertyChunk.FloatType.Float || m_FloatType == FloatPropertyChunk.FloatType.Toggle)
//{
result.Append("\", Float) = ");
/* }
else if (m_FloatType == FloatPropertyChunk.FloatType.Range || m_FloatType == FloatPropertyChunk.FloatType.PowerSlider)
{
result.Append("\", Range(");
result.Append(m_rangeValues.x + ", " + m_rangeValues.y);
result.Append(")) = ");
}*/
result.Append(value);
return result.ToString();
}
public override string GetPropertyDeclarationString()
{
return "float " + name + ";";
}
public override PreviewProperty GetPreviewMaterialProperty()
{
return new PreviewProperty()
{
m_Name = name,
m_PropType = PropertyType.Float,
m_Float = value
};
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/FloatShaderProperty.cs.meta


fileFormatVersion: 2
guid: 572cce24ed76430db4c21dfe82d01252
timeCreated: 1505346922

17
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/IShaderProperty.cs


using System;
namespace UnityEngine.MaterialGraph
{
public interface IShaderProperty
{
string name { get; set; }
string description { get; set; }
PropertyType propertyType { get; }
Guid guid { get; }
bool generatePropertyBlock { get; set; }
string GetPropertyBlockString();
string GetPropertyDeclarationString();
PreviewProperty GetPreviewMaterialProperty();
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/IShaderProperty.cs.meta


fileFormatVersion: 2
guid: 7594463b49eb4d70a1b938f328f0c0b0
timeCreated: 1505346909

34
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/SamplerStateShaderProperty.cs


using System;
namespace UnityEngine.MaterialGraph
{
class SamplerStateShaderProperty : AbstractShaderProperty<TextureSamplerState>
{
public override PropertyType propertyType
{
get { return PropertyType.SamplerState; }
}
public override string GetPropertyBlockString()
{
return string.Empty;
}
public override string GetPropertyDeclarationString()
{
string ss = name + "_"
+ Enum.GetName(typeof(TextureSamplerState.FilterMode), value.filter) + "_"
+ Enum.GetName(typeof(TextureSamplerState.WrapMode), value.wrap) + "_sampler;";
return string.Format(@"
#ifdef UNITY_COMPILER_HLSL
SamplerState {0};
#endif", ss);
}
public override PreviewProperty GetPreviewMaterialProperty()
{
return null;
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/SamplerStateShaderProperty.cs.meta


fileFormatVersion: 2
guid: b48a2e97e3e24303833a0062f90f4f13
timeCreated: 1505436387

44
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/SerializableTexture.cs


using System;
using UnityEditor;
namespace UnityEngine.MaterialGraph
{
[Serializable]
public class SerializableTexture
{
[SerializeField] private string m_SerializedTexture;
[Serializable]
private class TextureHelper
{
public Texture texture;
}
#if UNITY_EDITOR
public Texture texture
{
get
{
if (string.IsNullOrEmpty(m_SerializedTexture))
return null;
var tex = new TextureHelper();
EditorJsonUtility.FromJsonOverwrite(m_SerializedTexture, tex);
return tex.texture;
}
set
{
if (texture == value)
return;
var tex = new TextureHelper();
tex.texture = value;
m_SerializedTexture = EditorJsonUtility.ToJson(tex, true);
}
}
#else
public Texture defaultTexture {get; set; }
#endif
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/SerializableTexture.cs.meta


fileFormatVersion: 2
guid: a4a4ff926ce74b059400bb049aefcba2
timeCreated: 1505346945

25
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/ShaderGraphRequirements.cs


using System.Collections.Generic;
namespace UnityEngine.MaterialGraph
{
public struct ShaderGraphRequirements
{
public NeededCoordinateSpace requiresNormal;
public NeededCoordinateSpace requiresBitangent;
public NeededCoordinateSpace requiresTangent;
public NeededCoordinateSpace requiresViewDir;
public NeededCoordinateSpace requiresPosition;
public bool requiresScreenPosition;
public bool requiresVertexColor;
public List<UVChannel> requiresMeshUVs;
public bool NeedsTangentSpace()
{
var compoundSpaces = requiresBitangent | requiresNormal | requiresPosition
| requiresTangent | requiresViewDir | requiresPosition
| requiresNormal;
return (compoundSpaces & NeededCoordinateSpace.Tangent) > 0;
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/ShaderGraphRequirements.cs.meta


fileFormatVersion: 2
guid: b80c0c5cd7f940d7bc0f37b22c454d40
timeCreated: 1505698038

45
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/TextureSamplerState.cs


namespace UnityEngine.MaterialGraph
{
public class TextureSamplerState
{
public enum FilterMode
{
Linear,
Point
}
public enum WrapMode
{
Repeat,
Clamp
}
[SerializeField] private FilterMode m_filter = FilterMode.Linear;
public FilterMode filter
{
get { return m_filter; }
set
{
if (m_filter == value)
return;
m_filter = value;
}
}
[SerializeField] private WrapMode m_wrap = WrapMode.Repeat;
public WrapMode wrap
{
get { return m_wrap; }
set
{
if (m_wrap == value)
return;
m_wrap = value;
}
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/TextureSamplerState.cs.meta


fileFormatVersion: 2
guid: a0238123ffe44c05bc05acf347c4d52d
timeCreated: 1505436371

61
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/TextureShaderProperty.cs


using System;
using System.Text;
namespace UnityEngine.MaterialGraph
{
[Serializable]
public class TextureShaderProperty : AbstractShaderProperty<SerializableTexture>
{
[SerializeField]
private bool m_Modifiable;
public TextureShaderProperty()
{
value = new SerializableTexture();
}
public override PropertyType propertyType
{
get { return PropertyType.Texture; }
}
public bool modifiable
{
get { return m_Modifiable; }
set { m_Modifiable = value; }
}
public override string GetPropertyBlockString()
{
var result = new StringBuilder();
if (!m_Modifiable)
{
result.Append("[HideInInspector] ");
result.Append("[NonModifiableTextureData] ");
}
result.Append("[NoScaleOffset] ");
result.Append(name);
result.Append("(\"");
result.Append(description);
result.Append("\", 2D) = \"white\" {}");
return result.ToString();
}
public override string GetPropertyDeclarationString()
{
return "UNITY_DECLARE_TEX2D(" + name + ");";
}
public override PreviewProperty GetPreviewMaterialProperty()
{
return new PreviewProperty()
{
m_Name = name,
m_PropType = PropertyType.Texture,
m_Texture = value.texture
};
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/TextureShaderProperty.cs.meta


fileFormatVersion: 2
guid: 08e62564fb95471d9580619b660c6531
timeCreated: 1505346949

24
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/Vector2ShaderProperty.cs


using System;
namespace UnityEngine.MaterialGraph
{
[Serializable]
public class Vector2ShaderProperty : VectorShaderProperty
{
public override PropertyType propertyType
{
get { return PropertyType.Vector2; }
}
public override PreviewProperty GetPreviewMaterialProperty()
{
return new PreviewProperty()
{
m_Name = name,
m_PropType = PropertyType.Vector2,
m_Vector4 = value
};
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/Vector2ShaderProperty.cs.meta


fileFormatVersion: 2
guid: dbd5691737554a15ab0b098fca999382
timeCreated: 1505346926

23
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Graphs/Vector3ShaderProperty.cs


using System;
namespace UnityEngine.MaterialGraph
{
[Serializable]
public class Vector3ShaderProperty : VectorShaderProperty
{
public override PropertyType propertyType
{
get { return PropertyType.Vector3; }
}
public override PreviewProperty GetPreviewMaterialProperty()
{
return new PreviewProperty()
{
m_Name = name,
m_PropType = PropertyType.Vector3,
m_Vector4 = value
};
}
}
}

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

正在加载...
取消
保存