浏览代码

Added update title to master preview and blackboard.

cleaned up assetName parameter and dded it as a property instead
Made a seperate shader graph post processor file
/main
Martin Thorzen 7 年前
当前提交
37c00666
共有 12 个文件被更改,包括 234 次插入171 次删除
  1. 2
      com.unity.shadergraph/Editor/Data/Graphs/AbstractMaterialGraph.cs
  2. 12
      com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs
  3. 13
      com.unity.shadergraph/Editor/Drawing/Inspector/MasterPreviewView.cs
  4. 53
      com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs
  5. 17
      com.unity.shadergraph/Editor/Drawing/Views/GraphEditorView.cs
  6. 13
      com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs
  7. 135
      com.unity.shadergraph/Editor/Importers/ShaderGraphImporter.cs
  8. 69
      com.unity.shadergraph/Editor/Importers/ShaderGraphImporterEditor.cs
  9. 1
      com.unity.shadergraph/Editor/Importers/ShaderSubGraphImporter.cs
  10. 17
      com.unity.shadergraph/Editor/Importers/ShaderSubGraphImporterEditor.cs
  11. 62
      com.unity.shadergraph/Editor/Importers/ShaderGraphAssetPostProcessor.cs
  12. 11
      com.unity.shadergraph/Editor/Importers/ShaderGraphAssetPostProcessor.cs.meta

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


set { m_PreviewData = value; }
}
public string name { get; set; }
[SerializeField]
string m_Path;

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


// set { m_ResizeBorderFrame.OnResizeFinished = value; }
//}
public BlackboardProvider(string assetName, AbstractMaterialGraph graph)
public string assetName
{
get { return blackboard.title; }
set
{
blackboard.title = value;
}
}
public BlackboardProvider(AbstractMaterialGraph graph)
{
m_Graph = graph;
m_ExposedIcon = Resources.Load<Texture2D>("GraphView/Nodes/BlackboardFieldExposed");

{
scrollable = true,
title = assetName.Split('/').Last(),
subTitle = FormatPath(graph.path),
editTextRequested = EditTextRequested,
addItemRequested = AddItemRequested,

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


}
VisualElement m_Preview;
Label m_Title;
public VisualElement preview
{

static Type s_ContextualMenuManipulator = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypesOrNothing()).FirstOrDefault(t => t.FullName == "UnityEngine.Experimental.UIElements.ContextualMenuManipulator");
static Type s_ObjectSelector = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypesOrNothing()).FirstOrDefault(t => t.FullName == "UnityEditor.ObjectSelector");
public MasterPreviewView(string assetName, PreviewManager previewManager, AbstractMaterialGraph graph)
public string assetName
{
get { return m_Title.text; }
set { m_Title.text = value; }
}
public MasterPreviewView(PreviewManager previewManager, AbstractMaterialGraph graph)
{
this.clippingOptions = ClippingOptions.ClipAndCacheContents;
m_PreviewManager = previewManager;

var topContainer = new VisualElement() { name = "top" };
{
var title = new Label(assetName.Split('/').Last()) { name = "title" };
m_Title = new Label() { name = "title" };
// Add preview collapse button on top of preview
m_CollapsePreviewContainer = new VisualElement { name = "collapse-container" };

UpdatePreviewVisibility();
}));
topContainer.Add(title);
topContainer.Add(m_Title);
topContainer.Add(m_CollapsePreviewContainer);
}
Add(topContainer);

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


ColorSpace m_ColorSpace;
static MaterialGraphEditWindow s_Instance;
GraphEditorView m_GraphEditorView;
GraphEditorView graphEditorView

