浏览代码

Merge with master

/main
Martin Thorzen 6 年前
当前提交
f5ae4e88
共有 249 个文件被更改,包括 1592 次插入1604 次删除
  1. 26
      .gitignore
  2. 4
      com.unity.shadergraph.meta
  3. 1001
      TestbedAssets/Rock_Pack_01/Rocks_Models/Rock_A_01.OBJ
  4. 2
      com.unity.shadergraph/package.json
  5. 3
      com.unity.shadergraph/ShaderGraphLibrary/ShaderVariablesMatrixDefsLegacyUnity.hlsl.meta
  6. 3
      com.unity.shadergraph/ShaderGraphLibrary/ShaderVariablesFunctions.hlsl.meta
  7. 1
      com.unity.shadergraph/Editor/Util/GraphTypeMapper.cs
  8. 4
      com.unity.shadergraph/Editor/Util/CreateSerializableGraph.cs
  9. 2
      com.unity.shadergraph/Editor/Util/CopyPasteGraph.cs
  10. 3
      com.unity.shadergraph/Editor/Templates/shader.template
  11. 50
      com.unity.shadergraph/Editor/Templates/lightweightPBRForwardPass.template
  12. 26
      com.unity.shadergraph/Editor/Templates/lightweightPBRExtraPasses.template
  13. 9
      com.unity.shadergraph/Editor/Resources/Styles/ShaderPort.uss
  14. 14
      com.unity.shadergraph/Editor/Resources/Styles/PortInputView.uss
  15. 1
      com.unity.shadergraph/Editor/Resources/Styles/MaterialGraph.uss
  16. 2
      com.unity.shadergraph/Editor/Resources/Styles/MasterPreviewView.uss
  17. 11
      com.unity.shadergraph/Editor/Resources/Styles/GraphEditorView.uss
  18. 2
      com.unity.shadergraph/Editor/Importers/ShaderGraphImporterEditor.cs
  19. 2
      com.unity.shadergraph/Editor/Importers/ShaderGraphImporter.cs
  20. 1
      com.unity.shadergraph/Editor/Drawing/Views/Slots/TextureSlotControlView.cs
  21. 1
      com.unity.shadergraph/Editor/Drawing/Views/Slots/CubemapSlotControlView.cs
  22. 1
      com.unity.shadergraph/Editor/Drawing/Views/Slots/BooleanSlotControlView.cs
  23. 2
      com.unity.shadergraph/Editor/Drawing/Views/PortInputView.cs
  24. 22
      com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs
  25. 16
      com.unity.shadergraph/Editor/Drawing/Views/MaterialGraphView.cs
  26. 34
      com.unity.shadergraph/Editor/Drawing/Views/GraphEditorView.cs
  27. 1
      com.unity.shadergraph/Editor/Drawing/Views/GradientEdge.cs
  28. 16
      com.unity.shadergraph/Editor/Drawing/SearchWindowProvider.cs
  29. 4
      com.unity.shadergraph/Editor/Drawing/PreviewRate.cs.meta
  30. 44
      com.unity.shadergraph/Editor/Drawing/PreviewManager.cs
  31. 2
      com.unity.shadergraph/Editor/Drawing/MaterialGraphPreviewGenerator.cs
  32. 15
      com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs
  33. 12
      com.unity.shadergraph/Editor/Drawing/Manipulators/WindowDraggable.cs
  34. 4
      com.unity.shadergraph/Editor/Drawing/Manipulators/Scrollable.cs
  35. 440
      com.unity.shadergraph/Editor/Drawing/Manipulators/ResizeSideHandle.cs
  36. 1
      com.unity.shadergraph/Editor/Drawing/Manipulators/ResizeBorderFrame.cs
  37. 1
      com.unity.shadergraph/Editor/Drawing/Manipulators/GraphDropTarget.cs
  38. 2
      com.unity.shadergraph/Editor/Drawing/Manipulators/Draggable.cs
  39. 66
      com.unity.shadergraph/Editor/Drawing/Inspector/MasterPreviewView.cs
  40. 2
      com.unity.shadergraph/Editor/Drawing/Controls/VectorControl.cs
  41. 3
      com.unity.shadergraph/Editor/Drawing/Controls/ToggleControl.cs
  42. 2
      com.unity.shadergraph/Editor/Drawing/Controls/TextureControl.cs
  43. 9
      com.unity.shadergraph/Editor/Drawing/Controls/SliderControl.cs
  44. 2
      com.unity.shadergraph/Editor/Drawing/Controls/CubemapControl.cs
  45. 2
      com.unity.shadergraph/Editor/Drawing/Controls/ColorControl.cs
  46. 3
      com.unity.shadergraph/Editor/Drawing/Controls/ChannelMixerControl.cs
  47. 1
      com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardSection.cs
  48. 3
      com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs
  49. 7
      com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardField.cs
  50. 28
      com.unity.shadergraph/Editor/DefaultShaderIncludes.cs
  51. 66
      com.unity.shadergraph/Editor/Data/Util/ShaderGenerator.cs
  52. 1
      com.unity.shadergraph/Editor/Data/Util/SerializationHelper.cs
  53. 1
      com.unity.shadergraph/Editor/Data/Util/Logging.cs
  54. 1
      com.unity.shadergraph/Editor/Data/Util/CubemapPropertyChunk.cs
  55. 1
      com.unity.shadergraph/Editor/Data/SubGraph/SubGraph.cs
  56. 2
      com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/OrNode.cs
  57. 2
      com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NotNode.cs
  58. 2
      com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NandNode.cs
  59. 4
      com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsNanNode.cs
  60. 2
      com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsInfiniteNode.cs
  61. 2
      com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/BranchNode.cs
  62. 2
      com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AnyNode.cs
  63. 2
      com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AndNode.cs
  64. 2
      com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AllNode.cs
  65. 1
      com.unity.shadergraph/Editor/Data/Nodes/UV/TwirlNode.cs
  66. 128
      com.unity.shadergraph/Editor/Data/Nodes/UV/TriplanarNode.cs
  67. 32
      com.unity.shadergraph/Editor/Data/Nodes/SlotValue.cs
  68. 2
      com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/TransformNode.cs
  69. 7
      com.unity.shadergraph/Editor/Data/Nodes/Math/Round/StepNode.cs
  70. 5
      com.unity.shadergraph/Editor/Data/Nodes/Math/Range/SaturateNode.cs
  71. 5
      com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RemapNode.cs
  72. 5
      com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RandomRangeNode.cs
  73. 5
      com.unity.shadergraph/Editor/Data/Nodes/Math/Range/OneMinusNode.cs
  74. 5
      com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MinimumNode.cs
  75. 5
      com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MaximumNode.cs
  76. 5
      com.unity.shadergraph/Editor/Data/Nodes/Math/Range/FractionNode.cs
  77. 5
      com.unity.shadergraph/Editor/Data/Nodes/Math/Range/ClampNode.cs
  78. 20
      com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixTransposeNode.cs
  79. 13
      com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/SmoothstepNode.cs
  80. 5
      com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/LerpNode.cs
  81. 5
      com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/InverseLerpNode.cs
  82. 7
      com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDYNode.cs
  83. 7
      com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXYNode.cs
  84. 7
      com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXNode.cs
  85. 377
      com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/MultiplyNode.cs
  86. 115
      com.unity.shadergraph/Editor/Data/Nodes/MasterNode.cs
  87. 1
      com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs
  88. 1
      com.unity.shadergraph/Editor/Data/Nodes/Input/PBR/MetalReflectanceNode.cs
  89. 132
      com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix4Node.cs
  90. 110
      com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix3Node.cs
  91. 96
      com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix2Node.cs
  92. 2
      com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/UVNode.cs
  93. 31
      com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs
  94. 1
      com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/ConstantNode.cs
  95. 1
      com.unity.shadergraph/Editor/Data/Nodes/IMasterNode.cs
  96. 34
      com.unity.shadergraph/Editor/Data/Nodes/CodeFunctionNode.cs
  97. 3
      com.unity.shadergraph/Editor/Data/Nodes/Channel/SplitNode.cs
  98. 11
      com.unity.shadergraph/Editor/Data/Nodes/Channel/CombineNode.cs
  99. 1
      com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalStrengthNode.cs
  100. 3
      com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalCreateNode.cs

26
.gitignore


MaterialGraphProject/.vs
MaterialGraphProject/.vscode
MaterialGraphProject/Library
MaterialGraphProject/obj
MaterialGraphProject/MaterialGraphProject.CSharp.csproj
MaterialGraphProject/MaterialGraphProject.sln.DotSettings.user
*.csproj
MaterialGraphProject/MaterialGraphProject.sln
MaterialGraphProject/Temp
MaterialGraphProject/MaterialGraphProject.userprefs
MaterialGraphProject/.idea
MaterialGraphProject/Assets/Plugins*
artifacts/**
build/**
.vs
.vscode
.idea
MaterialGraphProject/Assets/_MingWai/New Custom Texture.asset.meta
MaterialGraphProject/Packages/*
MaterialGraphProject/GeneratedShader.shader
MaterialGraphProject/UberShader.shader
!MaterialGraphProject/Packages/manifest.json
.npmrc
.npmrc
DebugOutput.meta
DebugOutput/**

4
com.unity.shadergraph.meta


fileFormatVersion: 2
guid: 0b601fe23f0347ab8e4892edf2cf76d7
fileFormatVersion: 2
guid: 0b601fe23f0347ab8e4892edf2cf76d7
timeCreated: 1513757926

1001
TestbedAssets/Rock_Pack_01/Rocks_Models/Rock_A_01.OBJ
文件差异内容过多而无法显示
查看文件

2
com.unity.shadergraph/package.json


{
"name": "com.unity.shadergraph",
"description": "Shader Graph",
"version": "0.1.17",
"version": "0.1.18",
"unity": "2018.1",
"dependencies": {
}

3
com.unity.shadergraph/ShaderGraphLibrary/ShaderVariablesMatrixDefsLegacyUnity.hlsl.meta


fileFormatVersion: 2
guid: 77ec57a2ba7588b4b96bc4c87934003f
timeCreated: 1498228363
licenseType: Pro
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

3
com.unity.shadergraph/ShaderGraphLibrary/ShaderVariablesFunctions.hlsl.meta


fileFormatVersion: 2
guid: 919263f29f66aed49a283fe1f971c094
timeCreated: 1498227267
licenseType: Pro
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

1
com.unity.shadergraph/Editor/Util/GraphTypeMapper.cs


using System;
using UnityEditor.Experimental.UIElements.GraphView;
using UnityEditor.Graphing;
namespace UnityEditor.Graphing.Util
{

4
com.unity.shadergraph/Editor/Util/CreateSerializableGraph.cs


using System.IO;
using UnityEditor.ProjectWindowCallback;
using UnityEditor.Graphing;
namespace UnityEditor.Graphing
{
}

2
com.unity.shadergraph/Editor/Util/CopyPasteGraph.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
namespace UnityEditor.Graphing.Util

3
com.unity.shadergraph/Editor/Templates/shader.template


${SubShader}
FallBack "Diffuse"
CustomEditor "LegacyIlluminShaderGUI"
FallBack "Hidden/InternalErrorShader"
}

50
com.unity.shadergraph/Editor/Templates/lightweightPBRForwardPass.template


#pragma prefer_hlslcc gles
#pragma target 3.0
// -------------------------------------
// Lightweight Pipeline keywords
// We have no good approach exposed to skip shader variants, e.g, ideally we would like to skip _CASCADE for all puctual lights
// Lightweight combines light classification and shadows keywords to reduce shader variants.
// Lightweight shader library declares defines based on these keywords to avoid having to check them in the shaders
// Core.hlsl defines _MAIN_LIGHT_DIRECTIONAL and _MAIN_LIGHT_SPOT (point lights can't be main light)
// Shadow.hlsl defines _SHADOWS_ENABLED, _SHADOWS_SOFT, _SHADOWS_CASCADE, _SHADOWS_PERSPECTIVE
#pragma multi_compile _ _MAIN_LIGHT_DIRECTIONAL_SHADOW _MAIN_LIGHT_DIRECTIONAL_SHADOW_CASCADE _MAIN_LIGHT_DIRECTIONAL_SHADOW_SOFT _MAIN_LIGHT_DIRECTIONAL_SHADOW_CASCADE_SOFT _MAIN_LIGHT_SPOT_SHADOW _MAIN_LIGHT_SPOT_SHADOW_SOFT
#pragma multi_compile _ _MAIN_LIGHT_COOKIE
#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile _ _MIXED_LIGHTING_SUBTRACTIVE
#pragma multi_compile _ FOG_LINEAR FOG_EXP2
// -------------------------------------
// Lightweight Pipeline keywords
#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile _ _MIXED_LIGHTING_SUBTRACTIVE
#pragma multi_compile _ FOG_LINEAR FOG_EXP2
// -------------------------------------
// Unity defined keywords
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED LIGHTMAP_ON
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
// -------------------------------------
// Unity defined keywords
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ LIGHTMAP_ON
// LW doesn't support dynamic GI. So we save 30% shader variants if we assume
// LIGHTMAP_ON when DIRLIGHTMAP_COMBINED is set
#ifdef DIRLIGHTMAP_COMBINED
#define LIGHTMAP_ON
#endif
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag

o.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
o.clipPos = clipPos;
#if defined(_SHADOWS_ENABLED) && !defined(_SHADOWS_CASCADE)
o.shadowCoord = ComputeShadowCoord(lwWorldPos);
#else
o.shadowCoord = float4(0, 0, 0, 0);
#endif
o.shadowCoord = ComputeShadowCoord(o.clipPos);
return o;
}

inputData.viewDirectionWS = normalize(WorldSpaceViewDirection);
#endif
#ifdef _SHADOWS_ENABLED
#else
inputData.shadowCoord = float4(0, 0, 0, 0);
#endif
inputData.fogCoord = IN.fogFactorAndVertexLight.x;
inputData.vertexLighting = IN.fogFactorAndVertexLight.yzw;

26
com.unity.shadergraph/Editor/Templates/lightweightPBRExtraPasses.template


{
Tags{"LightMode" = "ShadowCaster"}
ZWrite On ZTest LEqual
ZWrite On
ZTest LEqual
#pragma fragment ShadowPassFragment
#pragma fragment LitPassFragmentNull
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
ENDHLSL

// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
#include "LWRP/ShaderLibrary/Core.hlsl"
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return TransformObjectToHClip(pos.xyz);
}
#pragma vertex LitPassVertex
#pragma fragment LitPassFragmentNull
half4 frag() : SV_TARGET
{
return 0;
}
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
ENDHLSL
}

9
com.unity.shadergraph/Editor/Resources/Styles/ShaderPort.uss


/* THIS FILE IS FROM GRAPHVIEW BUT CONTAINS MODIFICATIONS */
ShaderPort {
height: 24;
align-items: center;

port-color:#FF8B8B;
}
ShaderPort.typeCubemap {
/* Same as typeTexture */
port-color:#FF8B8B;
}
ShaderPort.typeGraphScript {
/* Todo: there is no such type in Unity atm */
port-color:#E681BA;

port-color:#9481E6;
}
ShaderPort.typeBool {
ShaderPort.typeBoolean {
port-color:#9481E6;
}

14
com.unity.shadergraph/Editor/Resources/Styles/PortInputView.uss


edge-color: #8FC1DF;
}
PortInputView.typeTexture2D > #container > #slot > #dot {
PortInputView.typeTexture2D > #container > #slot > #dot,
PortInputView.typeCubemap > #container > #slot > #dot {
PortInputView.typeTexture2D {
PortInputView.typeTexture2D,
PortInputView.typeCubemap {
edge-color: #FF8B8B;
}

PortInputView.typeVector1 {
edge-color: #84E4E7;
}
PortInputView.typeBoolean > #container > #slot > #dot {
background-color: #9481E6;
}
PortInputView.typeBoolean {
edge-color: #9481E6;
}

