using System;
using System.Collections.Generic;
using UnityEngine;
namespace XNode {
/// Base class for all node graphs
[Serializable]
public abstract class NodeGraph : ScriptableObject {
/// All nodes in the graph.
/// See:
[SerializeField] public List nodes = new List();
#if UNITY_EDITOR
/// Nodes used primarily for organization (Editor only)
public List reroutes = new List();
#endif
/// Add a node to the graph by type
public T AddNode() where T : Node {
return AddNode(typeof(T)) as T;
}
/// Add a node to the graph by type
public virtual Node AddNode(Type type) {
Node node = ScriptableObject.CreateInstance(type) as Node;
#if UNITY_EDITOR
if (!Application.isPlaying) {
UnityEditor.AssetDatabase.AddObjectToAsset(node, this);
UnityEditor.AssetDatabase.SaveAssets();
node.name = UnityEditor.ObjectNames.NicifyVariableName(node.name);
}
#endif
nodes.Add(node);
node.graph = this;
return node;
}
/// Creates a copy of the original node in the graph
public virtual Node CopyNode(Node original) {
Node node = ScriptableObject.Instantiate(original);
node.ClearConnections();
#if UNITY_EDITOR
if (!Application.isPlaying) {
UnityEditor.AssetDatabase.AddObjectToAsset(node, this);
UnityEditor.AssetDatabase.SaveAssets();
node.name = UnityEditor.ObjectNames.NicifyVariableName(node.name);
}
#endif
nodes.Add(node);
node.graph = this;
return node;
}
/// Safely remove a node and all its connections
///
public void RemoveNode(Node node) {
node.ClearConnections();
#if UNITY_EDITOR
if (!Application.isPlaying) {
DestroyImmediate(node, true);
UnityEditor.AssetDatabase.SaveAssets();
}
#endif
nodes.Remove(node);
}
/// Remove all nodes and connections from the graph
public void Clear() {
nodes.Clear();
}
/// Create a new deep copy of this graph
public XNode.NodeGraph Copy() {
// Instantiate a new nodegraph instance
NodeGraph graph = Instantiate(this);
// Instantiate all nodes inside the graph
for (int i = 0; i < nodes.Count; i++) {
Node node = Instantiate(nodes[i]) as Node;
node.graph = graph;
graph.nodes[i] = node;
}
// Redirect all connections
for (int i = 0; i < graph.nodes.Count; i++) {
foreach (NodePort port in graph.nodes[i].Ports) {
port.Redirect(nodes, graph.nodes);
}
}
return graph;
}
}
}