private set { m_Selected = value; }
}
// This is so that we can check if the file on disk has been renamed.
// If it has, we can update the Title of the shader graph tab.
class ShaderPostProcessor : AssetPostprocessor
public string assetName
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
get { return titleContent.text; }
set
if (s_Instance != null)
{
string ending = ".ShaderGraph";
bool anyShaders = importedAssets.Any(val => val.EndsWith(ending));
anyShaders |= movedAssets.Any(val => val.EndsWith(ending));
if (anyShaders)
s_Instance.UpdateAfterAssetChange();
}
titleContent.text = value;
graphEditorView.assetName = value;
void UpdateAfterAssetChange()
{
var asset = AssetDatabase.LoadAssetAtPath<Object>(AssetDatabase.GUIDToAssetPath(selectedGuid));
if (titleContent.text != asset.name)
titleContent.text = asset.name;
}
public void OnEnable()
{
s_Instance = this;
}
void Update()
{
if (m_HasError)

if (graphEditorView == null)
{
var asset = AssetDatabase.LoadAssetAtPath<Object>(AssetDatabase.GUIDToAssetPath(selectedGuid));
graphEditorView = new GraphEditorView(this, materialGraph, asset.name) { persistenceKey = selectedGuid };
graphEditorView = new GraphEditorView(this, materialGraph)
{
persistenceKey = selectedGuid,
assetName = asset.name
};
m_ColorSpace = PlayerSettings.colorSpace;
}

void OnDisable()
{
graphEditorView = null;
s_Instance = null;
}
void OnDestroy()

return;
var path = AssetDatabase.GetAssetPath(asset);
var extension = Path.GetExtension(path);
// Remove the "." in ".extension_name"
var extension = Path.GetExtension(path).Substring(1);
switch (extension)
switch (extension.ToLower())
case ".ShaderGraph":
case ShaderGraphImporter.ShaderGraphExtension:
case ".ShaderSubGraph":
case ShaderSubGraphImporter.ShaderSubGraphExtension:
graphType = typeof(SubGraph);
break;
default:

graphObject.graph.OnEnable();
graphObject.graph.ValidateGraph();
graphEditorView = new GraphEditorView(this, m_GraphObject.graph as AbstractMaterialGraph, asset.name) { persistenceKey = selectedGuid };
graphEditorView = new GraphEditorView(this, m_GraphObject.graph as AbstractMaterialGraph)
{
persistenceKey = selectedGuid,
assetName = asset.name
};
graphEditorView.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
titleContent = new GUIContent(asset.name);

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


set { m_PreviewManager = value; }
}
public GraphEditorView(EditorWindow editorWindow, AbstractMaterialGraph graph, string assetName)
public string assetName
{
get { return m_BlackboardProvider.blackboard.title; }
set
{
m_BlackboardProvider.blackboard.title = value;
m_MasterPreviewView.assetName = value;
}
}
public GraphEditorView(EditorWindow editorWindow, AbstractMaterialGraph graph)
{
m_Graph = graph;
AddStyleSheetPath("Styles/GraphEditorView");

var content = new VisualElement { name = "content" };
{
graph.name = assetName;
m_GraphView = new MaterialGraphView(graph) { name = "GraphView", persistenceKey = "MaterialGraphView" };
m_GraphView.SetupZoom(0.05f, ContentZoomer.DefaultMaxScale);
m_GraphView.AddManipulator(new ContentDragger());

m_GraphView.RegisterCallback<KeyDownEvent>(OnSpaceDown);
content.Add(m_GraphView);
m_BlackboardProvider = new BlackboardProvider(assetName, graph);
m_BlackboardProvider = new BlackboardProvider(graph);
m_GraphView.Add(m_BlackboardProvider.blackboard);
Rect blackboardLayout = m_BlackboardProvider.blackboard.layout;
blackboardLayout.x = 10f;

m_MasterPreviewView = new MasterPreviewView(assetName, previewManager, graph) { name = "masterPreview" };
m_MasterPreviewView = new MasterPreviewView(previewManager, graph) { name = "masterPreview" };
WindowDraggable masterPreviewViewDraggable = new WindowDraggable(null, this);
m_MasterPreviewView.AddManipulator(masterPreviewViewDraggable);

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


public void ShowGeneratedCode()
{
var graph = (AbstractMaterialGraph)node.owner;
string path = String.Format("Temp/GeneratedFromGraph-{0}-{1}-{2}.shader", SanitizeName(graph.name), SanitizeName(node.name), node.guid);
if (GraphUtil.WriteToFile(path, ConvertToShader()))
GraphUtil.OpenFile(path);
// var graph = (AbstractMaterialGraph)node.owner;
//
// string path = String.Format("Temp/GeneratedFromGraph-{0}-{1}-{2}.shader", SanitizeName(graph.name), SanitizeName(node.name), node.guid);
//
// if (GraphUtil.WriteToFile(path, ConvertToShader()))
// GraphUtil.OpenFile(path);
}
string ConvertToShader()

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


using UnityEditor.Experimental.AssetImporters;
using UnityEditor.ShaderGraph.Drawing;
[ScriptedImporter(15, ShaderGraphExtension)]
public class ShaderGraphImporter : ScriptedImporter
namespace UnityEditor.ShaderGraph
public const string ShaderGraphExtension = "shadergraph";
[ScriptedImporter(15, ShaderGraphExtension)]
public class ShaderGraphImporter : ScriptedImporter
{
public const string ShaderGraphExtension = "shadergraph";
const string k_ErrorShader = @"
const string k_ErrorShader = @"
Shader ""Hidden/GraphErrorShader2""
{
SubShader

Fallback Off
}";
public override void OnImportAsset(AssetImportContext ctx)
{
var oldShader = AssetDatabase.LoadAssetAtPath<Shader>(ctx.assetPath);
if (oldShader != null)
ShaderUtil.ClearShaderErrors(oldShader);
public override void OnImportAsset(AssetImportContext ctx)
{
var oldShader = AssetDatabase.LoadAssetAtPath<Shader>(ctx.assetPath);
if (oldShader != null)
ShaderUtil.ClearShaderErrors(oldShader);
List<PropertyCollector.TextureInfo> configuredTextures;
string path = ctx.assetPath;
var sourceAssetDependencyPaths = new List<string>();
var text = GetShaderText(path, out configuredTextures, sourceAssetDependencyPaths);
var shader = ShaderUtil.CreateShaderAsset(text);
List<PropertyCollector.TextureInfo> configuredTextures;
string path = ctx.assetPath;
var sourceAssetDependencyPaths = new List<string>();
var text = GetShaderText(path, out configuredTextures, sourceAssetDependencyPaths);
var shader = ShaderUtil.CreateShaderAsset(text);
EditorMaterialUtility.SetShaderDefaults(
shader,
configuredTextures.Where(x => x.modifiable).Select(x => x.name).ToArray(),
configuredTextures.Where(x => x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
EditorMaterialUtility.SetShaderNonModifiableDefaults(
shader,
configuredTextures.Where(x => !x.modifiable).Select(x => x.name).ToArray(),
configuredTextures.Where(x => !x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
EditorMaterialUtility.SetShaderDefaults(
shader,
configuredTextures.Where(x => x.modifiable).Select(x => x.name).ToArray(),
configuredTextures.Where(x => x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
EditorMaterialUtility.SetShaderNonModifiableDefaults(
shader,
configuredTextures.Where(x => !x.modifiable).Select(x => x.name).ToArray(),
configuredTextures.Where(x => !x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
ctx.AddObjectToAsset("MainAsset", shader);
ctx.SetMainObject(shader);
ctx.AddObjectToAsset("MainAsset", shader);
ctx.SetMainObject(shader);
foreach (var sourceAssetDependencyPath in sourceAssetDependencyPaths.Distinct())
ctx.DependsOnSourceAsset(sourceAssetDependencyPath);
}
foreach (var sourceAssetDependencyPath in sourceAssetDependencyPaths.Distinct())
ctx.DependsOnSourceAsset(sourceAssetDependencyPath);
}
internal static string GetShaderText(string path, out List<PropertyCollector.TextureInfo> configuredTextures, List<string> sourceAssetDependencyPaths)
{
string shaderString = null;
var shaderName = Path.GetFileNameWithoutExtension(path);
try
internal static string GetShaderText(string path, out List<PropertyCollector.TextureInfo> configuredTextures, List<string> sourceAssetDependencyPaths)
var textGraph = File.ReadAllText(path, Encoding.UTF8);
var graph = JsonUtility.FromJson<MaterialGraph>(textGraph);
graph.LoadedFromDisk();
string shaderString = null;
var shaderName = Path.GetFileNameWithoutExtension(path);
try
{
var textGraph = File.ReadAllText(path, Encoding.UTF8);
var graph = JsonUtility.FromJson<MaterialGraph>(textGraph);
graph.LoadedFromDisk();
if (!string.IsNullOrEmpty(graph.path))
shaderName = graph.path + "/" + shaderName;
shaderString = graph.GetShader(shaderName, GenerationMode.ForReals, out configuredTextures, sourceAssetDependencyPaths);
if (!string.IsNullOrEmpty(graph.path))
shaderName = graph.path + "/" + shaderName;
shaderString = graph.GetShader(shaderName, GenerationMode.ForReals, out configuredTextures, sourceAssetDependencyPaths);
if (sourceAssetDependencyPaths != null)
if (sourceAssetDependencyPaths != null)
{
foreach (var node in graph.GetNodes<AbstractMaterialNode>())
node.GetSourceAssetDependencies(sourceAssetDependencyPaths);
}
}
catch (Exception)
foreach (var node in graph.GetNodes<AbstractMaterialNode>())
node.GetSourceAssetDependencies(sourceAssetDependencyPaths);
configuredTextures = new List<PropertyCollector.TextureInfo>();
// ignored
}
catch (Exception)
{
configuredTextures = new List<PropertyCollector.TextureInfo>();
// ignored
}
return shaderString ?? k_ErrorShader.Replace("Hidden/GraphErrorShader2", shaderName);
}
internal static string GetShaderText(string path, out List<PropertyCollector.TextureInfo> configuredTextures)
{
return GetShaderText(path, out configuredTextures, null);
}
}
class ShaderGraphAssetPostProcessor : AssetPostprocessor
{
static void RegisterShaders(string[] paths)
{
foreach (var path in paths)
{
if (!path.EndsWith(ShaderGraphImporter.ShaderGraphExtension, StringComparison.InvariantCultureIgnoreCase))
continue;
var mainObj = AssetDatabase.LoadMainAssetAtPath(path);
if (mainObj is Shader)
ShaderUtil.RegisterShader((Shader)mainObj);
var objs = AssetDatabase.LoadAllAssetRepresentationsAtPath(path);
foreach (var obj in objs)
{
if (obj is Shader)
ShaderUtil.RegisterShader((Shader)obj);
}
return shaderString ?? k_ErrorShader.Replace("Hidden/GraphErrorShader2", shaderName);
}
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
MaterialGraphEditWindow[] windows = Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>();
foreach (var matGraphEditWindow in windows)
internal static string GetShaderText(string path, out List<PropertyCollector.TextureInfo> configuredTextures)
matGraphEditWindow.forceRedrawPreviews = true;
return GetShaderText(path, out configuredTextures, null);
RegisterShaders(importedAssets);
}
}

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


using UnityEditor.ShaderGraph.Drawing;
using UnityEngine;
[CustomEditor(typeof(ShaderGraphImporter))]
public class ShaderGraphImporterEditor : ScriptedImporterEditor
namespace UnityEditor.ShaderGraph
public override void OnInspectorGUI()
[CustomEditor(typeof(ShaderGraphImporter))]
public class ShaderGraphImporterEditor : ScriptedImporterEditor
if (GUILayout.Button("Open Shader Editor"))
public override void OnInspectorGUI()
AssetImporter importer = target as AssetImporter;
Debug.Assert(importer != null, "importer != null");
ShowGraphEditWindow(importer.assetPath);
if (GUILayout.Button("Open Shader Editor"))
{
AssetImporter importer = target as AssetImporter;
Debug.Assert(importer != null, "importer != null");
ShowGraphEditWindow(importer.assetPath);
}
}
internal static bool ShowGraphEditWindow(string path)
{
var guid = AssetDatabase.AssetPathToGUID(path);
var extension = Path.GetExtension(path);
if (extension != ".ShaderGraph" && extension != ".LayeredShaderGraph" && extension != ".ShaderSubGraph" && extension != ".ShaderRemapGraph")
return false;
internal static bool ShowGraphEditWindow(string path)
{
var guid = AssetDatabase.AssetPathToGUID(path);
var extension = Path.GetExtension(path);
if (extension != ".ShaderGraph" && extension != ".LayeredShaderGraph" && extension != ".ShaderSubGraph" && extension != ".ShaderRemapGraph")
return false;
var foundWindow = false;
foreach (var w in Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>())
{
if (w.selectedGuid == guid)
{
foundWindow = true;
w.Focus();
}
}
var foundWindow = false;
foreach (var w in Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>())
{
if (w.selectedGuid == guid)
if (!foundWindow)
foundWindow = true;
w.Focus();
var window = CreateInstance<MaterialGraphEditWindow>();
window.Show();
window.Initialize(guid);
return true;
if (!foundWindow)
[OnOpenAsset(0)]
public static bool OnOpenAsset(int instanceID, int line)
var window = CreateInstance<MaterialGraphEditWindow>();
window.Show();
window.Initialize(guid);
var path = AssetDatabase.GetAssetPath(instanceID);
return ShowGraphEditWindow(path);
return true;
}
[OnOpenAsset(0)]
public static bool OnOpenAsset(int instanceID, int line)
{
var path = AssetDatabase.GetAssetPath(instanceID);
return ShowGraphEditWindow(path);
}
}

1
com.unity.shadergraph/Editor/Importers/ShaderSubGraphImporter.cs


[ScriptedImporter(2, "ShaderSubGraph")]
public class ShaderSubGraphImporter : ScriptedImporter
{
public const string ShaderSubGraphExtension = "shadersubgraph";
public override void OnImportAsset(AssetImportContext ctx)
{
var textGraph = File.ReadAllText(ctx.assetPath, Encoding.UTF8);

17
com.unity.shadergraph/Editor/Importers/ShaderSubGraphImporterEditor.cs


using UnityEngine;
using Debug = System.Diagnostics.Debug;
[CustomEditor(typeof(ShaderSubGraphImporter))]
public class ShaderSubGraphImporterEditor : ScriptedImporterEditor
namespace UnityEditor.ShaderGraph
public override void OnInspectorGUI()
[CustomEditor(typeof(ShaderSubGraphImporter))]
public class ShaderSubGraphImporterEditor : ScriptedImporterEditor
if (GUILayout.Button("Open Shader Editor"))
public override void OnInspectorGUI()
AssetImporter importer = target as AssetImporter;
Debug.Assert(importer != null, "importer != null");
ShaderGraphImporterEditor.ShowGraphEditWindow(importer.assetPath);
if (GUILayout.Button("Open Shader Editor"))
{
AssetImporter importer = target as AssetImporter;
Debug.Assert(importer != null, "importer != null");
ShaderGraphImporterEditor.ShowGraphEditWindow(importer.assetPath);
}
}
}
}

62
com.unity.shadergraph/Editor/Importers/ShaderGraphAssetPostProcessor.cs


using UnityEngine;
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.ShaderGraph.Drawing;
namespace UnityEditor.ShaderGraph
{
class ShaderGraphAssetPostProcessor : AssetPostprocessor
{
static void RegisterShaders(string[] paths)
{
foreach (var path in paths)
{
if (!path.EndsWith(ShaderGraphImporter.ShaderGraphExtension, StringComparison.InvariantCultureIgnoreCase))
continue;
var mainObj = AssetDatabase.LoadMainAssetAtPath(path);
if (mainObj is Shader)
ShaderUtil.RegisterShader((Shader)mainObj);
var objs = AssetDatabase.LoadAllAssetRepresentationsAtPath(path);
foreach (var obj in objs)
{
if (obj is Shader)
ShaderUtil.RegisterShader((Shader)obj);
}
}
}
static void UpdateAfterAssetChange(string[] newNames)
{
// This will change the title of the window.
MaterialGraphEditWindow[] windows = Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>();
foreach (var matGraphEditWindow in windows)
{
for (int i = 0; i < newNames.Length; ++i)
{
if (matGraphEditWindow.selectedGuid == AssetDatabase.AssetPathToGUID(newNames[i]))
matGraphEditWindow.assetName = Path.GetFileNameWithoutExtension(newNames[i]);
}
}
}
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
MaterialGraphEditWindow[] windows = Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>();
foreach (var matGraphEditWindow in windows)
{
matGraphEditWindow.forceRedrawPreviews = true;
}
RegisterShaders(importedAssets);
bool anyShaders = movedAssets.Any(val => val.EndsWith(ShaderGraphImporter.ShaderGraphExtension, StringComparison.InvariantCultureIgnoreCase));
anyShaders |= movedAssets.Any(val => val.EndsWith(ShaderSubGraphImporter.ShaderSubGraphExtension, StringComparison.InvariantCultureIgnoreCase));
if (anyShaders)
UpdateAfterAssetChange(movedAssets);
}
}
}

11
com.unity.shadergraph/Editor/Importers/ShaderGraphAssetPostProcessor.cs.meta


fileFormatVersion: 2
guid: c6721e5578adf964fa914cf0d66e0bdb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存