1
com.unity.shadergraph/Editor/Resources/Styles/MaterialGraph.uss


2
com.unity.shadergraph/Editor/Resources/Styles/MasterPreviewView.uss


flex-grow: 1;
border-width: 10;
border-color: rgb(200,10,190);
}
}

11
com.unity.shadergraph/Editor/Resources/Styles/GraphEditorView.uss


edge-input-color: #8FC1DF;
}
.edge.fromTexture2D {
.edge.fromTexture2D, .edge.fromCubemap {
.edge.toTexture2D {
.edge.toTexture2D, .edge.toCubemap {
edge-input-color: #FF8B8B;
}

}
.edge.toVector1 {
edge-input-color: #84E4E7;
}
.edge.fromBoolean {
edge-output-color: #9481E6;
}
.edge.toBoolean {
edge-input-color: #9481E6;
}
#resizeBorderFrame > .resize {

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


{
var window = CreateInstance<MaterialGraphEditWindow>();
window.Show();
window.ChangeSelection(guid);
window.Initialize(guid);
}
return true;
}

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


using UnityEditor.Experimental.AssetImporters;
using UnityEditor.ShaderGraph.Drawing;
[ScriptedImporter(11, ShaderGraphImporter.ShaderGraphExtension)]
[ScriptedImporter(12, ShaderGraphImporter.ShaderGraphExtension)]
public class ShaderGraphImporter : ScriptedImporter
{
public const string ShaderGraphExtension = "shadergraph";

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


using UnityEditor.Graphing;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using Object = UnityEngine.Object;
namespace UnityEditor.ShaderGraph.Drawing.Slots

1
com.unity.shadergraph/Editor/Drawing/Views/Slots/CubemapSlotControlView.cs


using UnityEditor.Graphing;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using Object = UnityEngine.Object;
namespace UnityEditor.ShaderGraph.Drawing.Slots

1
com.unity.shadergraph/Editor/Drawing/Views/Slots/BooleanSlotControlView.cs


using System;
using UnityEditor.Experimental.UIElements;
using UnityEditor.Graphing;
using UnityEngine;
using UnityEngine.Experimental.UIElements;

2
com.unity.shadergraph/Editor/Drawing/Views/PortInputView.cs


using System;
using UnityEditor.Experimental.UIElements;
using UnityEditor.Graphing;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;

22
com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs


SetPosition(new Rect(node.drawState.position.x, node.drawState.position.y, 0, 0));
if (node is PreviewNode)
/*if (node is PreviewNode)
}*/
if (node is SubGraphNode)
{
RegisterCallback<MouseDownEvent>(OnSubGraphDoubleClick);
}
m_PortInputContainer.SendToBack();

buttonContainer.Add(collapseButton);
}
void OnSubGraphDoubleClick(MouseDownEvent evt)
{
if (evt.clickCount == 2 && evt.button == 0)
{
SubGraphNode subgraphNode = node as SubGraphNode;
var path = AssetDatabase.GetAssetPath(subgraphNode.subGraphAsset);
ShaderGraphImporterEditor.ShowGraphEditWindow(path);
}
}
public AbstractMaterialNode node { get; private set; }
public override bool expanded

void ConvertToShader(EventBase eventBase)
{
List<PropertyCollector.TextureInfo> textureInfo;
var masterNode = node as MasterNode;
var masterNode = node as IMasterNode;
var shader = masterNode.GetShader(GenerationMode.ForReals, masterNode.name, out textureInfo);
var shader = masterNode.GetShader(GenerationMode.ForReals, node.name, out textureInfo);
GUIUtility.systemCopyBuffer = shader;
}
else

16
com.unity.shadergraph/Editor/Drawing/Views/MaterialGraphView.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor.ShaderGraph;
using MouseButton = UnityEngine.Experimental.UIElements.MouseButton;
namespace UnityEditor.ShaderGraph.Drawing
{

evt.menu.AppendSeparator();
evt.menu.AppendAction("Open Documentation", SeeDocumentation, SeeDocumentationStatus);
}
if (selection.OfType<MaterialNodeView>().Count() == 1 && selection.OfType<MaterialNodeView>().First().node is SubGraphNode)
{
evt.menu.AppendSeparator();
evt.menu.AppendAction("Open Sub Graph", OpenSubGraph, ContextualMenu.MenuAction.AlwaysEnabled);
}
}
else if (evt.target is BlackboardField)
{

var node = selection.OfType<MaterialNodeView>().First().node;
if (node.documentationURL != null)
System.Diagnostics.Process.Start(node.documentationURL);
}
void OpenSubGraph(EventBase evt)
{
SubGraphNode subgraphNode = selection.OfType<MaterialNodeView>().First().node as SubGraphNode;
var path = AssetDatabase.GetAssetPath(subgraphNode.subGraphAsset);
ShaderGraphImporterEditor.ShowGraphEditWindow(path);
}
ContextualMenu.MenuAction.StatusFlags SeeDocumentationStatus(EventBase eventBase)

34
com.unity.shadergraph/Editor/Drawing/Views/GraphEditorView.cs


{
public WindowDockingLayout previewLayout = new WindowDockingLayout();
public WindowDockingLayout blackboardLayout = new WindowDockingLayout();
public WindowDockingLayout nodeSettingsLayout = new WindowDockingLayout();
public Vector2 masterPreviewSize = new Vector2(400, 400);
}
public class GraphEditorView : VisualElement, IDisposable

EdgeConnectorListener m_EdgeConnectorListener;
BlackboardProvider m_BlackboardProvider;
string m_FloatingWindowsLayoutKey;
const string k_FloatingWindowsLayoutKey = "UnityEditor.ShaderGraph.FloatingWindowsLayout";
FloatingWindowsLayout m_FloatingWindowsLayout;
public Action saveRequested { get; set; }

