浏览代码

Squash SerializableGraph into AbstractMaterialGraph

/main
Peter Bay Bastian 7 年前
当前提交
11a83d08
共有 7 个文件被更改,包括 404 次插入441 次删除
  1. 376
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/AbstractMaterialGraph.cs
  2. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/SerializableGraph/Implementation/SerializableGraphObject.cs
  3. 85
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/SerializedGraphTests.cs
  4. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/TestMaterialGraph.cs
  5. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/TestMaterialGraph.cs.meta
  6. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/SerializableGraph/Implementation/SerializableGraph.cs.meta
  7. 360
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/SerializableGraph/Implementation/SerializableGraph.cs

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


namespace UnityEditor.ShaderGraph
{
[Serializable]
public abstract class AbstractMaterialGraph : SerializableGraph, IGenerateProperties
public abstract class AbstractMaterialGraph : IGraph, ISerializationCallbackReceiver, IGenerateProperties
public IGraphObject owner { get; set; }
#region Property data
public IEnumerable<IShaderProperty> properties
{
get { return m_Properties; }
}
[SerializeField]
List<SerializationHelper.JSONSerializedElement> m_SerializedProperties = new List<SerializationHelper.JSONSerializedElement>();

public IEnumerable<IShaderProperty> addedProperties
{
get { return m_AddedProperties; }
}
public IEnumerable<Guid> removedProperties
{
get { return m_RemovedProperties; }
}
#endregion
#region Node data
InspectorPreviewData m_PreviewData = new InspectorPreviewData();
Dictionary<Guid, INode> m_Nodes = new Dictionary<Guid, INode>();
public InspectorPreviewData previewData
public IEnumerable<T> GetNodes<T>() where T : INode
get { return m_PreviewData; }
set { m_PreviewData = value; }
return m_Nodes.Values.OfType<T>();
public IEnumerable<IShaderProperty> properties
[SerializeField]
List<SerializationHelper.JSONSerializedElement> m_SerializableNodes = new List<SerializationHelper.JSONSerializedElement>();
[NonSerialized]
List<INode> m_AddedNodes = new List<INode>();
public IEnumerable<INode> addedNodes
get { return m_Properties; }
get { return m_AddedNodes; }
public IEnumerable<IShaderProperty> addedProperties
[NonSerialized]
List<INode> m_RemovedNodes = new List<INode>();
public IEnumerable<INode> removedNodes
get { return m_AddedProperties; }
get { return m_RemovedNodes; }
}
#endregion
#region Edge data
[NonSerialized]
List<IEdge> m_Edges = new List<IEdge>();
public IEnumerable<IEdge> edges
{
get { return m_Edges; }
}
[SerializeField]
List<SerializationHelper.JSONSerializedElement> m_SerializableEdges = new List<SerializationHelper.JSONSerializedElement>();
[NonSerialized]
Dictionary<Guid, List<IEdge>> m_NodeEdges = new Dictionary<Guid, List<IEdge>>();
[NonSerialized]
List<IEdge> m_AddedEdges = new List<IEdge>();
public IEnumerable<IEdge> addedEdges
{
get { return m_AddedEdges; }
public IEnumerable<Guid> removedProperties
[NonSerialized]
List<IEdge> m_RemovedEdges = new List<IEdge>();
public IEnumerable<IEdge> removedEdges
get { return m_RemovedProperties; }
get { return m_RemovedEdges; }
public override void ClearChanges()
#endregion
[NonSerialized]
InspectorPreviewData m_PreviewData = new InspectorPreviewData();
public InspectorPreviewData previewData
base.ClearChanges();
get { return m_PreviewData; }
set { m_PreviewData = value; }
}
public void ClearChanges()
{
m_AddedNodes.Clear();
m_RemovedNodes.Clear();
m_AddedEdges.Clear();
m_RemovedEdges.Clear();
public override void AddNode(INode node)
public virtual void AddNode(INode node)
base.AddNode(node);
AddNodeNoValidate(node);
ValidateGraph();
}
else
{

void AddNodeNoValidate(INode node)
{
m_Nodes.Add(node.guid, node);
node.owner = this;
m_AddedNodes.Add(node);
}
public void RemoveNode(INode node)
{
if (!node.canDeleteNode)
return;
m_Nodes.Remove(node.guid);
m_RemovedNodes.Add(node);
ValidateGraph();
}
void RemoveNodeNoValidate(INode node)
{
if (!node.canDeleteNode)
return;
m_Nodes.Remove(node.guid);
m_RemovedNodes.Add(node);
}
void AddEdgeToNodeEdges(IEdge edge)
{
List<IEdge> inputEdges;
if (!m_NodeEdges.TryGetValue(edge.inputSlot.nodeGuid, out inputEdges))
m_NodeEdges[edge.inputSlot.nodeGuid] = inputEdges = new List<IEdge>();
inputEdges.Add(edge);
List<IEdge> outputEdges;
if (!m_NodeEdges.TryGetValue(edge.outputSlot.nodeGuid, out outputEdges))
m_NodeEdges[edge.outputSlot.nodeGuid] = outputEdges = new List<IEdge>();
outputEdges.Add(edge);
}
IEdge ConnectNoValidate(SlotReference fromSlotRef, SlotReference toSlotRef)
{
var fromNode = GetNodeFromGuid(fromSlotRef.nodeGuid);
var toNode = GetNodeFromGuid(toSlotRef.nodeGuid);
if (fromNode == null || toNode == null)
return null;
// if fromNode is already connected to toNode
// do now allow a connection as toNode will then
// have an edge to fromNode creating a cycle.
// if this is parsed it will lead to an infinite loop.
var dependentNodes = new List<INode>();
NodeUtils.CollectNodesNodeFeedsInto(dependentNodes, toNode);
if (dependentNodes.Contains(fromNode))
return null;
var fromSlot = fromNode.FindSlot<ISlot>(fromSlotRef.slotId);
var toSlot = toNode.FindSlot<ISlot>(toSlotRef.slotId);
if (fromSlot.isOutputSlot == toSlot.isOutputSlot)
return null;
var outputSlot = fromSlot.isOutputSlot ? fromSlotRef : toSlotRef;
var inputSlot = fromSlot.isInputSlot ? fromSlotRef : toSlotRef;
s_TempEdges.Clear();
GetEdges(inputSlot, s_TempEdges);
// remove any inputs that exits before adding
foreach (var edge in s_TempEdges)
{
RemoveEdgeNoValidate(edge);
}
var newEdge = new Edge(outputSlot, inputSlot);
m_Edges.Add(newEdge);
m_AddedEdges.Add(newEdge);
AddEdgeToNodeEdges(newEdge);
//Debug.LogFormat("Connected edge: {0} -> {1} ({2} -> {3})\n{4}", newEdge.outputSlot.nodeGuid, newEdge.inputSlot.nodeGuid, fromNode.name, toNode.name, Environment.StackTrace);
return newEdge;
}
public virtual IEdge Connect(SlotReference fromSlotRef, SlotReference toSlotRef)
{
var newEdge = ConnectNoValidate(fromSlotRef, toSlotRef);
ValidateGraph();
return newEdge;
}
public virtual void RemoveEdge(IEdge e)
{
RemoveEdgeNoValidate(e);
ValidateGraph();
}
public void RemoveElements(IEnumerable<INode> nodes, IEnumerable<IEdge> edges)
{
foreach (var edge in edges.ToArray())
RemoveEdgeNoValidate(edge);
foreach (var serializableNode in nodes.ToArray())
RemoveNodeNoValidate(serializableNode);
ValidateGraph();
}
protected void RemoveEdgeNoValidate(IEdge e)
{
e = m_Edges.FirstOrDefault(x => x.Equals(e));
if (e == null)
throw new ArgumentException("Trying to remove an edge that does not exist.", "e");
m_Edges.Remove(e);
List<IEdge> inputNodeEdges;
if (m_NodeEdges.TryGetValue(e.inputSlot.nodeGuid, out inputNodeEdges))
inputNodeEdges.Remove(e);
List<IEdge> outputNodeEdges;
if (m_NodeEdges.TryGetValue(e.outputSlot.nodeGuid, out outputNodeEdges))
outputNodeEdges.Remove(e);
m_RemovedEdges.Add(e);
}
public INode GetNodeFromGuid(Guid guid)
{
INode node;
m_Nodes.TryGetValue(guid, out node);
return node;
}
public bool ContainsNodeGuid(Guid guid)
{
return m_Nodes.ContainsKey(guid);
}
public T GetNodeFromGuid<T>(Guid guid) where T : INode
{
var node = GetNodeFromGuid(guid);
if (node is T)
return (T)node;
return default(T);
}
public void GetEdges(SlotReference s, List<IEdge> foundEdges)
{
var node = GetNodeFromGuid(s.nodeGuid);
if (node == null)
{
Debug.LogWarning("Node does not exist");
return;
}
ISlot slot = node.FindSlot<ISlot>(s.slotId);
List<IEdge> candidateEdges;
if (!m_NodeEdges.TryGetValue(s.nodeGuid, out candidateEdges))
return;
foreach (var edge in candidateEdges)
{
var cs = slot.isInputSlot ? edge.inputSlot : edge.outputSlot;
if (cs.nodeGuid == s.nodeGuid && cs.slotId == s.slotId)
foundEdges.Add(edge);
}
}
public virtual void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
{
foreach (var prop in properties)

}
}
public override void ValidateGraph()
public void ValidateGraph()
base.ValidateGraph();
//First validate edges, remove any
//orphans. This can happen if a user
//manually modifies serialized data
//of if they delete a node in the inspector
//debug view.
foreach (var edge in edges.ToArray())
{
var outputNode = GetNodeFromGuid(edge.outputSlot.nodeGuid);
var inputNode = GetNodeFromGuid(edge.inputSlot.nodeGuid);
if (outputNode == null
|| inputNode == null
|| outputNode.FindOutputSlot<ISlot>(edge.outputSlot.slotId) == null
|| inputNode.FindInputSlot<ISlot>(edge.inputSlot.slotId) == null)
{
//orphaned edge
RemoveEdgeNoValidate(edge);
}
}
foreach (var node in GetNodes<INode>())
node.ValidateNode();
foreach (var edge in m_AddedEdges.ToList())
{
if (!ContainsNodeGuid(edge.outputSlot.nodeGuid) || !ContainsNodeGuid(edge.inputSlot.nodeGuid))
{
Debug.LogWarningFormat("Added edge is invalid: {0} -> {1}\n{2}", edge.outputSlot.nodeGuid, edge.inputSlot.nodeGuid, Environment.StackTrace);
m_AddedEdges.Remove(edge);
}
}
public override Dictionary<SerializationHelper.TypeSerializationInfo, SerializationHelper.TypeSerializationInfo> GetLegacyTypeRemapping()
public Dictionary<SerializationHelper.TypeSerializationInfo, SerializationHelper.TypeSerializationInfo> GetLegacyTypeRemapping()
var result = base.GetLegacyTypeRemapping();
var result = new Dictionary<SerializationHelper.TypeSerializationInfo, SerializationHelper.TypeSerializationInfo>();
var viewNode = new SerializationHelper.TypeSerializationInfo
{
fullName = "UnityEngine.MaterialGraph.ViewDirectionNode"

return result;
}
public override void ReplaceWith(IGraph other)
public void ReplaceWith(IGraph other)
{
var otherMG = other as AbstractMaterialGraph;
if (otherMG != null)

AddShaderProperty(otherProperty);
}
}
base.ReplaceWith(other);
other.ValidateGraph();
ValidateGraph();
// Current tactic is to remove all nodes and edges and then re-add them, such that depending systems
// will re-initialize with new references.
using (var pooledList = ListPool<IEdge>.GetDisposable())
{
var removedNodeEdges = pooledList.value;
removedNodeEdges.AddRange(m_Edges);
foreach (var edge in removedNodeEdges)
RemoveEdgeNoValidate(edge);
}
using (var removedNodesPooledObject = ListPool<Guid>.GetDisposable())
{
var removedNodeGuids = removedNodesPooledObject.value;
removedNodeGuids.AddRange(m_Nodes.Keys);
foreach (var nodeGuid in removedNodeGuids)
RemoveNodeNoValidate(m_Nodes[nodeGuid]);
}
ValidateGraph();
foreach (var node in other.GetNodes<INode>())
AddNodeNoValidate(node);
foreach (var edge in other.edges)
ConnectNoValidate(edge.outputSlot, edge.inputSlot);
ValidateGraph();
public override void OnBeforeSerialize()
public void OnBeforeSerialize()
base.OnBeforeSerialize();
m_SerializableNodes = SerializationHelper.Serialize<INode>(m_Nodes.Values);
m_SerializableEdges = SerializationHelper.Serialize<IEdge>(m_Edges);
public override void OnAfterDeserialize()
public virtual void OnAfterDeserialize()
base.OnAfterDeserialize();
var nodes = SerializationHelper.Deserialize<INode>(m_SerializableNodes, GetLegacyTypeRemapping());
m_Nodes = new Dictionary<Guid, INode>(nodes.Count);
foreach (var node in nodes)
{
node.owner = this;
node.UpdateNodeAfterDeserialization();
m_Nodes.Add(node.guid, node);
}
m_SerializableNodes = null;
m_Edges = SerializationHelper.Deserialize<IEdge>(m_SerializableEdges, null);
m_SerializableEdges = null;
foreach (var edge in m_Edges)
AddEdgeToNodeEdges(edge);
}
internal static ShaderGraphRequirements GetRequirements(List<INode> nodes)

