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();
/// All groups in the graph.
/// See:
[SerializeField] public List groups = new List();
/// 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.graphHotfix = this;
Node node = ScriptableObject.CreateInstance(type) as Node;
node.graph = this;
nodes.Add(node);
return node;
}
/// Creates a copy of the original node in the graph
public virtual Node CopyNode(Node original) {
Node.graphHotfix = this;
Node node = ScriptableObject.Instantiate(original);
node.graph = this;
node.ClearConnections();
nodes.Add(node);
return node;
}
/// Safely remove a node and all its connections
/// The node to remove
public void RemoveNode(Node node) {
node.ClearConnections();
nodes.Remove(node);
if (Application.isPlaying) Destroy(node);
}
/// Remove all nodes and connections from the graph
public void Clear() {
if (Application.isPlaying) {
for (int i = 0; i < nodes.Count; i++) {
Destroy(nodes[i]);
}
}
nodes.Clear();
}
/// Add a group to the graph
public NodeGroup AddGroup() {
NodeGroup group = ScriptableObject.CreateInstance();
group.graph = this;
groups.Add(group);
return group;
}
/// Creates a copy of the group node in the graph
public virtual NodeGroup CopyGroup(NodeGroup original) {
NodeGroup group = ScriptableObject.Instantiate(original);
group.graph = this;
groups.Add(group);
return group;
}
/// Safely remove a group
public void RemoveGroup(NodeGroup group) {
groups.Remove(group);
if (Application.isPlaying) Destroy(group);
}
/// 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++) {
if (nodes[i] == null) continue;
Node.graphHotfix = graph;
Node node = Instantiate(nodes[i]) as Node;
node.graph = graph;
graph.nodes[i] = node;
}
// Instantiate all groups inside the graph
for (int i = 0; i < groups.Count; i++) {
if (groups[i] == null) continue;
NodeGroup group = Instantiate(groups[i]) as NodeGroup;
group.graph = graph;
graph.groups[i] = group;
}
// Redirect all connections
for (int i = 0; i < graph.nodes.Count; i++) {
if (graph.nodes[i] == null) continue;
foreach (NodePort port in graph.nodes[i].Ports) {
port.Redirect(nodes, graph.nodes);
}
}
return graph;
}
private void OnDestroy() {
// Remove all nodes prior to graph destruction
Clear();
}
}
}