AddStyleSheetPath("Styles/GraphEditorView");
m_EditorWindow = editorWindow;
previewManager = new PreviewManager(graph);
string serializedWindowLayout = EditorUserSettings.GetConfigValue(k_FloatingWindowsLayoutKey);
if (!string.IsNullOrEmpty(serializedWindowLayout))
{
m_FloatingWindowsLayout = JsonUtility.FromJson<FloatingWindowsLayout>(serializedWindowLayout);
if (m_FloatingWindowsLayout.masterPreviewSize.x > 0f && m_FloatingWindowsLayout.masterPreviewSize.y > 0f)
previewManager.ResizeMasterPreview(m_FloatingWindowsLayout.masterPreviewSize);
}
previewManager.RenderPreviews();
var toolbar = new IMGUIContainer(() =>
{

foreach (var node in m_Graph.removedNodes)
{
node.onModified -= OnNodeChanged;
node.UnregisterCallback(OnNodeChanged);
var nodeView = m_GraphView.nodes.ToList().OfType<MaterialNodeView>().FirstOrDefault(p => p.node != null && p.node.guid == node.guid);
if (nodeView != null)
{

var nodeView = new MaterialNodeView { userData = node };
m_GraphView.AddElement(nodeView);
nodeView.Initialize(node as AbstractMaterialNode, m_PreviewManager, m_EdgeConnectorListener);
node.onModified += OnNodeChanged;
node.RegisterCallback(OnNodeChanged);
nodeView.Dirty(ChangeType.Repaint);
if (m_SearchWindowProvider.nodeNeedsRepositioning && m_SearchWindowProvider.targetSlotReference.nodeGuid.Equals(node.guid))

foreach (var edgeView in anchorView.connections.OfType<Edge>())
{
var targetSlot = edgeView.input.GetSlot();
if (targetSlot.valueType == SlotValueType.Dynamic)
if (targetSlot.valueType == SlotValueType.DynamicVector || targetSlot.valueType == SlotValueType.DynamicMatrix || targetSlot.valueType == SlotValueType.Dynamic)
{
var connectedNodeView = edgeView.input.node as MaterialNodeView;
if (connectedNodeView != null && !nodeViews.Contains(connectedNodeView))

foreach (var anchorView in nodeView.inputContainer.Children().OfType<Port>())
{
var targetSlot = anchorView.GetSlot();
if (targetSlot.valueType != SlotValueType.Dynamic)
if (targetSlot.valueType != SlotValueType.DynamicVector)
continue;
foreach (var edgeView in anchorView.connections.OfType<Edge>())
{

{
UnregisterCallback<PostLayoutEvent>(ApplySerializewindowLayouts);
m_FloatingWindowsLayoutKey = "UnityEditor.ShaderGraph.FloatingWindowsLayout";
string serializedWindowLayout = EditorUserSettings.GetConfigValue(m_FloatingWindowsLayoutKey);
if (!String.IsNullOrEmpty(serializedWindowLayout))
if (m_FloatingWindowsLayout != null)
m_FloatingWindowsLayout = JsonUtility.FromJson<FloatingWindowsLayout>(serializedWindowLayout);
m_MasterPreviewView.UpdateRenderTextureOnNextLayoutChange();
previewManager.ResizeMasterPreview(m_FloatingWindowsLayout.masterPreviewSize);
}
else
{

void UpdateSerializedWindowLayout()
{
if (m_FloatingWindowsLayout == null)
m_FloatingWindowsLayout = new FloatingWindowsLayout();
m_FloatingWindowsLayout.masterPreviewSize = m_MasterPreviewView.Q("preview").layout.size;
EditorUserSettings.SetConfigValue(m_FloatingWindowsLayoutKey, serializedWindowLayout);
EditorUserSettings.SetConfigValue(k_FloatingWindowsLayoutKey, serializedWindowLayout);
m_MasterPreviewView.RefreshRenderTextureSize();
}

1
com.unity.shadergraph/Editor/Drawing/Views/GradientEdge.cs


using UnityEditor.Experimental.UIElements.GraphView;
using UnityEngine;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph.Drawing
{

16
com.unity.shadergraph/Editor/Drawing/SearchWindowProvider.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor.Experimental.UIElements;
using UnityEditor.Experimental.UIElements.GraphView;
using UnityEditor.Graphing;

{
// First build up temporary data structure containing group & title as an array of strings (the last one is the actual title) and associated node type.
var nodeEntries = new List<NodeEntry>();
foreach (var type in Assembly.GetAssembly(typeof(AbstractMaterialNode)).GetTypes())
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
if (type.IsClass && !type.IsAbstract && (type.IsSubclassOf(typeof(AbstractMaterialNode))) && type != typeof(PropertyNode))
foreach (var type in assembly.GetTypes())
var attrs = type.GetCustomAttributes(typeof(TitleAttribute), false) as TitleAttribute[];
if (attrs != null && attrs.Length > 0)
if (type.IsClass && !type.IsAbstract && (type.IsSubclassOf(typeof(AbstractMaterialNode))) && type != typeof(PropertyNode))
var node = (AbstractMaterialNode) Activator.CreateInstance(type);
AddEntries(node, attrs[0].title, nodeEntries);
var attrs = type.GetCustomAttributes(typeof(TitleAttribute), false) as TitleAttribute[];
if (attrs != null && attrs.Length > 0)
{
var node = (AbstractMaterialNode)Activator.CreateInstance(type);
AddEntries(node, attrs[0].title, nodeEntries);
}
}
}
}

4
com.unity.shadergraph/Editor/Drawing/PreviewRate.cs.meta


fileFormatVersion: 2
guid: fa070520993a4b839e705dcd7f22e4d6
fileFormatVersion: 2
guid: fa070520993a4b839e705dcd7f22e4d6
timeCreated: 1506421104

44
com.unity.shadergraph/Editor/Drawing/PreviewManager.cs


Texture2D m_ErrorTexture;
Shader m_UberShader;
string m_OutputIdName;
Vector2? m_NewMasterPreviewSize;
public PreviewRenderData masterRenderData
{

{
renderTexture = new RenderTexture(400, 400, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default) { hideFlags = HideFlags.HideAndDontSave }
};
m_MasterRenderData.renderTexture.Create();
public void ResizeMasterPreview(Vector2 newSize)
{
m_NewMasterPreviewSize = newSize;
if (masterRenderData.shaderData != null)
m_DirtyPreviews.Add(masterRenderData.shaderData.node.tempId.index);
}
public PreviewRenderData GetPreview(AbstractMaterialNode node)
{
return m_RenderDatas[node.tempId.index];

shaderData = shaderData,
renderTexture = new RenderTexture(200, 200, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default) { hideFlags = HideFlags.HideAndDontSave }
};
renderData.renderTexture.Create();
node.onModified += OnNodeModified;
node.RegisterCallback(OnNodeModified);
if (node.RequiresTime())
m_TimeDependentPreviews.Add(node.tempId.index);

var renderMasterPreview = masterRenderData.shaderData != null && m_DirtyPreviews.Contains(masterRenderData.shaderData.node.tempId.index);
if (renderMasterPreview)
{
if (m_NewMasterPreviewSize.HasValue)
{
if (masterRenderData.renderTexture != null)
Object.DestroyImmediate(masterRenderData.renderTexture, true);
masterRenderData.renderTexture = new RenderTexture((int)m_NewMasterPreviewSize.Value.x, (int)m_NewMasterPreviewSize.Value.y, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default) { hideFlags = HideFlags.HideAndDontSave };
masterRenderData.renderTexture.Create();
masterRenderData.texture = masterRenderData.renderTexture;
m_NewMasterPreviewSize = null;
}
var mesh = m_Graph.previewData.serializedMesh.mesh ? m_Graph.previewData.serializedMesh.mesh : m_SceneResources.sphere;
var previewTransform = Matrix4x4.Rotate(m_Graph.previewData.rotation);
var scale = m_Graph.previewData.scale;

{
PropagateNodeSet(m_DirtyShaders);
var masterNodes = new List<MasterNode>();
var masterNodes = new List<INode>();
var uberNodes = new List<INode>();
foreach (var index in m_DirtyShaders)
{

var masterNode = node as MasterNode;
var masterNode = node as IMasterNode;
masterNodes.Add(masterNode);
masterNodes.Add(node);
else
uberNodes.Add(node);
}

var results = m_Graph.GetUberPreviewShader();
m_OutputIdName = results.outputIdProperty.referenceName;
ShaderUtil.UpdateShaderAsset(m_UberShader, results.shader);
File.WriteAllText(Application.dataPath + "/../UberShader.shader", (results.shader ?? "null").Replace("UnityEngine.MaterialGraph", "Generated"));
var debugOutputPath = DefaultShaderIncludes.GetDebugOutputPath();
if (debugOutputPath != null)
File.WriteAllText(debugOutputPath + "/UberShader.shader", (results.shader ?? "null").Replace("UnityEngine.MaterialGraph", "Generated"));
bool uberShaderHasError = false;
if (MaterialGraphAsset.ShaderHasError(m_UberShader))
{

shaderData.shaderString = m_Graph.GetPreviewShader(node).shader;
}
File.WriteAllText(Application.dataPath + "/../GeneratedShader.shader", (shaderData.shaderString ?? "null").Replace("UnityEngine.MaterialGraph", "Generated"));
var debugOutputPath = DefaultShaderIncludes.GetDebugOutputPath();
if (debugOutputPath != null)
File.WriteAllText(debugOutputPath + "/GeneratedShader.shader", (shaderData.shaderString ?? "null").Replace("UnityEngine.MaterialGraph", "Generated"));
if (string.IsNullOrEmpty(shaderData.shaderString))
{

}
// Debug output
var message = "RecreateShader: " + node.GetVariableNameForNode() + Environment.NewLine + shaderData.shaderString;
Debug.LogWarning(message);
if (debugOutputPath != null)
{
var message = "RecreateShader: " + node.GetVariableNameForNode() + Environment.NewLine + shaderData.shaderString;
Debug.LogWarning(message);
}
ShaderUtil.ClearShaderErrors(shaderData.shader);
Object.DestroyImmediate(shaderData.shader, true);
shaderData.shader = null;

Object.DestroyImmediate(renderData.renderTexture, true);
if (renderData.shaderData != null && renderData.shaderData.node != null)
renderData.shaderData.node.onModified -= OnNodeModified;
renderData.shaderData.node.UnregisterCallback(OnNodeModified);
}
void DestroyPreview(Identifier nodeId)

2
com.unity.shadergraph/Editor/Drawing/MaterialGraphPreviewGenerator.cs


using System;
using System.Collections.Generic;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

15
com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs


using System.Linq;
using System.Text;
using UnityEditor.Experimental.UIElements;
using UnityEditor.Experimental.UIElements.GraphView;
using UnityEngine.Assertions;
using UnityEditor.ShaderGraph;
using Object = UnityEngine.Object;
using Edge = UnityEditor.Experimental.UIElements.GraphView.Edge;

{
var guid = selectedGuid;
selectedGuid = null;
ChangeSelection(guid);
Initialize(guid);
}
if (graphObject == null)

}
}
public void ChangeSelection(string newSelectionGuid)
public void Initialize(string assetGuid)
var asset = AssetDatabase.LoadAssetAtPath<Object>(AssetDatabase.GUIDToAssetPath(newSelectionGuid));
m_ColorSpace = PlayerSettings.colorSpace;
var asset = AssetDatabase.LoadAssetAtPath<Object>(AssetDatabase.GUIDToAssetPath(assetGuid));
if (asset == null)
return;

if (selectedGuid == newSelectionGuid)
if (selectedGuid == assetGuid)
return;
var path = AssetDatabase.GetAssetPath(asset);

return;
}
selectedGuid = newSelectionGuid;
selectedGuid = assetGuid;
var textGraph = File.ReadAllText(path, Encoding.UTF8);
graphObject = CreateInstance<GraphObject>();

12
com.unity.shadergraph/Editor/Drawing/Manipulators/WindowDraggable.cs


using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
using UnityEditor.Experimental.UIElements;
namespace UnityEditor.ShaderGraph.Drawing
{

target.layout = layout;
}
}
void OnMouseUp(MouseUpEvent evt)
{

}
else
{
windowRect.y = (1f - normalizedDistanceFromEdge.y) * target.parent.layout.height- windowRect.height;
windowRect.y = (1f - normalizedDistanceFromEdge.y) * target.parent.layout.height - windowRect.height;
windowRect.width = Mathf.Max(Mathf.Min(windowRect.width, target.parent.layout.width), minSize.x);
windowRect.height = Mathf.Max(Mathf.Min(windowRect.height, target.parent.layout.height), minSize.y);
windowRect.width = Mathf.Max(windowRect.width, minSize.x);
windowRect.height = Mathf.Max(windowRect.height, minSize.y);
float maximumXPosition = Mathf.Max(target.parent.layout.width - windowRect.width, 0f);
float maximumYPosition = Mathf.Max(target.parent.layout.height - windowRect.height, 0f);

4
com.unity.shadergraph/Editor/Drawing/Manipulators/Scrollable.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using System;

440
com.unity.shadergraph/Editor/Drawing/Manipulators/ResizeSideHandle.cs


using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.UIElements;

public Action OnResizeFinished;
bool m_DockingLeft;
bool m_DockingTop;
bool m_Dragging;
float m_InitialAspectRatio;
Rect m_ResizeBeginLayout;
Vector2 m_ResizeBeginMousePosition;
public ResizeSideHandle(VisualElement resizeTarget, ResizeHandleAnchor anchor)
{
m_ResizeTarget = resizeTarget;

{
AddToClassList("vertical");
AddToClassList("top");
RegisterCallback<MouseMoveEvent>(HandleResizeFromTop);
break;
}
case ResizeHandleAnchor.TopRight:

RegisterCallback<MouseMoveEvent>(HandleResizeFromTopRight);
break;
}
case ResizeHandleAnchor.Right:

RegisterCallback<MouseMoveEvent>(HandleResizeFromRight);
break;
}
case ResizeHandleAnchor.BottomRight:

RegisterCallback<MouseMoveEvent>(HandleResizeFromBottomRight);
break;
}
case ResizeHandleAnchor.Bottom:

RegisterCallback<MouseMoveEvent>(HandleResizeFromBottom);
break;
}
case ResizeHandleAnchor.BottomLeft:

RegisterCallback<MouseMoveEvent>(HandleResizeFromBottomLeft);
break;
}
case ResizeHandleAnchor.Left:

RegisterCallback<MouseMoveEvent>(HandleResizeFromLeft);
break;
}
case ResizeHandleAnchor.TopLeft:

RegisterCallback<MouseMoveEvent>(HandleResizeFromTopLeft);
ResizeDirection resizeDirection;
RegisterCallback<MouseDownEvent>(HandleMouseDown);
RegisterCallback<MouseUpEvent>(HandleDraggableMouseUp);
m_ResizeTarget.RegisterCallback<PostLayoutEvent>(InitialLayoutSetup);
}
void InitialLayoutSetup(PostLayoutEvent evt)
{
m_ResizeTarget.UnregisterCallback<PostLayoutEvent>(InitialLayoutSetup);
m_InitialAspectRatio = m_ResizeTarget.layout.width / m_ResizeTarget.layout.height;
}
Vector2 GetMinSize()
{
Vector2 minSize = new Vector2(60f, 60f);
if (anchor == ResizeHandleAnchor.Left || anchor == ResizeHandleAnchor.Right)
if (!Mathf.Approximately(m_ResizeTarget.style.minWidth.value, 0f))
resizeDirection = ResizeDirection.Horizontal;
minSize.x = m_ResizeTarget.style.minWidth;
}
if (!Mathf.Approximately(m_ResizeTarget.style.minHeight.value, 0f))
{
minSize.y = m_ResizeTarget.style.minHeight.value;
else if (anchor == ResizeHandleAnchor.Top || anchor == ResizeHandleAnchor.Bottom)
return minSize;
}
float GetMaxHorizontalExpansion(bool expandingLeft)
{
float maxHorizontalExpansion;
if (expandingLeft)
resizeDirection = ResizeDirection.Vertical;
maxHorizontalExpansion = m_ResizeBeginLayout.x;
resizeDirection = ResizeDirection.Any;
maxHorizontalExpansion = m_ResizeTarget.parent.layout.width - m_ResizeBeginLayout.xMax;
bool moveWhileResizeHorizontal = anchor == ResizeHandleAnchor.TopLeft || anchor == ResizeHandleAnchor.BottomLeft || anchor == ResizeHandleAnchor.Left;
bool moveWhileResizeVertical = anchor == ResizeHandleAnchor.TopLeft || anchor == ResizeHandleAnchor.TopRight || anchor == ResizeHandleAnchor.Top;
if (maintainAspectRatio)
{
if (!m_DockingTop)
{
maxHorizontalExpansion = Mathf.Min(maxHorizontalExpansion, m_ResizeBeginLayout.y);
}
else
{
maxHorizontalExpansion = Mathf.Min(maxHorizontalExpansion, m_ResizeTarget.parent.layout.height - m_ResizeBeginLayout.yMax);
}
}
this.AddManipulator(new Draggable(mouseDelta => OnResize(mouseDelta, resizeDirection, moveWhileResizeHorizontal, moveWhileResizeVertical, anchor)));
RegisterCallback<MouseUpEvent>(HandleDraggableMouseUp);
return maxHorizontalExpansion;
void OnResize(Vector2 resizeDelta, ResizeDirection direction, bool moveWhileResizeHorizontal, bool moveWhileresizeVertical, ResizeHandleAnchor anchor)
float GetMaxVerticalExpansion(bool expandingUp)
Vector2 normalizedResizeDelta = resizeDelta / 2f;
float maxVerticalExpansion;
Vector2 minSize = new Vector2(60f, 60f);
if (expandingUp)
{
maxVerticalExpansion = m_ResizeBeginLayout.y;
}
else
{
maxVerticalExpansion = m_ResizeTarget.parent.layout.height - m_ResizeBeginLayout.yMax;
}
if (!Mathf.Approximately(m_ResizeTarget.style.minWidth.value, 0f))
if (maintainAspectRatio)
minSize.x = m_ResizeTarget.style.minWidth;
if (!m_DockingLeft)
{
maxVerticalExpansion = Mathf.Min(maxVerticalExpansion, m_ResizeBeginLayout.x);
}
else
{
maxVerticalExpansion = Mathf.Min(maxVerticalExpansion, m_ResizeTarget.parent.layout.width - m_ResizeBeginLayout.xMax);
}
if (!Mathf.Approximately(m_ResizeTarget.style.minHeight.value, 0f))
return maxVerticalExpansion;
}
void HandleResizeFromTop(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
minSize.y = m_ResizeTarget.style.minHeight.value;
return;
if (direction == ResizeDirection.Vertical)
Vector2 restrictedMousePosition = m_ResizeTarget.parent.WorldToLocal(mouseMoveEvent.mousePosition);
restrictedMousePosition.y = Mathf.Min(restrictedMousePosition.y, m_ResizeBeginLayout.yMax - GetMinSize().y);
if (stayWithinParentBounds)
normalizedResizeDelta.x = 0f;
restrictedMousePosition.y = Mathf.Max(restrictedMousePosition.y, m_ResizeBeginMousePosition.y - GetMaxVerticalExpansion(true));
else if (direction == ResizeDirection.Horizontal)
Vector2 delta = restrictedMousePosition - m_ResizeBeginMousePosition;
Rect newLayout = m_ResizeBeginLayout;
newLayout.yMin = m_ResizeBeginLayout.yMin + delta.y;
if (maintainAspectRatio)
normalizedResizeDelta.y = 0f;
if (m_DockingLeft)
{
newLayout.width = newLayout.height * m_InitialAspectRatio;
}
else
{
newLayout.xMin = newLayout.xMax - (newLayout.height * m_InitialAspectRatio);
}
Rect newLayout = m_ResizeTarget.layout;
m_ResizeTarget.layout = newLayout;
mouseMoveEvent.StopPropagation();
}
if (anchor == ResizeHandleAnchor.Left || anchor == ResizeHandleAnchor.TopLeft || anchor == ResizeHandleAnchor.BottomLeft)
void HandleResizeFromTopRight(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
newLayout.xMin = Mathf.Min(newLayout.xMin + normalizedResizeDelta.x, newLayout.xMax - minSize.x);
return;
else
Vector2 restrictedMousePosition = m_ResizeTarget.parent.WorldToLocal(mouseMoveEvent.mousePosition);
restrictedMousePosition.x = Mathf.Max(restrictedMousePosition.x, m_ResizeBeginLayout.xMin + GetMinSize().x);
restrictedMousePosition.y = Mathf.Min(restrictedMousePosition.y, m_ResizeBeginLayout.yMax - GetMinSize().y);
if (stayWithinParentBounds)
newLayout.xMax = Mathf.Max(newLayout.xMax + normalizedResizeDelta.x, newLayout.xMin + minSize.x);
restrictedMousePosition.x = Mathf.Min(restrictedMousePosition.x, m_ResizeBeginMousePosition.x + GetMaxHorizontalExpansion(false));
restrictedMousePosition.y = Mathf.Max(restrictedMousePosition.y, 0f);
if (anchor == ResizeHandleAnchor.Top || anchor == ResizeHandleAnchor.TopLeft || anchor == ResizeHandleAnchor.TopRight)
Vector2 delta = restrictedMousePosition - m_ResizeBeginMousePosition;
Rect newLayout = m_ResizeBeginLayout;
newLayout.width += delta.x;
newLayout.yMin += delta.y;
if (maintainAspectRatio)
newLayout.yMin = Mathf.Min(newLayout.yMin + normalizedResizeDelta.y, newLayout.yMax - minSize.y);
if (newLayout.width < newLayout.height * m_InitialAspectRatio)
{
newLayout.yMin = Mathf.Min(newLayout.yMax - newLayout.width / m_InitialAspectRatio, newLayout.yMax - GetMinSize().y);
}
else
{
newLayout.width = newLayout.height * m_InitialAspectRatio;
}
else
m_ResizeTarget.layout = newLayout;
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromRight(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
newLayout.yMax = Mathf.Max(newLayout.yMax + normalizedResizeDelta.y, newLayout.yMin + minSize.y);
return;
Vector2 restrictedMousePosition = m_ResizeTarget.parent.WorldToLocal(mouseMoveEvent.mousePosition);
restrictedMousePosition.x = Mathf.Max(restrictedMousePosition.x, m_ResizeBeginLayout.xMin + GetMinSize().x);
newLayout.xMin = Mathf.Max(newLayout.xMin, 0f);
newLayout.yMin = Mathf.Max(newLayout.yMin, 0f);
newLayout.xMax = Mathf.Min(newLayout.xMax, m_ResizeTarget.parent.layout.width);
newLayout.yMax = Mathf.Min(newLayout.yMax, m_ResizeTarget.parent.layout.height);
restrictedMousePosition.x = Mathf.Min(restrictedMousePosition.x, m_ResizeBeginMousePosition.x + GetMaxHorizontalExpansion(false));
}
Vector2 delta = restrictedMousePosition - m_ResizeBeginMousePosition;
Rect newLayout = m_ResizeBeginLayout;
newLayout.xMax = m_ResizeBeginLayout.xMax + delta.x;
if (maintainAspectRatio)
{
if (m_DockingTop)
{
newLayout.height = newLayout.width / m_InitialAspectRatio;
}
else
{
newLayout.yMin = newLayout.yMax - (newLayout.width / m_InitialAspectRatio);
}
mouseMoveEvent.StopPropagation();
void HandleDraggableMouseUp(MouseUpEvent evt)
void HandleResizeFromBottomRight(MouseMoveEvent mouseMoveEvent)
if (!m_Dragging)
{
return;
}
Vector2 restrictedMousePosition = m_ResizeTarget.parent.WorldToLocal(mouseMoveEvent.mousePosition);
restrictedMousePosition.x = Mathf.Max(restrictedMousePosition.x, m_ResizeBeginLayout.xMin + GetMinSize().x);
restrictedMousePosition.y = Mathf.Max(restrictedMousePosition.y, m_ResizeBeginLayout.yMin + GetMinSize().y);
if (stayWithinParentBounds)
{
restrictedMousePosition.x = Mathf.Min(restrictedMousePosition.x, m_ResizeBeginMousePosition.x + GetMaxHorizontalExpansion(false));
restrictedMousePosition.y = Mathf.Min(restrictedMousePosition.y, m_ResizeBeginMousePosition.y + GetMaxVerticalExpansion(false));
}
Vector2 delta = restrictedMousePosition - m_ResizeBeginMousePosition;
Rect newLayout = m_ResizeBeginLayout;
newLayout.size += delta;
if (maintainAspectRatio)
{
if (newLayout.width < newLayout.height * m_InitialAspectRatio)
{
newLayout.height = newLayout.width / m_InitialAspectRatio;
}
else
{
newLayout.width = newLayout.height * m_InitialAspectRatio;
}
}
m_ResizeTarget.layout = newLayout;
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromBottom(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
{
return;
}
Vector2 restrictedMousePosition = m_ResizeTarget.parent.WorldToLocal(mouseMoveEvent.mousePosition);
restrictedMousePosition.y = Mathf.Max(restrictedMousePosition.y, m_ResizeBeginLayout.yMin + GetMinSize().y);
if (stayWithinParentBounds)
{
restrictedMousePosition.y = Mathf.Min(restrictedMousePosition.y, m_ResizeBeginMousePosition.y + GetMaxVerticalExpansion(false));
}
Vector2 delta = restrictedMousePosition - m_ResizeBeginMousePosition;
Rect newLayout = m_ResizeBeginLayout;
newLayout.yMax = m_ResizeBeginLayout.yMax + delta.y;
if (maintainAspectRatio)
{
if (m_DockingLeft)
{
newLayout.width = newLayout.height * m_InitialAspectRatio;
}
else
{
newLayout.xMin = newLayout.xMax - (newLayout.height * m_InitialAspectRatio);
}
}
m_ResizeTarget.layout = newLayout;
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromBottomLeft(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
{
return;
}
Vector2 restrictedMousePosition = m_ResizeTarget.parent.WorldToLocal(mouseMoveEvent.mousePosition);
restrictedMousePosition.x = Mathf.Min(restrictedMousePosition.x, m_ResizeBeginLayout.xMax - GetMinSize().x);
restrictedMousePosition.y = Mathf.Max(restrictedMousePosition.y, m_ResizeBeginLayout.yMin + GetMinSize().y);
if (stayWithinParentBounds)
{
restrictedMousePosition.x = Mathf.Max(restrictedMousePosition.x, 0f);
restrictedMousePosition.y = Mathf.Min(restrictedMousePosition.y, m_ResizeBeginMousePosition.y + GetMaxVerticalExpansion(false));
}
Vector2 delta = restrictedMousePosition - m_ResizeBeginMousePosition;
Rect newLayout = m_ResizeBeginLayout;
newLayout.xMin += delta.x;
newLayout.height += delta.y;
if (maintainAspectRatio)
{
if (newLayout.width < newLayout.height * m_InitialAspectRatio)
{
newLayout.height = newLayout.width / m_InitialAspectRatio;
}
else
{
newLayout.xMin = Mathf.Min(newLayout.xMax - newLayout.height * m_InitialAspectRatio, newLayout.xMax - GetMinSize().x);
}
}
m_ResizeTarget.layout = newLayout;
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromLeft(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
{
return;
}
Vector2 restrictedMousePosition = m_ResizeTarget.parent.WorldToLocal(mouseMoveEvent.mousePosition);
restrictedMousePosition.x = Mathf.Min(restrictedMousePosition.x, m_ResizeBeginLayout.xMax - GetMinSize().x);
if (stayWithinParentBounds)
{
restrictedMousePosition.x = Mathf.Max(restrictedMousePosition.x, m_ResizeBeginMousePosition.x - GetMaxHorizontalExpansion(true));
}
Vector2 delta = restrictedMousePosition - m_ResizeBeginMousePosition;
Rect newLayout = m_ResizeBeginLayout;
newLayout.xMin = m_ResizeBeginLayout.xMin + delta.x;
if (maintainAspectRatio)
{
if (m_DockingTop)
{
newLayout.height = newLayout.width / m_InitialAspectRatio;
}
else
{
newLayout.yMin = newLayout.yMax - (newLayout.width / m_InitialAspectRatio);
}
}
m_ResizeTarget.layout = newLayout;
mouseMoveEvent.StopPropagation();
}
void HandleResizeFromTopLeft(MouseMoveEvent mouseMoveEvent)
{
if (!m_Dragging)
{
return;
}
Vector2 restrictedMousePosition = m_ResizeTarget.parent.WorldToLocal(mouseMoveEvent.mousePosition);
restrictedMousePosition.x = Mathf.Min(restrictedMousePosition.x, m_ResizeBeginLayout.xMax - GetMinSize().x);
restrictedMousePosition.y = Mathf.Min(restrictedMousePosition.y, m_ResizeBeginLayout.yMax - GetMinSize().y);
if (stayWithinParentBounds)
{
restrictedMousePosition.x = Mathf.Max(restrictedMousePosition.x, 0f);
restrictedMousePosition.y = Mathf.Max(restrictedMousePosition.y, 0f);
}
Vector2 delta = restrictedMousePosition - m_ResizeBeginMousePosition;
Rect newLayout = m_ResizeBeginLayout;
newLayout.xMin += delta.x;
newLayout.yMin += delta.y;
if (maintainAspectRatio)
{
if (newLayout.width < newLayout.height * m_InitialAspectRatio)
{
newLayout.yMin = Mathf.Min(newLayout.yMax - newLayout.width / m_InitialAspectRatio, newLayout.yMax - GetMinSize().y);
}
else
{
newLayout.xMin = Mathf.Min(newLayout.xMax - newLayout.height * m_InitialAspectRatio, newLayout.xMax - GetMinSize().x);
}
}
m_ResizeTarget.layout = newLayout;
mouseMoveEvent.StopPropagation();
}
void HandleMouseDown(MouseDownEvent mouseDownEvent)
{
m_Dragging = true;
m_DockingLeft = m_ResizeTarget.layout.center.x / m_ResizeTarget.parent.layout.width < .5f;
m_DockingTop = m_ResizeTarget.layout.center.y / m_ResizeTarget.parent.layout.height < .5f;
m_ResizeBeginLayout = m_ResizeTarget.layout;
m_ResizeBeginMousePosition = m_ResizeTarget.parent.WorldToLocal(mouseDownEvent.mousePosition);
m_Dragging = true;
this.TakeMouseCapture();
mouseDownEvent.StopPropagation();
}
void HandleDraggableMouseUp(MouseUpEvent mouseUpEvent)
{
m_Dragging = false;
if (this.HasMouseCapture())
{
this.ReleaseMouseCapture();
}
if (OnResizeFinished != null)
{
OnResizeFinished();

1
com.unity.shadergraph/Editor/Drawing/Manipulators/ResizeBorderFrame.cs


using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.UIElements;

1
com.unity.shadergraph/Editor/Drawing/Manipulators/GraphDropTarget.cs


using System.Collections.Generic;
using System.Linq;
using UnityEditor.Experimental.UIElements.GraphView;
using UnityEditor.MemoryProfiler;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using Object = UnityEngine.Object;

2
com.unity.shadergraph/Editor/Drawing/Manipulators/Draggable.cs


using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.UIElements;

66
com.unity.shadergraph/Editor/Drawing/Inspector/MasterPreviewView.cs


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

using UnityEditor.Graphing;
using UnityEngine.Experimental.UIElements.StyleSheets;
using Object = UnityEngine.Object;
namespace UnityEditor.ShaderGraph.Drawing.Inspector

PreviewManager m_PreviewManager;
PreviewTextureView m_PreviewTextureView;
Image m_PreviewTextureView;
MasterNode m_MasterNode;
IMasterNode m_MasterNode;
Mesh m_PreviousMesh;
List<string> m_DoNotShowPrimitives = new List<string>( new string[] {PrimitiveType.Plane.ToString()});

public MasterPreviewView(string assetName, PreviewManager previewManager, AbstractMaterialGraph graph)
{
this.clippingOptions = ClippingOptions.ClipAndCacheContents;
m_PreviewManager = previewManager;
m_PreviewRenderHandle.onPreviewChanged += OnPreviewChanged;
var topContainer = new VisualElement() { name = "top" };
{

var middleContainer = new VisualElement {name = "middle"};
{
m_PreviewTextureView = new PreviewTextureView { name = "preview", image = Texture2D.blackTexture };
m_PreviewTextureView.AddManipulator(new Draggable(OnMouseDragPreviewMesh, true));
m_PreviewTextureView.AddManipulator((IManipulator)Activator.CreateInstance(s_ContextualMenuManipulator, (Action<ContextualMenuPopulateEvent>)BuildContextualMenu));
middleContainer.Add(m_PreviewTextureView);
m_PreviewTextureView = CreatePreview(Texture2D.blackTexture);
m_PreviewRenderHandle.onPreviewChanged += OnPreviewChanged;
void OnScroll(float scrollValue)
Image CreatePreview(Texture texture)
float rescaleAmount = -scrollValue * .03f;
m_Graph.previewData.scale = Mathf.Clamp(m_Graph.previewData.scale + rescaleAmount, 0.2f, 5f);
var image = new Image { name = "preview", image = StyleValue<Texture>.Create(m_PreviewRenderHandle.texture ?? texture) };
image.AddManipulator(new Draggable(OnMouseDragPreviewMesh, true));
image.AddManipulator((IManipulator)Activator.CreateInstance(s_ContextualMenuManipulator, (Action<ContextualMenuPopulateEvent>)BuildContextualMenu));
return image;
}
void BuildContextualMenu(ContextualMenuPopulateEvent evt)

evt.menu.AppendAction("Custom Mesh", e => ChangeMeshCustom(), ContextualMenu.MenuAction.AlwaysEnabled);
}
MasterNode masterNode
IMasterNode masterNode
get { return m_PreviewRenderHandle.shaderData.node as MasterNode; }
get { return m_PreviewRenderHandle.shaderData != null ? m_PreviewRenderHandle.shaderData.node as IMasterNode : null; }
}
void DirtyMasterNode(ModificationScope scope)
{
var amn = masterNode as AbstractMaterialNode;
if (amn != null)
amn.Dirty(scope);
m_PreviewTextureView.image = m_PreviewRenderHandle.texture ?? Texture2D.blackTexture;
m_PreviewTextureView.image = StyleValue<Texture>.Create(m_PreviewRenderHandle.texture ?? Texture2D.blackTexture);
m_PreviewTextureView.Dirty(ChangeType.Repaint);
}

{
Mesh changedMesh = mesh;
masterNode.Dirty(ModificationScope.Node);
DirtyMasterNode(ModificationScope.Node);
if (m_Graph.previewData.serializedMesh.mesh != changedMesh)
{

public void RefreshRenderTextureSize()
{
RenderTextureDescriptor descriptor = m_PreviewRenderHandle.renderTexture.descriptor;
var currentWidth = m_PreviewRenderHandle.texture != null ? m_PreviewRenderHandle.texture.width : -1;
var currentHeight = m_PreviewRenderHandle.texture != null ? m_PreviewRenderHandle.texture.height : -1;
if (Mathf.Approximately(descriptor.width, targetHeight) && Mathf.Approximately(descriptor.height, targetWidth))
{
if (Mathf.Approximately(currentWidth, targetHeight) && Mathf.Approximately(currentHeight, targetWidth))
}
descriptor.width = (int)m_PreviewTextureView.contentRect.width;
descriptor.height = (int)m_PreviewTextureView.contentRect.height;
m_PreviewRenderHandle.renderTexture.Release();
Object.DestroyImmediate(m_PreviewRenderHandle.renderTexture);
m_PreviewRenderHandle.renderTexture = new RenderTexture(descriptor);
m_PreviewManager.ResizeMasterPreview(m_PreviewTextureView.contentRect.size);
}
public void UpdateRenderTextureOnNextLayoutChange()

RefreshRenderTextureSize();
}
void OnScroll(float scrollValue)
{
float rescaleAmount = -scrollValue * .03f;
m_Graph.previewData.scale = Mathf.Clamp(m_Graph.previewData.scale + rescaleAmount, 0.2f, 5f);
DirtyMasterNode(ModificationScope.Node);
}
void OnMouseDragPreviewMesh(Vector2 deltaMouse)
{
Vector2 previewSize = m_PreviewTextureView.contentRect.size;

Quaternion previewRotation = Quaternion.Euler(m_PreviewScrollPosition.y, 0, 0) * Quaternion.Euler(0, m_PreviewScrollPosition.x, 0);
m_Graph.previewData.rotation = previewRotation;
masterNode.Dirty(ModificationScope.Node);
DirtyMasterNode(ModificationScope.Node);
}
}
}

2
com.unity.shadergraph/Editor/Drawing/Controls/VectorControl.cs


using UnityEditor.Experimental.UIElements;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph.Drawing.Controls
{

3
com.unity.shadergraph/Editor/Drawing/Controls/ToggleControl.cs


using System;
using System.Reflection;
using UnityEditor.Graphing;
using UnityEditor.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph.Drawing.Controls
{

2
com.unity.shadergraph/Editor/Drawing/Controls/TextureControl.cs


using UnityEditor.Experimental.UIElements;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph.Drawing.Controls
{

9
com.unity.shadergraph/Editor/Drawing/Controls/SliderControl.cs


public class SliderControlView : VisualElement, INodeModificationListener
{
GUIContent m_Label;
AbstractMaterialNode m_Node;
PropertyInfo m_PropertyInfo;
bool m_DisplayMinMax;

VisualElement m_SliderPanel;
Slider m_Slider;
FloatField m_SliderInput;
FloatField m_MinField;
FloatField m_MaxField;
public SliderControlView(string label, bool displayMinMax, AbstractMaterialNode node, PropertyInfo propertyInfo)
{

if (propertyInfo.PropertyType != typeof(Vector3))
throw new ArgumentException("Property must be of type Vector3.", "propertyInfo");
m_Label = new GUIContent(label ?? ObjectNames.NicifyVariableName(propertyInfo.Name));
new GUIContent(label ?? ObjectNames.NicifyVariableName(propertyInfo.Name));
m_Value = (Vector3)m_PropertyInfo.GetValue(m_Node, null);
m_SliderPanel = new VisualElement { name = "SliderPanel" };

if(m_DisplayMinMax)
{
var fieldsPanel = new VisualElement { name = "FieldsPanel" };
m_MinField = AddField(fieldsPanel, "Min", 1, m_Value);
m_MaxField = AddField(fieldsPanel, "Max", 2, m_Value);
AddField(fieldsPanel, "Min", 1, m_Value);
AddField(fieldsPanel, "Max", 2, m_Value);
Add(fieldsPanel);
}
}

2
com.unity.shadergraph/Editor/Drawing/Controls/CubemapControl.cs


using UnityEditor.Experimental.UIElements;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph.Drawing.Controls
{

2
com.unity.shadergraph/Editor/Drawing/Controls/ColorControl.cs


using UnityEditor.Experimental.UIElements;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEditor.ShaderGraph;
using Color = UnityEditor.ShaderGraph.ColorNode.Color;
namespace UnityEditor.ShaderGraph.Drawing.Controls

3
com.unity.shadergraph/Editor/Drawing/Controls/ChannelMixerControl.cs


using System;
using System.Reflection;
using UnityEditor.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph.Drawing.Controls
{

1
com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardSection.cs


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

3
com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs


{
class BlackboardProvider
{
readonly string m_AssetName;
readonly AbstractMaterialGraph m_Graph;
readonly Texture2D m_ExposedIcon;
readonly Dictionary<Guid, BlackboardRow> m_PropertyRows;

public BlackboardProvider(string assetName, AbstractMaterialGraph graph)
{
m_AssetName = assetName;
m_Graph = graph;
m_ExposedIcon = Resources.Load("GraphView/Nodes/BlackboardFieldExposed") as Texture2D;
m_PropertyRows = new Dictionary<Guid, BlackboardRow>();

blackboard.AddManipulator(m_WindowDraggable);
m_ResizeBorderFrame = new ResizeBorderFrame(blackboard) { name = "resizeBorderFrame" };
m_ResizeBorderFrame.stayWithinParentBounds = true;
blackboard.shadow.Add(m_ResizeBorderFrame);
m_Section = new BlackboardSection { headerVisible = false };

7
com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardField.cs


if (dropTarget == null || !dropTarget.CanAcceptDrop(selection))
return;
var propagation = EventPropagation.Continue;
propagation = dropTarget.DragUpdated(evt, selection, dropTarget);
dropTarget.DragUpdated(evt, selection, dropTarget);
propagation = dropTarget.DragPerform(evt, selection, dropTarget);
dropTarget.DragPerform(evt, selection, dropTarget);
propagation = dropTarget.DragExited();
dropTarget.DragExited();
// if (propagation == EventPropagation.Stop)
// evt.StopPropagation();

28
com.unity.shadergraph/Editor/DefaultShaderIncludes.cs


using System.IO;
using System.Linq;
using UnityEngine;
public static string GetAssetsPackagePath()
{
var packageDirectories = Directory.GetDirectories(Application.dataPath, "com.unity.shadergraph", SearchOption.AllDirectories);
return packageDirectories.Length == 0 ? null : Path.GetFullPath(packageDirectories.First());
}
public static string GetRepositoryPath()
{
var path = GetAssetsPackagePath();
if (path == null)
return null;
return Path.GetFullPath(Directory.GetParent(path).ToString());
}
public static string GetDebugOutputPath()
{
var path = GetRepositoryPath();
if (path == null)
return null;
path = Path.Combine(path, "DebugOutput");
return Directory.Exists(path) ? path : null;
}
Path.GetFullPath("Assets/UnityShaderEditor"),
Path.GetFullPath("Packages/com.unity.shadergraph"),
GetAssetsPackagePath() ?? Path.GetFullPath("Packages/com.unity.shadergraph")
};
}
}

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


{
var path = new List<string>
{
Application.dataPath,
"UnityShaderEditor",
DefaultShaderIncludes.GetAssetsPackagePath() ?? Path.GetFullPath("Packages/com.unity.shadergraph"),
"Editor",
"Templates"
};

if (File.Exists(result))
return result;
//todo: fix this up... quick hack for working
// in a package
var path2 = new List<string>
{
"Packages",
"com.unity.shadergraph",
"Editor",
"Templates"
};
string result2 = path2[0];
for (int i = 1; i < path2.Count; i++)
result2 = Path.Combine(result2, path2[i]);
result2 = Path.Combine(result2, templateName);
result2 = Path.GetFullPath(result2);
if (File.Exists(result2))
return result2;
return string.Empty;
}

default:
return kErrorString;
}
case ConcreteSlotValueType.Matrix3:
return rawOutput;
case ConcreteSlotValueType.Matrix2:
return rawOutput;
default:
return kErrorString;
}

return res;
}
public static SurfaceMaterialOptions GetMaterialOptionsFromAlphaMode(AlphaMode alphaMode)
{
var materialOptions = new SurfaceMaterialOptions();
switch (alphaMode)
{
case AlphaMode.Opaque:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.Zero;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.On;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Geometry;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Opaque;
break;
case AlphaMode.AlphaBlend:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.SrcAlpha;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.OneMinusSrcAlpha;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
case AlphaMode.AdditiveBlend:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
}
return materialOptions;
}
private const string subShaderTemplate = @"
SubShader
{

}
}";
}
}

1
com.unity.shadergraph/Editor/Data/Util/SerializationHelper.cs


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

1
com.unity.shadergraph/Editor/Data/Util/Logging.cs


using System;
using UnityEngine;
using Object = System.Object;
namespace UnityEditor.Graphing
{

1
com.unity.shadergraph/Editor/Data/Util/CubemapPropertyChunk.cs


using System;
using System.Text;
namespace UnityEditor.ShaderGraph
{

1
com.unity.shadergraph/Editor/Data/SubGraph/SubGraph.cs


{
foreach (var node in activeNodes)
{
node.ValidateNode();
if (node is IGeneratesFunction)
(node as IGeneratesFunction).GenerateNodeFunction(registry, generationMode);
}

2
com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/OrNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

2
com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NotNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

2
com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NandNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

4
com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsNanNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

return
@"
{
Out = isnan(In);
Out = (In < 0.0 || In > 0.0 || In == 0.0) ? 0 : 1;
}
";
}

2
com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsInfiniteNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

2
com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/BranchNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

2
com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AnyNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

2
com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AndNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

2
com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AllNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

1
com.unity.shadergraph/Editor/Data/Nodes/UV/TwirlNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{

128
com.unity.shadergraph/Editor/Data/Nodes/UV/TriplanarNode.cs


namespace UnityEditor.ShaderGraph
{
[Title("UV", "Triplanar")]
public class TriplanarNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequirePosition, IMayRequireNormal
public class TriplanarNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent, IMayRequireBitangent
{
public const int OutputSlotId = 0;
public const int TextureInputId = 1;

sb.AppendLine("{0}3 {1}_UV = {2} * {3};", precision, GetVariableNameForNode(),
GetSlotValue(PositionInputId, generationMode), GetSlotValue(TileInputId, generationMode));
sb.AppendLine("{0}3 {1}_Blend = pow(abs({2}), {3});", precision, GetVariableNameForNode(),
GetSlotValue(NormalInputId, generationMode), GetSlotValue(BlendInputId, generationMode));
sb.AppendLine("{0}_Blend /= dot({0}_Blend, 1.0);", GetVariableNameForNode());
sb.AppendLine("{0}4 {1}_X = SAMPLE_TEXTURE2D({2}, {3}, {1}_UV.yz);"
, precision
, GetVariableNameForNode()
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id);
sb.AppendLine("{0}4 {1}_Y = SAMPLE_TEXTURE2D({2}, {3}, {1}_UV.xz);"
, precision
, GetVariableNameForNode()
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id);
switch(textureType)
{
// Whiteout blend method
// https://medium.com/@bgolus/normal-mapping-for-a-triplanar-shader-10bf39dca05a
case TextureType.Normal:
sb.AppendLine("{0}3 {1}_Blend = max(pow(abs({2}), {3}), 0);", precision, GetVariableNameForNode(),
GetSlotValue(NormalInputId, generationMode), GetSlotValue(BlendInputId, generationMode));
sb.AppendLine("{0}_Blend /= ({0}_Blend.x + {0}_Blend.y + {0}_Blend.z ).xxx;", GetVariableNameForNode());
sb.AppendLine("{0}3 {1}_X = UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D({2}, {3}, {1}_UV.zy));"
, precision
, GetVariableNameForNode()
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id);
sb.AppendLine("{0}3 {1}_Y = UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D({2}, {3}, {1}_UV.xz));"
, precision
, GetVariableNameForNode()
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id);
sb.AppendLine("{0}4 {1}_Z = SAMPLE_TEXTURE2D({2}, {3}, {1}_UV.xy);"
, precision
, GetVariableNameForNode()
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id);
sb.AppendLine("{0}3 {1}_Z = UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D({2}, {3}, {1}_UV.xy));"
, precision
, GetVariableNameForNode()
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id);
sb.AppendLine("{0}4 {1} = {2}_X * {2}_Blend.x + {2}_Y * {2}_Blend.y + {2}_Z * {2}_Blend.z;"
, precision
, GetVariableNameForSlot(OutputSlotId)
, GetVariableNameForNode());
sb.AppendLine("{0}_X = {1}3({0}_X.xy + {2}.zy, abs({0}_X.z) * {2}.x);"
, GetVariableNameForNode()
, precision
, GetSlotValue(NormalInputId, generationMode));
if (textureType == TextureType.Normal)
sb.AppendLine("{0}.rgb = UnpackNormalmapRGorAG({0});", GetVariableNameForSlot(OutputSlotId));
sb.AppendLine("{0}_Y = {1}3({0}_Y.xy + {2}.xz, abs({0}_Y.z) * {2}.y);"
, GetVariableNameForNode()
, precision
, GetSlotValue(NormalInputId, generationMode));
sb.AppendLine("{0}_Z = {1}3({0}_Z.xy + {2}.xy, abs({0}_Z.z) * {2}.z);"
, GetVariableNameForNode()
, precision
, GetSlotValue(NormalInputId, generationMode));
sb.AppendLine("{0}4 {1} = {0}4(normalize({2}_X.zyx * {2}_Blend.x + {2}_Y.xzy * {2}_Blend.y + {2}_Z.xyz * {2}_Blend.z), 1);"
, precision
, GetVariableNameForSlot(OutputSlotId)
, GetVariableNameForNode());
sb.AppendLine("float3x3 {0}_Transform = float3x3(IN.WorldSpaceTangent, IN.WorldSpaceBiTangent, IN.WorldSpaceNormal);", GetVariableNameForNode());
sb.AppendLine("{0}.rgb = TransformWorldToTangent({0}.rgb, {1}_Transform);"
, GetVariableNameForSlot(OutputSlotId)
, GetVariableNameForNode());
break;
default:
sb.AppendLine("{0}3 {1}_Blend = pow(abs({2}), {3});", precision, GetVariableNameForNode(),
GetSlotValue(NormalInputId, generationMode), GetSlotValue(BlendInputId, generationMode));
sb.AppendLine("{0}_Blend /= dot({0}_Blend, 1.0);", GetVariableNameForNode());
sb.AppendLine("{0}4 {1}_X = SAMPLE_TEXTURE2D({2}, {3}, {1}_UV.zy);"
, precision
, GetVariableNameForNode()
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id);
sb.AppendLine("{0}4 {1}_Y = SAMPLE_TEXTURE2D({2}, {3}, {1}_UV.xz);"
, precision
, GetVariableNameForNode()
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id);
sb.AppendLine("{0}4 {1}_Z = SAMPLE_TEXTURE2D({2}, {3}, {1}_UV.xy);"
, precision
, GetVariableNameForNode()
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id);
sb.AppendLine("{0}4 {1} = {2}_X * {2}_Blend.x + {2}_Y * {2}_Blend.y + {2}_Z * {2}_Blend.z;"
, precision
, GetVariableNameForSlot(OutputSlotId)
, GetVariableNameForNode());
break;
}
public NeededCoordinateSpace RequiresPosition()
{
return CoordinateSpace.World.ToNeededCoordinateSpace();

{
return CoordinateSpace.World.ToNeededCoordinateSpace();
}
public NeededCoordinateSpace RequiresTangent()
{
switch(m_TextureType)
{
case TextureType.Normal:
return CoordinateSpace.World.ToNeededCoordinateSpace();
default:
return NeededCoordinateSpace.None;
}
}
public NeededCoordinateSpace RequiresBitangent()
{
switch(m_TextureType)
{
case TextureType.Normal:
return CoordinateSpace.World.ToNeededCoordinateSpace();
default:
return NeededCoordinateSpace.None;
}
}
}
}

32
com.unity.shadergraph/Editor/Data/Nodes/SlotValue.cs


public enum SlotValueType
{
SamplerState,
DynamicMatrix,
Dynamic,
DynamicVector,
Dynamic,
Boolean
}

return 1;
default:
return 0;
}
}
public static int GetMatrixDimension(ConcreteSlotValueType type)
{
switch (type)
{
case ConcreteSlotValueType.Matrix4:
return 4;
case ConcreteSlotValueType.Matrix3:
return 3;
case ConcreteSlotValueType.Matrix2:
return 2;
default:
return 0;
}
}
public static ConcreteSlotValueType ConvertMatrixToVectorType(ConcreteSlotValueType matrixType)
{
switch(matrixType)
{
case ConcreteSlotValueType.Matrix4:
return ConcreteSlotValueType.Vector4;
case ConcreteSlotValueType.Matrix3:
return ConcreteSlotValueType.Vector3;
default:
return ConcreteSlotValueType.Vector2;
}
}

2
com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/TransformNode.cs


if (requiresTransposeTangentTransform)
visitor.AddShaderChunk(string.Format("float3x3 {0} = transpose(float3x3(IN.{1}SpaceTangent, IN.{1}SpaceBiTangent, IN.{1}SpaceNormal));", transposeTargetTransformString, CoordinateSpace.World.ToString()), true);
else if (requiresTangentTransform)
visitor.AddShaderChunk(string.Format("float3x3 {0} = CreateWorldToTangent(IN.{1}SpaceNormal, IN.{1}SpaceTangent, 1);", targetTransformString, tangentTransformSpace), true);
visitor.AddShaderChunk(string.Format("float3x3 {0} = float3x3(IN.{1}SpaceTangent, IN.{1}SpaceBiTangent, IN.{1}SpaceNormal);", targetTransformString, tangentTransformSpace), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2};", NodeUtils.ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType),
GetVariableNameForSlot(OutputSlotId),
transformString), true);

7
com.unity.shadergraph/Editor/Data/Nodes/Math/Round/StepNode.cs


using System.Linq.Expressions;
using System.Reflection;
namespace UnityEditor.ShaderGraph

}
static string Unity_Step(
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector A,
[Slot(1, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector B,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector Edge,
[Slot(1, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector In,
Out = step(A, B);
Out = step(Edge, In);
}
";
}

5
com.unity.shadergraph/Editor/Data/Nodes/Math/Range/SaturateNode.cs


name = "Saturate";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Saturate-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_Saturate", BindingFlags.Static | BindingFlags.NonPublic);

5
com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RemapNode.cs


name = "Remap";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Remap-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_Remap", BindingFlags.Static | BindingFlags.NonPublic);

5
com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RandomRangeNode.cs


name = "Random Range";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Random-Range-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_RandomRange", BindingFlags.Static | BindingFlags.NonPublic);

5
com.unity.shadergraph/Editor/Data/Nodes/Math/Range/OneMinusNode.cs


name = "One Minus";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/One-Minus-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_OneMinus", BindingFlags.Static | BindingFlags.NonPublic);

5
com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MinimumNode.cs


name = "Minimum";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Minimum-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_Minimum", BindingFlags.Static | BindingFlags.NonPublic);

5
com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MaximumNode.cs


name = "Maximum";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Maximum-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_Maximum", BindingFlags.Static | BindingFlags.NonPublic);

5
com.unity.shadergraph/Editor/Data/Nodes/Math/Range/FractionNode.cs


name = "Fraction";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Fraction-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_Fraction", BindingFlags.Static | BindingFlags.NonPublic);

5
com.unity.shadergraph/Editor/Data/Nodes/Math/Range/ClampNode.cs


name = "Clamp";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Clamp-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_Clamp", BindingFlags.Static | BindingFlags.NonPublic);

20
com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixTransposeNode.cs


namespace UnityEditor.ShaderGraph
{
[Title("Math", "Matrix", "TransposeMatrix")]
[Title("Math", "Matrix", "Matrix Transpose")]
name = "TransposeMatrix";
name = "Matrix Transpose";
}
public override bool hasPreview
{
get { return false; }
return GetType().GetMethod("unity_MatrixTranspose_", BindingFlags.Static | BindingFlags.NonPublic);
return GetType().GetMethod("Unity_MatrixTranspose", BindingFlags.Static | BindingFlags.NonPublic);
static string unity_MatrixTranspose_(
[Slot(0, Binding.None)] Matrix4x4 inMatrix,
[Slot(1, Binding.None)] out Matrix4x4 outMatrix)
static string Unity_MatrixTranspose(
[Slot(0, Binding.None)] DynamicDimensionMatrix In,
[Slot(1, Binding.None)] out DynamicDimensionMatrix Out)
outMatrix = Matrix4x4.identity;
outMatrix = transpose(inMatrix);
Out = transpose(In);
}
";
}

13
com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/SmoothstepNode.cs


name = "Smoothstep";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Smoothstep-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_Smoothstep", BindingFlags.Static | BindingFlags.NonPublic);

[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector B,
[Slot(2, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector T,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector Edge1,
[Slot(1, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector Edge2,
[Slot(2, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector In,
Out = smoothstep(A, B, T);
Out = smoothstep(Edge1, Edge2, In);
}";
}
}

5
com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/LerpNode.cs


name = "Lerp";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Lerp-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_Lerp", BindingFlags.Static | BindingFlags.NonPublic);

5
com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/InverseLerpNode.cs


name = "Inverse Lerp";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Inverse-Lerp-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_InverseLerp", BindingFlags.Static | BindingFlags.NonPublic);

7
com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDYNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{

public DDYNode()
{
name = "DDY";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/DDY-Node"; }
}
protected override MethodInfo GetFunctionToConvert()

7
com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXYNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{

public DDXYNode()
{
name = "DDXY";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/DDXY-Node"; }
}
protected override MethodInfo GetFunctionToConvert()

7
com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{

public DDXNode()
{
name = "DDX";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/DDX-Node"; }
}
protected override MethodInfo GetFunctionToConvert()

377
com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/MultiplyNode.cs


using System.Reflection;
//using System.Reflection;
using System;
using System.Collections.Generic;
using UnityEditor.Graphing;
using UnityEngine;
using System.Linq;
public class MultiplyNode : CodeFunctionNode
public class MultiplyNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction
UpdateNodeAfterDeserialization();
}
public override string documentationURL

protected override MethodInfo GetFunctionToConvert()
const int Input1SlotId = 0;
const int Input2SlotId = 1;
const int OutputSlotId = 2;
const string kInput1SlotName = "A";
const string kInput2SlotName = "B";
const string kOutputSlotName = "Out";
public enum MultiplyType
{
Vector,
Matrix,
Mixed
}
MultiplyType m_MultiplyType;
public override bool hasPreview
{
get { return m_MultiplyType != MultiplyType.Matrix; }
}
string GetFunctionHeader()
{
return string.Format("Unity_Multiply_{0}", precision);
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new DynamicValueMaterialSlot(Input1SlotId, kInput1SlotName, kInput1SlotName, SlotType.Input, Matrix4x4.zero));
AddSlot(new DynamicValueMaterialSlot(Input2SlotId, kInput2SlotName, kInput2SlotName, SlotType.Input, new Matrix4x4(new Vector4(2,2,2,2), Vector4.zero, Vector4.zero, Vector4.zero)));
AddSlot(new DynamicValueMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Matrix4x4.zero));
RemoveSlotsNameNotMatching(new[] { Input1SlotId, Input2SlotId, OutputSlotId });
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
var sb = new ShaderStringBuilder();
var input1Value = GetSlotValue(Input1SlotId, generationMode);
var input2Value = GetSlotValue(Input2SlotId, generationMode);
var outputValue = GetSlotValue(OutputSlotId, generationMode);
sb.AppendLine("{0} {1};", NodeUtils.ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType), GetVariableNameForSlot(OutputSlotId));
sb.AppendLine("{0}({1}, {2}, {3});", GetFunctionHeader(), input1Value, input2Value, outputValue);
visitor.AddShaderChunk(sb.ToString(), false);
}
string GetFunctionName()
{
return string.Format("{0}_{1}_{2}",
GetFunctionHeader(),
FindInputSlot<MaterialSlot>(Input1SlotId).concreteValueType.ToString(precision),
FindInputSlot<MaterialSlot>(Input2SlotId).concreteValueType.ToString(precision));
}
public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode)
{
registry.ProvideFunction(GetFunctionName(), s =>
{
s.AppendLine("void {0} ({1} A, {2} B, out {3} Out)",
GetFunctionHeader(),
FindInputSlot<MaterialSlot>(Input1SlotId).concreteValueType.ToString(precision),
FindInputSlot<MaterialSlot>(Input2SlotId).concreteValueType.ToString(precision),
FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision));
using (s.BlockScope())
{
switch(m_MultiplyType)
{
case MultiplyType.Vector:
s.AppendLine("Out = A * B;");
break;
default:
s.AppendLine("Out = mul(A, B);");
break;
}
}
});
}
// Internal validation
// -------------------------------------------------
public override void ValidateNode()
{
var isInError = false;
// all children nodes needs to be updated first
// so do that here
var slots = ListPool<MaterialSlot>.Get();
GetInputSlots(slots);
foreach (var inputSlot in slots)
{
inputSlot.hasError = false;
var edges = owner.GetEdges(inputSlot.slotReference);
foreach (var edge in edges)
{
var fromSocketRef = edge.outputSlot;
var outputNode = owner.GetNodeFromGuid(fromSocketRef.nodeGuid);
if (outputNode == null)
continue;
outputNode.ValidateNode();
if (outputNode.hasError)
isInError = true;
}
}
ListPool<MaterialSlot>.Release(slots);
var dynamicInputSlotsToCompare = DictionaryPool<DynamicValueMaterialSlot, ConcreteSlotValueType>.Get();
var skippedDynamicSlots = ListPool<DynamicValueMaterialSlot>.Get();
// iterate the input slots
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
foreach (var inputSlot in s_TempSlots)
{
// if there is a connection
var edges = owner.GetEdges(inputSlot.slotReference).ToList();
if (!edges.Any())
{
if (inputSlot is DynamicValueMaterialSlot)
skippedDynamicSlots.Add(inputSlot as DynamicValueMaterialSlot);
continue;
}
// get the output details
var outputSlotRef = edges[0].outputSlot;
var outputNode = owner.GetNodeFromGuid(outputSlotRef.nodeGuid);
if (outputNode == null)
continue;
var outputSlot = outputNode.FindOutputSlot<MaterialSlot>(outputSlotRef.slotId);
if (outputSlot == null)
continue;
if (outputSlot.hasError)
{
inputSlot.hasError = true;
continue;
}
var outputConcreteType = outputSlot.concreteValueType;
// dynamic input... depends on output from other node.
// we need to compare ALL dynamic inputs to make sure they
// are compatable.
if (inputSlot is DynamicValueMaterialSlot)
{
dynamicInputSlotsToCompare.Add((DynamicValueMaterialSlot)inputSlot, outputConcreteType);
continue;
}
// if we have a standard connection... just check the types work!
if (!ImplicitConversionExists(outputConcreteType, inputSlot.concreteValueType))
inputSlot.hasError = true;
}
m_MultiplyType = GetMultiplyType(dynamicInputSlotsToCompare.Values);
// Resolve dynamics depending on matrix/vector configuration
switch(m_MultiplyType)
{
// If all matrix resolve as per dynamic matrix
case MultiplyType.Matrix:
var dynamicMatrixType = ConvertDynamicMatrixInputTypeToConcrete(dynamicInputSlotsToCompare.Values);
foreach (var dynamicKvP in dynamicInputSlotsToCompare)
dynamicKvP.Key.SetConcreteType(dynamicMatrixType);
foreach (var skippedSlot in skippedDynamicSlots)
skippedSlot.SetConcreteType(dynamicMatrixType);
break;
// If mixed handle differently:
// Iterate all slots and set their concretes based on their edges
// Find matrix slot and convert its type to a vector type
// Reiterate all slots and set non matrix slots to the vector type
case MultiplyType.Mixed:
foreach (var dynamicKvP in dynamicInputSlotsToCompare)
{
SetConcreteValueTypeFromEdge(dynamicKvP.Key);
}
MaterialSlot matrixSlot = GetMatrixSlot();
ConcreteSlotValueType vectorType = SlotValueHelper.ConvertMatrixToVectorType(matrixSlot.concreteValueType);
foreach (var dynamicKvP in dynamicInputSlotsToCompare)
{
if(dynamicKvP.Key != matrixSlot)
dynamicKvP.Key.SetConcreteType(vectorType);
}
foreach (var skippedSlot in skippedDynamicSlots)
{
skippedSlot.SetConcreteType(vectorType);
}
break;
// If all vector resolve as per dynamic vector
default:
var dynamicVectorType = ConvertDynamicInputTypeToConcrete(dynamicInputSlotsToCompare.Values);
foreach (var dynamicKvP in dynamicInputSlotsToCompare)
dynamicKvP.Key.SetConcreteType(dynamicVectorType);
foreach (var skippedSlot in skippedDynamicSlots)
skippedSlot.SetConcreteType(dynamicVectorType);
break;
}
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
var inputError = s_TempSlots.Any(x => x.hasError);
// configure the output slots now
// their slotType will either be the default output slotType
// or the above dynanic slotType for dynamic nodes
// or error if there is an input error
s_TempSlots.Clear();
GetOutputSlots(s_TempSlots);
foreach (var outputSlot in s_TempSlots)
{
outputSlot.hasError = false;
if (inputError)
{
outputSlot.hasError = true;
continue;
}
if (outputSlot is DynamicValueMaterialSlot)
{
// Apply similar logic to output slot
switch(m_MultiplyType)
{
// As per dynamic matrix
case MultiplyType.Matrix:
var dynamicMatrixType = ConvertDynamicMatrixInputTypeToConcrete(dynamicInputSlotsToCompare.Values);
(outputSlot as DynamicValueMaterialSlot).SetConcreteType(dynamicMatrixType);
break;
// Mixed configuration
// Find matrix slot and convert type to vector
// Set output concrete to vector
case MultiplyType.Mixed:
MaterialSlot matrixSlot = GetMatrixSlot();
ConcreteSlotValueType vectorType = SlotValueHelper.ConvertMatrixToVectorType(matrixSlot.concreteValueType);
(outputSlot as DynamicValueMaterialSlot).SetConcreteType(vectorType);
break;
// As per dynamic vector
default:
var dynamicVectorType = ConvertDynamicInputTypeToConcrete(dynamicInputSlotsToCompare.Values);
(outputSlot as DynamicValueMaterialSlot).SetConcreteType(dynamicVectorType);
break;
}
continue;
}
}
isInError |= inputError;
s_TempSlots.Clear();
GetOutputSlots(s_TempSlots);
isInError |= s_TempSlots.Any(x => x.hasError);
isInError |= CalculateNodeHasError();
hasError = isInError;
if (!hasError)
{
++version;
}
ListPool<DynamicValueMaterialSlot>.Release(skippedDynamicSlots);
DictionaryPool<DynamicValueMaterialSlot, ConcreteSlotValueType>.Release(dynamicInputSlotsToCompare);
}
protected override bool CalculateNodeHasError()
return GetType().GetMethod("Unity_Multiply", BindingFlags.Static | BindingFlags.NonPublic);
if(m_MultiplyType == MultiplyType.Matrix)
{
foreach (var slot in this.GetOutputSlots<ISlot>())
{
foreach (var edge in owner.GetEdges(slot.slotReference))
{
var inputNode = owner.GetNodeFromGuid(edge.inputSlot.nodeGuid);
List<MaterialSlot> slots = new List<MaterialSlot>();
inputNode.GetInputSlots(slots);
foreach(var s in slots)
{
foreach(var inputEdge in inputNode.owner.GetEdges(s.slotReference))
{
if(inputEdge == edge)
{
if(s as DynamicValueMaterialSlot == null)
{
if(s.concreteValueType != ConcreteSlotValueType.Matrix4
&& s.concreteValueType != ConcreteSlotValueType.Matrix3
&& s.concreteValueType != ConcreteSlotValueType.Matrix2)
{
Debug.Log("ERROR: slot "+s.displayName+" cannot accept a Matrix type input");
return true;
}
}
}
}
}
}
}
}
return false;
static string Unity_Multiply(
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 2, 2, 2, 2)] DynamicDimensionVector B,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
private MultiplyType GetMultiplyType(IEnumerable<ConcreteSlotValueType> inputTypes)
return
@"
{
Out = A * B;
}
";
var concreteSlotValueTypes = inputTypes as List<ConcreteSlotValueType> ?? inputTypes.ToList();
int matrixCount = 0;
int vectorCount = 0;
for (int i = 0; i < concreteSlotValueTypes.Count; i++)
{
if(concreteSlotValueTypes[i] == ConcreteSlotValueType.Vector4
|| concreteSlotValueTypes[i] == ConcreteSlotValueType.Vector3
|| concreteSlotValueTypes[i] == ConcreteSlotValueType.Vector2
|| concreteSlotValueTypes[i] == ConcreteSlotValueType.Vector1)
{
vectorCount++;
}
else if(concreteSlotValueTypes[i] == ConcreteSlotValueType.Matrix4
|| concreteSlotValueTypes[i] == ConcreteSlotValueType.Matrix3
|| concreteSlotValueTypes[i] == ConcreteSlotValueType.Matrix2)
{
matrixCount++;
}
}
if(matrixCount == 2)
return MultiplyType.Matrix;
else if(vectorCount == 2)
return MultiplyType.Vector;
else if(matrixCount == 1)
return MultiplyType.Mixed;
else
return MultiplyType.Vector;
}
private MaterialSlot GetMatrixSlot()
{
List<MaterialSlot> slots = new List<MaterialSlot>();
GetInputSlots(slots);
for (int i = 0; i < slots.Count; i++)
{
var edges = owner.GetEdges(slots[i].slotReference).ToList();
if(!edges.Any())
continue;
var outputNode = owner.GetNodeFromGuid(edges[0].outputSlot.nodeGuid);
var outputSlot = outputNode.FindOutputSlot<MaterialSlot>(edges[0].outputSlot.slotId);
if(outputSlot.concreteValueType == ConcreteSlotValueType.Matrix4
|| outputSlot.concreteValueType == ConcreteSlotValueType.Matrix3
|| outputSlot.concreteValueType == ConcreteSlotValueType.Matrix2)
return slots[i];
}
return null;
}
private void SetConcreteValueTypeFromEdge(DynamicValueMaterialSlot slot)
{
var edges = owner.GetEdges(slot.slotReference).ToList();
if(!edges.Any())
return;
var outputNode = owner.GetNodeFromGuid(edges[0].outputSlot.nodeGuid);
var outputSlot = outputNode.FindOutputSlot<MaterialSlot>(edges[0].outputSlot.slotId);
slot.SetConcreteType(outputSlot.concreteValueType);
}
}
}

115
com.unity.shadergraph/Editor/Data/Nodes/MasterNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Graphing;
public abstract class MasterNode : AbstractMaterialNode, IMasterNode
public abstract class MasterNode<T> : AbstractMaterialNode, IMasterNode where T : class, ISubShader
[NonSerialized]
List<T> m_SubShaders = new List<T>();
protected SurfaceMaterialOptions m_MaterialOptions = new SurfaceMaterialOptions();
List<SerializationHelper.JSONSerializedElement> m_SerializableSubShaders = new List<SerializationHelper.JSONSerializedElement>();
public override bool hasPreview
{

get { return PreviewMode.Preview3D; }
}
public SurfaceMaterialOptions options
public Type supportedSubshaderType
{
get { return typeof(T); }
}
public IEnumerable<T> subShaders
{
get { return m_SubShaders; }
}
public void AddSubShader(T subshader)
{
if (m_SubShaders.Contains(subshader))
return;
m_SubShaders.Add(subshader);
Dirty(ModificationScope.Node);
}
public void RemoveSubShader(T subshader)
{
m_SubShaders.RemoveAll(x => x == subshader);
Dirty(ModificationScope.Node);
}
public string GetShader(GenerationMode mode, string outputName, out List<PropertyCollector.TextureInfo> configuredTextures)
{
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, this);
var shaderProperties = new PropertyCollector();
var abstractMaterialGraph = owner as AbstractMaterialGraph;
if (abstractMaterialGraph != null)
abstractMaterialGraph.CollectShaderProperties(shaderProperties, mode);
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
activeNode.CollectShaderProperties(shaderProperties, mode);
var finalShader = new ShaderGenerator();
finalShader.AddShaderChunk(string.Format(@"Shader ""{0}""", outputName), false);
finalShader.AddShaderChunk("{", false);
finalShader.Indent();
finalShader.AddShaderChunk("Properties", false);
finalShader.AddShaderChunk("{", false);
finalShader.Indent();
finalShader.AddShaderChunk(shaderProperties.GetPropertiesBlock(2), false);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
foreach (var subShader in m_SubShaders)
finalShader.AddShaderChunk(subShader.GetSubshader(this, mode), true);
finalShader.AddShaderChunk(@"FallBack ""Hidden/InternalErrorShader""", false);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
configuredTextures = shaderProperties.GetConfiguredTexutres();
return finalShader.GetShaderString(0);
}
public override void OnBeforeSerialize()
get { return m_MaterialOptions; }
base.OnBeforeSerialize();
m_SerializableSubShaders = SerializationHelper.Serialize<T>(m_SubShaders);
public abstract string GetShader(GenerationMode mode, string name, out List<PropertyCollector.TextureInfo> configuredTextures);
public static SurfaceMaterialOptions GetMaterialOptionsFromAlphaMode(AlphaMode alphaMode)
public override void OnAfterDeserialize()
var materialOptions = new SurfaceMaterialOptions();
switch (alphaMode)
{
case AlphaMode.Opaque:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.Zero;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.On;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Geometry;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Opaque;
break;
case AlphaMode.AlphaBlend:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.SrcAlpha;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.OneMinusSrcAlpha;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
case AlphaMode.AdditiveBlend:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
}
return materialOptions;
base.OnAfterDeserialize();
m_SubShaders = SerializationHelper.Deserialize<T>(m_SerializableSubShaders, GraphUtil.GetLegacyTypeRemapping());
m_SerializableSubShaders = null;
}
}
}