configuredTextures = shaderProperties.GetConfiguredTexutres();
return finalShader.GetShaderString(0);
}
public void OnEnable()
{
foreach (var node in GetNodes<INode>().OfType<IOnAssetEnabled>())
{
node.OnEnable();
}
}
public class InspectorPreviewData
{

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/SerializableGraph/Implementation/SerializableGraphObject.cs


if (graph == null)
graph = deserializedGraph;
else
m_DeserializedGraph = deserializedGraph; // graph.ReplaceWith(m_DeserializedGraph);
m_DeserializedGraph = deserializedGraph;
}
void Validate()

85
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/UnitTests/SerializedGraphTests.cs


using NUnit.Framework;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
public class SerializableGraphTests
public class BaseMaterialGraphTests
{
[OneTimeSetUp]
public void RunBeforeAnyTests()

[Test]
public void TestCanCreateSerializableGraph()
public void TestCanCreateBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
Assert.AreEqual(0, graph.edges.Count());
Assert.AreEqual(0, graph.GetNodes<INode>().Count());

public void TestCanAddNodeToSerializableGraph()
public void TestCanAddNodeToBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new SerializableNode();
node.name = "Test Node";
graph.AddNode(node);

}
[Test]
public void TestCanRemoveNodeFromSerializableGraph()
public void TestCanRemoveNodeFromBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new SerializableNode();
node.name = "Test Node";
graph.AddNode(node);

}
[Test]
public void TestRemoveNodeFromSerializableGraphCleansEdges()
public void TestRemoveNodeFromBaseMaterialGraphCleansEdges()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

}
[Test]
public void TestCanNotRemoveNoDeleteNodeFromSerializableGraph()
public void TestCanNotRemoveNoDeleteNodeFromBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new NoDeleteNode();
node.name = "Test Node";
graph.AddNode(node);

