This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,27 @@
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityEditor.ShaderGraph
{
static class RenderPipelineChangedCallback
{
internal static readonly string k_CustomDependencyKey = "ShaderGraph/RenderPipelineChanged";
[InitializeOnLoadMethod]
private static void RegisterSRPChangeCallback()
{
if (AssetDatabase.IsAssetImportWorkerProcess())
return;
RenderPipelineManager.activeRenderPipelineTypeChanged -= SRPChanged;
RenderPipelineManager.activeRenderPipelineTypeChanged += SRPChanged;
SRPChanged();
}
static Hash128 ComputeCurrentRenderPipelineHash()
=> Hash128.Compute(GraphicsSettings.currentRenderPipelineAssetType?.FullName ?? string.Empty);
static void SRPChanged()
=> AssetDatabase.RegisterCustomDependency(k_CustomDependencyKey,ComputeCurrentRenderPipelineHash());
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 37cdee768bffc4e49b528c0ddbb20e6d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,148 @@
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.Extension, 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.UpdateTitle();
}
}
}
static void DisplayDeletionDialog(string[] deletedAssets)
{
MaterialGraphEditWindow[] windows = Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>();
foreach (var matGraphEditWindow in windows)
{
for (int i = 0; i < deletedAssets.Length; ++i)
{
if (matGraphEditWindow.selectedGuid == AssetDatabase.AssetPathToGUID(deletedAssets[i]))
matGraphEditWindow.AssetWasDeleted();
}
}
}
void OnPreprocessAsset()
{
ShaderGraphImporter sgImporter = assetImporter as ShaderGraphImporter;
if (sgImporter != null)
{
// Before importing, clear shader messages for any existing old shaders, if any.
// This is a terrible way to do it, but currently how the shader message system works at the moment.
// to workaround a bug with LoadAllAssetsAtPath(), which crashes if the asset has not yet been imported
// we first call LoadAssetAtPath<>, which handles assets not yet imported by returning null
if (AssetDatabase.LoadAssetAtPath<Shader>(assetPath) != null)
{
var oldArtifacts = AssetDatabase.LoadAllAssetsAtPath(assetPath);
foreach (var artifact in oldArtifacts)
{
if ((artifact != null) && (artifact is Shader oldShader))
{
ShaderUtil.ClearShaderMessages(oldShader);
}
}
}
}
}
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
RegisterShaders(importedAssets);
// Moved assets
bool anyMovedShaders = movedAssets.Any(val => val.EndsWith(ShaderGraphImporter.Extension, StringComparison.InvariantCultureIgnoreCase));
anyMovedShaders |= movedAssets.Any(val => val.EndsWith(ShaderSubGraphImporter.Extension, StringComparison.InvariantCultureIgnoreCase));
if (anyMovedShaders)
UpdateAfterAssetChange(movedAssets);
// Deleted assets
bool anyRemovedShaders = deletedAssets.Any(val => val.EndsWith(ShaderGraphImporter.Extension, StringComparison.InvariantCultureIgnoreCase));
anyRemovedShaders |= deletedAssets.Any(val => val.EndsWith(ShaderSubGraphImporter.Extension, StringComparison.InvariantCultureIgnoreCase));
if (anyRemovedShaders)
DisplayDeletionDialog(deletedAssets);
var changedGraphGuids = importedAssets
.Where(x => x.EndsWith(ShaderGraphImporter.Extension, StringComparison.InvariantCultureIgnoreCase)
|| x.EndsWith(ShaderSubGraphImporter.Extension, StringComparison.InvariantCultureIgnoreCase))
.Select(AssetDatabase.AssetPathToGUID)
.ToList();
MaterialGraphEditWindow[] windows = null;
if (changedGraphGuids.Count > 0)
{
windows = Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>();
foreach (var window in windows)
{
if (changedGraphGuids.Contains(window.selectedGuid))
{
window.CheckForChanges();
}
}
}
// moved or imported subgraphs or HLSL files should notify open shadergraphs that they need to handle them
var changedFileGUIDs = movedAssets.Concat(importedAssets).Concat(deletedAssets)
.Where(x =>
{
if (x.EndsWith(ShaderSubGraphImporter.Extension, StringComparison.InvariantCultureIgnoreCase) || CustomFunctionNode.s_ValidExtensions.Contains(Path.GetExtension(x)))
{
return true;
}
else
{
var asset = AssetDatabase.GetMainAssetTypeAtPath(x);
return asset is null || asset.IsSubclassOf(typeof(Texture));
}
})
.Select(AssetDatabase.AssetPathToGUID)
.Distinct()
.ToList();
if (changedFileGUIDs.Count > 0)
{
if (windows == null)
{
windows = Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>();
}
foreach (var window in windows)
{
window.ReloadSubGraphsOnNextUpdate(changedFileGUIDs);
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c6721e5578adf964fa914cf0d66e0bdb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 625f186215c104763be7675aa2d941aa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,216 @@
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor.Callbacks;
using UnityEditor.AssetImporters;
using UnityEditor.ShaderGraph.Drawing;
using UnityEngine;
using UnityEditor.Graphing;
using System.Text;
using UnityEditor.ShaderGraph.Serialization;
namespace UnityEditor.ShaderGraph
{
[CustomEditor(typeof(ShaderGraphImporter))]
class ShaderGraphImporterEditor : ScriptedImporterEditor
{
MaterialEditor materialEditor = null;
public override void OnInspectorGUI()
{
var useAsTemplateProp = serializedObject.FindProperty(ShaderGraphImporter.UseAsTemplateFieldName);
var exposeTemplateAsShaderProp = serializedObject.FindProperty(ShaderGraphImporter.ExposeTemplateAsShaderFieldName);
var templateProp = serializedObject.FindProperty(ShaderGraphImporter.TemplateFieldName);
serializedObject.Update();
GraphData GetGraphData(AssetImporter importer)
{
var textGraph = FileUtilities.ReadAllTextUTF8(importer.assetPath);
var graphObject = CreateInstance<GraphObject>();
graphObject.hideFlags = HideFlags.HideAndDontSave;
bool isSubGraph;
var extension = Path.GetExtension(importer.assetPath).Replace(".", "");
switch (extension)
{
case ShaderGraphImporter.Extension:
isSubGraph = false;
break;
case ShaderGraphImporter.LegacyExtension:
isSubGraph = false;
break;
case ShaderSubGraphImporter.Extension:
isSubGraph = true;
break;
default:
throw new Exception($"Invalid file extension {extension}");
}
var assetGuid = AssetDatabase.AssetPathToGUID(importer.assetPath);
graphObject.graph = new GraphData
{
assetGuid = assetGuid,
isSubGraph = isSubGraph,
messageManager = null
};
MultiJson.Deserialize(graphObject.graph, textGraph);
graphObject.graph.OnEnable();
graphObject.graph.ValidateGraph();
return graphObject.graph;
}
if (GUILayout.Button("Open Shader Editor"))
{
AssetImporter importer = target as AssetImporter;
Debug.Assert(importer != null, "importer != null");
ShowGraphEditWindow(importer.assetPath);
}
using (var horizontalScope = new GUILayout.HorizontalScope())
{
AssetImporter importer = target as AssetImporter;
string assetName = Path.GetFileNameWithoutExtension(importer.assetPath);
string path = String.Format("Temp/GeneratedFromGraph-{0}.shader", assetName.Replace(" ", ""));
bool alreadyExists = File.Exists(path);
bool update = false;
bool open = false;
if (GUILayout.Button("View Generated Shader"))
{
update = true;
open = true;
}
if (alreadyExists && GUILayout.Button("Regenerate"))
update = true;
var pathList = new List<string>();
pathList.Add(path);
if (update)
{
var graphData = GetGraphData(importer);
var generator = new Generator(graphData, null, GenerationMode.ForReals, assetName, humanReadable: true);
if (!GraphUtil.WriteToFile(path, generator.generatedShader))
open = false;
var generatedShaderCount = 0;
foreach (var generatedShader in generator.allGeneratedShaders)
{
if (generatedShaderCount > 0)
{
string pathSub = String.Format("Temp/GeneratedFromGraph-{0}_{1}.shader", assetName.Replace(" ", ""), generatedShaderCount);
pathList.Add(pathSub);
GraphUtil.WriteToFile(pathSub, generatedShader.codeString);
}
generatedShaderCount++;
}
}
if (open)
{
for (int i = 1; i < pathList.Count; ++i)
GraphUtil.OpenFile(pathList[i]);
GraphUtil.OpenFile(pathList[0]);
}
}
if (Unsupported.IsDeveloperMode())
{
if (GUILayout.Button("View Preview Shader"))
{
AssetImporter importer = target as AssetImporter;
string assetName = Path.GetFileNameWithoutExtension(importer.assetPath);
string path = String.Format("Temp/GeneratedFromGraph-{0}-Preview.shader", assetName.Replace(" ", ""));
var graphData = GetGraphData(importer);
var generator = new Generator(graphData, null, GenerationMode.Preview, $"{assetName}-Preview", humanReadable: true);
if (GraphUtil.WriteToFile(path, generator.generatedShader))
GraphUtil.OpenFile(path);
}
}
if (GUILayout.Button("Copy Shader"))
{
AssetImporter importer = target as AssetImporter;
string assetName = Path.GetFileNameWithoutExtension(importer.assetPath);
var graphData = GetGraphData(importer);
var generator = new Generator(graphData, null, GenerationMode.ForReals, assetName, humanReadable: true);
GUIUtility.systemCopyBuffer = generator.generatedShader;
}
EditorGUI.BeginDisabled(EditorApplication.isPlaying);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(useAsTemplateProp);
using (new EditorGUI.IndentLevelScope(1))
using (new EditorGUI.DisabledScope(!useAsTemplateProp.boolValue))
{
EditorGUILayout.PropertyField(exposeTemplateAsShaderProp, new GUIContent("Expose as Shader", "Toggle whether or not the template shader should be exposed in shader dropdowns."));
EditorGUILayout.PropertyField(templateProp);
}
EditorGUI.EndDisabled();
ApplyRevertGUI();
if (materialEditor)
{
EditorGUILayout.Space();
materialEditor.DrawHeader();
using (new EditorGUI.DisabledGroupScope(true))
materialEditor.OnInspectorGUI();
}
}
public override void OnEnable()
{
base.OnEnable();
AssetImporter importer = (AssetImporter)target;
var material = AssetDatabase.LoadAssetAtPath<Material>(importer.assetPath);
if (material)
materialEditor = (MaterialEditor)CreateEditor(material);
}
public override void OnDisable()
{
base.OnDisable();
if (materialEditor != null)
DestroyImmediate(materialEditor);
}
internal static bool ShowGraphEditWindow(string path, bool disablePreviewsForTesting = false)
{
var guid = AssetDatabase.AssetPathToGUID(path);
var extension = Path.GetExtension(path);
if (string.IsNullOrEmpty(extension))
return false;
// Path.GetExtension returns the extension prefixed with ".", so we remove it. We force lower case such that
// the comparison will be case-insensitive.
extension = extension.Substring(1).ToLowerInvariant();
if (extension != ShaderGraphImporter.Extension && extension != ShaderSubGraphImporter.Extension)
return false;
foreach (var w in Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>())
{
if (w.selectedGuid == guid)
{
if (w.m_Parent != null)
{
w.Focus();
return true;
}
}
}
var window = EditorWindow.CreateWindow<MaterialGraphEditWindow>(typeof(MaterialGraphEditWindow), typeof(SceneView));
window.m_DisablePreviewsForTesting = disablePreviewsForTesting;
window.Initialize(guid);
window.Focus();
return true;
}
[OnOpenAsset(0)]
public static bool OnOpenAsset(EntityId entityId, int line)
{
var path = AssetDatabase.GetAssetPath(entityId);
return ShowGraphEditWindow(path);
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 575791f1eb8b54602829004c8bcbe802
timeCreated: 1503169819
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,19 @@
using System;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Serializable]
class ShaderGraphIndexedData : ScriptableObject
{
[SerializeField] internal Experimental.GraphView.DataBag additionalSearchTerms;
public Experimental.GraphView.DataBag AdditionalSeachTerms
{
get => additionalSearchTerms;
set => additionalSearchTerms = value;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6c86adf534154b62940167041ccb0bee
timeCreated: 1769180573
@@ -0,0 +1,26 @@
using UnityEditor.Experimental.GraphView;
using UnityEditor.Search;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
static class ShaderGraphIndexerExtension
{
static void ShaderGraphIndexer(CustomObjectIndexerTarget context, ObjectIndexer indexer)
{
if (ShaderGraphTemplateHelper.TryGetTemplateStatic(context.id, out var template, out var dataBag))
{
GraphViewIndexerExtension.IndexCommonData<ShaderGraphImporter>(context, indexer, template);
GraphViewIndexerExtension.IndexCustomData<ShaderGraphImporter>(context, indexer, dataBag.GetCustomData($"{template.ToolKey}."));
}
}
[CustomObjectIndexer(typeof(ShaderGraphImporter), version = 2)]
internal static void ShaderGraphImporterIndexer(CustomObjectIndexerTarget context, ObjectIndexer indexer)
=> ShaderGraphIndexer(context, indexer);
[CustomObjectIndexer(typeof(Shader), version = 2)]
internal static void ShaderGraphShaderIndexer(CustomObjectIndexerTarget context, ObjectIndexer indexer)
=> ShaderGraphIndexer(context, indexer);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1da453bbfb3b450fa1b226dbffebffbb
timeCreated: 1763474542
@@ -0,0 +1,204 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.ShaderGraph.Internal;
using UnityEngine;
using static UnityEditor.ShaderGraph.CategoryDataCollection;
using Object = UnityEngine.Object;
namespace UnityEditor.ShaderGraph
{
[Serializable]
struct GraphInputData
{
public string referenceName;
public bool isKeyword;
public PropertyType propertyType;
public KeywordType keywordType;
public bool isCompoundProperty;
public List<SubPropertyData> subProperties;
public string tooltip;
public override bool Equals(object obj)
{
if (obj is null || obj is not GraphInputData o)
return false;
if (subProperties is null != o.subProperties is null
|| referenceName is null != o.referenceName is null
|| tooltip is null != o.tooltip is null
|| referenceName is not null && !referenceName.Equals(o.referenceName)
|| !isKeyword.Equals(o.isKeyword)
|| !propertyType.Equals(o.propertyType)
|| !keywordType.Equals(o.keywordType)
|| !isCompoundProperty.Equals(o.isCompoundProperty)
// || tooltip is not null && !tooltip.Equals(o.tooltip)
|| subProperties is not null && !subProperties.Count.Equals(o.subProperties.Count))
return false;
if (subProperties is not null)
for (int i = 0; i < subProperties.Count; ++i)
if (!subProperties[i].Equals(o.subProperties[i]))
return false;
return true;
}
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(referenceName);
hash.Add(isKeyword);
hash.Add(propertyType);
hash.Add(keywordType);
hash.Add(isCompoundProperty);
// hash.Add(tooltip); This is not part of the graph inputs identity.
if (subProperties is not null)
foreach (var subproperty in subProperties)
{
hash.Add(subproperty.referenceName);
hash.Add(subproperty.propertyType);
}
return hash.ToHashCode();
}
}
[Serializable]
struct SubPropertyData
{
public string referenceName;
public PropertyType propertyType;
}
[Serializable]
class MinimalCategoryData
{
// ShaderLab doesn't understand virtual texture inputs, they need to be processed to replace the virtual texture input with the layers that compose it instead
public static GraphInputData ProcessVirtualTextureProperty(VirtualTextureShaderProperty virtualTextureShaderProperty)
{
var layerReferenceNames = new List<string>();
virtualTextureShaderProperty.GetPropertyReferenceNames(layerReferenceNames);
var virtualTextureLayerDataList = new List<SubPropertyData>();
// Skip the first entry in this list as that's the Virtual Texture reference name itself, which won't exist in ShaderLab
foreach (var referenceName in layerReferenceNames.Skip(1))
{
var layerPropertyData = new SubPropertyData() { referenceName = referenceName, propertyType = PropertyType.Texture2D };
virtualTextureLayerDataList.Add(layerPropertyData);
}
var virtualTexturePropertyData = new GraphInputData() { referenceName = virtualTextureShaderProperty.displayName, propertyType = PropertyType.VirtualTexture, isKeyword = false };
virtualTexturePropertyData.isCompoundProperty = true;
virtualTexturePropertyData.subProperties = virtualTextureLayerDataList;
return virtualTexturePropertyData;
}
public static bool TryProcessInput(ShaderInput input, out GraphInputData data)
{
data = default;
if (!input.isExposed)
return false;
string tooltip = "";
if (input.promoteToFinalShader)
tooltip = $"from {input.PromotedAssetPath}";
switch(input)
{
case VirtualTextureShaderProperty vt:
data = ProcessVirtualTextureProperty(vt);
return true;
case AbstractShaderProperty prop:
data = new GraphInputData() { referenceName = prop.referenceName, propertyType = prop.propertyType, isKeyword = false, tooltip = tooltip };
return true;
case ShaderKeyword keyword:
var sanitizedReferenceName = keyword.referenceName;
if (keyword.keywordType == KeywordType.Boolean && keyword.referenceName.Contains("_ON"))
sanitizedReferenceName = sanitizedReferenceName.Replace("_ON", String.Empty);
data = new GraphInputData() { referenceName = sanitizedReferenceName, keywordType = keyword.keywordType, isKeyword = true, tooltip = tooltip };
return true;
default:
return false;
}
}
public string categoryName;
public List<GraphInputData> propertyDatas;
[NonSerialized]
public bool expanded = true;
}
class ShaderGraphMetadata : ScriptableObject
{
public string outputNodeTypeName;
// these asset dependencies are stored here as a way for "Export Package..." to discover them
// and automatically pull them in to the .unitypackage
public List<Object> assetDependencies;
public List<MinimalCategoryData> categoryDatas;
}
internal class CategoryDataCollection
{
HashSet<(GraphInputData input, string category)> lookup = new();
Dictionary<string, int> categoryScores = new();
Dictionary<GraphInputData, int> propertyScores = new();
internal void Set(string categoryName, GraphInputData data, int propertyScore = 0, int categoryScore = 0)
{
if (!categoryScores.TryAdd(categoryName, categoryScore) && categoryScore < categoryScores[categoryName])
categoryScores[categoryName] = categoryScore;
if (!propertyScores.TryAdd(data, propertyScore) && propertyScore < propertyScores[data])
propertyScores[data] = propertyScore;
// append the tooltip if it doesn't already exist.
if (lookup.TryGetValue((data, categoryName), out var currentEntry) && !currentEntry.input.tooltip.Contains(data.tooltip))
{
lookup.Remove((data, categoryName));
currentEntry.input.tooltip += $"\n{data.tooltip}";
lookup.Add(currentEntry);
}
else lookup.Add((data, categoryName));
}
internal List<MinimalCategoryData> GenerateMCD()
{
var result = new List<MinimalCategoryData>();
var buckets = new Dictionary<string, List<GraphInputData>>();
var order = new List<string>(categoryScores.Keys);
order.Sort((a, b) => {
var score = categoryScores[a].CompareTo(categoryScores[b]);
if (score == 0) score = a.CompareTo(b);
return score;
});
foreach(var data in lookup)
{
buckets.TryAdd(data.category, new());
buckets[data.category].Add(data.input);
}
foreach(var name in order)
{
if (!buckets.ContainsKey(name))
continue;
buckets[name].Sort((a, b) => {
var score = propertyScores[a].CompareTo(propertyScores[b]);
if (score == 0) score = a.referenceName.CompareTo(b.referenceName);
return score;
});
result.Add(new() { categoryName = name, propertyDatas = buckets[name] });
}
return result;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b64ab828cd6c5b3479a4c575ca6617d5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,52 @@
using System;
using UnityEditor.ShaderGraph.Serialization;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Serializable]
struct ShaderGraphTemplate
{
public string name;
public string category;
[Multiline]
public string description;
public Texture2D icon;
public Texture2D thumbnail;
public int order;
internal static Experimental.GraphView.DataBag GatherSearchTerms(GraphData graph)
{
// clear the existing terms, as this object's serialization persists across imports.
var additionalSearchTerms = default(Experimental.GraphView.DataBag);
if (graph is null || graph.objectIdIsEmpty)
return additionalSearchTerms;
foreach (var target in graph.activeTargets)
{
if (target is null or MultiJsonInternal.UnknownTargetType || target.objectIdIsEmpty || target.activeSubTarget is null || target.activeSubTarget.objectIdIsEmpty)
continue;
additionalSearchTerms.AddCustomData("RenderPipeline", target.displayName);
additionalSearchTerms.AddCustomData("Material", target.activeSubTarget.displayName);
additionalSearchTerms.AddCustomData("VFX", target.SupportsVFX() ? "Supported" : "Not Supported");
if (target.SearchTerms != null)
foreach (var term in target.SearchTerms)
additionalSearchTerms.AddCustomData(term.key, term.value);
if (target.activeSubTarget.SearchTerms != null)
foreach (var term in target.activeSubTarget.SearchTerms)
additionalSearchTerms.AddCustomData(term.key, term.value);
}
foreach (var subData in graph.SubDatas)
if (subData == null || subData is MultiJsonInternal.UnknownGraphDataExtension || subData.objectIdIsEmpty || string.IsNullOrEmpty(subData.displayName))
continue;
else additionalSearchTerms.AddCustomData("DataExtension", subData.displayName);
return additionalSearchTerms;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f0349177f7b8495389bcfe64a9e6a475
timeCreated: 1744226977
@@ -0,0 +1,118 @@
using System;
using System.IO;
using UnityEditor.Experimental.GraphView;
using UnityEditor.Search;
using UnityEngine;
using UnityEngine.Rendering.ShaderGraph;
namespace UnityEditor.ShaderGraph
{
class ShaderGraphTemplateHelper : ITemplateHelper
{
class SaveFileDialog : GraphViewTemplateWindow.ISaveFileDialogHelper
{
public string OpenSaveFileDialog()
{
return EditorUtility.SaveFilePanelInProject("", "New Shader Graph", "shadergraph", "Create new Shader Graph");
}
}
public static string ShaderGraphToolKey => "ShaderGraph";
public string toolKey => ShaderGraphToolKey;
public string packageInfoName => "Shader Graph";
public string learningSampleName => string.Empty;
public string templateWindowDocUrl => Documentation.GetPageLink("index");
public string builtInTemplatePath => string.Empty;
public string builtInCategory => string.Empty;
public Type assetType => typeof(Shader);
public string createNewAssetTitle => "Create new Shader Graph Asset";
public string insertTemplateTitle => "Insert a template into current Shader Graph Asset";
public string emptyTemplateGuid => null;
public string customTemplateIcon => "Packages/com.unity.shadergraph/Editor/Resources/Icons/sg_graph_icon@2x.png";
public bool showPackageIndexingBanner { get; set; } = true;
public GraphViewTemplateWindow.ISaveFileDialogHelper saveFileDialogHelper { get; set; } = new SaveFileDialog();
public void RaiseTemplateUsed(GraphViewTemplateDescriptor usedTemplate) =>
ShaderGraphAnalytics.SendShaderGraphTemplateEvent(usedTemplate);
public bool TryGetTemplate(string assetPath, out GraphViewTemplateDescriptor graphViewTemplate) => TryGetTemplateStatic(assetPath, out graphViewTemplate, out _);
internal static bool TryGetTemplateStatic(string assetPath, out GraphViewTemplateDescriptor graphViewTemplate, out DataBag dataBag)
{
if (FileUtilities.TryGetImporter(assetPath, out var importer))
{
dataBag = importer.AdditionalSearchTerms;
var template = importer.Template;
if (importer.UseAsTemplate)
{
graphViewTemplate = new GraphViewTemplateDescriptor(ShaderGraphToolKey)
{
name = template.name,
category = template.category,
description = template.description,
icon = template.icon,
thumbnail = template.thumbnail,
searchTerms = dataBag,
};
return true;
}
}
graphViewTemplate = default;
return false;
}
public bool TrySetTemplate(string assetPath, GraphViewTemplateDescriptor graphViewTemplate)
{
if (FileUtilities.TryGetImporter(assetPath, out var importer))
{
importer.UseAsTemplate = true;
var template = new ShaderGraphTemplate
{
name = graphViewTemplate.name,
category = graphViewTemplate.category,
description = graphViewTemplate.description,
icon = graphViewTemplate.icon,
thumbnail = graphViewTemplate.thumbnail,
order = graphViewTemplate.order,
};
importer.Template = template;
return true;
}
return false;
}
internal static bool TryGetTemplateDescriptor(string assetPath, out GraphViewTemplateDescriptor graphViewTemplate)
{
if (FileUtilities.TryGetImporter(assetPath, out var importer))
{
var template = importer.Template;
if (importer.UseAsTemplate)
{
var templateName = !string.IsNullOrEmpty(template.name) ? template.name : Path.GetFileNameWithoutExtension(assetPath);
graphViewTemplate = new GraphViewTemplateDescriptor(ShaderGraphToolKey)
{
name = templateName,
category = template.category,
description = template.description,
icon = template.icon,
thumbnail = template.thumbnail,
order = template.order,
};
return true;
}
}
graphViewTemplate = default;
return false;
}
public ITemplateSorter[] GetTemplateSorter() => Array.Empty<ITemplateSorter>();
public SearchProposition[] GetSearchPropositions()
{
return Array.Empty<SearchProposition>();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f8a051cd8f1045d1bbb37860ed4ef796
timeCreated: 1744151320
@@ -0,0 +1,588 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
#if UNITY_2020_2_OR_NEWER
using UnityEditor.AssetImporters;
#else
using UnityEditor.Experimental.AssetImporters;
#endif
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.Graphing.Util;
using UnityEditor.ShaderGraph.Internal;
using UnityEditor.ShaderGraph.Serialization;
using UnityEngine.Pool;
using UnityEngine.Rendering;
namespace UnityEditor.ShaderGraph
{
[ExcludeFromPreset]
[ScriptedImporter(31, Extension, -905)]
[CoreRPHelpURL("Sub-graph", "com.unity.shadergraph")]
class ShaderSubGraphImporter : ScriptedImporter
{
[SerializeField, HideInInspector]
private string documentationPath;
public const string Extension = "shadersubgraph";
const string IconPath = "Packages/com.unity.shadergraph/Editor/Resources/Icons/sg_subgraph_icon@2x.png";
public static Texture2D GetIcon() => AssetDatabase.LoadAssetAtPath<Texture2D>(IconPath);
[SuppressMessage("ReSharper", "UnusedMember.Local")]
static string[] GatherDependenciesFromSourceFile(string assetPath)
{
try
{
AssetCollection assetCollection = new AssetCollection();
MinimalGraphData.GatherMinimalDependenciesFromFile(assetPath, assetCollection);
List<string> dependencyPaths = new List<string>
{
IconPath
};
foreach (var asset in assetCollection.assets)
{
// only artifact dependencies need to be declared in GatherDependenciesFromSourceFile
// to force their imports to run before ours
if (asset.Value.HasFlag(AssetCollection.Flags.ArtifactDependency))
{
var dependencyPath = AssetDatabase.GUIDToAssetPath(asset.Key);
// it is unfortunate that we can't declare these dependencies unless they have a path...
// I asked AssetDatabase team for GatherDependenciesFromSourceFileByGUID()
if (!string.IsNullOrEmpty(dependencyPath))
dependencyPaths.Add(dependencyPath);
}
}
return dependencyPaths.ToArray();
}
catch (Exception e)
{
Debug.LogException(e);
return new string[0];
}
}
static bool NodeWasUsedByGraph(string nodeId, GraphData graphData)
{
var node = graphData.GetNodeFromId(nodeId);
return node?.wasUsedByGenerator ?? false;
}
public override void OnImportAsset(AssetImportContext ctx)
{
var importLog = new ShaderGraphImporter.AssetImportErrorLog(ctx);
var graphAsset = ScriptableObject.CreateInstance<SubGraphAsset>();
var subGraphPath = ctx.assetPath;
var subGraphGuid = AssetDatabase.AssetPathToGUID(subGraphPath);
graphAsset.assetGuid = subGraphGuid;
var textGraph = FileUtilities.ReadAllTextUTF8(subGraphPath);
var messageManager = new MessageManager();
var graphData = new GraphData
{
isSubGraph = true,
assetGuid = subGraphGuid,
messageManager = messageManager
};
MultiJson.Deserialize(graphData, textGraph);
try
{
ProcessSubGraph(graphAsset, graphData, importLog, documentationPath);
}
catch (Exception e)
{
graphAsset.isValid = false;
Debug.LogException(e, graphAsset);
}
finally
{
var errors = messageManager.ErrorStrings((nodeId) => NodeWasUsedByGraph(nodeId, graphData));
int errCount = errors.Count();
if (errCount > 0)
{
var firstError = errors.FirstOrDefault();
importLog.LogError($"Sub Graph at {subGraphPath} has {errCount} error(s), the first is: {firstError}", graphAsset);
graphAsset.isValid = false;
}
else
{
var warnings = messageManager.ErrorStrings((nodeId) => NodeWasUsedByGraph(nodeId, graphData), Rendering.ShaderCompilerMessageSeverity.Warning);
int warningCount = warnings.Count();
if (warningCount > 0)
{
var firstWarning = warnings.FirstOrDefault();
importLog.LogWarning($"Sub Graph at {subGraphPath} has {warningCount} warning(s), the first is: {firstWarning}", graphAsset);
}
}
messageManager.ClearAll();
}
ctx.AddObjectToAsset("MainAsset", graphAsset, GetIcon());
ctx.SetMainObject(graphAsset);
var metadata = ScriptableObject.CreateInstance<ShaderSubGraphMetadata>();
metadata.hideFlags = HideFlags.HideInHierarchy;
metadata.assetDependencies = new List<UnityEngine.Object>();
AssetCollection assetCollection = new AssetCollection();
MinimalGraphData.GatherMinimalDependenciesFromFile(assetPath, assetCollection);
foreach (var asset in assetCollection.assets)
{
if (asset.Value.HasFlag(AssetCollection.Flags.IncludeInExportPackage))
{
// this sucks that we have to fully load these assets just to set the reference,
// which then gets serialized as the GUID that we already have here. :P
var dependencyPath = AssetDatabase.GUIDToAssetPath(asset.Key);
if (!string.IsNullOrEmpty(dependencyPath))
{
metadata.assetDependencies.Add(
AssetDatabase.LoadAssetAtPath(dependencyPath, typeof(UnityEngine.Object)));
}
}
}
ctx.AddObjectToAsset("Metadata", metadata);
// declare dependencies
foreach (var asset in assetCollection.assets)
{
if (asset.Value.HasFlag(AssetCollection.Flags.SourceDependency))
{
ctx.DependsOnSourceAsset(asset.Key);
// I'm not sure if this warning below is actually used or not, keeping it to be safe
var assetPath = AssetDatabase.GUIDToAssetPath(asset.Key);
// Ensure that dependency path is relative to project
if (!string.IsNullOrEmpty(assetPath) && !assetPath.StartsWith("Packages/") && !assetPath.StartsWith("Assets/"))
{
importLog.LogWarning($"Invalid dependency path: {assetPath}", graphAsset);
}
}
// NOTE: dependencies declared by GatherDependenciesFromSourceFile are automatically registered as artifact dependencies
// HOWEVER: that path ONLY grabs dependencies via MinimalGraphData, and will fail to register dependencies
// on GUIDs that don't exist in the project. For both of those reasons, we re-declare the dependencies here.
if (asset.Value.HasFlag(AssetCollection.Flags.ArtifactDependency))
{
ctx.DependsOnArtifact(asset.Key);
}
}
}
static void ProcessSubGraph(SubGraphAsset asset, GraphData graph, ShaderGraphImporter.AssetImportErrorLog importLog, string documentationPath)
{
var graphIncludes = new IncludeCollection();
var registry = new FunctionRegistry(new ShaderStringBuilder(), graphIncludes, true);
asset.functions.Clear();
asset.isValid = true;
graph.OnEnable();
graph.messageManager.ClearAll();
graph.ValidateGraph();
var assetPath = AssetDatabase.GUIDToAssetPath(asset.assetGuid);
asset.hlslName = NodeUtils.GetHLSLSafeName(Path.GetFileNameWithoutExtension(assetPath));
asset.inputStructName = $"Bindings_{asset.hlslName}_{asset.assetGuid}_$precision";
asset.functionName = $"SG_{asset.hlslName}_{asset.assetGuid}_$precision";
asset.path = graph.path;
asset.documentationPath = documentationPath;
asset.isDeprecated = graph.m_DeprecateSubgraph;
asset.deprecationMessage = graph.m_DeprecateSubgraphMessage;
var outputNode = graph.outputNode;
var outputSlots = UnityEngine.Pool.ListPool<MaterialSlot>.Get();
outputNode.GetInputSlots(outputSlots);
List<AbstractMaterialNode> nodes = new List<AbstractMaterialNode>();
NodeUtils.DepthFirstCollectNodesFromNode(nodes, outputNode);
// flag the used nodes so we can filter out errors from unused nodes
foreach (var node in nodes)
node.SetUsedByGenerator();
// Start with a clean slate for the input/output capabilities and dependencies
asset.inputCapabilities.Clear();
asset.outputCapabilities.Clear();
asset.slotDependencies.Clear();
ShaderStageCapability effectiveShaderStage = ShaderStageCapability.All;
var shaderStageCapabilityCache = new Dictionary<SlotReference, ShaderStageCapability>();
foreach (var slot in outputSlots)
{
var stage = NodeUtils.GetEffectiveShaderStageCapability(slot, true, shaderStageCapabilityCache);
if (effectiveShaderStage == ShaderStageCapability.All && stage != ShaderStageCapability.All)
effectiveShaderStage = stage;
asset.outputCapabilities.Add(new SlotCapability { slotName = slot.RawDisplayName(), capabilities = stage });
// Find all unique property nodes used by this slot and record a dependency for this input/output pair
var inputPropertyNames = new HashSet<string>();
var nodeSet = new HashSet<AbstractMaterialNode>();
NodeUtils.CollectNodeSet(nodeSet, slot);
foreach (var node in nodeSet)
{
if (node is PropertyNode propNode && !inputPropertyNames.Contains(propNode.property.displayName))
{
inputPropertyNames.Add(propNode.property.displayName);
var slotDependency = new SlotDependencyPair();
slotDependency.inputSlotName = propNode.property.displayName;
slotDependency.outputSlotName = slot.RawDisplayName();
asset.slotDependencies.Add(slotDependency);
}
}
}
CollectInputCapabilities(asset, graph);
asset.vtFeedbackVariables = VirtualTexturingFeedbackUtils.GetFeedbackVariables(outputNode as SubGraphOutputNode);
asset.requirements = ShaderGraphRequirements.FromNodes(nodes, effectiveShaderStage, false);
// output precision is whatever the output node has as a graph precision, falling back to the graph default
asset.outputGraphPrecision = outputNode.graphPrecision.GraphFallback(graph.graphDefaultPrecision);
// this saves the graph precision, which indicates whether this subgraph is switchable or not
asset.subGraphGraphPrecision = graph.graphDefaultPrecision;
asset.previewMode = graph.previewMode;
asset.includes = graphIncludes;
GatherDescendentsFromGraph(new GUID(asset.assetGuid), out var containsCircularDependency, out var descendents);
asset.descendents.AddRange(descendents.Select(g => g.ToString()));
asset.descendents.Sort(); // ensure deterministic order
var keywordCollector = new KeywordCollector();
graph.CollectShaderKeywords(keywordCollector, GenerationMode.ForReals);
var childrenSet = new HashSet<string>();
var anyErrors = false;
asset.hasPromotedPropertiesInInspector = false;
foreach (var node in nodes)
{
if (node is SubGraphNode subGraphNode)
{
var subGraphGuid = subGraphNode.subGraphGuid;
if (childrenSet.Add(subGraphGuid))
subGraphNode.CollectShaderKeywords(keywordCollector, GenerationMode.ForReals);
if (!asset.hasPromotedPropertiesInInspector
&& subGraphNode.asset != null
&& subGraphNode.asset.hasPromotedPropertiesInInspector)
{
asset.hasPromotedPropertiesInInspector = true;
}
}
else
{
node.CollectShaderKeywords(keywordCollector, GenerationMode.ForReals);
}
if (node.hasError)
{
anyErrors = true;
}
asset.children = childrenSet.ToList();
asset.children.Sort(); // ensure deterministic order
}
if (!anyErrors && containsCircularDependency)
{
importLog.LogError($"Error in Graph at {assetPath}: Sub Graph contains a circular dependency.", asset);
anyErrors = true;
}
if (anyErrors)
{
asset.isValid = false;
registry.ProvideFunction(asset.functionName, sb => { });
UnityEngine.Pool.ListPool<MaterialSlot>.Release(outputSlots);
return;
}
foreach (var node in nodes)
{
if (node is IGeneratesFunction generatesFunction)
{
registry.builder.currentNode = node;
generatesFunction.GenerateNodeFunction(registry, GenerationMode.ForReals);
}
}
// Need to order the properties so that they are in the same order on a subgraph node in a shadergraph
// as they are in the blackboard for the subgraph itself. The (blackboard) categories keep that ordering,
// so traverse those and add those items to the ordered properties list. Needs to be used to set up the
// function _and_ to write out the final asset data so that the function call parameter order matches as well.
var orderedProperties = new List<AbstractShaderProperty>();
var collector = new PropertyCollector(); // for promoted properties or properties from nodes.
var propertiesList = graph.properties.ToList();
int order = 0;
foreach (var category in graph.categories)
{
foreach (var child in category.Children)
{
if (child != null && child.promoteToFinalShader)
{
child.promotedFromCategoryName = category.IsNamedCategory() ? category.name : null;
child.promotedOrdering = order++;
child.promotedFromAssetID = asset.assetGuid;
if (child is AbstractShaderProperty asProp)
collector.AddShaderProperty(asProp);
else if (child is ShaderKeyword asKeyword)
keywordCollector.AddShaderKeyword(asKeyword);
continue;
}
// Not all properties in the category are actually on the graph.
// In particular, it seems as if keywords are not properties on sub-graphs.
var prop = propertiesList.Find(p => p.guid == child.guid);
if (prop != null && !orderedProperties.Contains(prop))
orderedProperties.Add(prop);
}
}
// If we are importing an older file that has not had categories generated for it yet, include those now.
foreach(var prop in graph.properties)
{
if (prop == null)
continue;
if (prop.promoteToFinalShader)
{
if (prop.GetDefaultHLSLDeclaration() != HLSLDeclaration.Global)
asset.hasPromotedPropertiesInInspector = true;
continue;
}
if(orderedProperties.Contains(prop))
continue;
orderedProperties.Add(prop);
}
// provide top level subgraph function
// NOTE: actual concrete precision here shouldn't matter, it's irrelevant when building the subgraph asset
registry.ProvideFunction(asset.functionName, asset.subGraphGraphPrecision, ConcretePrecision.Single, sb =>
{
GenerationUtils.GenerateSurfaceInputStruct(sb, asset.requirements, asset.inputStructName);
sb.AppendNewLine();
// Generate the arguments... first INPUTS
var arguments = new List<string>();
foreach (var prop in orderedProperties)
{
// apply fallback to the graph default precision (but don't convert to concrete)
// this means "graph switchable" properties will use the precision token
GraphPrecision propGraphPrecision = prop.precision.ToGraphPrecision(graph.graphDefaultPrecision);
string precisionString = propGraphPrecision.ToGenericString();
arguments.Add(prop.GetPropertyAsArgumentString(precisionString));
if (prop.isConnectionTestable)
{
arguments.Add($"bool {prop.GetConnectionStateHLSLVariableName()}");
}
}
{
var dropdowns = graph.dropdowns;
foreach (var dropdown in dropdowns)
arguments.Add($"int {dropdown.referenceName}");
}
// now pass surface inputs
arguments.Add(string.Format("{0} IN", asset.inputStructName));
// Now generate output arguments
foreach (MaterialSlot output in outputSlots)
arguments.Add($"out {output.concreteValueType.ToShaderString(asset.outputGraphPrecision.ToGenericString())} {output.shaderOutputName}_{output.id}");
// Vt Feedback output arguments (always full float4)
foreach (var output in asset.vtFeedbackVariables)
arguments.Add($"out {ConcreteSlotValueType.Vector4.ToShaderString(ConcretePrecision.Single)} {output}_out");
if (asset.hasPromotedPropertiesInInspector)
{
sb.AppendLine("void {0}({1}"
, asset.functionName
, string.Join(", ", arguments));
sb.AppendLine("#ifdef HAVE_VFX_MODIFICATION");
sb.AppendLine(", GraphProperties PROP");
sb.AppendLine("#endif");
sb.AppendLine(")");
}
else
{
sb.AppendLine("void {0}({1})"
, asset.functionName
, string.Join(", ", arguments));
}
// now generate the function
using (sb.BlockScope())
{
// Just grab the body from the active nodes
foreach (var node in nodes)
{
if (node is IGeneratesBodyCode generatesBodyCode)
{
sb.currentNode = node;
generatesBodyCode.GenerateNodeCode(sb, GenerationMode.ForReals);
if (node.graphPrecision == GraphPrecision.Graph)
{
// code generated by nodes that use graph precision stays in generic form with embedded tokens
// those tokens are replaced when this subgraph function is pulled into a graph that defines the precision
}
else
{
sb.ReplaceInCurrentMapping(PrecisionUtil.Token, node.concretePrecision.ToShaderString());
}
}
}
foreach (var slot in outputSlots)
{
sb.AppendLine($"{slot.shaderOutputName}_{slot.id} = {outputNode.GetSlotValue(slot.id, GenerationMode.ForReals)};");
}
foreach (var slot in asset.vtFeedbackVariables)
{
sb.AppendLine($"{slot}_out = {slot};");
}
}
});
// save all of the node-declared functions to the subgraph asset
foreach (var name in registry.names)
{
var source = registry.sources[name];
var func = new FunctionPair(name, source.code, source.graphPrecisionFlags);
asset.functions.Add(func);
}
foreach (var node in nodes)
{
int previousPropertyCount = Math.Max(0, collector.propertyCount - 1);
node.CollectShaderProperties(collector, GenerationMode.ForReals);
// This is a stop-gap to prevent the autogenerated values from JsonObject and ShaderInput from
// resulting in non-deterministic import data. While we should move to local ids in the future,
// this will prevent cascading shader recompilations.
for (int i = previousPropertyCount; i < collector.propertyCount; ++i)
{
var prop = collector.GetProperty(i);
var namespaceId = node.objectId;
var nameId = prop.referenceName;
prop.OverrideObjectId(namespaceId, nameId + "_ObjectId_" + i);
prop.OverrideGuid(namespaceId, nameId + "_Guid_" + i);
}
}
asset.WriteData(orderedProperties, keywordCollector.keywords, graph.dropdowns, collector.properties, outputSlots, graph.unsupportedTargets);
UnityEngine.Pool.ListPool<MaterialSlot>.Release(outputSlots);
}
static void GatherDescendentsFromGraph(GUID rootAssetGuid, out bool containsCircularDependency, out HashSet<GUID> descendentGuids)
{
var dependencyMap = new Dictionary<GUID, GUID[]>();
AssetCollection tempAssetCollection = new AssetCollection();
using (UnityEngine.Pool.ListPool<GUID>.Get(out var tempList))
{
GatherDependencyMap(rootAssetGuid, dependencyMap, tempAssetCollection);
containsCircularDependency = ContainsCircularDependency(rootAssetGuid, dependencyMap, tempList);
}
descendentGuids = new HashSet<GUID>();
GatherDescendentsUsingDependencyMap(rootAssetGuid, descendentGuids, dependencyMap);
}
static void GatherDependencyMap(GUID rootAssetGUID, Dictionary<GUID, GUID[]> dependencyMap, AssetCollection tempAssetCollection)
{
if (!dependencyMap.ContainsKey(rootAssetGUID))
{
// if it is a subgraph, try to recurse into it
var assetPath = AssetDatabase.GUIDToAssetPath(rootAssetGUID);
if (!string.IsNullOrEmpty(assetPath) && assetPath.EndsWith(Extension, true, null))
{
tempAssetCollection.Clear();
MinimalGraphData.GatherMinimalDependenciesFromFile(assetPath, tempAssetCollection);
var subgraphGUIDs = tempAssetCollection.assets.Where(asset => asset.Value.HasFlag(AssetCollection.Flags.IsSubGraph)).Select(asset => asset.Key).ToArray();
dependencyMap[rootAssetGUID] = subgraphGUIDs;
foreach (var guid in subgraphGUIDs)
{
GatherDependencyMap(guid, dependencyMap, tempAssetCollection);
}
}
}
}
static void GatherDescendentsUsingDependencyMap(GUID rootAssetGUID, HashSet<GUID> descendentGuids, Dictionary<GUID, GUID[]> dependencyMap)
{
var dependencies = dependencyMap[rootAssetGUID];
foreach (GUID dependency in dependencies)
{
if (descendentGuids.Add(dependency))
{
GatherDescendentsUsingDependencyMap(dependency, descendentGuids, dependencyMap);
}
}
}
static bool ContainsCircularDependency(GUID assetGUID, Dictionary<GUID, GUID[]> dependencyMap, List<GUID> ancestors)
{
if (ancestors.Contains(assetGUID))
{
return true;
}
ancestors.Add(assetGUID);
foreach (var dependencyGUID in dependencyMap[assetGUID])
{
if (ContainsCircularDependency(dependencyGUID, dependencyMap, ancestors))
{
return true;
}
}
ancestors.RemoveAt(ancestors.Count - 1);
return false;
}
static void CollectInputCapabilities(SubGraphAsset asset, GraphData graph)
{
// Collect each input's capabilities. There can be multiple property nodes
// contributing to the same input, so we cache these in a map while building
var inputCapabilities = new Dictionary<string, SlotCapability>();
var shaderStageCapabilityCache = new Dictionary<SlotReference, ShaderStageCapability>();
// Walk all property node output slots, computing and caching the capabilities for that slot
var propertyNodes = graph.GetNodes<PropertyNode>();
foreach (var propertyNode in propertyNodes)
{
foreach (var slot in propertyNode.GetOutputSlots<MaterialSlot>())
{
var slotName = slot.RawDisplayName();
SlotCapability capabilityInfo;
if (!inputCapabilities.TryGetValue(slotName, out capabilityInfo))
{
capabilityInfo = new SlotCapability();
capabilityInfo.slotName = slotName;
inputCapabilities.Add(propertyNode.property.displayName, capabilityInfo);
}
capabilityInfo.capabilities &= NodeUtils.GetEffectiveShaderStageCapability(slot, false, shaderStageCapabilityCache);
}
}
asset.inputCapabilities.AddRange(inputCapabilities.Values);
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 60072b568d64c40a485e0fc55012dc9f
timeCreated: 1495613811
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,30 @@
using UnityEditor;
#if UNITY_2020_2_OR_NEWER
using UnityEditor.AssetImporters;
#else
using UnityEditor.Experimental.AssetImporters;
#endif
using UnityEngine;
using Debug = System.Diagnostics.Debug;
namespace UnityEditor.ShaderGraph
{
[CustomEditor(typeof(ShaderSubGraphImporter))]
class ShaderSubGraphImporterEditor : ScriptedImporterEditor
{
public override bool showImportedObject => Unsupported.IsDeveloperMode();
protected override bool needsApplyRevert => false;
public override void OnInspectorGUI()
{
if (GUILayout.Button("Open Shader Editor"))
{
AssetImporter importer = target as AssetImporter;
Debug.Assert(importer != null, "importer != null");
ShaderGraphImporterEditor.ShowGraphEditWindow(importer.assetPath);
}
ApplyRevertGUI();
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: ca6b9d3e5c1927e4cb49fc3107f72c1c
timeCreated: 1503169819
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,10 @@
using System.Collections.Generic;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
class ShaderSubGraphMetadata : ScriptableObject
{
public List<Object> assetDependencies;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0169c6aa153625741a0b332e73a43fb2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: b7e9b48c3a9534782bdc85af295da963
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 5910b62eb45374b03ab137b783dc1f6a, type: 3}