1
com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs


using System;
using System.Linq;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
using UnityEditor.Graphing;

1
com.unity.shadergraph/Editor/Data/Nodes/Input/PBR/MetalReflectanceNode.cs


using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Graphing;

132
com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix4Node.cs


using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
using UnityEditor.Graphing;
using System.Collections.Generic;
namespace UnityEditor.ShaderGraph
{

const int kOutputSlotId = 0;
public const int OutputSlotId = 0;
const string kOutputSlotName = "Out";
[SerializeField]

if (value == row)
return;
row = value;
Dirty(ModificationScope.Graph);
Dirty(ModificationScope.Node);
}
public Matrix4Node()

public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Matrix4MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output));
RemoveSlotsNameNotMatching(new[] { kOutputSlotId });
AddSlot(new Matrix4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
public string propertyName
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
get
if (!generationMode.IsPreview())
return;
properties.AddShaderProperty(new Vector4ShaderProperty()
return string.Format("{0}_{1}_Uniform", name, GetVariableNameForNode());
}
}
overrideReferenceName = string.Format("_{0}_m0", GetVariableNameForNode()),
generatePropertyBlock = false,
value = m_Row0
});
public override string GetVariableNameForSlot(int slotId)
{
return propertyName;
}
properties.AddShaderProperty(new Vector4ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_m1", GetVariableNameForNode()),
generatePropertyBlock = false,
value = m_Row1
});
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
//if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
// return;
properties.AddShaderProperty(new Vector4ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_m2", GetVariableNameForNode()),
generatePropertyBlock = false,
value = m_Row2
});
visitor.AddShaderChunk(precision + "4x4 " + propertyName + " = " + precision + "4x4 (" + row0.x + ", " + row0.y + ", " + row0.z + ", " + row0.w + ", " + m_Row1.x + ", " + m_Row1.y + ", " + m_Row1.z + ", " + m_Row1.w + ", " + m_Row2.x + ", " + m_Row2.y + ", " + m_Row2.z + ", " + m_Row2.w + ", " + m_Row3.x + ", " + m_Row3.y + ", " + m_Row3.z + ", " + m_Row3.w + ");", true);
properties.AddShaderProperty(new Vector4ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_m3", GetVariableNameForNode()),
generatePropertyBlock = false,
value = m_Row3
});
[SerializeField]
string m_Description = string.Empty;
public string description
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
get
var sb = new ShaderStringBuilder();
if (!generationMode.IsPreview())
return string.IsNullOrEmpty(m_Description) ? name : m_Description;
sb.AppendLine("{0}4 _{1}_m0 = {0}4 ({2}, {3}, {4}, {5});", precision, GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Row0.x),
NodeUtils.FloatToShaderValue(m_Row0.y),
NodeUtils.FloatToShaderValue(m_Row0.z),
NodeUtils.FloatToShaderValue(m_Row0.w));
sb.AppendLine("{0}4 _{1}_m1 = {0}4 ({2}, {3}, {4}, {5});", precision, GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Row1.x),
NodeUtils.FloatToShaderValue(m_Row1.y),
NodeUtils.FloatToShaderValue(m_Row1.z),
NodeUtils.FloatToShaderValue(m_Row1.w));
sb.AppendLine("{0}4 _{1}_m2 = {0}4 ({2}, {3}, {4}, {5});", precision, GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Row2.x),
NodeUtils.FloatToShaderValue(m_Row2.y),
NodeUtils.FloatToShaderValue(m_Row2.z),
NodeUtils.FloatToShaderValue(m_Row2.w));
sb.AppendLine("{0}4 _{1}_m3 = {0}4 ({2}, {3}, {4}, {5});", precision, GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Row3.x),
NodeUtils.FloatToShaderValue(m_Row3.y),
NodeUtils.FloatToShaderValue(m_Row3.z),
NodeUtils.FloatToShaderValue(m_Row3.w));
set { m_Description = value; }
sb.AppendLine("{0}4x4 {1} = {0}4x4 (_{1}_m0.x, _{1}_m0.y, _{1}_m0.z, _{1}_m0.w, _{1}_m1.x, _{1}_m1.y, _{1}_m1.z, _{1}_m1.w, _{1}_m2.x, _{1}_m2.y, _{1}_m2.z, _{1}_m2.w, _{1}_m3.x, _{1}_m3.y, _{1}_m3.z, _{1}_m3.w);",
precision, GetVariableNameForNode());
visitor.AddShaderChunk(sb.ToString(), false);
// TODO - Remove Property entries everywhere?
// Matrix cant be a shader property
/*public override PropertyType propertyType
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
get { return PropertyType.Matrix2; }
}*/
properties.Add(new PreviewProperty(PropertyType.Vector4)
{
name = string.Format("_{0}_m0", GetVariableNameForNode()),
vector4Value = m_Row0
});
/*public override void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
{
if (exposedState == ExposedState.Exposed)
visitor.AddShaderProperty(new VectorPropertyChunk(propertyName, description, m_Value, PropertyChunk.HideState.Visible));
}*/
properties.Add(new PreviewProperty(PropertyType.Vector4)
{
name = string.Format("_{0}_m1", GetVariableNameForNode()),
vector4Value = m_Row1
});
/*public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
visitor.AddShaderChunk(precision + "2 " + propertyName + ";", true);
}*/
properties.Add(new PreviewProperty(PropertyType.Vector4)
{
name = string.Format("_{0}_m2", GetVariableNameForNode()),
vector4Value = m_Row2
});
properties.Add(new PreviewProperty(PropertyType.Vector4)
{
name = string.Format("_{0}_m3", GetVariableNameForNode()),
vector4Value = m_Row3
});
}
/*public override PreviewProperty GetPreviewProperty()
public override string GetVariableNameForSlot(int slotId)
return new PreviewProperty
{
m_Name = propertyName,
m_PropType = PropertyType.Vector2,
m_Vector4 = m_Value
};
}*/
return GetVariableNameForNode();
}
}
}