[Test]
public void TestSerializedGraphDelegatesOnEnableCalls()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new OnEnableNode();
node.name = "Test Node";
graph.AddNode(node);

}
[Test]
public void TestCanFindNodeInSerializableGraph()
public void TestCanFindNodeInBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new SerializableNode();
graph.AddNode(node);

[Test]
public void TestCanAddSlotToSerializableNode()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new SerializableNode();
node.AddSlot(new SerializableSlot(0, "output", SlotType.Output));
node.AddSlot(new SerializableSlot(1, "input", SlotType.Input));

[Test]
public void TestCanRemoveSlotFromSerializableNode()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new SerializableNode();
node.AddSlot(new SerializableSlot(0, "output", SlotType.Output));
node.AddSlot(new SerializableSlot(1, "input", SlotType.Input));

[Test]
public void TestCanRemoveSlotsWithNonMathingNameFromSerializableNode()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new TestableNode();
graph.AddNode(node);

[Test]
public void TestCanNotAddDuplicateSlotToSerializableNode()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new SerializableNode();
node.AddSlot(new SerializableSlot(0, "output", SlotType.Output));
node.AddSlot(new SerializableSlot(0, "output", SlotType.Output));

[Test]
public void TestCanUpdateDisplaynameByReaddingSlotToSerializableNode()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new SerializableNode();
node.AddSlot(new SerializableSlot(0, "output", SlotType.Output));
node.AddSlot(new SerializableSlot(0, "output_updated", SlotType.Output));

[Test]
public void TestCanUpdateSlotPriority()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new SerializableNode();
node.AddSlot(new SerializableSlot(0, "output", SlotType.Output, 0));
node.name = "Test Node";

[Test]
public void TestCanUpdateSlotPriorityByReaddingSlotToSerializableNode()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var node = new SerializableNode();
node.AddSlot(new SerializableSlot(0, "output", SlotType.Output, 0));
node.AddSlot(new SerializableSlot(0, "output", SlotType.Output, 5));

}
[Test]
public void TestCanConnectAndTraverseTwoNodesOnSerializableGraph()
public void TestCanConnectAndTraverseTwoNodesOnBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

}
[Test]
public void TestCanConnectAndTraverseThreeNodesOnSerializableGraph()
public void TestCanConnectAndTraverseThreeNodesOnBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

[Test]
public void TestConectionToSameInputReplacesOldInput()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

[Test]
public void TestRemovingSlotRemovesConnectedEdges()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

[Test]
public void TestCanNotConnectToNullSlot()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

}
[Test]
public void TestCanNotConnectTwoOuputSlotsOnSerializableGraph()
public void TestCanNotConnectTwoOuputSlotsOnBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

}
[Test]
public void TestCanNotConnectTwoInputSlotsOnSerializableGraph()
public void TestCanNotConnectTwoInputSlotsOnBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var inputNode = new TestableNode();
graph.AddNode(inputNode);

}
[Test]
public void TestRemovingNodeRemovesConectedEdgesOnSerializableGraph()
public void TestRemovingNodeRemovesConectedEdgesOnBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

}
[Test]
public void TestRemovingEdgeOnSerializableGraph()
public void TestRemovingEdgeOnBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

}
[Test]
public void TestRemovingElementsFromSerializableGraph()
public void TestRemovingElementsFromBaseMaterialGraph()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

}
[Test]
public void TestCanGetEdgesOnSerializableGraphFromSlotReference()
public void TestCanGetEdgesOnBaseMaterialGraphFromSlotReference()
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