110
com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix3Node.cs


using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
using UnityEditor.Graphing;
using System.Collections.Generic;
namespace UnityEditor.ShaderGraph
{

const int kOutputSlotId = 0;
public const int OutputSlotId = 0;
const string kOutputSlotName = "Out";
[SerializeField]

if (value == row)
return;
row = value;
Dirty(ModificationScope.Graph);
Dirty(ModificationScope.Node);
}
public Matrix3Node()

public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Matrix3MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output));
RemoveSlotsNameNotMatching(new[] { kOutputSlotId });
AddSlot(new Matrix3MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
public string propertyName
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
get { return string.Format("{0}_{1}_Uniform", name, GetVariableNameForNode()); }
}
if (!generationMode.IsPreview())
return;
public override string GetVariableNameForSlot(int slotId)
{
return propertyName;
}
properties.AddShaderProperty(new Vector3ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_m0", GetVariableNameForNode()),
generatePropertyBlock = false,
value = m_Row0
});
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
//if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
// return;
properties.AddShaderProperty(new Vector3ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_m1", GetVariableNameForNode()),
generatePropertyBlock = false,
value = m_Row1
});
visitor.AddShaderChunk(precision + "3x3 " + propertyName + " = " + precision + "3x3 (" + m_Row0.x + ", " + m_Row0.y + ", " + m_Row0.z + ", " + m_Row1.x + ", " + m_Row1.y + ", " + m_Row1.z + ", " + m_Row2.x + ", " + m_Row2.y + ", " + m_Row2.z + ");", true);
properties.AddShaderProperty(new Vector3ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_m2", GetVariableNameForNode()),
generatePropertyBlock = false,
value = m_Row2
});
[SerializeField]
string m_Description = string.Empty;
public string description
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
get
var sb = new ShaderStringBuilder();
if (!generationMode.IsPreview())
return string.IsNullOrEmpty(m_Description) ? name : m_Description;
sb.AppendLine("{0}3 _{1}_m0 = {0}3 ({2}, {3}, {4});", precision, GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Row0.x),
NodeUtils.FloatToShaderValue(m_Row0.y),
NodeUtils.FloatToShaderValue(m_Row0.z));
sb.AppendLine("{0}3 _{1}_m1 = {0}3 ({2}, {3}, {4});", precision, GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Row1.x),
NodeUtils.FloatToShaderValue(m_Row1.y),
NodeUtils.FloatToShaderValue(m_Row1.z));
sb.AppendLine("{0}3 _{1}_m2 = {0}3 ({2}, {3}, {4});", precision, GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Row2.x),
NodeUtils.FloatToShaderValue(m_Row2.y),
NodeUtils.FloatToShaderValue(m_Row2.z));
set { m_Description = value; }
sb.AppendLine("{0}3x3 {1} = {0}3x3 (_{1}_m0.x, _{1}_m0.y, _{1}_m0.z, _{1}_m1.x, _{1}_m1.y, _{1}_m1.z, _{1}_m2.x, _{1}_m2.y, _{1}_m2.z);",
precision, GetVariableNameForNode());
visitor.AddShaderChunk(sb.ToString(), false);
// TODO - Remove Property entries everywhere?
// Matrix cant be a shader property
/*public override PropertyType propertyType
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
get { return PropertyType.Matrix2; }
}*/
properties.Add(new PreviewProperty(PropertyType.Vector3)
{
name = string.Format("_{0}_m0", GetVariableNameForNode()),
vector4Value = m_Row0
});
/*public override void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
{
if (exposedState == ExposedState.Exposed)
visitor.AddShaderProperty(new VectorPropertyChunk(propertyName, description, m_Value, PropertyChunk.HideState.Visible));
}*/
properties.Add(new PreviewProperty(PropertyType.Vector3)
{
name = string.Format("_{0}_m1", GetVariableNameForNode()),
vector4Value = m_Row1
});
/*public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
visitor.AddShaderChunk(precision + "2 " + propertyName + ";", true);
}*/
properties.Add(new PreviewProperty(PropertyType.Vector3)
{
name = string.Format("_{0}_m2", GetVariableNameForNode()),
vector4Value = m_Row2
});
}
/*public override PreviewProperty GetPreviewProperty()
public override string GetVariableNameForSlot(int slotId)
return new PreviewProperty
{
m_Name = propertyName,
m_PropType = PropertyType.Vector2,
m_Vector3 = m_Value
};
}*/
return GetVariableNameForNode();
}
}
}

96
com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix2Node.cs


using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
using UnityEditor.Graphing;
using System.Collections.Generic;
namespace UnityEditor.ShaderGraph
{

const int kOutputSlotId = 0;
public const int OutputSlotId = 0;
const string kOutputSlotName = "Out";
[SerializeField]

if (value == row)
return;
row = value;
Dirty(ModificationScope.Graph);
Dirty(ModificationScope.Node);
}
public Matrix2Node()

public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Matrix2MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output));
RemoveSlotsNameNotMatching(new[] { kOutputSlotId });
AddSlot(new Matrix2MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
public string propertyName
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
get
if (!generationMode.IsPreview())
return;
properties.AddShaderProperty(new Vector2ShaderProperty()
return string.Format("{0}_{1}_Uniform", name, GetVariableNameForNode());
}
}
overrideReferenceName = string.Format("_{0}_m0", GetVariableNameForNode()),
generatePropertyBlock = false,
value = m_Row0
});
public override string GetVariableNameForSlot(int slotId)
{
return propertyName;
properties.AddShaderProperty(new Vector2ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_m1", GetVariableNameForNode()),
generatePropertyBlock = false,
value = m_Row1
});
//if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
// return;
visitor.AddShaderChunk(precision + "2 " + name + " = " + precision + "2x2 (" + m_Row0.x + ", " + m_Row0.y + ", " + m_Row1.x + ", " + m_Row1.y + ");", true);
}
[SerializeField]
string m_Description = string.Empty;
public string description
{
get
var sb = new ShaderStringBuilder();
if (!generationMode.IsPreview())
return string.IsNullOrEmpty(m_Description) ? name : m_Description;
sb.AppendLine("{0}2 _{1}_m0 = {0}2 ({2}, {3});", precision, GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Row0.x),
NodeUtils.FloatToShaderValue(m_Row0.y));
sb.AppendLine("{0}2 _{1}_m1 = {0}2 ({2}, {3});", precision, GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Row1.x),
NodeUtils.FloatToShaderValue(m_Row1.y));
set { m_Description = value; }
sb.AppendLine("{0}2x2 {1} = {0}2x2 (_{1}_m0.x, _{1}_m0.y, _{1}_m1.x, _{1}_m1.y);",
precision, GetVariableNameForNode());
visitor.AddShaderChunk(sb.ToString(), false);
// TODO - Remove Property entries everywhere?
// Matrix cant be a shader property
/*public override PropertyType propertyType
{
get { return PropertyType.Matrix2; }
}*/
/*public override void GeneratePropertyBlock(PropertyGenerator visitor, GenerationMode generationMode)
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
if (exposedState == ExposedState.Exposed)
visitor.AddShaderProperty(new VectorPropertyChunk(propertyName, description, m_Value, PropertyChunk.HideState.Visible));
}*/
properties.Add(new PreviewProperty(PropertyType.Vector2)
{
name = string.Format("_{0}_m0", GetVariableNameForNode()),
vector4Value = m_Row0
});
/*public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)
{
if (exposedState == ExposedState.Exposed || generationMode.IsPreview())
visitor.AddShaderChunk(precision + "2 " + propertyName + ";", true);
}*/
properties.Add(new PreviewProperty(PropertyType.Vector2)
{
name = string.Format("_{0}_m1", GetVariableNameForNode()),
vector4Value = m_Row1
});
}
/*public override PreviewProperty GetPreviewProperty()
public override string GetVariableNameForSlot(int slotId)
return new PreviewProperty
{
m_Name = propertyName,
m_PropType = PropertyType.Vector2,
m_Vector2 = m_Value
};
}*/
return GetVariableNameForNode();
}
}
}