[Test]
public void TestGetInputsWithNoConnection()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var outputNode = new TestableNode();
graph.AddNode(outputNode);

[Test]
public void TestCyclicConnectionsAreNotAllowedOnGraph()
{
var graph = new SerializableGraph();
var graph = new TestMaterialGraph();
var nodeA = new TestableNode();

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/TestMaterialGraph.cs


namespace UnityEditor.ShaderGraph
{
class TestMaterialGraph : AbstractMaterialGraph
{
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/TestMaterialGraph.cs.meta


fileFormatVersion: 2
guid: 803f320a1aae4bb28cd8234a7623f9df
timeCreated: 1513335106

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/SerializableGraph/Implementation/SerializableGraph.cs.meta


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

360
MaterialGraphProject/Assets/UnityShaderEditor/Editor/SerializableGraph/Implementation/SerializableGraph.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UnityEditor.Graphing
{
[Serializable]
public class SerializableGraph : IGraph, ISerializationCallbackReceiver
{
[NonSerialized]
List<IEdge> m_Edges = new List<IEdge>();
[NonSerialized]
Dictionary<Guid, List<IEdge>> m_NodeEdges = new Dictionary<Guid, List<IEdge>>();
[NonSerialized]
Dictionary<Guid, INode> m_Nodes = new Dictionary<Guid, INode>();
[SerializeField]
List<SerializationHelper.JSONSerializedElement> m_SerializableNodes = new List<SerializationHelper.JSONSerializedElement>();
[SerializeField]
List<SerializationHelper.JSONSerializedElement> m_SerializableEdges = new List<SerializationHelper.JSONSerializedElement>();
[NonSerialized]
List<INode> m_AddedNodes = new List<INode>();
[NonSerialized]
List<INode> m_RemovedNodes = new List<INode>();
[NonSerialized]
List<IEdge> m_AddedEdges = new List<IEdge>();
[NonSerialized]
List<IEdge> m_RemovedEdges = new List<IEdge>();
public IEnumerable<INode> addedNodes
{
get { return m_AddedNodes; }
}
public IEnumerable<INode> removedNodes
{
get { return m_RemovedNodes; }
}
public IEnumerable<IEdge> addedEdges
{
get { return m_AddedEdges; }
}
public IEnumerable<IEdge> removedEdges
{
get { return m_RemovedEdges; }
}
public IGraphObject owner { get; set; }
public virtual void ClearChanges()
{
m_AddedNodes.Clear();
m_RemovedNodes.Clear();
m_AddedEdges.Clear();
m_RemovedEdges.Clear();
}
public IEnumerable<T> GetNodes<T>() where T : INode
{
return m_Nodes.Values.OfType<T>();
}
public IEnumerable<IEdge> edges
{
get { return m_Edges; }
}
public virtual void AddNode(INode node)
{
AddNodeNoValidate(node);
ValidateGraph();
}
protected void AddNodeNoValidate(INode node)
{
m_Nodes.Add(node.guid, node);
node.owner = this;
m_AddedNodes.Add(node);
}
public virtual void RemoveNode(INode node)
{
if (!node.canDeleteNode)
return;
m_Nodes.Remove(node.guid);
m_RemovedNodes.Add(node);
ValidateGraph();
}
protected void RemoveNodeNoValidate(INode node)
{
if (!node.canDeleteNode)
return;
m_Nodes.Remove(node.guid);
m_RemovedNodes.Add(node);
}
void AddEdgeToNodeEdges(IEdge edge)
{
List<IEdge> inputEdges;
if (!m_NodeEdges.TryGetValue(edge.inputSlot.nodeGuid, out inputEdges))
m_NodeEdges[edge.inputSlot.nodeGuid] = inputEdges = new List<IEdge>();
inputEdges.Add(edge);
List<IEdge> outputEdges;
if (!m_NodeEdges.TryGetValue(edge.outputSlot.nodeGuid, out outputEdges))
m_NodeEdges[edge.outputSlot.nodeGuid] = outputEdges = new List<IEdge>();
outputEdges.Add(edge);
}
public virtual Dictionary<SerializationHelper.TypeSerializationInfo, SerializationHelper.TypeSerializationInfo> GetLegacyTypeRemapping()
{
return new Dictionary<SerializationHelper.TypeSerializationInfo, SerializationHelper.TypeSerializationInfo>();
}
static List<IEdge> s_TempEdges = new List<IEdge>();
protected IEdge ConnectNoValidate(SlotReference fromSlotRef, SlotReference toSlotRef)
{
var fromNode = GetNodeFromGuid(fromSlotRef.nodeGuid);
var toNode = GetNodeFromGuid(toSlotRef.nodeGuid);
if (fromNode == null || toNode == null)
return null;
// if fromNode is already connected to toNode
// do now allow a connection as toNode will then
// have an edge to fromNode creating a cycle.
// if this is parsed it will lead to an infinite loop.
var dependentNodes = new List<INode>();
NodeUtils.CollectNodesNodeFeedsInto(dependentNodes, toNode);
if (dependentNodes.Contains(fromNode))
return null;
var fromSlot = fromNode.FindSlot<ISlot>(fromSlotRef.slotId);
var toSlot = toNode.FindSlot<ISlot>(toSlotRef.slotId);
if (fromSlot.isOutputSlot == toSlot.isOutputSlot)
return null;
var outputSlot = fromSlot.isOutputSlot ? fromSlotRef : toSlotRef;
var inputSlot = fromSlot.isInputSlot ? fromSlotRef : toSlotRef;
s_TempEdges.Clear();
GetEdges(inputSlot, s_TempEdges);
// remove any inputs that exits before adding
foreach (var edge in s_TempEdges)
{
RemoveEdgeNoValidate(edge);
}
var newEdge = new Edge(outputSlot, inputSlot);
m_Edges.Add(newEdge);
m_AddedEdges.Add(newEdge);
AddEdgeToNodeEdges(newEdge);
//Debug.LogFormat("Connected edge: {0} -> {1} ({2} -> {3})\n{4}", newEdge.outputSlot.nodeGuid, newEdge.inputSlot.nodeGuid, fromNode.name, toNode.name, Environment.StackTrace);
return newEdge;
}
public virtual IEdge Connect(SlotReference fromSlotRef, SlotReference toSlotRef)
{
var newEdge = ConnectNoValidate(fromSlotRef, toSlotRef);
ValidateGraph();
return newEdge;
}
public virtual void RemoveEdge(IEdge e)
{
RemoveEdgeNoValidate(e);
ValidateGraph();
}
public void RemoveElements(IEnumerable<INode> nodes, IEnumerable<IEdge> edges)
{
foreach (var edge in edges.ToArray())
RemoveEdgeNoValidate(edge);
foreach (var serializableNode in nodes.ToArray())
RemoveNodeNoValidate(serializableNode);
ValidateGraph();
}
protected void RemoveEdgeNoValidate(IEdge e)
{
e = m_Edges.FirstOrDefault(x => x.Equals(e));
if (e == null)
throw new ArgumentException("Trying to remove an edge that does not exist.", "e");
m_Edges.Remove(e);
List<IEdge> inputNodeEdges;
if (m_NodeEdges.TryGetValue(e.inputSlot.nodeGuid, out inputNodeEdges))
inputNodeEdges.Remove(e);
List<IEdge> outputNodeEdges;
if (m_NodeEdges.TryGetValue(e.outputSlot.nodeGuid, out outputNodeEdges))
outputNodeEdges.Remove(e);
m_RemovedEdges.Add(e);
}
public INode GetNodeFromGuid(Guid guid)
{
INode node;
m_Nodes.TryGetValue(guid, out node);
return node;
}
public bool ContainsNodeGuid(Guid guid)
{
return m_Nodes.ContainsKey(guid);
}
public T GetNodeFromGuid<T>(Guid guid) where T : INode
{
var node = GetNodeFromGuid(guid);
if (node is T)
return (T)node;
return default(T);
}
public void GetEdges(SlotReference s, List<IEdge> foundEdges)
{
var node = GetNodeFromGuid(s.nodeGuid);
if (node == null)
{
Debug.LogWarning("Node does not exist");
return;
}
ISlot slot = node.FindSlot<ISlot>(s.slotId);
List<IEdge> candidateEdges;
if (!m_NodeEdges.TryGetValue(s.nodeGuid, out candidateEdges))
return;
foreach (var edge in candidateEdges)
{
var cs = slot.isInputSlot ? edge.inputSlot : edge.outputSlot;
if (cs.nodeGuid == s.nodeGuid && cs.slotId == s.slotId)
foundEdges.Add(edge);
}
}
public virtual void OnBeforeSerialize()
{
m_SerializableNodes = SerializationHelper.Serialize<INode>(m_Nodes.Values);
m_SerializableEdges = SerializationHelper.Serialize<IEdge>(m_Edges);
}
public virtual void OnAfterDeserialize()
{
var nodes = SerializationHelper.Deserialize<INode>(m_SerializableNodes, GetLegacyTypeRemapping());
m_Nodes = new Dictionary<Guid, INode>(nodes.Count);
foreach (var node in nodes)
{
node.owner = this;
node.UpdateNodeAfterDeserialization();
m_Nodes.Add(node.guid, node);
}
m_SerializableNodes = null;
m_Edges = SerializationHelper.Deserialize<IEdge>(m_SerializableEdges, null);
m_SerializableEdges = null;
foreach (var edge in m_Edges)
AddEdgeToNodeEdges(edge);
}
public virtual void ValidateGraph()
{
//First validate edges, remove any
//orphans. This can happen if a user
//manually modifies serialized data
//of if they delete a node in the inspector
//debug view.
foreach (var edge in edges.ToArray())
{
var outputNode = GetNodeFromGuid(edge.outputSlot.nodeGuid);
var inputNode = GetNodeFromGuid(edge.inputSlot.nodeGuid);
if (outputNode == null
|| inputNode == null
|| outputNode.FindOutputSlot<ISlot>(edge.outputSlot.slotId) == null
|| inputNode.FindInputSlot<ISlot>(edge.inputSlot.slotId) == null)
{
//orphaned edge
RemoveEdgeNoValidate(edge);
}
}
foreach (var node in GetNodes<INode>())
node.ValidateNode();
foreach (var edge in m_AddedEdges.ToList())
{
if (!ContainsNodeGuid(edge.outputSlot.nodeGuid) || !ContainsNodeGuid(edge.inputSlot.nodeGuid))
{
Debug.LogWarningFormat("Added edge is invalid: {0} -> {1}\n{2}", edge.outputSlot.nodeGuid, edge.inputSlot.nodeGuid, Environment.StackTrace);
m_AddedEdges.Remove(edge);
}
}
}
public virtual void ReplaceWith(IGraph other)
{
other.ValidateGraph();
ValidateGraph();
// Current tactic is to remove all nodes and edges and then re-add them, such that depending systems
// will re-initialize with new references.
using (var pooledList = ListPool<IEdge>.GetDisposable())
{
var removedNodeEdges = pooledList.value;
removedNodeEdges.AddRange(m_Edges);
foreach (var edge in removedNodeEdges)
RemoveEdgeNoValidate(edge);
}
using (var removedNodesPooledObject = ListPool<Guid>.GetDisposable())
{
var removedNodeGuids = removedNodesPooledObject.value;
removedNodeGuids.AddRange(m_Nodes.Keys);
foreach (var nodeGuid in removedNodeGuids)
RemoveNodeNoValidate(m_Nodes[nodeGuid]);
}
ValidateGraph();
foreach (var node in other.GetNodes<INode>())
AddNodeNoValidate(node);
foreach (var edge in other.edges)
ConnectNoValidate(edge.outputSlot, edge.inputSlot);
ValidateGraph();
}
public void OnEnable()
{
foreach (var node in GetNodes<INode>().OfType<IOnAssetEnabled>())
{
node.OnEnable();
}
}
}
}
正在加载...
取消
保存