2
com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/UVNode.cs


public override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector2MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector2.zero));
AddSlot(new Vector4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector2.zero));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
}

31
com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;

public enum ScreenSpaceType
{
Default,
Raw,
Center,
Tiled
};
[Title("Input", "Geometry", "Screen Position")]
public class ScreenPositionNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequireScreenPosition
{

public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
switch (m_ScreenSpaceType)
{
case ScreenSpaceType.Raw:
visitor.AddShaderChunk(string.Format("{0}4 {1} = IN.{2};", precision, GetVariableNameForSlot(kOutputSlotId),
ShaderGeneratorNames.ScreenPosition), true);
break;
case ScreenSpaceType.Center:
visitor.AddShaderChunk(string.Format("{0}4 {1} = {2};", precision, GetVariableNameForSlot(kOutputSlotId),
string.Format("float4((IN.{0}.xy / IN.{0}.w) * 2 - 1, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
break;
case ScreenSpaceType.Tiled:
visitor.AddShaderChunk(string.Format("{0}4 {1} = {2};", precision, GetVariableNameForSlot(kOutputSlotId),
string.Format("float4((IN.{0}.xy / IN.{0}.w) * 2 - 1, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
visitor.AddShaderChunk(string.Format("{0} = {1};", GetVariableNameForSlot(kOutputSlotId),
string.Format("frac(float4({0}.x * _ScreenParams.x / _ScreenParams.y, {0}.y, 0, 0))", GetVariableNameForSlot(kOutputSlotId))), true);
break;
default:
visitor.AddShaderChunk(string.Format("{0}4 {1} = {2};", precision, GetVariableNameForSlot(kOutputSlotId),
string.Format("float4(IN.{0}.xy / IN.{0}.w, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
break;
}
visitor.AddShaderChunk(string.Format("{0}4 {1} = {2};", precision, GetVariableNameForSlot(kOutputSlotId), m_ScreenSpaceType.ToValueAsVariable()), true);
}
public bool RequiresScreenPosition()

1
com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/ConstantNode.cs


using System.Collections.Generic;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
using UnityEditor.ShaderGraph;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph

1
com.unity.shadergraph/Editor/Data/Nodes/IMasterNode.cs


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

34
com.unity.shadergraph/Editor/Data/Nodes/CodeFunctionNode.cs


protected struct DynamicDimensionVector
{}
protected struct ColorRGBA
{}
protected struct ColorRGB
{}
protected struct Matrix3x3
{}
protected struct Matrix2x2
{}
protected struct DynamicDimensionMatrix
{ }
protected enum Binding
{
None,

protected abstract MethodInfo GetFunctionToConvert();
public class ColorRGBA { };
public class ColorRGB { };
private static SlotValueType ConvertTypeToSlotValueType(ParameterInfo p)
{
Type t = p.ParameterType;

}
if (t == typeof(DynamicDimensionVector))
{
return SlotValueType.Dynamic;
return SlotValueType.DynamicVector;
}
if (t == typeof(Matrix3x3))
{
return SlotValueType.Matrix3;
}
if (t == typeof(Matrix2x2))
{
return SlotValueType.Matrix2;
}
if (t == typeof(DynamicDimensionMatrix))
{
return SlotValueType.DynamicMatrix;
}
throw new ArgumentException("Unsupported type " + t);
}

case Binding.MeshUV3:
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.UV3);
case Binding.ScreenPosition:
return new ScreenPositionMaterialSlot(slotId, displayName, shaderOutputName);
return new ScreenPositionMaterialSlot(slotId, displayName, shaderOutputName, ScreenSpaceType.Default);
case Binding.ObjectSpaceViewDirection:
return new ViewDirectionMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Object);
case Binding.ViewSpaceViewDirection:

3
com.unity.shadergraph/Editor/Data/Nodes/Channel/SplitNode.cs


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

[Title("Channel", "Split")]
public class SplitNode : AbstractMaterialNode, IGeneratesBodyCode
{
const string kInputSlotName = "Input";
const string kInputSlotName = "In";
const string kOutputSlotRName = "R";
const string kOutputSlotGName = "G";
const string kOutputSlotBName = "B";

11
com.unity.shadergraph/Editor/Data/Nodes/Channel/CombineNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{

[Slot(1, Binding.None)] Vector1 G,
[Slot(2, Binding.None)] Vector1 B,
[Slot(3, Binding.None)] Vector1 A,
[Slot(4, Binding.None)] out Vector4 RGBA)
[Slot(4, Binding.None)] out Vector4 RGBA,
[Slot(5, Binding.None)] out Vector3 RGB,
[Slot(6, Binding.None)] out Vector2 RG)
RGB = Vector3.zero;
RG = Vector2.zero;
RGB = float3(R, G, B);
RG = float2(R, G);
}
";
}

1
com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalStrengthNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{

3
com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalCreateNode.cs


using System.Linq;
using UnityEngine;
using UnityEditor.Graphing;
using System.Collections.Generic;
using UnityEditor.ShaderGraph.Drawing.Slots;
using UnityEngine.Experimental.UIElements;
namespace UnityEditor.ShaderGraph
{

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

正在加载...
取消
保存