mirror of
https://github.com/Siccity/xNode.git
synced 2026-02-04 14:24:54 +08:00
Simple refactoring.
This commit is contained in:
parent
82f7887931
commit
b3465b269e
@ -1,5 +1,8 @@
|
|||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
/// <summary> Draw enums correctly within nodes. Without it, enums show up at the wrong positions. </summary>
|
namespace Attributes
|
||||||
/// <remarks> Enums with this attribute are not detected by EditorGui.ChangeCheck due to waiting before executing </remarks>
|
{
|
||||||
public class NodeEnumAttribute : PropertyAttribute { }
|
/// <summary> Draw enums correctly within nodes. Without it, enums show up at the wrong positions. </summary>
|
||||||
|
/// <remarks> Enums with this attribute are not detected by EditorGui.ChangeCheck due to waiting before executing </remarks>
|
||||||
|
public class NodeEnumAttribute : PropertyAttribute { }
|
||||||
|
}
|
||||||
@ -1,12 +1,16 @@
|
|||||||
using System;
|
using System;
|
||||||
/// <summary> Overrides the ValueType of the Port, to have a ValueType different from the type of its serializable field </summary>
|
|
||||||
/// <remarks> Especially useful in Dynamic Port Lists to create Value-Port Pairs with different type. </remarks>
|
namespace Attributes
|
||||||
[AttributeUsage(AttributeTargets.Field)]
|
{
|
||||||
public class PortTypeOverrideAttribute : Attribute {
|
/// <summary> Overrides the ValueType of the Port, to have a ValueType different from the type of its serializable field </summary>
|
||||||
public Type type;
|
/// <remarks> Especially useful in Dynamic Port Lists to create Value-Port Pairs with different type. </remarks>
|
||||||
/// <summary> Overrides the ValueType of the Port </summary>
|
[AttributeUsage(AttributeTargets.Field)]
|
||||||
/// <param name="type">ValueType of the Port</param>
|
public class PortTypeOverrideAttribute : Attribute {
|
||||||
public PortTypeOverrideAttribute(Type type) {
|
public Type type;
|
||||||
this.type = type;
|
/// <summary> Overrides the ValueType of the Port </summary>
|
||||||
|
/// <param name="type">ValueType of the Port</param>
|
||||||
|
public PortTypeOverrideAttribute(Type type) {
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections;
|
using System.Collections;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using Attributes;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using XNode;
|
|
||||||
using XNodeEditor;
|
using XNodeEditor;
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor {
|
||||||
|
|||||||
@ -8,7 +8,7 @@ using Sirenix.Utilities.Editor;
|
|||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor {
|
||||||
/// <summary> Override graph inspector to show an 'Open Graph' button at the top </summary>
|
/// <summary> Override graph inspector to show an 'Open Graph' button at the top </summary>
|
||||||
[CustomEditor(typeof(XNode.NodeGraph), true)]
|
[CustomEditor(typeof(NodeGraph), true)]
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
public class GlobalGraphEditor : OdinEditor {
|
public class GlobalGraphEditor : OdinEditor {
|
||||||
public override void OnInspectorGUI() {
|
public override void OnInspectorGUI() {
|
||||||
@ -25,7 +25,7 @@ namespace XNodeEditor {
|
|||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
|
|
||||||
if (GUILayout.Button("Edit graph", GUILayout.Height(40))) {
|
if (GUILayout.Button("Edit graph", GUILayout.Height(40))) {
|
||||||
NodeEditorWindow.Open(serializedObject.targetObject as XNode.NodeGraph);
|
NodeEditorWindow.Open(serializedObject.targetObject as NodeGraph);
|
||||||
}
|
}
|
||||||
|
|
||||||
GUILayout.Space(EditorGUIUtility.singleLineHeight);
|
GUILayout.Space(EditorGUIUtility.singleLineHeight);
|
||||||
@ -38,7 +38,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
[CustomEditor(typeof(XNode.Node), true)]
|
[CustomEditor(typeof(Node), true)]
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
public class GlobalNodeEditor : OdinEditor {
|
public class GlobalNodeEditor : OdinEditor {
|
||||||
public override void OnInspectorGUI() {
|
public override void OnInspectorGUI() {
|
||||||
@ -58,7 +58,7 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
if (GUILayout.Button("Edit graph", GUILayout.Height(40))) {
|
if (GUILayout.Button("Edit graph", GUILayout.Height(40))) {
|
||||||
SerializedProperty graphProp = serializedObject.FindProperty("graph");
|
SerializedProperty graphProp = serializedObject.FindProperty("graph");
|
||||||
NodeEditorWindow w = NodeEditorWindow.Open(graphProp.objectReferenceValue as XNode.NodeGraph);
|
NodeEditorWindow w = NodeEditorWindow.Open(graphProp.objectReferenceValue as NodeGraph);
|
||||||
w.Home(); // Focus selected node
|
w.Home(); // Focus selected node
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,13 +1,12 @@
|
|||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using XNode;
|
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor {
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// This asset processor resolves an issue with the new v2 AssetDatabase system present on 2019.3 and later. When
|
/// This asset processor resolves an issue with the new v2 AssetDatabase system present on 2019.3 and later. When
|
||||||
/// renaming a <see cref="XNode.NodeGraph"/> asset, it appears that sometimes the v2 AssetDatabase will swap which asset
|
/// renaming a <see cref="NodeGraph"/> asset, it appears that sometimes the v2 AssetDatabase will swap which asset
|
||||||
/// is the main asset (present at top level) between the <see cref="XNode.NodeGraph"/> and one of its <see cref="XNode.Node"/>
|
/// is the main asset (present at top level) between the <see cref="NodeGraph"/> and one of its <see cref="Node"/>
|
||||||
/// sub-assets. As a workaround until Unity fixes this, this asset processor checks all renamed assets and if it
|
/// sub-assets. As a workaround until Unity fixes this, this asset processor checks all renamed assets and if it
|
||||||
/// finds a case where a <see cref="XNode.Node"/> has been made the main asset it will swap it back to being a sub-asset
|
/// finds a case where a <see cref="Node"/> has been made the main asset it will swap it back to being a sub-asset
|
||||||
/// and rename the node to the default name for that node type.
|
/// and rename the node to the default name for that node type.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class GraphRenameFixAssetProcessor : AssetPostprocessor {
|
internal sealed class GraphRenameFixAssetProcessor : AssetPostprocessor {
|
||||||
|
|||||||
@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
namespace XNodeEditor.Internal {
|
namespace XNodeEditor.Internal {
|
||||||
public struct RerouteReference {
|
public struct RerouteReference {
|
||||||
public XNode.NodePort port;
|
public NodePort port;
|
||||||
public int connectionIndex;
|
public int connectionIndex;
|
||||||
public int pointIndex;
|
public int pointIndex;
|
||||||
|
|
||||||
public RerouteReference(XNode.NodePort port, int connectionIndex, int pointIndex) {
|
public RerouteReference(NodePort port, int connectionIndex, int pointIndex) {
|
||||||
this.port = port;
|
this.port = port;
|
||||||
this.connectionIndex = connectionIndex;
|
this.connectionIndex = connectionIndex;
|
||||||
this.pointIndex = pointIndex;
|
this.pointIndex = pointIndex;
|
||||||
|
|||||||
@ -14,12 +14,12 @@ using GenericMenu = XNodeEditor.AdvancedGenericMenu;
|
|||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor {
|
||||||
/// <summary> Base class to derive custom Node editors from. Use this to create your own custom inspectors and editors for your nodes. </summary>
|
/// <summary> Base class to derive custom Node editors from. Use this to create your own custom inspectors and editors for your nodes. </summary>
|
||||||
[CustomNodeEditor(typeof(XNode.Node))]
|
[CustomNodeEditor(typeof(Node))]
|
||||||
public class NodeEditor : XNodeEditor.Internal.NodeEditorBase<NodeEditor, NodeEditor.CustomNodeEditorAttribute, XNode.Node> {
|
public class NodeEditor : XNodeEditor.Internal.NodeEditorBase<NodeEditor, NodeEditor.CustomNodeEditorAttribute, Node> {
|
||||||
|
|
||||||
/// <summary> Fires every whenever a node was modified through the editor </summary>
|
/// <summary> Fires every whenever a node was modified through the editor </summary>
|
||||||
public static Action<XNode.Node> onUpdateNode;
|
public static Action<Node> onUpdateNode;
|
||||||
public readonly static Dictionary<XNode.NodePort, Vector2> portPositions = new Dictionary<XNode.NodePort, Vector2>();
|
public readonly static Dictionary<NodePort, Vector2> portPositions = new Dictionary<NodePort, Vector2>();
|
||||||
|
|
||||||
#if ODIN_INSPECTOR
|
#if ODIN_INSPECTOR
|
||||||
protected internal static bool inNodeEditor = false;
|
protected internal static bool inNodeEditor = false;
|
||||||
@ -82,7 +82,7 @@ namespace XNodeEditor {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Iterate through dynamic ports and draw them in the order in which they are serialized
|
// Iterate through dynamic ports and draw them in the order in which they are serialized
|
||||||
foreach (XNode.NodePort dynamicPort in target.DynamicPorts) {
|
foreach (NodePort dynamicPort in target.DynamicPorts) {
|
||||||
if (NodeEditorGUILayout.IsDynamicPortListPort(dynamicPort)) continue;
|
if (NodeEditorGUILayout.IsDynamicPortListPort(dynamicPort)) continue;
|
||||||
NodeEditorGUILayout.PortField(dynamicPort);
|
NodeEditorGUILayout.PortField(dynamicPort);
|
||||||
}
|
}
|
||||||
@ -136,8 +136,8 @@ namespace XNodeEditor {
|
|||||||
public virtual void AddContextMenuItems(GenericMenu menu) {
|
public virtual void AddContextMenuItems(GenericMenu menu) {
|
||||||
bool canRemove = true;
|
bool canRemove = true;
|
||||||
// Actions if only one node is selected
|
// Actions if only one node is selected
|
||||||
if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) {
|
if (Selection.objects.Length == 1 && Selection.activeObject is Node) {
|
||||||
XNode.Node node = Selection.activeObject as XNode.Node;
|
Node node = Selection.activeObject as Node;
|
||||||
menu.AddItem(new GUIContent("Move To Top"), false, () => NodeEditorWindow.current.MoveNodeToTop(node));
|
menu.AddItem(new GUIContent("Move To Top"), false, () => NodeEditorWindow.current.MoveNodeToTop(node));
|
||||||
menu.AddItem(new GUIContent("Rename"), false, NodeEditorWindow.current.RenameSelectedNode);
|
menu.AddItem(new GUIContent("Rename"), false, NodeEditorWindow.current.RenameSelectedNode);
|
||||||
|
|
||||||
@ -152,8 +152,8 @@ namespace XNodeEditor {
|
|||||||
else menu.AddItem(new GUIContent("Remove"), false, null);
|
else menu.AddItem(new GUIContent("Remove"), false, null);
|
||||||
|
|
||||||
// Custom sctions if only one node is selected
|
// Custom sctions if only one node is selected
|
||||||
if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) {
|
if (Selection.objects.Length == 1 && Selection.activeObject is Node) {
|
||||||
XNode.Node node = Selection.activeObject as XNode.Node;
|
Node node = Selection.activeObject as Node;
|
||||||
menu.AddCustomContextMenuItems(node);
|
menu.AddCustomContextMenuItems(node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -171,7 +171,7 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
[AttributeUsage(AttributeTargets.Class)]
|
[AttributeUsage(AttributeTargets.Class)]
|
||||||
public class CustomNodeEditorAttribute : Attribute,
|
public class CustomNodeEditorAttribute : Attribute,
|
||||||
XNodeEditor.Internal.NodeEditorBase<NodeEditor, NodeEditor.CustomNodeEditorAttribute, XNode.Node>.INodeEditorAttrib {
|
XNodeEditor.Internal.NodeEditorBase<NodeEditor, NodeEditor.CustomNodeEditorAttribute, Node>.INodeEditorAttrib {
|
||||||
private Type inspectedType;
|
private Type inspectedType;
|
||||||
/// <summary> Tells a NodeEditor which Node type it is an editor for </summary>
|
/// <summary> Tells a NodeEditor which Node type it is an editor for </summary>
|
||||||
/// <param name="inspectedType">Type that this editor can edit</param>
|
/// <param name="inspectedType">Type that this editor can edit</param>
|
||||||
|
|||||||
@ -15,7 +15,7 @@ namespace XNodeEditor {
|
|||||||
public static bool isPanning { get; private set; }
|
public static bool isPanning { get; private set; }
|
||||||
public static Vector2[] dragOffset;
|
public static Vector2[] dragOffset;
|
||||||
|
|
||||||
public static XNode.Node[] copyBuffer = null;
|
public static Node[] copyBuffer = null;
|
||||||
|
|
||||||
public bool IsDraggingPort { get { return draggedOutput != null; } }
|
public bool IsDraggingPort { get { return draggedOutput != null; } }
|
||||||
public bool IsHoveringPort { get { return hoveredPort != null; } }
|
public bool IsHoveringPort { get { return hoveredPort != null; } }
|
||||||
@ -23,17 +23,17 @@ namespace XNodeEditor {
|
|||||||
public bool IsHoveringReroute { get { return hoveredReroute.port != null; } }
|
public bool IsHoveringReroute { get { return hoveredReroute.port != null; } }
|
||||||
|
|
||||||
/// <summary> Return the dragged port or null if not exist </summary>
|
/// <summary> Return the dragged port or null if not exist </summary>
|
||||||
public XNode.NodePort DraggedOutputPort { get { XNode.NodePort result = draggedOutput; return result; } }
|
public NodePort DraggedOutputPort { get { NodePort result = draggedOutput; return result; } }
|
||||||
/// <summary> Return the Hovered port or null if not exist </summary>
|
/// <summary> Return the Hovered port or null if not exist </summary>
|
||||||
public XNode.NodePort HoveredPort { get { XNode.NodePort result = hoveredPort; return result; } }
|
public NodePort HoveredPort { get { NodePort result = hoveredPort; return result; } }
|
||||||
/// <summary> Return the Hovered node or null if not exist </summary>
|
/// <summary> Return the Hovered node or null if not exist </summary>
|
||||||
public XNode.Node HoveredNode { get { XNode.Node result = hoveredNode; return result; } }
|
public Node HoveredNode { get { Node result = hoveredNode; return result; } }
|
||||||
|
|
||||||
private XNode.Node hoveredNode = null;
|
private Node hoveredNode = null;
|
||||||
[NonSerialized] public XNode.NodePort hoveredPort = null;
|
[NonSerialized] public NodePort hoveredPort = null;
|
||||||
[NonSerialized] private XNode.NodePort draggedOutput = null;
|
[NonSerialized] private NodePort draggedOutput = null;
|
||||||
[NonSerialized] private XNode.NodePort draggedOutputTarget = null;
|
[NonSerialized] private NodePort draggedOutputTarget = null;
|
||||||
[NonSerialized] private XNode.NodePort autoConnectOutput = null;
|
[NonSerialized] private NodePort autoConnectOutput = null;
|
||||||
[NonSerialized] private List<Vector2> draggedOutputReroutes = new List<Vector2>();
|
[NonSerialized] private List<Vector2> draggedOutputReroutes = new List<Vector2>();
|
||||||
|
|
||||||
private RerouteReference hoveredReroute = new RerouteReference();
|
private RerouteReference hoveredReroute = new RerouteReference();
|
||||||
@ -91,8 +91,8 @@ namespace XNodeEditor {
|
|||||||
Vector2 mousePos = WindowToGridPosition(e.mousePosition);
|
Vector2 mousePos = WindowToGridPosition(e.mousePosition);
|
||||||
// Move selected nodes with offset
|
// Move selected nodes with offset
|
||||||
for (int i = 0; i < Selection.objects.Length; i++) {
|
for (int i = 0; i < Selection.objects.Length; i++) {
|
||||||
if (Selection.objects[i] is XNode.Node) {
|
if (Selection.objects[i] is Node) {
|
||||||
XNode.Node node = Selection.objects[i] as XNode.Node;
|
Node node = Selection.objects[i] as Node;
|
||||||
Undo.RecordObject(node, "Moved Node");
|
Undo.RecordObject(node, "Moved Node");
|
||||||
Vector2 initial = node.position;
|
Vector2 initial = node.position;
|
||||||
node.position = mousePos + dragOffset[i];
|
node.position = mousePos + dragOffset[i];
|
||||||
@ -104,7 +104,7 @@ namespace XNodeEditor {
|
|||||||
// Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame.
|
// Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame.
|
||||||
Vector2 offset = node.position - initial;
|
Vector2 offset = node.position - initial;
|
||||||
if (offset.sqrMagnitude > 0) {
|
if (offset.sqrMagnitude > 0) {
|
||||||
foreach (XNode.NodePort output in node.Outputs) {
|
foreach (NodePort output in node.Outputs) {
|
||||||
Rect rect;
|
Rect rect;
|
||||||
if (portConnectionPoints.TryGetValue(output, out rect)) {
|
if (portConnectionPoints.TryGetValue(output, out rect)) {
|
||||||
rect.position += offset;
|
rect.position += offset;
|
||||||
@ -112,7 +112,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (XNode.NodePort input in node.Inputs) {
|
foreach (NodePort input in node.Inputs) {
|
||||||
Rect rect;
|
Rect rect;
|
||||||
if (portConnectionPoints.TryGetValue(input, out rect)) {
|
if (portConnectionPoints.TryGetValue(input, out rect)) {
|
||||||
rect.position += offset;
|
rect.position += offset;
|
||||||
@ -167,8 +167,8 @@ namespace XNodeEditor {
|
|||||||
hoveredPort.VerifyConnections();
|
hoveredPort.VerifyConnections();
|
||||||
autoConnectOutput = null;
|
autoConnectOutput = null;
|
||||||
if (hoveredPort.IsConnected) {
|
if (hoveredPort.IsConnected) {
|
||||||
XNode.Node node = hoveredPort.node;
|
Node node = hoveredPort.node;
|
||||||
XNode.NodePort output = hoveredPort.Connection;
|
NodePort output = hoveredPort.Connection;
|
||||||
int outputConnectionIndex = output.GetConnectionIndex(hoveredPort);
|
int outputConnectionIndex = output.GetConnectionIndex(hoveredPort);
|
||||||
draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex);
|
draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex);
|
||||||
hoveredPort.Disconnect(output);
|
hoveredPort.Disconnect(output);
|
||||||
@ -222,7 +222,7 @@ namespace XNodeEditor {
|
|||||||
if (IsDraggingPort) {
|
if (IsDraggingPort) {
|
||||||
// If connection is valid, save it
|
// If connection is valid, save it
|
||||||
if (draggedOutputTarget != null && graphEditor.CanConnect(draggedOutput, draggedOutputTarget)) {
|
if (draggedOutputTarget != null && graphEditor.CanConnect(draggedOutput, draggedOutputTarget)) {
|
||||||
XNode.Node node = draggedOutputTarget.node;
|
Node node = draggedOutputTarget.node;
|
||||||
if (graph.nodes.Count != 0) draggedOutput.Connect(draggedOutputTarget);
|
if (graph.nodes.Count != 0) draggedOutput.Connect(draggedOutputTarget);
|
||||||
|
|
||||||
// ConnectionIndex can be -1 if the connection is removed instantly after creation
|
// ConnectionIndex can be -1 if the connection is removed instantly after creation
|
||||||
@ -245,8 +245,8 @@ namespace XNodeEditor {
|
|||||||
EditorUtility.SetDirty(graph);
|
EditorUtility.SetDirty(graph);
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
||||||
} else if (currentActivity == NodeActivity.DragNode) {
|
} else if (currentActivity == NodeActivity.DragNode) {
|
||||||
IEnumerable<XNode.Node> nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node);
|
IEnumerable<Node> nodes = Selection.objects.Where(x => x is Node).Select(x => x as Node);
|
||||||
foreach (XNode.Node node in nodes) EditorUtility.SetDirty(node);
|
foreach (Node node in nodes) EditorUtility.SetDirty(node);
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
||||||
} else if (!IsHoveringNode) {
|
} else if (!IsHoveringNode) {
|
||||||
// If click outside node, release field focus
|
// If click outside node, release field focus
|
||||||
@ -316,12 +316,12 @@ namespace XNodeEditor {
|
|||||||
if (e.keyCode == KeyCode.F2) RenameSelectedNode();
|
if (e.keyCode == KeyCode.F2) RenameSelectedNode();
|
||||||
}
|
}
|
||||||
if (e.keyCode == KeyCode.A) {
|
if (e.keyCode == KeyCode.A) {
|
||||||
if (Selection.objects.Any(x => graph.nodes.Contains(x as XNode.Node))) {
|
if (Selection.objects.Any(x => graph.nodes.Contains(x as Node))) {
|
||||||
foreach (XNode.Node node in graph.nodes) {
|
foreach (Node node in graph.nodes) {
|
||||||
DeselectNode(node);
|
DeselectNode(node);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
foreach (XNode.Node node in graph.nodes) {
|
foreach (Node node in graph.nodes) {
|
||||||
SelectNode(node, true);
|
SelectNode(node, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -366,8 +366,8 @@ namespace XNodeEditor {
|
|||||||
dragOffset = new Vector2[Selection.objects.Length + selectedReroutes.Count];
|
dragOffset = new Vector2[Selection.objects.Length + selectedReroutes.Count];
|
||||||
// Selected nodes
|
// Selected nodes
|
||||||
for (int i = 0; i < Selection.objects.Length; i++) {
|
for (int i = 0; i < Selection.objects.Length; i++) {
|
||||||
if (Selection.objects[i] is XNode.Node) {
|
if (Selection.objects[i] is Node) {
|
||||||
XNode.Node node = Selection.objects[i] as XNode.Node;
|
Node node = Selection.objects[i] as Node;
|
||||||
dragOffset[i] = node.position - WindowToGridPosition(current.mousePosition);
|
dragOffset[i] = node.position - WindowToGridPosition(current.mousePosition);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -380,7 +380,7 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
/// <summary> Puts all selected nodes in focus. If no nodes are present, resets view and zoom to to origin </summary>
|
/// <summary> Puts all selected nodes in focus. If no nodes are present, resets view and zoom to to origin </summary>
|
||||||
public void Home() {
|
public void Home() {
|
||||||
var nodes = Selection.objects.Where(o => o is XNode.Node).Cast<XNode.Node>().ToList();
|
var nodes = Selection.objects.Where(o => o is Node).Cast<Node>().ToList();
|
||||||
if (nodes.Count > 0) {
|
if (nodes.Count > 0) {
|
||||||
Vector2 minPos = nodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y)));
|
Vector2 minPos = nodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y)));
|
||||||
Vector2 maxPos = nodes.Select(x => x.position + (nodeSizes.ContainsKey(x) ? nodeSizes[x] : Vector2.zero)).Aggregate((x, y) => new Vector2(Mathf.Max(x.x, y.x), Mathf.Max(x.y, y.y)));
|
Vector2 maxPos = nodes.Select(x => x.position + (nodeSizes.ContainsKey(x) ? nodeSizes[x] : Vector2.zero)).Aggregate((x, y) => new Vector2(Mathf.Max(x.x, y.x), Mathf.Max(x.y, y.y)));
|
||||||
@ -400,8 +400,8 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
selectedReroutes.Clear();
|
selectedReroutes.Clear();
|
||||||
foreach (UnityEngine.Object item in Selection.objects) {
|
foreach (UnityEngine.Object item in Selection.objects) {
|
||||||
if (item is XNode.Node) {
|
if (item is Node) {
|
||||||
XNode.Node node = item as XNode.Node;
|
Node node = item as Node;
|
||||||
graphEditor.RemoveNode(node);
|
graphEditor.RemoveNode(node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -409,8 +409,8 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
/// <summary> Initiate a rename on the currently selected node </summary>
|
/// <summary> Initiate a rename on the currently selected node </summary>
|
||||||
public void RenameSelectedNode() {
|
public void RenameSelectedNode() {
|
||||||
if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) {
|
if (Selection.objects.Length == 1 && Selection.activeObject is Node) {
|
||||||
XNode.Node node = Selection.activeObject as XNode.Node;
|
Node node = Selection.activeObject as Node;
|
||||||
Vector2 size;
|
Vector2 size;
|
||||||
if (nodeSizes.TryGetValue(node, out size)) {
|
if (nodeSizes.TryGetValue(node, out size)) {
|
||||||
RenamePopup.Show(Selection.activeObject, size.x);
|
RenamePopup.Show(Selection.activeObject, size.x);
|
||||||
@ -421,7 +421,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Draw this node on top of other nodes by placing it last in the graph.nodes list </summary>
|
/// <summary> Draw this node on top of other nodes by placing it last in the graph.nodes list </summary>
|
||||||
public void MoveNodeToTop(XNode.Node node) {
|
public void MoveNodeToTop(Node node) {
|
||||||
int index;
|
int index;
|
||||||
while ((index = graph.nodes.IndexOf(node)) != graph.nodes.Count - 1) {
|
while ((index = graph.nodes.IndexOf(node)) != graph.nodes.Count - 1) {
|
||||||
graph.nodes[index] = graph.nodes[index + 1];
|
graph.nodes[index] = graph.nodes[index + 1];
|
||||||
@ -432,7 +432,7 @@ namespace XNodeEditor {
|
|||||||
/// <summary> Duplicate selected nodes and select the duplicates </summary>
|
/// <summary> Duplicate selected nodes and select the duplicates </summary>
|
||||||
public void DuplicateSelectedNodes() {
|
public void DuplicateSelectedNodes() {
|
||||||
// Get selected nodes which are part of this graph
|
// Get selected nodes which are part of this graph
|
||||||
XNode.Node[] selectedNodes = Selection.objects.Select(x => x as XNode.Node).Where(x => x != null && x.graph == graph).ToArray();
|
Node[] selectedNodes = Selection.objects.Select(x => x as Node).Where(x => x != null && x.graph == graph).ToArray();
|
||||||
if (selectedNodes == null || selectedNodes.Length == 0) return;
|
if (selectedNodes == null || selectedNodes.Length == 0) return;
|
||||||
// Get top left node position
|
// Get top left node position
|
||||||
Vector2 topLeftNode = selectedNodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y)));
|
Vector2 topLeftNode = selectedNodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y)));
|
||||||
@ -440,14 +440,14 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void CopySelectedNodes() {
|
public void CopySelectedNodes() {
|
||||||
copyBuffer = Selection.objects.Select(x => x as XNode.Node).Where(x => x != null && x.graph == graph).ToArray();
|
copyBuffer = Selection.objects.Select(x => x as Node).Where(x => x != null && x.graph == graph).ToArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void PasteNodes(Vector2 pos) {
|
public void PasteNodes(Vector2 pos) {
|
||||||
InsertDuplicateNodes(copyBuffer, pos);
|
InsertDuplicateNodes(copyBuffer, pos);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void InsertDuplicateNodes(XNode.Node[] nodes, Vector2 topLeft) {
|
private void InsertDuplicateNodes(Node[] nodes, Vector2 topLeft) {
|
||||||
if (nodes == null || nodes.Length == 0) return;
|
if (nodes == null || nodes.Length == 0) return;
|
||||||
|
|
||||||
// Get top-left node
|
// Get top-left node
|
||||||
@ -455,20 +455,20 @@ namespace XNodeEditor {
|
|||||||
Vector2 offset = topLeft - topLeftNode;
|
Vector2 offset = topLeft - topLeftNode;
|
||||||
|
|
||||||
UnityEngine.Object[] newNodes = new UnityEngine.Object[nodes.Length];
|
UnityEngine.Object[] newNodes = new UnityEngine.Object[nodes.Length];
|
||||||
Dictionary<XNode.Node, XNode.Node> substitutes = new Dictionary<XNode.Node, XNode.Node>();
|
Dictionary<Node, Node> substitutes = new Dictionary<Node, Node>();
|
||||||
for (int i = 0; i < nodes.Length; i++) {
|
for (int i = 0; i < nodes.Length; i++) {
|
||||||
XNode.Node srcNode = nodes[i];
|
Node srcNode = nodes[i];
|
||||||
if (srcNode == null) continue;
|
if (srcNode == null) continue;
|
||||||
|
|
||||||
// Check if user is allowed to add more of given node type
|
// Check if user is allowed to add more of given node type
|
||||||
XNode.Node.DisallowMultipleNodesAttribute disallowAttrib;
|
Node.DisallowMultipleNodesAttribute disallowAttrib;
|
||||||
Type nodeType = srcNode.GetType();
|
Type nodeType = srcNode.GetType();
|
||||||
if (NodeEditorUtilities.GetAttrib(nodeType, out disallowAttrib)) {
|
if (NodeEditorUtilities.GetAttrib(nodeType, out disallowAttrib)) {
|
||||||
int typeCount = graph.nodes.Count(x => x.GetType() == nodeType);
|
int typeCount = graph.nodes.Count(x => x.GetType() == nodeType);
|
||||||
if (typeCount >= disallowAttrib.max) continue;
|
if (typeCount >= disallowAttrib.max) continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
XNode.Node newNode = graphEditor.CopyNode(srcNode);
|
Node newNode = graphEditor.CopyNode(srcNode);
|
||||||
substitutes.Add(srcNode, newNode);
|
substitutes.Add(srcNode, newNode);
|
||||||
newNode.position = srcNode.position + offset;
|
newNode.position = srcNode.position + offset;
|
||||||
newNodes[i] = newNode;
|
newNodes[i] = newNode;
|
||||||
@ -476,14 +476,14 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
// Walk through the selected nodes again, recreate connections, using the new nodes
|
// Walk through the selected nodes again, recreate connections, using the new nodes
|
||||||
for (int i = 0; i < nodes.Length; i++) {
|
for (int i = 0; i < nodes.Length; i++) {
|
||||||
XNode.Node srcNode = nodes[i];
|
Node srcNode = nodes[i];
|
||||||
if (srcNode == null) continue;
|
if (srcNode == null) continue;
|
||||||
foreach (XNode.NodePort port in srcNode.Ports) {
|
foreach (NodePort port in srcNode.Ports) {
|
||||||
for (int c = 0; c < port.ConnectionCount; c++) {
|
for (int c = 0; c < port.ConnectionCount; c++) {
|
||||||
XNode.NodePort inputPort = port.direction == XNode.NodePort.IO.Input ? port : port.GetConnection(c);
|
NodePort inputPort = port.direction == NodePort.IO.Input ? port : port.GetConnection(c);
|
||||||
XNode.NodePort outputPort = port.direction == XNode.NodePort.IO.Output ? port : port.GetConnection(c);
|
NodePort outputPort = port.direction == NodePort.IO.Output ? port : port.GetConnection(c);
|
||||||
|
|
||||||
XNode.Node newNodeIn, newNodeOut;
|
Node newNodeIn, newNodeOut;
|
||||||
if (substitutes.TryGetValue(inputPort.node, out newNodeIn) && substitutes.TryGetValue(outputPort.node, out newNodeOut)) {
|
if (substitutes.TryGetValue(inputPort.node, out newNodeIn) && substitutes.TryGetValue(outputPort.node, out newNodeOut)) {
|
||||||
newNodeIn.UpdatePorts();
|
newNodeIn.UpdatePorts();
|
||||||
newNodeOut.UpdatePorts();
|
newNodeOut.UpdatePorts();
|
||||||
@ -537,7 +537,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool IsHoveringTitle(XNode.Node node) {
|
bool IsHoveringTitle(Node node) {
|
||||||
Vector2 mousePos = Event.current.mousePosition;
|
Vector2 mousePos = Event.current.mousePosition;
|
||||||
//Get node position
|
//Get node position
|
||||||
Vector2 nodePos = GridToWindowPosition(node.position);
|
Vector2 nodePos = GridToWindowPosition(node.position);
|
||||||
@ -550,11 +550,11 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Attempt to connect dragged output to target node </summary>
|
/// <summary> Attempt to connect dragged output to target node </summary>
|
||||||
public void AutoConnect(XNode.Node node) {
|
public void AutoConnect(Node node) {
|
||||||
if (autoConnectOutput == null) return;
|
if (autoConnectOutput == null) return;
|
||||||
|
|
||||||
// Find compatible input port
|
// Find compatible input port
|
||||||
XNode.NodePort inputPort = node.Ports.FirstOrDefault(x => x.IsInput && graphEditor.CanConnect(autoConnectOutput, x));
|
NodePort inputPort = node.Ports.FirstOrDefault(x => x.IsInput && graphEditor.CanConnect(autoConnectOutput, x));
|
||||||
if (inputPort != null) autoConnectOutput.Connect(inputPort);
|
if (inputPort != null) autoConnectOutput.Connect(inputPort);
|
||||||
|
|
||||||
// Save changes
|
// Save changes
|
||||||
|
|||||||
@ -22,7 +22,7 @@ namespace XNodeEditor {
|
|||||||
// Check script type. Return if deleting a non-node script
|
// Check script type. Return if deleting a non-node script
|
||||||
UnityEditor.MonoScript script = obj as UnityEditor.MonoScript;
|
UnityEditor.MonoScript script = obj as UnityEditor.MonoScript;
|
||||||
System.Type scriptType = script.GetClass ();
|
System.Type scriptType = script.GetClass ();
|
||||||
if (scriptType == null || (scriptType != typeof (XNode.Node) && !scriptType.IsSubclassOf (typeof (XNode.Node)))) return AssetDeleteResult.DidNotDelete;
|
if (scriptType == null || (scriptType != typeof (Node) && !scriptType.IsSubclassOf (typeof (Node)))) return AssetDeleteResult.DidNotDelete;
|
||||||
|
|
||||||
// Find all ScriptableObjects using this script
|
// Find all ScriptableObjects using this script
|
||||||
string[] guids = AssetDatabase.FindAssets ("t:" + scriptType);
|
string[] guids = AssetDatabase.FindAssets ("t:" + scriptType);
|
||||||
@ -30,7 +30,7 @@ namespace XNodeEditor {
|
|||||||
string assetpath = AssetDatabase.GUIDToAssetPath (guids[i]);
|
string assetpath = AssetDatabase.GUIDToAssetPath (guids[i]);
|
||||||
Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath (assetpath);
|
Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath (assetpath);
|
||||||
for (int k = 0; k < objs.Length; k++) {
|
for (int k = 0; k < objs.Length; k++) {
|
||||||
XNode.Node node = objs[k] as XNode.Node;
|
Node node = objs[k] as Node;
|
||||||
if (node.GetType () == scriptType) {
|
if (node.GetType () == scriptType) {
|
||||||
if (node != null && node.graph != null) {
|
if (node != null && node.graph != null) {
|
||||||
// Delete the node and notify the user
|
// Delete the node and notify the user
|
||||||
@ -48,17 +48,17 @@ namespace XNodeEditor {
|
|||||||
[InitializeOnLoadMethod]
|
[InitializeOnLoadMethod]
|
||||||
private static void OnReloadEditor () {
|
private static void OnReloadEditor () {
|
||||||
// Find all NodeGraph assets
|
// Find all NodeGraph assets
|
||||||
string[] guids = AssetDatabase.FindAssets ("t:" + typeof (XNode.NodeGraph));
|
string[] guids = AssetDatabase.FindAssets ("t:" + typeof (NodeGraph));
|
||||||
for (int i = 0; i < guids.Length; i++) {
|
for (int i = 0; i < guids.Length; i++) {
|
||||||
string assetpath = AssetDatabase.GUIDToAssetPath (guids[i]);
|
string assetpath = AssetDatabase.GUIDToAssetPath (guids[i]);
|
||||||
XNode.NodeGraph graph = AssetDatabase.LoadAssetAtPath (assetpath, typeof (XNode.NodeGraph)) as XNode.NodeGraph;
|
NodeGraph graph = AssetDatabase.LoadAssetAtPath (assetpath, typeof (NodeGraph)) as NodeGraph;
|
||||||
graph.nodes.RemoveAll(x => x == null); //Remove null items
|
graph.nodes.RemoveAll(x => x == null); //Remove null items
|
||||||
Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath (assetpath);
|
Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath (assetpath);
|
||||||
// Ensure that all sub node assets are present in the graph node list
|
// Ensure that all sub node assets are present in the graph node list
|
||||||
for (int u = 0; u < objs.Length; u++) {
|
for (int u = 0; u < objs.Length; u++) {
|
||||||
// Ignore null sub assets
|
// Ignore null sub assets
|
||||||
if (objs[u] == null) continue;
|
if (objs[u] == null) continue;
|
||||||
if (!graph.nodes.Contains (objs[u] as XNode.Node)) graph.nodes.Add(objs[u] as XNode.Node);
|
if (!graph.nodes.Contains (objs[u] as Node)) graph.nodes.Add(objs[u] as Node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -13,7 +13,7 @@ namespace XNodeEditor {
|
|||||||
public partial class NodeEditorWindow {
|
public partial class NodeEditorWindow {
|
||||||
public NodeGraphEditor graphEditor;
|
public NodeGraphEditor graphEditor;
|
||||||
private List<UnityEngine.Object> selectionCache;
|
private List<UnityEngine.Object> selectionCache;
|
||||||
private List<XNode.Node> culledNodes;
|
private List<Node> culledNodes;
|
||||||
/// <summary> 19 if docked, 22 if not </summary>
|
/// <summary> 19 if docked, 22 if not </summary>
|
||||||
private int topPadding { get { return isDocked() ? 19 : 22; } }
|
private int topPadding { get { return isDocked() ? 19 : 22; } }
|
||||||
/// <summary> Executed after all other window GUI. Useful if Zoom is ruining your day. Automatically resets after being run.</summary>
|
/// <summary> Executed after all other window GUI. Useful if Zoom is ruining your day. Automatically resets after being run.</summary>
|
||||||
@ -113,7 +113,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Show right-click context menu for hovered port </summary>
|
/// <summary> Show right-click context menu for hovered port </summary>
|
||||||
void ShowPortContextMenu(XNode.NodePort hoveredPort) {
|
void ShowPortContextMenu(NodePort hoveredPort) {
|
||||||
GenericMenu contextMenu = new GenericMenu();
|
GenericMenu contextMenu = new GenericMenu();
|
||||||
foreach (var port in hoveredPort.GetConnections()) {
|
foreach (var port in hoveredPort.GetConnections()) {
|
||||||
var name = port.node.name;
|
var name = port.node.name;
|
||||||
@ -125,10 +125,10 @@ namespace XNodeEditor {
|
|||||||
if (NodeEditorPreferences.GetSettings().createFilter) {
|
if (NodeEditorPreferences.GetSettings().createFilter) {
|
||||||
contextMenu.AddSeparator("");
|
contextMenu.AddSeparator("");
|
||||||
|
|
||||||
if (hoveredPort.direction == XNode.NodePort.IO.Input)
|
if (hoveredPort.direction == NodePort.IO.Input)
|
||||||
graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, XNode.NodePort.IO.Output);
|
graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, NodePort.IO.Output);
|
||||||
else
|
else
|
||||||
graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, XNode.NodePort.IO.Input);
|
graphEditor.AddContextMenuItems(contextMenu, hoveredPort.ValueType, NodePort.IO.Input);
|
||||||
}
|
}
|
||||||
contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
|
contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
|
||||||
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
|
||||||
@ -335,12 +335,12 @@ namespace XNodeEditor {
|
|||||||
List<Vector2> gridPoints = new List<Vector2>(2);
|
List<Vector2> gridPoints = new List<Vector2>(2);
|
||||||
|
|
||||||
Color col = GUI.color;
|
Color col = GUI.color;
|
||||||
foreach (XNode.Node node in graph.nodes) {
|
foreach (Node node in graph.nodes) {
|
||||||
//If a null node is found, return. This can happen if the nodes associated script is deleted. It is currently not possible in Unity to delete a null asset.
|
//If a null node is found, return. This can happen if the nodes associated script is deleted. It is currently not possible in Unity to delete a null asset.
|
||||||
if (node == null) continue;
|
if (node == null) continue;
|
||||||
|
|
||||||
// Draw full connections and output > reroute
|
// Draw full connections and output > reroute
|
||||||
foreach (XNode.NodePort output in node.Outputs) {
|
foreach (NodePort output in node.Outputs) {
|
||||||
//Needs cleanup. Null checks are ugly
|
//Needs cleanup. Null checks are ugly
|
||||||
Rect fromRect;
|
Rect fromRect;
|
||||||
if (!_portConnectionPoints.TryGetValue(output, out fromRect)) continue;
|
if (!_portConnectionPoints.TryGetValue(output, out fromRect)) continue;
|
||||||
@ -349,7 +349,7 @@ namespace XNodeEditor {
|
|||||||
GUIStyle portStyle = graphEditor.GetPortStyle(output);
|
GUIStyle portStyle = graphEditor.GetPortStyle(output);
|
||||||
|
|
||||||
for (int k = 0; k < output.ConnectionCount; k++) {
|
for (int k = 0; k < output.ConnectionCount; k++) {
|
||||||
XNode.NodePort input = output.GetConnection(k);
|
NodePort input = output.GetConnection(k);
|
||||||
|
|
||||||
Gradient noodleGradient = graphEditor.GetNoodleGradient(output, input);
|
Gradient noodleGradient = graphEditor.GetNoodleGradient(output, input);
|
||||||
float noodleThickness = graphEditor.GetNoodleThickness(output, input);
|
float noodleThickness = graphEditor.GetNoodleThickness(output, input);
|
||||||
@ -404,7 +404,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
System.Reflection.MethodInfo onValidate = null;
|
System.Reflection.MethodInfo onValidate = null;
|
||||||
if (Selection.activeObject != null && Selection.activeObject is XNode.Node) {
|
if (Selection.activeObject != null && Selection.activeObject is Node) {
|
||||||
onValidate = Selection.activeObject.GetType().GetMethod("OnValidate");
|
onValidate = Selection.activeObject.GetType().GetMethod("OnValidate");
|
||||||
if (onValidate != null) EditorGUI.BeginChangeCheck();
|
if (onValidate != null) EditorGUI.BeginChangeCheck();
|
||||||
}
|
}
|
||||||
@ -430,14 +430,14 @@ namespace XNodeEditor {
|
|||||||
//Save guiColor so we can revert it
|
//Save guiColor so we can revert it
|
||||||
Color guiColor = GUI.color;
|
Color guiColor = GUI.color;
|
||||||
|
|
||||||
List<XNode.NodePort> removeEntries = new List<XNode.NodePort>();
|
List<NodePort> removeEntries = new List<NodePort>();
|
||||||
|
|
||||||
if (e.type == EventType.Layout) culledNodes = new List<XNode.Node>();
|
if (e.type == EventType.Layout) culledNodes = new List<Node>();
|
||||||
for (int n = 0; n < graph.nodes.Count; n++) {
|
for (int n = 0; n < graph.nodes.Count; n++) {
|
||||||
// Skip null nodes. The user could be in the process of renaming scripts, so removing them at this point is not advisable.
|
// Skip null nodes. The user could be in the process of renaming scripts, so removing them at this point is not advisable.
|
||||||
if (graph.nodes[n] == null) continue;
|
if (graph.nodes[n] == null) continue;
|
||||||
if (n >= graph.nodes.Count) return;
|
if (n >= graph.nodes.Count) return;
|
||||||
XNode.Node node = graph.nodes[n];
|
Node node = graph.nodes[n];
|
||||||
|
|
||||||
// Culling
|
// Culling
|
||||||
if (e.type == EventType.Layout) {
|
if (e.type == EventType.Layout) {
|
||||||
@ -529,14 +529,14 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
//Check if we are hovering any of this nodes ports
|
//Check if we are hovering any of this nodes ports
|
||||||
//Check input ports
|
//Check input ports
|
||||||
foreach (XNode.NodePort input in node.Inputs) {
|
foreach (NodePort input in node.Inputs) {
|
||||||
//Check if port rect is available
|
//Check if port rect is available
|
||||||
if (!portConnectionPoints.ContainsKey(input)) continue;
|
if (!portConnectionPoints.ContainsKey(input)) continue;
|
||||||
Rect r = GridToWindowRectNoClipped(portConnectionPoints[input]);
|
Rect r = GridToWindowRectNoClipped(portConnectionPoints[input]);
|
||||||
if (r.Contains(mousePos)) hoveredPort = input;
|
if (r.Contains(mousePos)) hoveredPort = input;
|
||||||
}
|
}
|
||||||
//Check all output ports
|
//Check all output ports
|
||||||
foreach (XNode.NodePort output in node.Outputs) {
|
foreach (NodePort output in node.Outputs) {
|
||||||
//Check if port rect is available
|
//Check if port rect is available
|
||||||
if (!portConnectionPoints.ContainsKey(output)) continue;
|
if (!portConnectionPoints.ContainsKey(output)) continue;
|
||||||
Rect r = GridToWindowRectNoClipped(portConnectionPoints[output]);
|
Rect r = GridToWindowRectNoClipped(portConnectionPoints[output]);
|
||||||
@ -556,7 +556,7 @@ namespace XNodeEditor {
|
|||||||
if (onValidate != null && EditorGUI.EndChangeCheck()) onValidate.Invoke(Selection.activeObject, null);
|
if (onValidate != null && EditorGUI.EndChangeCheck()) onValidate.Invoke(Selection.activeObject, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool ShouldBeCulled(XNode.Node node) {
|
private bool ShouldBeCulled(Node node) {
|
||||||
|
|
||||||
Vector2 nodePos = GridToWindowPositionNoClipped(node.position);
|
Vector2 nodePos = GridToWindowPositionNoClipped(node.position);
|
||||||
if (nodePos.x / _zoom > position.width) return true; // Right
|
if (nodePos.x / _zoom > position.width) return true; // Right
|
||||||
|
|||||||
@ -22,18 +22,18 @@ namespace XNodeEditor {
|
|||||||
/// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary>
|
/// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary>
|
||||||
public static void PropertyField(SerializedProperty property, GUIContent label, bool includeChildren = true, params GUILayoutOption[] options) {
|
public static void PropertyField(SerializedProperty property, GUIContent label, bool includeChildren = true, params GUILayoutOption[] options) {
|
||||||
if (property == null) throw new NullReferenceException();
|
if (property == null) throw new NullReferenceException();
|
||||||
XNode.Node node = property.serializedObject.targetObject as XNode.Node;
|
Node node = property.serializedObject.targetObject as Node;
|
||||||
XNode.NodePort port = node.GetPort(property.name);
|
NodePort port = node.GetPort(property.name);
|
||||||
PropertyField(property, label, port, includeChildren);
|
PropertyField(property, label, port, includeChildren);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a field for a serialized property. Manual node port override. </summary>
|
/// <summary> Make a field for a serialized property. Manual node port override. </summary>
|
||||||
public static void PropertyField(SerializedProperty property, XNode.NodePort port, bool includeChildren = true, params GUILayoutOption[] options) {
|
public static void PropertyField(SerializedProperty property, NodePort port, bool includeChildren = true, params GUILayoutOption[] options) {
|
||||||
PropertyField(property, null, port, includeChildren, options);
|
PropertyField(property, null, port, includeChildren, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a field for a serialized property. Manual node port override. </summary>
|
/// <summary> Make a field for a serialized property. Manual node port override. </summary>
|
||||||
public static void PropertyField(SerializedProperty property, GUIContent label, XNode.NodePort port, bool includeChildren = true, params GUILayoutOption[] options) {
|
public static void PropertyField(SerializedProperty property, GUIContent label, NodePort port, bool includeChildren = true, params GUILayoutOption[] options) {
|
||||||
if (property == null) throw new NullReferenceException();
|
if (property == null) throw new NullReferenceException();
|
||||||
|
|
||||||
// If property is not a port, display a regular property field
|
// If property is not a port, display a regular property field
|
||||||
@ -44,10 +44,10 @@ namespace XNodeEditor {
|
|||||||
List<PropertyAttribute> propertyAttributes = NodeEditorUtilities.GetCachedPropertyAttribs(port.node.GetType(), property.name);
|
List<PropertyAttribute> propertyAttributes = NodeEditorUtilities.GetCachedPropertyAttribs(port.node.GetType(), property.name);
|
||||||
|
|
||||||
// If property is an input, display a regular property field and put a port handle on the left side
|
// If property is an input, display a regular property field and put a port handle on the left side
|
||||||
if (port.direction == XNode.NodePort.IO.Input) {
|
if (port.direction == NodePort.IO.Input) {
|
||||||
// Get data from [Input] attribute
|
// Get data from [Input] attribute
|
||||||
XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
|
Node.ShowBackingValue showBacking = Node.ShowBackingValue.Unconnected;
|
||||||
XNode.Node.InputAttribute inputAttribute;
|
Node.InputAttribute inputAttribute;
|
||||||
bool dynamicPortList = false;
|
bool dynamicPortList = false;
|
||||||
if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute)) {
|
if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute)) {
|
||||||
dynamicPortList = inputAttribute.dynamicPortList;
|
dynamicPortList = inputAttribute.dynamicPortList;
|
||||||
@ -55,8 +55,8 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool usePropertyAttributes = dynamicPortList ||
|
bool usePropertyAttributes = dynamicPortList ||
|
||||||
showBacking == XNode.Node.ShowBackingValue.Never ||
|
showBacking == Node.ShowBackingValue.Never ||
|
||||||
(showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected);
|
(showBacking == Node.ShowBackingValue.Unconnected && port.IsConnected);
|
||||||
|
|
||||||
float spacePadding = 0;
|
float spacePadding = 0;
|
||||||
string tooltip = null;
|
string tooltip = null;
|
||||||
@ -79,22 +79,22 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
if (dynamicPortList) {
|
if (dynamicPortList) {
|
||||||
Type type = GetType(property);
|
Type type = GetType(property);
|
||||||
XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
|
Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : Node.ConnectionType.Multiple;
|
||||||
DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
|
DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (showBacking) {
|
switch (showBacking) {
|
||||||
case XNode.Node.ShowBackingValue.Unconnected:
|
case Node.ShowBackingValue.Unconnected:
|
||||||
// Display a label if port is connected
|
// Display a label if port is connected
|
||||||
if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
|
if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
|
||||||
// Display an editable property field if port is not connected
|
// Display an editable property field if port is not connected
|
||||||
else EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
else EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
||||||
break;
|
break;
|
||||||
case XNode.Node.ShowBackingValue.Never:
|
case Node.ShowBackingValue.Never:
|
||||||
// Display a label
|
// Display a label
|
||||||
EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
|
EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
|
||||||
break;
|
break;
|
||||||
case XNode.Node.ShowBackingValue.Always:
|
case Node.ShowBackingValue.Always:
|
||||||
// Display an editable property field
|
// Display an editable property field
|
||||||
EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
||||||
break;
|
break;
|
||||||
@ -104,10 +104,10 @@ namespace XNodeEditor {
|
|||||||
float paddingLeft = NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.left;
|
float paddingLeft = NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.left;
|
||||||
rect.position = rect.position - new Vector2(16 + paddingLeft, -spacePadding);
|
rect.position = rect.position - new Vector2(16 + paddingLeft, -spacePadding);
|
||||||
// If property is an output, display a text label and put a port handle on the right side
|
// If property is an output, display a text label and put a port handle on the right side
|
||||||
} else if (port.direction == XNode.NodePort.IO.Output) {
|
} else if (port.direction == NodePort.IO.Output) {
|
||||||
// Get data from [Output] attribute
|
// Get data from [Output] attribute
|
||||||
XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
|
Node.ShowBackingValue showBacking = Node.ShowBackingValue.Unconnected;
|
||||||
XNode.Node.OutputAttribute outputAttribute;
|
Node.OutputAttribute outputAttribute;
|
||||||
bool dynamicPortList = false;
|
bool dynamicPortList = false;
|
||||||
if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute)) {
|
if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute)) {
|
||||||
dynamicPortList = outputAttribute.dynamicPortList;
|
dynamicPortList = outputAttribute.dynamicPortList;
|
||||||
@ -115,8 +115,8 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool usePropertyAttributes = dynamicPortList ||
|
bool usePropertyAttributes = dynamicPortList ||
|
||||||
showBacking == XNode.Node.ShowBackingValue.Never ||
|
showBacking == Node.ShowBackingValue.Never ||
|
||||||
(showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected);
|
(showBacking == Node.ShowBackingValue.Unconnected && port.IsConnected);
|
||||||
|
|
||||||
float spacePadding = 0;
|
float spacePadding = 0;
|
||||||
string tooltip = null;
|
string tooltip = null;
|
||||||
@ -139,22 +139,22 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
if (dynamicPortList) {
|
if (dynamicPortList) {
|
||||||
Type type = GetType(property);
|
Type type = GetType(property);
|
||||||
XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
|
Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : Node.ConnectionType.Multiple;
|
||||||
DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
|
DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (showBacking) {
|
switch (showBacking) {
|
||||||
case XNode.Node.ShowBackingValue.Unconnected:
|
case Node.ShowBackingValue.Unconnected:
|
||||||
// Display a label if port is connected
|
// Display a label if port is connected
|
||||||
if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
|
if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
|
||||||
// Display an editable property field if port is not connected
|
// Display an editable property field if port is not connected
|
||||||
else EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
else EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
||||||
break;
|
break;
|
||||||
case XNode.Node.ShowBackingValue.Never:
|
case Node.ShowBackingValue.Never:
|
||||||
// Display a label
|
// Display a label
|
||||||
EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
|
EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
|
||||||
break;
|
break;
|
||||||
case XNode.Node.ShowBackingValue.Always:
|
case Node.ShowBackingValue.Always:
|
||||||
// Display an editable property field
|
// Display an editable property field
|
||||||
EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
|
||||||
break;
|
break;
|
||||||
@ -185,19 +185,19 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a simple port field. </summary>
|
/// <summary> Make a simple port field. </summary>
|
||||||
public static void PortField(XNode.NodePort port, params GUILayoutOption[] options) {
|
public static void PortField(NodePort port, params GUILayoutOption[] options) {
|
||||||
PortField(null, port, options);
|
PortField(null, port, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a simple port field. </summary>
|
/// <summary> Make a simple port field. </summary>
|
||||||
public static void PortField(GUIContent label, XNode.NodePort port, params GUILayoutOption[] options) {
|
public static void PortField(GUIContent label, NodePort port, params GUILayoutOption[] options) {
|
||||||
if (port == null) return;
|
if (port == null) return;
|
||||||
if (options == null) options = new GUILayoutOption[] { GUILayout.MinWidth(30) };
|
if (options == null) options = new GUILayoutOption[] { GUILayout.MinWidth(30) };
|
||||||
Vector2 position = Vector3.zero;
|
Vector2 position = Vector3.zero;
|
||||||
GUIContent content = label != null ? label : new GUIContent(ObjectNames.NicifyVariableName(port.fieldName));
|
GUIContent content = label != null ? label : new GUIContent(ObjectNames.NicifyVariableName(port.fieldName));
|
||||||
|
|
||||||
// If property is an input, display a regular property field and put a port handle on the left side
|
// If property is an input, display a regular property field and put a port handle on the left side
|
||||||
if (port.direction == XNode.NodePort.IO.Input) {
|
if (port.direction == NodePort.IO.Input) {
|
||||||
// Display a label
|
// Display a label
|
||||||
EditorGUILayout.LabelField(content, options);
|
EditorGUILayout.LabelField(content, options);
|
||||||
|
|
||||||
@ -206,7 +206,7 @@ namespace XNodeEditor {
|
|||||||
position = rect.position - new Vector2(16 + paddingLeft, 0);
|
position = rect.position - new Vector2(16 + paddingLeft, 0);
|
||||||
}
|
}
|
||||||
// If property is an output, display a text label and put a port handle on the right side
|
// If property is an output, display a text label and put a port handle on the right side
|
||||||
else if (port.direction == XNode.NodePort.IO.Output) {
|
else if (port.direction == NodePort.IO.Output) {
|
||||||
// Display a label
|
// Display a label
|
||||||
EditorGUILayout.LabelField(content, NodeEditorResources.OutputPort, options);
|
EditorGUILayout.LabelField(content, NodeEditorResources.OutputPort, options);
|
||||||
|
|
||||||
@ -218,7 +218,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Make a simple port field. </summary>
|
/// <summary> Make a simple port field. </summary>
|
||||||
public static void PortField(Vector2 position, XNode.NodePort port) {
|
public static void PortField(Vector2 position, NodePort port) {
|
||||||
if (port == null) return;
|
if (port == null) return;
|
||||||
|
|
||||||
Rect rect = new Rect(position, new Vector2(16, 16));
|
Rect rect = new Rect(position, new Vector2(16, 16));
|
||||||
@ -235,17 +235,17 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Add a port field to previous layout element. </summary>
|
/// <summary> Add a port field to previous layout element. </summary>
|
||||||
public static void AddPortField(XNode.NodePort port) {
|
public static void AddPortField(NodePort port) {
|
||||||
if (port == null) return;
|
if (port == null) return;
|
||||||
Rect rect = new Rect();
|
Rect rect = new Rect();
|
||||||
|
|
||||||
// If property is an input, display a regular property field and put a port handle on the left side
|
// If property is an input, display a regular property field and put a port handle on the left side
|
||||||
if (port.direction == XNode.NodePort.IO.Input) {
|
if (port.direction == NodePort.IO.Input) {
|
||||||
rect = GUILayoutUtility.GetLastRect();
|
rect = GUILayoutUtility.GetLastRect();
|
||||||
float paddingLeft = NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.left;
|
float paddingLeft = NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.left;
|
||||||
rect.position = rect.position - new Vector2(16 + paddingLeft, 0);
|
rect.position = rect.position - new Vector2(16 + paddingLeft, 0);
|
||||||
// If property is an output, display a text label and put a port handle on the right side
|
// If property is an output, display a text label and put a port handle on the right side
|
||||||
} else if (port.direction == XNode.NodePort.IO.Output) {
|
} else if (port.direction == NodePort.IO.Output) {
|
||||||
rect = GUILayoutUtility.GetLastRect();
|
rect = GUILayoutUtility.GetLastRect();
|
||||||
rect.width += NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.right;
|
rect.width += NodeEditorWindow.current.graphEditor.GetPortStyle(port).padding.right;
|
||||||
rect.position = rect.position + new Vector2(rect.width, 0);
|
rect.position = rect.position + new Vector2(rect.width, 0);
|
||||||
@ -265,7 +265,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Draws an input and an output port on the same line </summary>
|
/// <summary> Draws an input and an output port on the same line </summary>
|
||||||
public static void PortPair(XNode.NodePort input, XNode.NodePort output) {
|
public static void PortPair(NodePort input, NodePort output) {
|
||||||
GUILayout.BeginHorizontal();
|
GUILayout.BeginHorizontal();
|
||||||
NodeEditorGUILayout.PortField(input, GUILayout.MinWidth(0));
|
NodeEditorGUILayout.PortField(input, GUILayout.MinWidth(0));
|
||||||
NodeEditorGUILayout.PortField(output, GUILayout.MinWidth(0));
|
NodeEditorGUILayout.PortField(output, GUILayout.MinWidth(0));
|
||||||
@ -292,18 +292,18 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
#region Obsolete
|
#region Obsolete
|
||||||
[Obsolete("Use IsDynamicPortListPort instead")]
|
[Obsolete("Use IsDynamicPortListPort instead")]
|
||||||
public static bool IsInstancePortListPort(XNode.NodePort port) {
|
public static bool IsInstancePortListPort(NodePort port) {
|
||||||
return IsDynamicPortListPort(port);
|
return IsDynamicPortListPort(port);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Obsolete("Use DynamicPortList instead")]
|
[Obsolete("Use DynamicPortList instead")]
|
||||||
public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple, XNode.Node.TypeConstraint typeConstraint = XNode.Node.TypeConstraint.None, Action<ReorderableList> onCreation = null) {
|
public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, NodePort.IO io, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = Node.TypeConstraint.None, Action<ReorderableList> onCreation = null) {
|
||||||
DynamicPortList(fieldName, type, serializedObject, io, connectionType, typeConstraint, onCreation);
|
DynamicPortList(fieldName, type, serializedObject, io, connectionType, typeConstraint, onCreation);
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
/// <summary> Is this port part of a DynamicPortList? </summary>
|
/// <summary> Is this port part of a DynamicPortList? </summary>
|
||||||
public static bool IsDynamicPortListPort(XNode.NodePort port) {
|
public static bool IsDynamicPortListPort(NodePort port) {
|
||||||
string[] parts = port.fieldName.Split(' ');
|
string[] parts = port.fieldName.Split(' ');
|
||||||
if (parts.Length != 2) return false;
|
if (parts.Length != 2) return false;
|
||||||
Dictionary<string, ReorderableList> cache;
|
Dictionary<string, ReorderableList> cache;
|
||||||
@ -320,8 +320,8 @@ namespace XNodeEditor {
|
|||||||
/// <param name="serializedObject">The serializedObject of the node</param>
|
/// <param name="serializedObject">The serializedObject of the node</param>
|
||||||
/// <param name="connectionType">Connection type of added dynamic ports</param>
|
/// <param name="connectionType">Connection type of added dynamic ports</param>
|
||||||
/// <param name="onCreation">Called on the list on creation. Use this if you want to customize the created ReorderableList</param>
|
/// <param name="onCreation">Called on the list on creation. Use this if you want to customize the created ReorderableList</param>
|
||||||
public static void DynamicPortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple, XNode.Node.TypeConstraint typeConstraint = XNode.Node.TypeConstraint.None, Action<ReorderableList> onCreation = null) {
|
public static void DynamicPortList(string fieldName, Type type, SerializedObject serializedObject, NodePort.IO io, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = Node.TypeConstraint.None, Action<ReorderableList> onCreation = null) {
|
||||||
XNode.Node node = serializedObject.targetObject as XNode.Node;
|
Node node = serializedObject.targetObject as Node;
|
||||||
|
|
||||||
var indexedPorts = node.DynamicPorts.Select(x => {
|
var indexedPorts = node.DynamicPorts.Select(x => {
|
||||||
string[] split = x.fieldName.Split(' ');
|
string[] split = x.fieldName.Split(' ');
|
||||||
@ -331,9 +331,9 @@ namespace XNodeEditor {
|
|||||||
return new { index = i, port = x };
|
return new { index = i, port = x };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new { index = -1, port = (XNode.NodePort)null };
|
return new { index = -1, port = (NodePort)null };
|
||||||
}).Where(x => x.port != null);
|
}).Where(x => x.port != null);
|
||||||
List<XNode.NodePort> dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();
|
List<NodePort> dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();
|
||||||
|
|
||||||
node.UpdatePorts();
|
node.UpdatePorts();
|
||||||
|
|
||||||
@ -354,15 +354,15 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ReorderableList CreateReorderableList(string fieldName, List<XNode.NodePort> dynamicPorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType, XNode.Node.TypeConstraint typeConstraint, Action<ReorderableList> onCreation) {
|
private static ReorderableList CreateReorderableList(string fieldName, List<NodePort> dynamicPorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, NodePort.IO io, Node.ConnectionType connectionType, Node.TypeConstraint typeConstraint, Action<ReorderableList> onCreation) {
|
||||||
bool hasArrayData = arrayData != null && arrayData.isArray;
|
bool hasArrayData = arrayData != null && arrayData.isArray;
|
||||||
XNode.Node node = serializedObject.targetObject as XNode.Node;
|
Node node = serializedObject.targetObject as Node;
|
||||||
ReorderableList list = new ReorderableList(dynamicPorts, null, true, true, true, true);
|
ReorderableList list = new ReorderableList(dynamicPorts, null, true, true, true, true);
|
||||||
string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName);
|
string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName);
|
||||||
|
|
||||||
list.drawElementCallback =
|
list.drawElementCallback =
|
||||||
(Rect rect, int index, bool isActive, bool isFocused) => {
|
(Rect rect, int index, bool isActive, bool isFocused) => {
|
||||||
XNode.NodePort port = node.GetPort(fieldName + " " + index);
|
NodePort port = node.GetPort(fieldName + " " + index);
|
||||||
if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String) {
|
if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String) {
|
||||||
if (arrayData.arraySize <= index) {
|
if (arrayData.arraySize <= index) {
|
||||||
EditorGUI.LabelField(rect, "Array[" + index + "] data out of range");
|
EditorGUI.LabelField(rect, "Array[" + index + "] data out of range");
|
||||||
@ -402,8 +402,8 @@ namespace XNodeEditor {
|
|||||||
// Move up
|
// Move up
|
||||||
if (rl.index > reorderableListIndex) {
|
if (rl.index > reorderableListIndex) {
|
||||||
for (int i = reorderableListIndex; i < rl.index; ++i) {
|
for (int i = reorderableListIndex; i < rl.index; ++i) {
|
||||||
XNode.NodePort port = node.GetPort(fieldName + " " + i);
|
NodePort port = node.GetPort(fieldName + " " + i);
|
||||||
XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i + 1));
|
NodePort nextPort = node.GetPort(fieldName + " " + (i + 1));
|
||||||
port.SwapConnections(nextPort);
|
port.SwapConnections(nextPort);
|
||||||
|
|
||||||
// Swap cached positions to mitigate twitching
|
// Swap cached positions to mitigate twitching
|
||||||
@ -416,8 +416,8 @@ namespace XNodeEditor {
|
|||||||
// Move down
|
// Move down
|
||||||
else {
|
else {
|
||||||
for (int i = reorderableListIndex; i > rl.index; --i) {
|
for (int i = reorderableListIndex; i > rl.index; --i) {
|
||||||
XNode.NodePort port = node.GetPort(fieldName + " " + i);
|
NodePort port = node.GetPort(fieldName + " " + i);
|
||||||
XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i - 1));
|
NodePort nextPort = node.GetPort(fieldName + " " + (i - 1));
|
||||||
port.SwapConnections(nextPort);
|
port.SwapConnections(nextPort);
|
||||||
|
|
||||||
// Swap cached positions to mitigate twitching
|
// Swap cached positions to mitigate twitching
|
||||||
@ -449,7 +449,7 @@ namespace XNodeEditor {
|
|||||||
int i = 0;
|
int i = 0;
|
||||||
while (node.HasPort(newName)) newName = fieldName + " " + (++i);
|
while (node.HasPort(newName)) newName = fieldName + " " + (++i);
|
||||||
|
|
||||||
if (io == XNode.NodePort.IO.Output) node.AddDynamicOutput(type, connectionType, XNode.Node.TypeConstraint.None, newName);
|
if (io == NodePort.IO.Output) node.AddDynamicOutput(type, connectionType, Node.TypeConstraint.None, newName);
|
||||||
else node.AddDynamicInput(type, connectionType, typeConstraint, newName);
|
else node.AddDynamicInput(type, connectionType, typeConstraint, newName);
|
||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
EditorUtility.SetDirty(node);
|
EditorUtility.SetDirty(node);
|
||||||
@ -469,7 +469,7 @@ namespace XNodeEditor {
|
|||||||
return new { index = i, port = x };
|
return new { index = i, port = x };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new { index = -1, port = (XNode.NodePort)null };
|
return new { index = -1, port = (NodePort)null };
|
||||||
}).Where(x => x.port != null);
|
}).Where(x => x.port != null);
|
||||||
dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();
|
dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();
|
||||||
|
|
||||||
@ -486,7 +486,7 @@ namespace XNodeEditor {
|
|||||||
// Move following connections one step up to replace the missing connection
|
// Move following connections one step up to replace the missing connection
|
||||||
for (int k = index + 1; k < dynamicPorts.Count(); k++) {
|
for (int k = index + 1; k < dynamicPorts.Count(); k++) {
|
||||||
for (int j = 0; j < dynamicPorts[k].ConnectionCount; j++) {
|
for (int j = 0; j < dynamicPorts[k].ConnectionCount; j++) {
|
||||||
XNode.NodePort other = dynamicPorts[k].GetConnection(j);
|
NodePort other = dynamicPorts[k].GetConnection(j);
|
||||||
dynamicPorts[k].Disconnect(other);
|
dynamicPorts[k].Disconnect(other);
|
||||||
dynamicPorts[k - 1].Connect(other);
|
dynamicPorts[k - 1].Connect(other);
|
||||||
}
|
}
|
||||||
@ -523,7 +523,7 @@ namespace XNodeEditor {
|
|||||||
string newName = arrayData.name + " 0";
|
string newName = arrayData.name + " 0";
|
||||||
int i = 0;
|
int i = 0;
|
||||||
while (node.HasPort(newName)) newName = arrayData.name + " " + (++i);
|
while (node.HasPort(newName)) newName = arrayData.name + " " + (++i);
|
||||||
if (io == XNode.NodePort.IO.Output) node.AddDynamicOutput(type, connectionType, typeConstraint, newName);
|
if (io == NodePort.IO.Output) node.AddDynamicOutput(type, connectionType, typeConstraint, newName);
|
||||||
else node.AddDynamicInput(type, connectionType, typeConstraint, newName);
|
else node.AddDynamicInput(type, connectionType, typeConstraint, newName);
|
||||||
EditorUtility.SetDirty(node);
|
EditorUtility.SetDirty(node);
|
||||||
dynamicPortCount++;
|
dynamicPortCount++;
|
||||||
|
|||||||
@ -28,13 +28,13 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
public static Type[] GetNodeTypes() {
|
public static Type[] GetNodeTypes() {
|
||||||
//Get all classes deriving from Node via reflection
|
//Get all classes deriving from Node via reflection
|
||||||
return GetDerivedTypes(typeof(XNode.Node));
|
return GetDerivedTypes(typeof(Node));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Custom node tint colors defined with [NodeColor(r, g, b)] </summary>
|
/// <summary> Custom node tint colors defined with [NodeColor(r, g, b)] </summary>
|
||||||
public static bool TryGetAttributeTint(this Type nodeType, out Color tint) {
|
public static bool TryGetAttributeTint(this Type nodeType, out Color tint) {
|
||||||
if (nodeTint == null) {
|
if (nodeTint == null) {
|
||||||
CacheAttributes<Color, XNode.Node.NodeTintAttribute>(ref nodeTint, x => x.color);
|
CacheAttributes<Color, Node.NodeTintAttribute>(ref nodeTint, x => x.color);
|
||||||
}
|
}
|
||||||
return nodeTint.TryGetValue(nodeType, out tint);
|
return nodeTint.TryGetValue(nodeType, out tint);
|
||||||
}
|
}
|
||||||
@ -42,7 +42,7 @@ namespace XNodeEditor {
|
|||||||
/// <summary> Get custom node widths defined with [NodeWidth(width)] </summary>
|
/// <summary> Get custom node widths defined with [NodeWidth(width)] </summary>
|
||||||
public static bool TryGetAttributeWidth(this Type nodeType, out int width) {
|
public static bool TryGetAttributeWidth(this Type nodeType, out int width) {
|
||||||
if (nodeWidth == null) {
|
if (nodeWidth == null) {
|
||||||
CacheAttributes<int, XNode.Node.NodeWidthAttribute>(ref nodeWidth, x => x.width);
|
CacheAttributes<int, Node.NodeWidthAttribute>(ref nodeWidth, x => x.width);
|
||||||
}
|
}
|
||||||
return nodeWidth.TryGetValue(nodeType, out width);
|
return nodeWidth.TryGetValue(nodeType, out width);
|
||||||
}
|
}
|
||||||
@ -62,7 +62,7 @@ namespace XNodeEditor {
|
|||||||
// If we can't find field in the first run, it's probably a private field in a base class.
|
// If we can't find field in the first run, it's probably a private field in a base class.
|
||||||
FieldInfo field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
|
FieldInfo field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
|
||||||
// Search base classes for private fields only. Public fields are found above
|
// Search base classes for private fields only. Public fields are found above
|
||||||
while (field == null && (type = type.BaseType) != typeof(XNode.Node)) field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
|
while (field == null && (type = type.BaseType) != typeof(Node)) field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
|
||||||
return field;
|
return field;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -134,14 +134,14 @@ namespace XNodeEditor {
|
|||||||
/// <param name="compatibleType">Type to find compatiblities</param>
|
/// <param name="compatibleType">Type to find compatiblities</param>
|
||||||
/// <param name="direction"></param>
|
/// <param name="direction"></param>
|
||||||
/// <returns>True if NodeType has some port with value type compatible</returns>
|
/// <returns>True if NodeType has some port with value type compatible</returns>
|
||||||
public static bool HasCompatiblePortType(Type nodeType, Type compatibleType, XNode.NodePort.IO direction = XNode.NodePort.IO.Input) {
|
public static bool HasCompatiblePortType(Type nodeType, Type compatibleType, NodePort.IO direction = NodePort.IO.Input) {
|
||||||
Type findType = typeof(XNode.Node.InputAttribute);
|
Type findType = typeof(Node.InputAttribute);
|
||||||
if (direction == XNode.NodePort.IO.Output)
|
if (direction == NodePort.IO.Output)
|
||||||
findType = typeof(XNode.Node.OutputAttribute);
|
findType = typeof(Node.OutputAttribute);
|
||||||
|
|
||||||
//Get All fields from node type and we go filter only field with portAttribute.
|
//Get All fields from node type and we go filter only field with portAttribute.
|
||||||
//This way is possible to know the values of the all ports and if have some with compatible value tue
|
//This way is possible to know the values of the all ports and if have some with compatible value tue
|
||||||
foreach (FieldInfo f in XNode.NodeDataCache.GetNodeFields(nodeType)) {
|
foreach (FieldInfo f in NodeDataCache.GetNodeFields(nodeType)) {
|
||||||
var portAttribute = f.GetCustomAttributes(findType, false).FirstOrDefault();
|
var portAttribute = f.GetCustomAttributes(findType, false).FirstOrDefault();
|
||||||
if (portAttribute != null) {
|
if (portAttribute != null) {
|
||||||
if (IsCastableTo(f.FieldType, compatibleType)) {
|
if (IsCastableTo(f.FieldType, compatibleType)) {
|
||||||
@ -159,7 +159,7 @@ namespace XNodeEditor {
|
|||||||
/// <param name="nodeTypes">List with all nodes type to filter</param>
|
/// <param name="nodeTypes">List with all nodes type to filter</param>
|
||||||
/// <param name="compatibleType">Compatible Type to Filter</param>
|
/// <param name="compatibleType">Compatible Type to Filter</param>
|
||||||
/// <returns>Return Only Node Types with ports compatible, or an empty list</returns>
|
/// <returns>Return Only Node Types with ports compatible, or an empty list</returns>
|
||||||
public static List<Type> GetCompatibleNodesTypes(Type[] nodeTypes, Type compatibleType, XNode.NodePort.IO direction = XNode.NodePort.IO.Input) {
|
public static List<Type> GetCompatibleNodesTypes(Type[] nodeTypes, Type compatibleType, NodePort.IO direction = NodePort.IO.Input) {
|
||||||
//Result List
|
//Result List
|
||||||
List<Type> filteredTypes = new List<Type>();
|
List<Type> filteredTypes = new List<Type>();
|
||||||
|
|
||||||
|
|||||||
@ -11,8 +11,8 @@ namespace XNodeEditor {
|
|||||||
public static NodeEditorWindow current;
|
public static NodeEditorWindow current;
|
||||||
|
|
||||||
/// <summary> Stores node positions for all nodePorts. </summary>
|
/// <summary> Stores node positions for all nodePorts. </summary>
|
||||||
public Dictionary<XNode.NodePort, Rect> portConnectionPoints { get { return _portConnectionPoints; } }
|
public Dictionary<NodePort, Rect> portConnectionPoints { get { return _portConnectionPoints; } }
|
||||||
private Dictionary<XNode.NodePort, Rect> _portConnectionPoints = new Dictionary<XNode.NodePort, Rect>();
|
private Dictionary<NodePort, Rect> _portConnectionPoints = new Dictionary<NodePort, Rect>();
|
||||||
[SerializeField] private NodePortReference[] _references = new NodePortReference[0];
|
[SerializeField] private NodePortReference[] _references = new NodePortReference[0];
|
||||||
[SerializeField] private Rect[] _rects = new Rect[0];
|
[SerializeField] private Rect[] _rects = new Rect[0];
|
||||||
|
|
||||||
@ -25,15 +25,15 @@ namespace XNodeEditor {
|
|||||||
private Func<bool> _isDocked;
|
private Func<bool> _isDocked;
|
||||||
|
|
||||||
[System.Serializable] private class NodePortReference {
|
[System.Serializable] private class NodePortReference {
|
||||||
[SerializeField] private XNode.Node _node;
|
[SerializeField] private Node _node;
|
||||||
[SerializeField] private string _name;
|
[SerializeField] private string _name;
|
||||||
|
|
||||||
public NodePortReference(XNode.NodePort nodePort) {
|
public NodePortReference(NodePort nodePort) {
|
||||||
_node = nodePort.node;
|
_node = nodePort.node;
|
||||||
_name = nodePort.fieldName;
|
_name = nodePort.fieldName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public XNode.NodePort GetNodePort() {
|
public NodePort GetNodePort() {
|
||||||
if (_node == null) {
|
if (_node == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -59,16 +59,16 @@ namespace XNodeEditor {
|
|||||||
int length = _references.Length;
|
int length = _references.Length;
|
||||||
if (length == _rects.Length) {
|
if (length == _rects.Length) {
|
||||||
for (int i = 0; i < length; i++) {
|
for (int i = 0; i < length; i++) {
|
||||||
XNode.NodePort nodePort = _references[i].GetNodePort();
|
NodePort nodePort = _references[i].GetNodePort();
|
||||||
if (nodePort != null)
|
if (nodePort != null)
|
||||||
_portConnectionPoints.Add(nodePort, _rects[i]);
|
_portConnectionPoints.Add(nodePort, _rects[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Dictionary<XNode.Node, Vector2> nodeSizes { get { return _nodeSizes; } }
|
public Dictionary<Node, Vector2> nodeSizes { get { return _nodeSizes; } }
|
||||||
private Dictionary<XNode.Node, Vector2> _nodeSizes = new Dictionary<XNode.Node, Vector2>();
|
private Dictionary<Node, Vector2> _nodeSizes = new Dictionary<Node, Vector2>();
|
||||||
public XNode.NodeGraph graph;
|
public NodeGraph graph;
|
||||||
public Vector2 panOffset { get { return _panOffset; } set { _panOffset = value; Repaint(); } }
|
public Vector2 panOffset { get { return _panOffset; } set { _panOffset = value; Repaint(); } }
|
||||||
private Vector2 _panOffset;
|
private Vector2 _panOffset;
|
||||||
public float zoom { get { return _zoom; } set { _zoom = Mathf.Clamp(value, NodeEditorPreferences.GetSettings().minZoom, NodeEditorPreferences.GetSettings().maxZoom); Repaint(); } }
|
public float zoom { get { return _zoom; } set { _zoom = Mathf.Clamp(value, NodeEditorPreferences.GetSettings().minZoom, NodeEditorPreferences.GetSettings().maxZoom); Repaint(); } }
|
||||||
@ -97,7 +97,7 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
/// <summary> Handle Selection Change events</summary>
|
/// <summary> Handle Selection Change events</summary>
|
||||||
private static void OnSelectionChanged() {
|
private static void OnSelectionChanged() {
|
||||||
XNode.NodeGraph nodeGraph = Selection.activeObject as XNode.NodeGraph;
|
NodeGraph nodeGraph = Selection.activeObject as NodeGraph;
|
||||||
if (nodeGraph && !AssetDatabase.Contains(nodeGraph)) {
|
if (nodeGraph && !AssetDatabase.Contains(nodeGraph)) {
|
||||||
if (NodeEditorPreferences.GetSettings().openOnCreate) Open(nodeGraph);
|
if (NodeEditorPreferences.GetSettings().openOnCreate) Open(nodeGraph);
|
||||||
}
|
}
|
||||||
@ -132,7 +132,7 @@ namespace XNodeEditor {
|
|||||||
string path = EditorUtility.SaveFilePanelInProject("Save NodeGraph", "NewNodeGraph", "asset", "");
|
string path = EditorUtility.SaveFilePanelInProject("Save NodeGraph", "NewNodeGraph", "asset", "");
|
||||||
if (string.IsNullOrEmpty(path)) return;
|
if (string.IsNullOrEmpty(path)) return;
|
||||||
else {
|
else {
|
||||||
XNode.NodeGraph existingGraph = AssetDatabase.LoadAssetAtPath<XNode.NodeGraph>(path);
|
NodeGraph existingGraph = AssetDatabase.LoadAssetAtPath<NodeGraph>(path);
|
||||||
if (existingGraph != null) AssetDatabase.DeleteAsset(path);
|
if (existingGraph != null) AssetDatabase.DeleteAsset(path);
|
||||||
AssetDatabase.CreateAsset(graph, path);
|
AssetDatabase.CreateAsset(graph, path);
|
||||||
EditorUtility.SetDirty(graph);
|
EditorUtility.SetDirty(graph);
|
||||||
@ -171,7 +171,7 @@ namespace XNodeEditor {
|
|||||||
return new Vector2(xOffset, yOffset);
|
return new Vector2(xOffset, yOffset);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SelectNode(XNode.Node node, bool add) {
|
public void SelectNode(Node node, bool add) {
|
||||||
if (add) {
|
if (add) {
|
||||||
List<Object> selection = new List<Object>(Selection.objects);
|
List<Object> selection = new List<Object>(Selection.objects);
|
||||||
selection.Add(node);
|
selection.Add(node);
|
||||||
@ -179,7 +179,7 @@ namespace XNodeEditor {
|
|||||||
} else Selection.objects = new Object[] { node };
|
} else Selection.objects = new Object[] { node };
|
||||||
}
|
}
|
||||||
|
|
||||||
public void DeselectNode(XNode.Node node) {
|
public void DeselectNode(Node node) {
|
||||||
List<Object> selection = new List<Object>(Selection.objects);
|
List<Object> selection = new List<Object>(Selection.objects);
|
||||||
selection.Remove(node);
|
selection.Remove(node);
|
||||||
Selection.objects = selection.ToArray();
|
Selection.objects = selection.ToArray();
|
||||||
@ -187,7 +187,7 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
[OnOpenAsset(0)]
|
[OnOpenAsset(0)]
|
||||||
public static bool OnOpen(int instanceID, int line) {
|
public static bool OnOpen(int instanceID, int line) {
|
||||||
XNode.NodeGraph nodeGraph = EditorUtility.InstanceIDToObject(instanceID) as XNode.NodeGraph;
|
NodeGraph nodeGraph = EditorUtility.InstanceIDToObject(instanceID) as NodeGraph;
|
||||||
if (nodeGraph != null) {
|
if (nodeGraph != null) {
|
||||||
Open(nodeGraph);
|
Open(nodeGraph);
|
||||||
return true;
|
return true;
|
||||||
@ -196,7 +196,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Open the provided graph in the NodeEditor</summary>
|
/// <summary>Open the provided graph in the NodeEditor</summary>
|
||||||
public static NodeEditorWindow Open(XNode.NodeGraph graph) {
|
public static NodeEditorWindow Open(NodeGraph graph) {
|
||||||
if (!graph) return null;
|
if (!graph) return null;
|
||||||
|
|
||||||
NodeEditorWindow w = GetWindow(typeof(NodeEditorWindow), false, "xNode", true) as NodeEditorWindow;
|
NodeEditorWindow w = GetWindow(typeof(NodeEditorWindow), false, "xNode", true) as NodeEditorWindow;
|
||||||
|
|||||||
@ -8,8 +8,8 @@ using GenericMenu = XNodeEditor.AdvancedGenericMenu;
|
|||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor {
|
||||||
/// <summary> Base class to derive custom Node Graph editors from. Use this to override how graphs are drawn in the editor. </summary>
|
/// <summary> Base class to derive custom Node Graph editors from. Use this to override how graphs are drawn in the editor. </summary>
|
||||||
[CustomNodeGraphEditor(typeof(XNode.NodeGraph))]
|
[CustomNodeGraphEditor(typeof(NodeGraph))]
|
||||||
public class NodeGraphEditor : XNodeEditor.Internal.NodeEditorBase<NodeGraphEditor, NodeGraphEditor.CustomNodeGraphEditorAttribute, XNode.NodeGraph> {
|
public class NodeGraphEditor : XNodeEditor.Internal.NodeEditorBase<NodeGraphEditor, NodeGraphEditor.CustomNodeGraphEditorAttribute, NodeGraph> {
|
||||||
[Obsolete("Use window.position instead")]
|
[Obsolete("Use window.position instead")]
|
||||||
public Rect position { get { return window.position; } set { window.position = value; } }
|
public Rect position { get { return window.position; } set { window.position = value; } }
|
||||||
/// <summary> Are we currently renaming a node? </summary>
|
/// <summary> Are we currently renaming a node? </summary>
|
||||||
@ -42,7 +42,7 @@ namespace XNodeEditor {
|
|||||||
/// <summary> Returns context node menu path. Null or empty strings for hidden nodes. </summary>
|
/// <summary> Returns context node menu path. Null or empty strings for hidden nodes. </summary>
|
||||||
public virtual string GetNodeMenuName(Type type) {
|
public virtual string GetNodeMenuName(Type type) {
|
||||||
//Check if type has the CreateNodeMenuAttribute
|
//Check if type has the CreateNodeMenuAttribute
|
||||||
XNode.Node.CreateNodeMenuAttribute attrib;
|
Node.CreateNodeMenuAttribute attrib;
|
||||||
if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
|
if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
|
||||||
return attrib.menuName;
|
return attrib.menuName;
|
||||||
else // Return generated path
|
else // Return generated path
|
||||||
@ -52,7 +52,7 @@ namespace XNodeEditor {
|
|||||||
/// <summary> The order by which the menu items are displayed. </summary>
|
/// <summary> The order by which the menu items are displayed. </summary>
|
||||||
public virtual int GetNodeMenuOrder(Type type) {
|
public virtual int GetNodeMenuOrder(Type type) {
|
||||||
//Check if type has the CreateNodeMenuAttribute
|
//Check if type has the CreateNodeMenuAttribute
|
||||||
XNode.Node.CreateNodeMenuAttribute attrib;
|
Node.CreateNodeMenuAttribute attrib;
|
||||||
if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
|
if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
|
||||||
return attrib.order;
|
return attrib.order;
|
||||||
else
|
else
|
||||||
@ -62,7 +62,7 @@ namespace XNodeEditor {
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Called before connecting two ports in the graph view to see if the output port is compatible with the input port
|
/// Called before connecting two ports in the graph view to see if the output port is compatible with the input port
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public virtual bool CanConnect(XNode.NodePort output, XNode.NodePort input) {
|
public virtual bool CanConnect(NodePort output, NodePort input) {
|
||||||
return output.CanConnectTo(input);
|
return output.CanConnectTo(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -73,7 +73,7 @@ namespace XNodeEditor {
|
|||||||
/// <param name="menu"></param>
|
/// <param name="menu"></param>
|
||||||
/// <param name="compatibleType">Use it to filter only nodes with ports value type, compatible with this type</param>
|
/// <param name="compatibleType">Use it to filter only nodes with ports value type, compatible with this type</param>
|
||||||
/// <param name="direction">Direction of the compatiblity</param>
|
/// <param name="direction">Direction of the compatiblity</param>
|
||||||
public virtual void AddContextMenuItems(GenericMenu menu, Type compatibleType = null, XNode.NodePort.IO direction = XNode.NodePort.IO.Input) {
|
public virtual void AddContextMenuItems(GenericMenu menu, Type compatibleType = null, NodePort.IO direction = NodePort.IO.Input) {
|
||||||
Vector2 pos = NodeEditorWindow.current.WindowToGridPosition(Event.current.mousePosition);
|
Vector2 pos = NodeEditorWindow.current.WindowToGridPosition(Event.current.mousePosition);
|
||||||
|
|
||||||
Type[] nodeTypes;
|
Type[] nodeTypes;
|
||||||
@ -92,7 +92,7 @@ namespace XNodeEditor {
|
|||||||
if (string.IsNullOrEmpty(path)) continue;
|
if (string.IsNullOrEmpty(path)) continue;
|
||||||
|
|
||||||
// Check if user is allowed to add more of given node type
|
// Check if user is allowed to add more of given node type
|
||||||
XNode.Node.DisallowMultipleNodesAttribute disallowAttrib;
|
Node.DisallowMultipleNodesAttribute disallowAttrib;
|
||||||
bool disallowed = false;
|
bool disallowed = false;
|
||||||
if (NodeEditorUtilities.GetAttrib(type, out disallowAttrib)) {
|
if (NodeEditorUtilities.GetAttrib(type, out disallowAttrib)) {
|
||||||
int typeCount = target.nodes.Count(x => x.GetType() == type);
|
int typeCount = target.nodes.Count(x => x.GetType() == type);
|
||||||
@ -102,7 +102,7 @@ namespace XNodeEditor {
|
|||||||
// Add node entry to context menu
|
// Add node entry to context menu
|
||||||
if (disallowed) menu.AddItem(new GUIContent(path), false, null);
|
if (disallowed) menu.AddItem(new GUIContent(path), false, null);
|
||||||
else menu.AddItem(new GUIContent(path), false, () => {
|
else menu.AddItem(new GUIContent(path), false, () => {
|
||||||
XNode.Node node = CreateNode(type, pos);
|
Node node = CreateNode(type, pos);
|
||||||
if (node != null) NodeEditorWindow.current.AutoConnect(node); // handle null nodes to avoid nullref exceptions
|
if (node != null) NodeEditorWindow.current.AutoConnect(node); // handle null nodes to avoid nullref exceptions
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -116,7 +116,7 @@ namespace XNodeEditor {
|
|||||||
/// <summary> Returned gradient is used to color noodles </summary>
|
/// <summary> Returned gradient is used to color noodles </summary>
|
||||||
/// <param name="output"> The output this noodle comes from. Never null. </param>
|
/// <param name="output"> The output this noodle comes from. Never null. </param>
|
||||||
/// <param name="input"> The output this noodle comes from. Can be null if we are dragging the noodle. </param>
|
/// <param name="input"> The output this noodle comes from. Can be null if we are dragging the noodle. </param>
|
||||||
public virtual Gradient GetNoodleGradient(XNode.NodePort output, XNode.NodePort input) {
|
public virtual Gradient GetNoodleGradient(NodePort output, NodePort input) {
|
||||||
Gradient grad = new Gradient();
|
Gradient grad = new Gradient();
|
||||||
|
|
||||||
// If dragging the noodle, draw solid, slightly transparent
|
// If dragging the noodle, draw solid, slightly transparent
|
||||||
@ -147,20 +147,20 @@ namespace XNodeEditor {
|
|||||||
/// <summary> Returned float is used for noodle thickness </summary>
|
/// <summary> Returned float is used for noodle thickness </summary>
|
||||||
/// <param name="output"> The output this noodle comes from. Never null. </param>
|
/// <param name="output"> The output this noodle comes from. Never null. </param>
|
||||||
/// <param name="input"> The output this noodle comes from. Can be null if we are dragging the noodle. </param>
|
/// <param name="input"> The output this noodle comes from. Can be null if we are dragging the noodle. </param>
|
||||||
public virtual float GetNoodleThickness(XNode.NodePort output, XNode.NodePort input) {
|
public virtual float GetNoodleThickness(NodePort output, NodePort input) {
|
||||||
return NodeEditorPreferences.GetSettings().noodleThickness;
|
return NodeEditorPreferences.GetSettings().noodleThickness;
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual NoodlePath GetNoodlePath(XNode.NodePort output, XNode.NodePort input) {
|
public virtual NoodlePath GetNoodlePath(NodePort output, NodePort input) {
|
||||||
return NodeEditorPreferences.GetSettings().noodlePath;
|
return NodeEditorPreferences.GetSettings().noodlePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual NoodleStroke GetNoodleStroke(XNode.NodePort output, XNode.NodePort input) {
|
public virtual NoodleStroke GetNoodleStroke(NodePort output, NodePort input) {
|
||||||
return NodeEditorPreferences.GetSettings().noodleStroke;
|
return NodeEditorPreferences.GetSettings().noodleStroke;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Returned color is used to color ports </summary>
|
/// <summary> Returned color is used to color ports </summary>
|
||||||
public virtual Color GetPortColor(XNode.NodePort port) {
|
public virtual Color GetPortColor(NodePort port) {
|
||||||
return GetTypeColor(port.ValueType);
|
return GetTypeColor(port.ValueType);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -174,8 +174,8 @@ namespace XNodeEditor {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="port">the owner of the style</param>
|
/// <param name="port">the owner of the style</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public virtual GUIStyle GetPortStyle(XNode.NodePort port) {
|
public virtual GUIStyle GetPortStyle(NodePort port) {
|
||||||
if (port.direction == XNode.NodePort.IO.Input)
|
if (port.direction == NodePort.IO.Input)
|
||||||
return NodeEditorResources.styles.inputPort;
|
return NodeEditorResources.styles.inputPort;
|
||||||
|
|
||||||
return NodeEditorResources.styles.outputPort;
|
return NodeEditorResources.styles.outputPort;
|
||||||
@ -183,7 +183,7 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
/// <summary> The returned color is used to color the background of the door.
|
/// <summary> The returned color is used to color the background of the door.
|
||||||
/// Usually used for outer edge effect </summary>
|
/// Usually used for outer edge effect </summary>
|
||||||
public virtual Color GetPortBackgroundColor(XNode.NodePort port) {
|
public virtual Color GetPortBackgroundColor(NodePort port) {
|
||||||
return Color.gray;
|
return Color.gray;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -193,7 +193,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Override to display custom tooltips </summary>
|
/// <summary> Override to display custom tooltips </summary>
|
||||||
public virtual string GetPortTooltip(XNode.NodePort port) {
|
public virtual string GetPortTooltip(NodePort port) {
|
||||||
Type portType = port.ValueType;
|
Type portType = port.ValueType;
|
||||||
string tooltip = "";
|
string tooltip = "";
|
||||||
tooltip = portType.PrettyName();
|
tooltip = portType.PrettyName();
|
||||||
@ -210,9 +210,9 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Create a node and save it in the graph asset </summary>
|
/// <summary> Create a node and save it in the graph asset </summary>
|
||||||
public virtual XNode.Node CreateNode(Type type, Vector2 position) {
|
public virtual Node CreateNode(Type type, Vector2 position) {
|
||||||
Undo.RecordObject(target, "Create Node");
|
Undo.RecordObject(target, "Create Node");
|
||||||
XNode.Node node = target.AddNode(type);
|
Node node = target.AddNode(type);
|
||||||
if (node == null) return null; // handle null nodes to avoid nullref exceptions
|
if (node == null) return null; // handle null nodes to avoid nullref exceptions
|
||||||
Undo.RegisterCreatedObjectUndo(node, "Create Node");
|
Undo.RegisterCreatedObjectUndo(node, "Create Node");
|
||||||
node.position = position;
|
node.position = position;
|
||||||
@ -224,9 +224,9 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Creates a copy of the original node in the graph </summary>
|
/// <summary> Creates a copy of the original node in the graph </summary>
|
||||||
public virtual XNode.Node CopyNode(XNode.Node original) {
|
public virtual Node CopyNode(Node original) {
|
||||||
Undo.RecordObject(target, "Duplicate Node");
|
Undo.RecordObject(target, "Duplicate Node");
|
||||||
XNode.Node node = target.CopyNode(original);
|
Node node = target.CopyNode(original);
|
||||||
Undo.RegisterCreatedObjectUndo(node, "Duplicate Node");
|
Undo.RegisterCreatedObjectUndo(node, "Duplicate Node");
|
||||||
node.name = original.name;
|
node.name = original.name;
|
||||||
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) AssetDatabase.AddObjectToAsset(node, target);
|
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) AssetDatabase.AddObjectToAsset(node, target);
|
||||||
@ -235,11 +235,11 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Return false for nodes that can't be removed </summary>
|
/// <summary> Return false for nodes that can't be removed </summary>
|
||||||
public virtual bool CanRemove(XNode.Node node) {
|
public virtual bool CanRemove(Node node) {
|
||||||
// Check graph attributes to see if this node is required
|
// Check graph attributes to see if this node is required
|
||||||
Type graphType = target.GetType();
|
Type graphType = target.GetType();
|
||||||
XNode.NodeGraph.RequireNodeAttribute[] attribs = Array.ConvertAll(
|
NodeGraph.RequireNodeAttribute[] attribs = Array.ConvertAll(
|
||||||
graphType.GetCustomAttributes(typeof(XNode.NodeGraph.RequireNodeAttribute), true), x => x as XNode.NodeGraph.RequireNodeAttribute);
|
graphType.GetCustomAttributes(typeof(NodeGraph.RequireNodeAttribute), true), x => x as NodeGraph.RequireNodeAttribute);
|
||||||
if (attribs.Any(x => x.Requires(node.GetType()))) {
|
if (attribs.Any(x => x.Requires(node.GetType()))) {
|
||||||
if (target.nodes.Count(x => x.GetType() == node.GetType()) <= 1) {
|
if (target.nodes.Count(x => x.GetType() == node.GetType()) <= 1) {
|
||||||
return false;
|
return false;
|
||||||
@ -249,7 +249,7 @@ namespace XNodeEditor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Safely remove a node and all its connections. </summary>
|
/// <summary> Safely remove a node and all its connections. </summary>
|
||||||
public virtual void RemoveNode(XNode.Node node) {
|
public virtual void RemoveNode(Node node) {
|
||||||
if (!CanRemove(node)) return;
|
if (!CanRemove(node)) return;
|
||||||
|
|
||||||
// Remove the node
|
// Remove the node
|
||||||
@ -265,7 +265,7 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
[AttributeUsage(AttributeTargets.Class)]
|
[AttributeUsage(AttributeTargets.Class)]
|
||||||
public class CustomNodeGraphEditorAttribute : Attribute,
|
public class CustomNodeGraphEditorAttribute : Attribute,
|
||||||
XNodeEditor.Internal.NodeEditorBase<NodeGraphEditor, NodeGraphEditor.CustomNodeGraphEditorAttribute, XNode.NodeGraph>.INodeEditorAttrib {
|
XNodeEditor.Internal.NodeEditorBase<NodeGraphEditor, NodeGraphEditor.CustomNodeGraphEditorAttribute, NodeGraph>.INodeEditorAttrib {
|
||||||
private Type inspectedType;
|
private Type inspectedType;
|
||||||
public string editorPrefsKey;
|
public string editorPrefsKey;
|
||||||
/// <summary> Tells a NodeGraphEditor which Graph type it is an editor for </summary>
|
/// <summary> Tells a NodeGraphEditor which Graph type it is an editor for </summary>
|
||||||
|
|||||||
@ -4,7 +4,6 @@ using System.Linq;
|
|||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEditor.Experimental.AssetImporters;
|
using UnityEditor.Experimental.AssetImporters;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using XNode;
|
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor {
|
||||||
/// <summary> Deals with modified assets </summary>
|
/// <summary> Deals with modified assets </summary>
|
||||||
@ -34,7 +33,7 @@ namespace XNodeEditor {
|
|||||||
|
|
||||||
private static void AddRequired(NodeGraph graph, Type type, ref Vector2 position) {
|
private static void AddRequired(NodeGraph graph, Type type, ref Vector2 position) {
|
||||||
if (!graph.nodes.Any(x => x.GetType() == type)) {
|
if (!graph.nodes.Any(x => x.GetType() == type)) {
|
||||||
XNode.Node node = graph.AddNode(type);
|
Node node = graph.AddNode(type);
|
||||||
node.position = position;
|
node.position = position;
|
||||||
position.x += 200;
|
position.x += 200;
|
||||||
if (node.name == null || node.name.Trim() == "") node.name = NodeEditorUtilities.NodeDefaultName(type);
|
if (node.name == null || node.name.Trim() == "") node.name = NodeEditorUtilities.NodeDefaultName(type);
|
||||||
|
|||||||
109
Scripts/Editor/NodeGroupEditor.cs
Normal file
109
Scripts/Editor/NodeGroupEditor.cs
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using UnityEditor;
|
||||||
|
using UnityEngine;
|
||||||
|
|
||||||
|
namespace XNodeEditor.NodeGroups {
|
||||||
|
[CustomNodeEditor(typeof(NodeGroup))]
|
||||||
|
public class NodeGroupEditor : NodeEditor {
|
||||||
|
private NodeGroup group { get { return _group != null ? _group : _group = target as NodeGroup; } }
|
||||||
|
private NodeGroup _group;
|
||||||
|
public static Texture2D corner { get { return _corner != null ? _corner : _corner = Resources.Load<Texture2D>("xnode_corner"); } }
|
||||||
|
private static Texture2D _corner;
|
||||||
|
private bool isDragging;
|
||||||
|
private Vector2 size;
|
||||||
|
|
||||||
|
public override void OnBodyGUI() {
|
||||||
|
Event e = Event.current;
|
||||||
|
switch (e.type) {
|
||||||
|
case EventType.MouseDrag:
|
||||||
|
if (isDragging) {
|
||||||
|
group.width = Mathf.Max(200, (int) e.mousePosition.x + 16);
|
||||||
|
group.height = Mathf.Max(100, (int) e.mousePosition.y - 34);
|
||||||
|
NodeEditorWindow.current.Repaint();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case EventType.MouseDown:
|
||||||
|
// Ignore everything except left clicks
|
||||||
|
if (e.button != 0) return;
|
||||||
|
if (NodeEditorWindow.current.nodeSizes.TryGetValue(target, out size)) {
|
||||||
|
// Mouse position checking is in node local space
|
||||||
|
Rect lowerRight = new Rect(size.x - 34, size.y - 34, 30, 30);
|
||||||
|
if (lowerRight.Contains(e.mousePosition)) {
|
||||||
|
isDragging = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case EventType.MouseUp:
|
||||||
|
isDragging = false;
|
||||||
|
// Select nodes inside the group
|
||||||
|
if (Selection.Contains(target)) {
|
||||||
|
List<Object> selection = Selection.objects.ToList();
|
||||||
|
// Select Nodes
|
||||||
|
selection.AddRange(group.GetNodes());
|
||||||
|
// Select Reroutes
|
||||||
|
foreach (Node node in target.graph.nodes) {
|
||||||
|
if (node != null)
|
||||||
|
{
|
||||||
|
foreach (NodePort port in node.Ports) {
|
||||||
|
for (int i = 0; i < port.ConnectionCount; i++) {
|
||||||
|
List<Vector2> reroutes = port.GetReroutePoints(i);
|
||||||
|
for (int k = 0; k < reroutes.Count; k++) {
|
||||||
|
Vector2 p = reroutes[k];
|
||||||
|
if (p.x < group.position.x) continue;
|
||||||
|
if (p.y < group.position.y) continue;
|
||||||
|
if (p.x > group.position.x + group.width) continue;
|
||||||
|
if (p.y > group.position.y + group.height + 30) continue;
|
||||||
|
if (NodeEditorWindow.current.selectedReroutes.Any(x => x.port == port && x.connectionIndex == i && x.pointIndex == k)) continue;
|
||||||
|
NodeEditorWindow.current.selectedReroutes.Add(
|
||||||
|
new Internal.RerouteReference(port, i, k)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Selection.objects = selection.Distinct().ToArray();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case EventType.Repaint:
|
||||||
|
// Move to bottom
|
||||||
|
if (target.graph.nodes.IndexOf(target) != 0) {
|
||||||
|
target.graph.nodes.Remove(target);
|
||||||
|
target.graph.nodes.Insert(0, target);
|
||||||
|
}
|
||||||
|
// Add scale cursors
|
||||||
|
if (NodeEditorWindow.current.nodeSizes.TryGetValue(target, out size)) {
|
||||||
|
Rect lowerRight = new Rect(target.position, new Vector2(30, 30));
|
||||||
|
lowerRight.y += size.y - 34;
|
||||||
|
lowerRight.x += size.x - 34;
|
||||||
|
lowerRight = NodeEditorWindow.current.GridToWindowRect(lowerRight);
|
||||||
|
NodeEditorWindow.current.onLateGUI += () => AddMouseRect(lowerRight);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Control height of node
|
||||||
|
GUILayout.Space(group.height);
|
||||||
|
|
||||||
|
GUI.DrawTexture(new Rect(group.width - 34, group.height + 16, 24, 24), corner);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int GetWidth() {
|
||||||
|
return group.width;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Color GetTint() {
|
||||||
|
return group.color;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void AddMouseRect(Rect rect) {
|
||||||
|
EditorGUIUtility.AddCursorRect(rect, MouseCursor.ResizeUpLeft);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -52,9 +52,9 @@ namespace XNodeEditor {
|
|||||||
if (input == null || input.Trim() == "") {
|
if (input == null || input.Trim() == "") {
|
||||||
if (GUILayout.Button("Revert to default") || (e.isKey && e.keyCode == KeyCode.Return)) {
|
if (GUILayout.Button("Revert to default") || (e.isKey && e.keyCode == KeyCode.Return)) {
|
||||||
target.name = NodeEditorUtilities.NodeDefaultName(target.GetType());
|
target.name = NodeEditorUtilities.NodeDefaultName(target.GetType());
|
||||||
NodeEditor.GetEditor((XNode.Node)target, NodeEditorWindow.current).OnRename();
|
NodeEditor.GetEditor((Node)target, NodeEditorWindow.current).OnRename();
|
||||||
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) {
|
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) {
|
||||||
AssetDatabase.SetMainObject((target as XNode.Node).graph, AssetDatabase.GetAssetPath(target));
|
AssetDatabase.SetMainObject((target as Node).graph, AssetDatabase.GetAssetPath(target));
|
||||||
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
|
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
|
||||||
}
|
}
|
||||||
Close();
|
Close();
|
||||||
@ -65,9 +65,9 @@ namespace XNodeEditor {
|
|||||||
else {
|
else {
|
||||||
if (GUILayout.Button("Apply") || (e.isKey && e.keyCode == KeyCode.Return)) {
|
if (GUILayout.Button("Apply") || (e.isKey && e.keyCode == KeyCode.Return)) {
|
||||||
target.name = input;
|
target.name = input;
|
||||||
NodeEditor.GetEditor((XNode.Node)target, NodeEditorWindow.current).OnRename();
|
NodeEditor.GetEditor((Node)target, NodeEditorWindow.current).OnRename();
|
||||||
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) {
|
if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target))) {
|
||||||
AssetDatabase.SetMainObject((target as XNode.Node).graph, AssetDatabase.GetAssetPath(target));
|
AssetDatabase.SetMainObject((target as Node).graph, AssetDatabase.GetAssetPath(target));
|
||||||
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
|
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
|
||||||
}
|
}
|
||||||
Close();
|
Close();
|
||||||
|
|||||||
@ -3,7 +3,6 @@ using System.Collections;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using XNode;
|
|
||||||
|
|
||||||
namespace XNodeEditor {
|
namespace XNodeEditor {
|
||||||
[CustomEditor(typeof(SceneGraph), true)]
|
[CustomEditor(typeof(SceneGraph), true)]
|
||||||
|
|||||||
758
Scripts/Node.cs
758
Scripts/Node.cs
@ -2,420 +2,418 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
namespace XNode {
|
/// <summary>
|
||||||
/// <summary>
|
/// Base class for all nodes
|
||||||
/// Base class for all nodes
|
/// </summary>
|
||||||
/// </summary>
|
/// <example>
|
||||||
/// <example>
|
/// Classes extending this class will be considered as valid nodes by xNode.
|
||||||
/// Classes extending this class will be considered as valid nodes by xNode.
|
/// <code>
|
||||||
/// <code>
|
/// [System.Serializable]
|
||||||
/// [System.Serializable]
|
/// public class Adder : Node {
|
||||||
/// public class Adder : Node {
|
/// [Input] public float a;
|
||||||
/// [Input] public float a;
|
/// [Input] public float b;
|
||||||
/// [Input] public float b;
|
/// [Output] public float result;
|
||||||
/// [Output] public float result;
|
///
|
||||||
///
|
/// // GetValue should be overridden to return a value for any specified output port
|
||||||
/// // GetValue should be overridden to return a value for any specified output port
|
/// public override object GetValue(NodePort port) {
|
||||||
/// public override object GetValue(NodePort port) {
|
/// return a + b;
|
||||||
/// return a + b;
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// </code>
|
||||||
/// </code>
|
/// </example>
|
||||||
/// </example>
|
[Serializable]
|
||||||
[Serializable]
|
public abstract class Node : ScriptableObject {
|
||||||
public abstract class Node : ScriptableObject {
|
/// <summary> Used by <see cref="InputAttribute"/> and <see cref="OutputAttribute"/> to determine when to display the field value associated with a <see cref="NodePort"/> </summary>
|
||||||
/// <summary> Used by <see cref="InputAttribute"/> and <see cref="OutputAttribute"/> to determine when to display the field value associated with a <see cref="NodePort"/> </summary>
|
public enum ShowBackingValue {
|
||||||
public enum ShowBackingValue {
|
/// <summary> Never show the backing value </summary>
|
||||||
/// <summary> Never show the backing value </summary>
|
Never,
|
||||||
Never,
|
/// <summary> Show the backing value only when the port does not have any active connections </summary>
|
||||||
/// <summary> Show the backing value only when the port does not have any active connections </summary>
|
Unconnected,
|
||||||
Unconnected,
|
/// <summary> Always show the backing value </summary>
|
||||||
/// <summary> Always show the backing value </summary>
|
Always
|
||||||
Always
|
}
|
||||||
|
|
||||||
|
public enum ConnectionType {
|
||||||
|
/// <summary> Allow multiple connections</summary>
|
||||||
|
Multiple,
|
||||||
|
/// <summary> always override the current connection </summary>
|
||||||
|
Override,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Tells which types of input to allow </summary>
|
||||||
|
public enum TypeConstraint {
|
||||||
|
/// <summary> Allow all types of input</summary>
|
||||||
|
None,
|
||||||
|
/// <summary> Allow connections where input value type is assignable from output value type (eg. ScriptableObject --> Object)</summary>
|
||||||
|
Inherited,
|
||||||
|
/// <summary> Allow only similar types </summary>
|
||||||
|
Strict,
|
||||||
|
/// <summary> Allow connections where output value type is assignable from input value type (eg. Object --> ScriptableObject)</summary>
|
||||||
|
InheritedInverse,
|
||||||
|
/// <summary> Allow connections where output value type is assignable from input value or input value type is assignable from output value type</summary>
|
||||||
|
InheritedAny
|
||||||
|
}
|
||||||
|
|
||||||
|
#region Obsolete
|
||||||
|
[Obsolete("Use DynamicPorts instead")]
|
||||||
|
public IEnumerable<NodePort> InstancePorts { get { return DynamicPorts; } }
|
||||||
|
|
||||||
|
[Obsolete("Use DynamicOutputs instead")]
|
||||||
|
public IEnumerable<NodePort> InstanceOutputs { get { return DynamicOutputs; } }
|
||||||
|
|
||||||
|
[Obsolete("Use DynamicInputs instead")]
|
||||||
|
public IEnumerable<NodePort> InstanceInputs { get { return DynamicInputs; } }
|
||||||
|
|
||||||
|
[Obsolete("Use AddDynamicInput instead")]
|
||||||
|
public NodePort AddInstanceInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
||||||
|
return AddDynamicInput(type, connectionType, typeConstraint, fieldName);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use AddDynamicOutput instead")]
|
||||||
|
public NodePort AddInstanceOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
||||||
|
return AddDynamicOutput(type, connectionType, typeConstraint, fieldName);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use AddDynamicPort instead")]
|
||||||
|
private NodePort AddInstancePort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
||||||
|
return AddDynamicPort(type, direction, connectionType, typeConstraint, fieldName);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use RemoveDynamicPort instead")]
|
||||||
|
public void RemoveInstancePort(string fieldName) {
|
||||||
|
RemoveDynamicPort(fieldName);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use RemoveDynamicPort instead")]
|
||||||
|
public void RemoveInstancePort(NodePort port) {
|
||||||
|
RemoveDynamicPort(port);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Obsolete("Use ClearDynamicPorts instead")]
|
||||||
|
public void ClearInstancePorts() {
|
||||||
|
ClearDynamicPorts();
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
/// <summary> Iterate over all ports on this node. </summary>
|
||||||
|
public IEnumerable<NodePort> Ports { get { foreach (NodePort port in ports.Values) yield return port; } }
|
||||||
|
/// <summary> Iterate over all outputs on this node. </summary>
|
||||||
|
public IEnumerable<NodePort> Outputs { get { foreach (NodePort port in Ports) { if (port.IsOutput) yield return port; } } }
|
||||||
|
/// <summary> Iterate over all inputs on this node. </summary>
|
||||||
|
public IEnumerable<NodePort> Inputs { get { foreach (NodePort port in Ports) { if (port.IsInput) yield return port; } } }
|
||||||
|
/// <summary> Iterate over all dynamic ports on this node. </summary>
|
||||||
|
public IEnumerable<NodePort> DynamicPorts { get { foreach (NodePort port in Ports) { if (port.IsDynamic) yield return port; } } }
|
||||||
|
/// <summary> Iterate over all dynamic outputs on this node. </summary>
|
||||||
|
public IEnumerable<NodePort> DynamicOutputs { get { foreach (NodePort port in Ports) { if (port.IsDynamic && port.IsOutput) yield return port; } } }
|
||||||
|
/// <summary> Iterate over all dynamic inputs on this node. </summary>
|
||||||
|
public IEnumerable<NodePort> DynamicInputs { get { foreach (NodePort port in Ports) { if (port.IsDynamic && port.IsInput) yield return port; } } }
|
||||||
|
/// <summary> Parent <see cref="NodeGraph"/> </summary>
|
||||||
|
[SerializeField] public NodeGraph graph;
|
||||||
|
/// <summary> Position on the <see cref="NodeGraph"/> </summary>
|
||||||
|
[SerializeField] public Vector2 position;
|
||||||
|
/// <summary> It is recommended not to modify these at hand. Instead, see <see cref="InputAttribute"/> and <see cref="OutputAttribute"/> </summary>
|
||||||
|
[SerializeField] private NodePortDictionary ports = new NodePortDictionary();
|
||||||
|
|
||||||
|
/// <summary> Used during node instantiation to fix null/misconfigured graph during OnEnable/Init. Set it before instantiating a node. Will automatically be unset during OnEnable </summary>
|
||||||
|
public static NodeGraph graphHotfix;
|
||||||
|
|
||||||
|
protected void OnEnable() {
|
||||||
|
if (graphHotfix != null) graph = graphHotfix;
|
||||||
|
graphHotfix = null;
|
||||||
|
UpdatePorts();
|
||||||
|
Init();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Update static ports and dynamic ports managed by DynamicPortLists to reflect class fields. This happens automatically on enable or on redrawing a dynamic port list. </summary>
|
||||||
|
public void UpdatePorts() {
|
||||||
|
NodeDataCache.UpdatePorts(this, ports);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Initialize node. Called on enable. </summary>
|
||||||
|
protected virtual void Init() { }
|
||||||
|
|
||||||
|
/// <summary> Checks all connections for invalid references, and removes them. </summary>
|
||||||
|
public void VerifyConnections() {
|
||||||
|
foreach (NodePort port in Ports) port.VerifyConnections();
|
||||||
|
}
|
||||||
|
|
||||||
|
#region Dynamic Ports
|
||||||
|
/// <summary> Convenience function. </summary>
|
||||||
|
/// <seealso cref="AddInstancePort"/>
|
||||||
|
/// <seealso cref="AddInstanceOutput"/>
|
||||||
|
public NodePort AddDynamicInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
||||||
|
return AddDynamicPort(type, NodePort.IO.Input, connectionType, typeConstraint, fieldName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Convenience function. </summary>
|
||||||
|
/// <seealso cref="AddInstancePort"/>
|
||||||
|
/// <seealso cref="AddInstanceInput"/>
|
||||||
|
public NodePort AddDynamicOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
||||||
|
return AddDynamicPort(type, NodePort.IO.Output, connectionType, typeConstraint, fieldName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Add a dynamic, serialized port to this node. </summary>
|
||||||
|
/// <seealso cref="AddDynamicInput"/>
|
||||||
|
/// <seealso cref="AddDynamicOutput"/>
|
||||||
|
private NodePort AddDynamicPort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
||||||
|
if (fieldName == null) {
|
||||||
|
fieldName = "dynamicInput_0";
|
||||||
|
int i = 0;
|
||||||
|
while (HasPort(fieldName)) fieldName = "dynamicInput_" + (++i);
|
||||||
|
} else if (HasPort(fieldName)) {
|
||||||
|
Debug.LogWarning("Port '" + fieldName + "' already exists in " + name, this);
|
||||||
|
return ports[fieldName];
|
||||||
}
|
}
|
||||||
|
NodePort port = new NodePort(fieldName, type, direction, connectionType, typeConstraint, this);
|
||||||
|
ports.Add(fieldName, port);
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
public enum ConnectionType {
|
/// <summary> Remove an dynamic port from the node </summary>
|
||||||
/// <summary> Allow multiple connections</summary>
|
public void RemoveDynamicPort(string fieldName) {
|
||||||
Multiple,
|
NodePort dynamicPort = GetPort(fieldName);
|
||||||
/// <summary> always override the current connection </summary>
|
if (dynamicPort == null) throw new ArgumentException("port " + fieldName + " doesn't exist");
|
||||||
Override,
|
RemoveDynamicPort(GetPort(fieldName));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Tells which types of input to allow </summary>
|
/// <summary> Remove an dynamic port from the node </summary>
|
||||||
public enum TypeConstraint {
|
public void RemoveDynamicPort(NodePort port) {
|
||||||
/// <summary> Allow all types of input</summary>
|
if (port == null) throw new ArgumentNullException("port");
|
||||||
None,
|
else if (port.IsStatic) throw new ArgumentException("cannot remove static port");
|
||||||
/// <summary> Allow connections where input value type is assignable from output value type (eg. ScriptableObject --> Object)</summary>
|
port.ClearConnections();
|
||||||
Inherited,
|
ports.Remove(port.fieldName);
|
||||||
/// <summary> Allow only similar types </summary>
|
}
|
||||||
Strict,
|
|
||||||
/// <summary> Allow connections where output value type is assignable from input value type (eg. Object --> ScriptableObject)</summary>
|
|
||||||
InheritedInverse,
|
|
||||||
/// <summary> Allow connections where output value type is assignable from input value or input value type is assignable from output value type</summary>
|
|
||||||
InheritedAny
|
|
||||||
}
|
|
||||||
|
|
||||||
#region Obsolete
|
/// <summary> Removes all dynamic ports from the node </summary>
|
||||||
[Obsolete("Use DynamicPorts instead")]
|
[ContextMenu("Clear Dynamic Ports")]
|
||||||
public IEnumerable<NodePort> InstancePorts { get { return DynamicPorts; } }
|
public void ClearDynamicPorts() {
|
||||||
|
List<NodePort> dynamicPorts = new List<NodePort>(DynamicPorts);
|
||||||
[Obsolete("Use DynamicOutputs instead")]
|
foreach (NodePort port in dynamicPorts) {
|
||||||
public IEnumerable<NodePort> InstanceOutputs { get { return DynamicOutputs; } }
|
|
||||||
|
|
||||||
[Obsolete("Use DynamicInputs instead")]
|
|
||||||
public IEnumerable<NodePort> InstanceInputs { get { return DynamicInputs; } }
|
|
||||||
|
|
||||||
[Obsolete("Use AddDynamicInput instead")]
|
|
||||||
public NodePort AddInstanceInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
|
||||||
return AddDynamicInput(type, connectionType, typeConstraint, fieldName);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Obsolete("Use AddDynamicOutput instead")]
|
|
||||||
public NodePort AddInstanceOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
|
||||||
return AddDynamicOutput(type, connectionType, typeConstraint, fieldName);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Obsolete("Use AddDynamicPort instead")]
|
|
||||||
private NodePort AddInstancePort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
|
||||||
return AddDynamicPort(type, direction, connectionType, typeConstraint, fieldName);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Obsolete("Use RemoveDynamicPort instead")]
|
|
||||||
public void RemoveInstancePort(string fieldName) {
|
|
||||||
RemoveDynamicPort(fieldName);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Obsolete("Use RemoveDynamicPort instead")]
|
|
||||||
public void RemoveInstancePort(NodePort port) {
|
|
||||||
RemoveDynamicPort(port);
|
RemoveDynamicPort(port);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
[Obsolete("Use ClearDynamicPorts instead")]
|
#region Ports
|
||||||
public void ClearInstancePorts() {
|
/// <summary> Returns output port which matches fieldName </summary>
|
||||||
ClearDynamicPorts();
|
public NodePort GetOutputPort(string fieldName) {
|
||||||
}
|
NodePort port = GetPort(fieldName);
|
||||||
#endregion
|
if (port == null || port.direction != NodePort.IO.Output) return null;
|
||||||
|
else return port;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary> Iterate over all ports on this node. </summary>
|
/// <summary> Returns input port which matches fieldName </summary>
|
||||||
public IEnumerable<NodePort> Ports { get { foreach (NodePort port in ports.Values) yield return port; } }
|
public NodePort GetInputPort(string fieldName) {
|
||||||
/// <summary> Iterate over all outputs on this node. </summary>
|
NodePort port = GetPort(fieldName);
|
||||||
public IEnumerable<NodePort> Outputs { get { foreach (NodePort port in Ports) { if (port.IsOutput) yield return port; } } }
|
if (port == null || port.direction != NodePort.IO.Input) return null;
|
||||||
/// <summary> Iterate over all inputs on this node. </summary>
|
else return port;
|
||||||
public IEnumerable<NodePort> Inputs { get { foreach (NodePort port in Ports) { if (port.IsInput) yield return port; } } }
|
}
|
||||||
/// <summary> Iterate over all dynamic ports on this node. </summary>
|
|
||||||
public IEnumerable<NodePort> DynamicPorts { get { foreach (NodePort port in Ports) { if (port.IsDynamic) yield return port; } } }
|
|
||||||
/// <summary> Iterate over all dynamic outputs on this node. </summary>
|
|
||||||
public IEnumerable<NodePort> DynamicOutputs { get { foreach (NodePort port in Ports) { if (port.IsDynamic && port.IsOutput) yield return port; } } }
|
|
||||||
/// <summary> Iterate over all dynamic inputs on this node. </summary>
|
|
||||||
public IEnumerable<NodePort> DynamicInputs { get { foreach (NodePort port in Ports) { if (port.IsDynamic && port.IsInput) yield return port; } } }
|
|
||||||
/// <summary> Parent <see cref="NodeGraph"/> </summary>
|
|
||||||
[SerializeField] public NodeGraph graph;
|
|
||||||
/// <summary> Position on the <see cref="NodeGraph"/> </summary>
|
|
||||||
[SerializeField] public Vector2 position;
|
|
||||||
/// <summary> It is recommended not to modify these at hand. Instead, see <see cref="InputAttribute"/> and <see cref="OutputAttribute"/> </summary>
|
|
||||||
[SerializeField] private NodePortDictionary ports = new NodePortDictionary();
|
|
||||||
|
|
||||||
/// <summary> Used during node instantiation to fix null/misconfigured graph during OnEnable/Init. Set it before instantiating a node. Will automatically be unset during OnEnable </summary>
|
/// <summary> Returns port which matches fieldName </summary>
|
||||||
public static NodeGraph graphHotfix;
|
public NodePort GetPort(string fieldName) {
|
||||||
|
NodePort port;
|
||||||
|
if (ports.TryGetValue(fieldName, out port)) return port;
|
||||||
|
else return null;
|
||||||
|
}
|
||||||
|
|
||||||
protected void OnEnable() {
|
public bool HasPort(string fieldName) {
|
||||||
if (graphHotfix != null) graph = graphHotfix;
|
return ports.ContainsKey(fieldName);
|
||||||
graphHotfix = null;
|
}
|
||||||
UpdatePorts();
|
#endregion
|
||||||
Init();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Update static ports and dynamic ports managed by DynamicPortLists to reflect class fields. This happens automatically on enable or on redrawing a dynamic port list. </summary>
|
#region Inputs/Outputs
|
||||||
public void UpdatePorts() {
|
/// <summary> Return input value for a specified port. Returns fallback value if no ports are connected </summary>
|
||||||
NodeDataCache.UpdatePorts(this, ports);
|
/// <param name="fieldName">Field name of requested input port</param>
|
||||||
}
|
/// <param name="fallback">If no ports are connected, this value will be returned</param>
|
||||||
|
public T GetInputValue<T>(string fieldName, T fallback = default(T)) {
|
||||||
|
NodePort port = GetPort(fieldName);
|
||||||
|
if (port != null && port.IsConnected) return port.GetInputValue<T>();
|
||||||
|
else return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary> Initialize node. Called on enable. </summary>
|
/// <summary> Return all input values for a specified port. Returns fallback value if no ports are connected </summary>
|
||||||
protected virtual void Init() { }
|
/// <param name="fieldName">Field name of requested input port</param>
|
||||||
|
/// <param name="fallback">If no ports are connected, this value will be returned</param>
|
||||||
|
public T[] GetInputValues<T>(string fieldName, params T[] fallback) {
|
||||||
|
NodePort port = GetPort(fieldName);
|
||||||
|
if (port != null && port.IsConnected) return port.GetInputValues<T>();
|
||||||
|
else return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary> Checks all connections for invalid references, and removes them. </summary>
|
/// <summary> Returns a value based on requested port output. Should be overridden in all derived nodes with outputs. </summary>
|
||||||
public void VerifyConnections() {
|
/// <param name="port">The requested port.</param>
|
||||||
foreach (NodePort port in Ports) port.VerifyConnections();
|
public virtual object GetValue(NodePort port) {
|
||||||
}
|
Debug.LogWarning("No GetValue(NodePort port) override defined for " + GetType());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
#region Dynamic Ports
|
/// <summary> Called after a connection between two <see cref="NodePort"/>s is created </summary>
|
||||||
/// <summary> Convenience function. </summary>
|
/// <param name="from">Output</param> <param name="to">Input</param>
|
||||||
/// <seealso cref="AddInstancePort"/>
|
public virtual void OnCreateConnection(NodePort from, NodePort to) { }
|
||||||
/// <seealso cref="AddInstanceOutput"/>
|
|
||||||
public NodePort AddDynamicInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
|
||||||
return AddDynamicPort(type, NodePort.IO.Input, connectionType, typeConstraint, fieldName);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Convenience function. </summary>
|
/// <summary> Called after a connection is removed from this port </summary>
|
||||||
/// <seealso cref="AddInstancePort"/>
|
/// <param name="port">Output or Input</param>
|
||||||
/// <seealso cref="AddInstanceInput"/>
|
public virtual void OnRemoveConnection(NodePort port) { }
|
||||||
public NodePort AddDynamicOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
|
||||||
return AddDynamicPort(type, NodePort.IO.Output, connectionType, typeConstraint, fieldName);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Add a dynamic, serialized port to this node. </summary>
|
/// <summary> Disconnect everything from this node </summary>
|
||||||
/// <seealso cref="AddDynamicInput"/>
|
public void ClearConnections() {
|
||||||
/// <seealso cref="AddDynamicOutput"/>
|
foreach (NodePort port in Ports) port.ClearConnections();
|
||||||
private NodePort AddDynamicPort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) {
|
}
|
||||||
if (fieldName == null) {
|
|
||||||
fieldName = "dynamicInput_0";
|
|
||||||
int i = 0;
|
|
||||||
while (HasPort(fieldName)) fieldName = "dynamicInput_" + (++i);
|
|
||||||
} else if (HasPort(fieldName)) {
|
|
||||||
Debug.LogWarning("Port '" + fieldName + "' already exists in " + name, this);
|
|
||||||
return ports[fieldName];
|
|
||||||
}
|
|
||||||
NodePort port = new NodePort(fieldName, type, direction, connectionType, typeConstraint, this);
|
|
||||||
ports.Add(fieldName, port);
|
|
||||||
return port;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Remove an dynamic port from the node </summary>
|
#region Attributes
|
||||||
public void RemoveDynamicPort(string fieldName) {
|
/// <summary> Mark a serializable field as an input port. You can access this through <see cref="GetInputPort(string)"/> </summary>
|
||||||
NodePort dynamicPort = GetPort(fieldName);
|
[AttributeUsage(AttributeTargets.Field)]
|
||||||
if (dynamicPort == null) throw new ArgumentException("port " + fieldName + " doesn't exist");
|
public class InputAttribute : Attribute {
|
||||||
RemoveDynamicPort(GetPort(fieldName));
|
public ShowBackingValue backingValue;
|
||||||
}
|
public ConnectionType connectionType;
|
||||||
|
[Obsolete("Use dynamicPortList instead")]
|
||||||
|
public bool instancePortList { get { return dynamicPortList; } set { dynamicPortList = value; } }
|
||||||
|
public bool dynamicPortList;
|
||||||
|
public TypeConstraint typeConstraint;
|
||||||
|
|
||||||
/// <summary> Remove an dynamic port from the node </summary>
|
|
||||||
public void RemoveDynamicPort(NodePort port) {
|
|
||||||
if (port == null) throw new ArgumentNullException("port");
|
|
||||||
else if (port.IsStatic) throw new ArgumentException("cannot remove static port");
|
|
||||||
port.ClearConnections();
|
|
||||||
ports.Remove(port.fieldName);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Removes all dynamic ports from the node </summary>
|
|
||||||
[ContextMenu("Clear Dynamic Ports")]
|
|
||||||
public void ClearDynamicPorts() {
|
|
||||||
List<NodePort> dynamicPorts = new List<NodePort>(DynamicPorts);
|
|
||||||
foreach (NodePort port in dynamicPorts) {
|
|
||||||
RemoveDynamicPort(port);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Ports
|
|
||||||
/// <summary> Returns output port which matches fieldName </summary>
|
|
||||||
public NodePort GetOutputPort(string fieldName) {
|
|
||||||
NodePort port = GetPort(fieldName);
|
|
||||||
if (port == null || port.direction != NodePort.IO.Output) return null;
|
|
||||||
else return port;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Returns input port which matches fieldName </summary>
|
|
||||||
public NodePort GetInputPort(string fieldName) {
|
|
||||||
NodePort port = GetPort(fieldName);
|
|
||||||
if (port == null || port.direction != NodePort.IO.Input) return null;
|
|
||||||
else return port;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Returns port which matches fieldName </summary>
|
|
||||||
public NodePort GetPort(string fieldName) {
|
|
||||||
NodePort port;
|
|
||||||
if (ports.TryGetValue(fieldName, out port)) return port;
|
|
||||||
else return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool HasPort(string fieldName) {
|
|
||||||
return ports.ContainsKey(fieldName);
|
|
||||||
}
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Inputs/Outputs
|
|
||||||
/// <summary> Return input value for a specified port. Returns fallback value if no ports are connected </summary>
|
|
||||||
/// <param name="fieldName">Field name of requested input port</param>
|
|
||||||
/// <param name="fallback">If no ports are connected, this value will be returned</param>
|
|
||||||
public T GetInputValue<T>(string fieldName, T fallback = default(T)) {
|
|
||||||
NodePort port = GetPort(fieldName);
|
|
||||||
if (port != null && port.IsConnected) return port.GetInputValue<T>();
|
|
||||||
else return fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Return all input values for a specified port. Returns fallback value if no ports are connected </summary>
|
|
||||||
/// <param name="fieldName">Field name of requested input port</param>
|
|
||||||
/// <param name="fallback">If no ports are connected, this value will be returned</param>
|
|
||||||
public T[] GetInputValues<T>(string fieldName, params T[] fallback) {
|
|
||||||
NodePort port = GetPort(fieldName);
|
|
||||||
if (port != null && port.IsConnected) return port.GetInputValues<T>();
|
|
||||||
else return fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Returns a value based on requested port output. Should be overridden in all derived nodes with outputs. </summary>
|
|
||||||
/// <param name="port">The requested port.</param>
|
|
||||||
public virtual object GetValue(NodePort port) {
|
|
||||||
Debug.LogWarning("No GetValue(NodePort port) override defined for " + GetType());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
/// <summary> Called after a connection between two <see cref="NodePort"/>s is created </summary>
|
|
||||||
/// <param name="from">Output</param> <param name="to">Input</param>
|
|
||||||
public virtual void OnCreateConnection(NodePort from, NodePort to) { }
|
|
||||||
|
|
||||||
/// <summary> Called after a connection is removed from this port </summary>
|
|
||||||
/// <param name="port">Output or Input</param>
|
|
||||||
public virtual void OnRemoveConnection(NodePort port) { }
|
|
||||||
|
|
||||||
/// <summary> Disconnect everything from this node </summary>
|
|
||||||
public void ClearConnections() {
|
|
||||||
foreach (NodePort port in Ports) port.ClearConnections();
|
|
||||||
}
|
|
||||||
|
|
||||||
#region Attributes
|
|
||||||
/// <summary> Mark a serializable field as an input port. You can access this through <see cref="GetInputPort(string)"/> </summary>
|
/// <summary> Mark a serializable field as an input port. You can access this through <see cref="GetInputPort(string)"/> </summary>
|
||||||
[AttributeUsage(AttributeTargets.Field)]
|
/// <param name="backingValue">Should we display the backing value for this port as an editor field? </param>
|
||||||
public class InputAttribute : Attribute {
|
/// <param name="connectionType">Should we allow multiple connections? </param>
|
||||||
public ShowBackingValue backingValue;
|
/// <param name="typeConstraint">Constrains which input connections can be made to this port </param>
|
||||||
public ConnectionType connectionType;
|
/// <param name="dynamicPortList">If true, will display a reorderable list of inputs instead of a single port. Will automatically add and display values for lists and arrays </param>
|
||||||
[Obsolete("Use dynamicPortList instead")]
|
public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnected, ConnectionType connectionType = ConnectionType.Multiple, TypeConstraint typeConstraint = TypeConstraint.None, bool dynamicPortList = false) {
|
||||||
public bool instancePortList { get { return dynamicPortList; } set { dynamicPortList = value; } }
|
this.backingValue = backingValue;
|
||||||
public bool dynamicPortList;
|
this.connectionType = connectionType;
|
||||||
public TypeConstraint typeConstraint;
|
this.dynamicPortList = dynamicPortList;
|
||||||
|
this.typeConstraint = typeConstraint;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary> Mark a serializable field as an input port. You can access this through <see cref="GetInputPort(string)"/> </summary>
|
/// <summary> Mark a serializable field as an output port. You can access this through <see cref="GetOutputPort(string)"/> </summary>
|
||||||
/// <param name="backingValue">Should we display the backing value for this port as an editor field? </param>
|
[AttributeUsage(AttributeTargets.Field)]
|
||||||
/// <param name="connectionType">Should we allow multiple connections? </param>
|
public class OutputAttribute : Attribute {
|
||||||
/// <param name="typeConstraint">Constrains which input connections can be made to this port </param>
|
public ShowBackingValue backingValue;
|
||||||
/// <param name="dynamicPortList">If true, will display a reorderable list of inputs instead of a single port. Will automatically add and display values for lists and arrays </param>
|
public ConnectionType connectionType;
|
||||||
public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnected, ConnectionType connectionType = ConnectionType.Multiple, TypeConstraint typeConstraint = TypeConstraint.None, bool dynamicPortList = false) {
|
[Obsolete("Use dynamicPortList instead")]
|
||||||
this.backingValue = backingValue;
|
public bool instancePortList { get { return dynamicPortList; } set { dynamicPortList = value; } }
|
||||||
this.connectionType = connectionType;
|
public bool dynamicPortList;
|
||||||
this.dynamicPortList = dynamicPortList;
|
public TypeConstraint typeConstraint;
|
||||||
this.typeConstraint = typeConstraint;
|
|
||||||
}
|
/// <summary> Mark a serializable field as an output port. You can access this through <see cref="GetOutputPort(string)"/> </summary>
|
||||||
|
/// <param name="backingValue">Should we display the backing value for this port as an editor field? </param>
|
||||||
|
/// <param name="connectionType">Should we allow multiple connections? </param>
|
||||||
|
/// <param name="typeConstraint">Constrains which input connections can be made from this port </param>
|
||||||
|
/// <param name="dynamicPortList">If true, will display a reorderable list of outputs instead of a single port. Will automatically add and display values for lists and arrays </param>
|
||||||
|
public OutputAttribute(ShowBackingValue backingValue = ShowBackingValue.Never, ConnectionType connectionType = ConnectionType.Multiple, TypeConstraint typeConstraint = TypeConstraint.None, bool dynamicPortList = false) {
|
||||||
|
this.backingValue = backingValue;
|
||||||
|
this.connectionType = connectionType;
|
||||||
|
this.dynamicPortList = dynamicPortList;
|
||||||
|
this.typeConstraint = typeConstraint;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Mark a serializable field as an output port. You can access this through <see cref="GetOutputPort(string)"/> </summary>
|
/// <summary> Mark a serializable field as an output port. You can access this through <see cref="GetOutputPort(string)"/> </summary>
|
||||||
[AttributeUsage(AttributeTargets.Field)]
|
/// <param name="backingValue">Should we display the backing value for this port as an editor field? </param>
|
||||||
public class OutputAttribute : Attribute {
|
/// <param name="connectionType">Should we allow multiple connections? </param>
|
||||||
public ShowBackingValue backingValue;
|
/// <param name="dynamicPortList">If true, will display a reorderable list of outputs instead of a single port. Will automatically add and display values for lists and arrays </param>
|
||||||
public ConnectionType connectionType;
|
[Obsolete("Use constructor with TypeConstraint")]
|
||||||
[Obsolete("Use dynamicPortList instead")]
|
public OutputAttribute(ShowBackingValue backingValue, ConnectionType connectionType, bool dynamicPortList) : this(backingValue, connectionType, TypeConstraint.None, dynamicPortList) { }
|
||||||
public bool instancePortList { get { return dynamicPortList; } set { dynamicPortList = value; } }
|
}
|
||||||
public bool dynamicPortList;
|
|
||||||
public TypeConstraint typeConstraint;
|
|
||||||
|
|
||||||
/// <summary> Mark a serializable field as an output port. You can access this through <see cref="GetOutputPort(string)"/> </summary>
|
/// <summary> Manually supply node class with a context menu path </summary>
|
||||||
/// <param name="backingValue">Should we display the backing value for this port as an editor field? </param>
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
|
||||||
/// <param name="connectionType">Should we allow multiple connections? </param>
|
public class CreateNodeMenuAttribute : Attribute {
|
||||||
/// <param name="typeConstraint">Constrains which input connections can be made from this port </param>
|
public string menuName;
|
||||||
/// <param name="dynamicPortList">If true, will display a reorderable list of outputs instead of a single port. Will automatically add and display values for lists and arrays </param>
|
public int order;
|
||||||
public OutputAttribute(ShowBackingValue backingValue = ShowBackingValue.Never, ConnectionType connectionType = ConnectionType.Multiple, TypeConstraint typeConstraint = TypeConstraint.None, bool dynamicPortList = false) {
|
/// <summary> Manually supply node class with a context menu path </summary>
|
||||||
this.backingValue = backingValue;
|
/// <param name="menuName"> Path to this node in the context menu. Null or empty hides it. </param>
|
||||||
this.connectionType = connectionType;
|
public CreateNodeMenuAttribute(string menuName) {
|
||||||
this.dynamicPortList = dynamicPortList;
|
this.menuName = menuName;
|
||||||
this.typeConstraint = typeConstraint;
|
this.order = 0;
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Mark a serializable field as an output port. You can access this through <see cref="GetOutputPort(string)"/> </summary>
|
|
||||||
/// <param name="backingValue">Should we display the backing value for this port as an editor field? </param>
|
|
||||||
/// <param name="connectionType">Should we allow multiple connections? </param>
|
|
||||||
/// <param name="dynamicPortList">If true, will display a reorderable list of outputs instead of a single port. Will automatically add and display values for lists and arrays </param>
|
|
||||||
[Obsolete("Use constructor with TypeConstraint")]
|
|
||||||
public OutputAttribute(ShowBackingValue backingValue, ConnectionType connectionType, bool dynamicPortList) : this(backingValue, connectionType, TypeConstraint.None, dynamicPortList) { }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Manually supply node class with a context menu path </summary>
|
/// <summary> Manually supply node class with a context menu path </summary>
|
||||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
|
/// <param name="menuName"> Path to this node in the context menu. Null or empty hides it. </param>
|
||||||
public class CreateNodeMenuAttribute : Attribute {
|
/// <param name="order"> The order by which the menu items are displayed. </param>
|
||||||
public string menuName;
|
public CreateNodeMenuAttribute(string menuName, int order) {
|
||||||
public int order;
|
this.menuName = menuName;
|
||||||
/// <summary> Manually supply node class with a context menu path </summary>
|
this.order = order;
|
||||||
/// <param name="menuName"> Path to this node in the context menu. Null or empty hides it. </param>
|
|
||||||
public CreateNodeMenuAttribute(string menuName) {
|
|
||||||
this.menuName = menuName;
|
|
||||||
this.order = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Manually supply node class with a context menu path </summary>
|
|
||||||
/// <param name="menuName"> Path to this node in the context menu. Null or empty hides it. </param>
|
|
||||||
/// <param name="order"> The order by which the menu items are displayed. </param>
|
|
||||||
public CreateNodeMenuAttribute(string menuName, int order) {
|
|
||||||
this.menuName = menuName;
|
|
||||||
this.order = order;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Prevents Node of the same type to be added more than once (configurable) to a NodeGraph </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
|
||||||
|
public class DisallowMultipleNodesAttribute : Attribute {
|
||||||
|
// TODO: Make inheritance work in such a way that applying [DisallowMultipleNodes(1)] to type NodeBar : Node
|
||||||
|
// while type NodeFoo : NodeBar exists, will let you add *either one* of these nodes, but not both.
|
||||||
|
public int max;
|
||||||
/// <summary> Prevents Node of the same type to be added more than once (configurable) to a NodeGraph </summary>
|
/// <summary> Prevents Node of the same type to be added more than once (configurable) to a NodeGraph </summary>
|
||||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
|
/// <param name="max"> How many nodes to allow. Defaults to 1. </param>
|
||||||
public class DisallowMultipleNodesAttribute : Attribute {
|
public DisallowMultipleNodesAttribute(int max = 1) {
|
||||||
// TODO: Make inheritance work in such a way that applying [DisallowMultipleNodes(1)] to type NodeBar : Node
|
this.max = max;
|
||||||
// while type NodeFoo : NodeBar exists, will let you add *either one* of these nodes, but not both.
|
}
|
||||||
public int max;
|
}
|
||||||
/// <summary> Prevents Node of the same type to be added more than once (configurable) to a NodeGraph </summary>
|
|
||||||
/// <param name="max"> How many nodes to allow. Defaults to 1. </param>
|
/// <summary> Specify a color for this node type </summary>
|
||||||
public DisallowMultipleNodesAttribute(int max = 1) {
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
|
||||||
this.max = max;
|
public class NodeTintAttribute : Attribute {
|
||||||
}
|
public Color color;
|
||||||
|
/// <summary> Specify a color for this node type </summary>
|
||||||
|
/// <param name="r"> Red [0.0f .. 1.0f] </param>
|
||||||
|
/// <param name="g"> Green [0.0f .. 1.0f] </param>
|
||||||
|
/// <param name="b"> Blue [0.0f .. 1.0f] </param>
|
||||||
|
public NodeTintAttribute(float r, float g, float b) {
|
||||||
|
color = new Color(r, g, b);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Specify a color for this node type </summary>
|
/// <summary> Specify a color for this node type </summary>
|
||||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
|
/// <param name="hex"> HEX color value </param>
|
||||||
public class NodeTintAttribute : Attribute {
|
public NodeTintAttribute(string hex) {
|
||||||
public Color color;
|
ColorUtility.TryParseHtmlString(hex, out color);
|
||||||
/// <summary> Specify a color for this node type </summary>
|
|
||||||
/// <param name="r"> Red [0.0f .. 1.0f] </param>
|
|
||||||
/// <param name="g"> Green [0.0f .. 1.0f] </param>
|
|
||||||
/// <param name="b"> Blue [0.0f .. 1.0f] </param>
|
|
||||||
public NodeTintAttribute(float r, float g, float b) {
|
|
||||||
color = new Color(r, g, b);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Specify a color for this node type </summary>
|
|
||||||
/// <param name="hex"> HEX color value </param>
|
|
||||||
public NodeTintAttribute(string hex) {
|
|
||||||
ColorUtility.TryParseHtmlString(hex, out color);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Specify a color for this node type </summary>
|
|
||||||
/// <param name="r"> Red [0 .. 255] </param>
|
|
||||||
/// <param name="g"> Green [0 .. 255] </param>
|
|
||||||
/// <param name="b"> Blue [0 .. 255] </param>
|
|
||||||
public NodeTintAttribute(byte r, byte g, byte b) {
|
|
||||||
color = new Color32(r, g, b, byte.MaxValue);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary> Specify a width for this node type </summary>
|
/// <summary> Specify a color for this node type </summary>
|
||||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
|
/// <param name="r"> Red [0 .. 255] </param>
|
||||||
public class NodeWidthAttribute : Attribute {
|
/// <param name="g"> Green [0 .. 255] </param>
|
||||||
public int width;
|
/// <param name="b"> Blue [0 .. 255] </param>
|
||||||
/// <summary> Specify a width for this node type </summary>
|
public NodeTintAttribute(byte r, byte g, byte b) {
|
||||||
/// <param name="width"> Width </param>
|
color = new Color32(r, g, b, byte.MaxValue);
|
||||||
public NodeWidthAttribute(int width) {
|
|
||||||
this.width = width;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
[Serializable] private class NodePortDictionary : Dictionary<string, NodePort>, ISerializationCallbackReceiver {
|
|
||||||
[SerializeField] private List<string> keys = new List<string>();
|
|
||||||
[SerializeField] private List<NodePort> values = new List<NodePort>();
|
|
||||||
|
|
||||||
public void OnBeforeSerialize() {
|
|
||||||
keys.Clear();
|
|
||||||
values.Clear();
|
|
||||||
keys.Capacity = this.Count;
|
|
||||||
values.Capacity = this.Count;
|
|
||||||
foreach (KeyValuePair<string, NodePort> pair in this) {
|
|
||||||
keys.Add(pair.Key);
|
|
||||||
values.Add(pair.Value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void OnAfterDeserialize() {
|
|
||||||
this.Clear();
|
|
||||||
#if UNITY_2021_3_OR_NEWER
|
|
||||||
this.EnsureCapacity(keys.Count);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (keys.Count != values.Count)
|
|
||||||
throw new System.Exception("there are " + keys.Count + " keys and " + values.Count + " values after deserialization. Make sure that both key and value types are serializable.");
|
|
||||||
|
|
||||||
for (int i = 0; i < keys.Count; i++)
|
|
||||||
this.Add(keys[i], values[i]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
/// <summary> Specify a width for this node type </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
|
||||||
|
public class NodeWidthAttribute : Attribute {
|
||||||
|
public int width;
|
||||||
|
/// <summary> Specify a width for this node type </summary>
|
||||||
|
/// <param name="width"> Width </param>
|
||||||
|
public NodeWidthAttribute(int width) {
|
||||||
|
this.width = width;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
[Serializable] private class NodePortDictionary : Dictionary<string, NodePort>, ISerializationCallbackReceiver {
|
||||||
|
[SerializeField] private List<string> keys = new List<string>();
|
||||||
|
[SerializeField] private List<NodePort> values = new List<NodePort>();
|
||||||
|
|
||||||
|
public void OnBeforeSerialize() {
|
||||||
|
keys.Clear();
|
||||||
|
values.Clear();
|
||||||
|
keys.Capacity = this.Count;
|
||||||
|
values.Capacity = this.Count;
|
||||||
|
foreach (KeyValuePair<string, NodePort> pair in this) {
|
||||||
|
keys.Add(pair.Key);
|
||||||
|
values.Add(pair.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnAfterDeserialize() {
|
||||||
|
this.Clear();
|
||||||
|
#if UNITY_2021_3_OR_NEWER
|
||||||
|
this.EnsureCapacity(keys.Count);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
if (keys.Count != values.Count)
|
||||||
|
throw new System.Exception("there are " + keys.Count + " keys and " + values.Count + " values after deserialization. Make sure that both key and value types are serializable.");
|
||||||
|
|
||||||
|
for (int i = 0; i < keys.Count; i++)
|
||||||
|
this.Add(keys[i], values[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -3,224 +3,222 @@ using System.Linq;
|
|||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
namespace XNode {
|
/// <summary> Precaches reflection data in editor so we won't have to do it runtime </summary>
|
||||||
/// <summary> Precaches reflection data in editor so we won't have to do it runtime </summary>
|
public static class NodeDataCache {
|
||||||
public static class NodeDataCache {
|
private static PortDataCache portDataCache;
|
||||||
private static PortDataCache portDataCache;
|
private static Dictionary<System.Type, Dictionary<string, string>> formerlySerializedAsCache;
|
||||||
private static Dictionary<System.Type, Dictionary<string, string>> formerlySerializedAsCache;
|
private static Dictionary<System.Type, string> typeQualifiedNameCache;
|
||||||
private static Dictionary<System.Type, string> typeQualifiedNameCache;
|
private static bool Initialized { get { return portDataCache != null; } }
|
||||||
private static bool Initialized { get { return portDataCache != null; } }
|
|
||||||
|
|
||||||
public static string GetTypeQualifiedName(System.Type type) {
|
public static string GetTypeQualifiedName(System.Type type) {
|
||||||
if(typeQualifiedNameCache == null) typeQualifiedNameCache = new Dictionary<System.Type, string>();
|
if(typeQualifiedNameCache == null) typeQualifiedNameCache = new Dictionary<System.Type, string>();
|
||||||
|
|
||||||
string name;
|
string name;
|
||||||
if (!typeQualifiedNameCache.TryGetValue(type, out name)) {
|
if (!typeQualifiedNameCache.TryGetValue(type, out name)) {
|
||||||
name = type.AssemblyQualifiedName;
|
name = type.AssemblyQualifiedName;
|
||||||
typeQualifiedNameCache.Add(type, name);
|
typeQualifiedNameCache.Add(type, name);
|
||||||
}
|
|
||||||
return name;
|
|
||||||
}
|
}
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary> Update static ports and dynamic ports managed by DynamicPortLists to reflect class fields. </summary>
|
/// <summary> Update static ports and dynamic ports managed by DynamicPortLists to reflect class fields. </summary>
|
||||||
public static void UpdatePorts(Node node, Dictionary<string, NodePort> ports) {
|
public static void UpdatePorts(Node node, Dictionary<string, NodePort> ports) {
|
||||||
if (!Initialized) BuildCache();
|
if (!Initialized) BuildCache();
|
||||||
|
|
||||||
Dictionary<string, List<NodePort>> removedPorts = new Dictionary<string, List<NodePort>>();
|
Dictionary<string, List<NodePort>> removedPorts = new Dictionary<string, List<NodePort>>();
|
||||||
System.Type nodeType = node.GetType();
|
System.Type nodeType = node.GetType();
|
||||||
|
|
||||||
Dictionary<string, string> formerlySerializedAs = null;
|
Dictionary<string, string> formerlySerializedAs = null;
|
||||||
if (formerlySerializedAsCache != null) formerlySerializedAsCache.TryGetValue(nodeType, out formerlySerializedAs);
|
if (formerlySerializedAsCache != null) formerlySerializedAsCache.TryGetValue(nodeType, out formerlySerializedAs);
|
||||||
|
|
||||||
List<NodePort> dynamicListPorts = new List<NodePort>();
|
List<NodePort> dynamicListPorts = new List<NodePort>();
|
||||||
|
|
||||||
Dictionary<string, NodePort> staticPorts;
|
Dictionary<string, NodePort> staticPorts;
|
||||||
if (!portDataCache.TryGetValue(nodeType, out staticPorts)) {
|
if (!portDataCache.TryGetValue(nodeType, out staticPorts)) {
|
||||||
staticPorts = new Dictionary<string, NodePort>();
|
staticPorts = new Dictionary<string, NodePort>();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cleanup port dict - Remove nonexisting static ports - update static port types
|
|
||||||
// AND update dynamic ports (albeit only those in lists) too, in order to enforce proper serialisation.
|
|
||||||
// Loop through current node ports
|
|
||||||
foreach (NodePort port in ports.Values.ToArray()) {
|
|
||||||
// If port still exists, check it it has been changed
|
|
||||||
NodePort staticPort;
|
|
||||||
if (staticPorts.TryGetValue(port.fieldName, out staticPort)) {
|
|
||||||
// If port exists but with wrong settings, remove it. Re-add it later.
|
|
||||||
if (port.IsDynamic || port.direction != staticPort.direction || port.connectionType != staticPort.connectionType || port.typeConstraint != staticPort.typeConstraint) {
|
|
||||||
// If port is not dynamic and direction hasn't changed, add it to the list so we can try reconnecting the ports connections.
|
|
||||||
if (!port.IsDynamic && port.direction == staticPort.direction) removedPorts.Add(port.fieldName, port.GetConnections());
|
|
||||||
port.ClearConnections();
|
|
||||||
ports.Remove(port.fieldName);
|
|
||||||
} else port.ValueType = staticPort.ValueType;
|
|
||||||
}
|
|
||||||
// If port doesn't exist anymore, remove it
|
|
||||||
else if (port.IsStatic) {
|
|
||||||
//See if the field is tagged with FormerlySerializedAs, if so add the port with its new field name to removedPorts
|
|
||||||
// so it can be reconnected in missing ports stage.
|
|
||||||
string newName = null;
|
|
||||||
if (formerlySerializedAs != null && formerlySerializedAs.TryGetValue(port.fieldName, out newName)) removedPorts.Add(newName, port.GetConnections());
|
|
||||||
|
|
||||||
|
// Cleanup port dict - Remove nonexisting static ports - update static port types
|
||||||
|
// AND update dynamic ports (albeit only those in lists) too, in order to enforce proper serialisation.
|
||||||
|
// Loop through current node ports
|
||||||
|
foreach (NodePort port in ports.Values.ToArray()) {
|
||||||
|
// If port still exists, check it it has been changed
|
||||||
|
NodePort staticPort;
|
||||||
|
if (staticPorts.TryGetValue(port.fieldName, out staticPort)) {
|
||||||
|
// If port exists but with wrong settings, remove it. Re-add it later.
|
||||||
|
if (port.IsDynamic || port.direction != staticPort.direction || port.connectionType != staticPort.connectionType || port.typeConstraint != staticPort.typeConstraint) {
|
||||||
|
// If port is not dynamic and direction hasn't changed, add it to the list so we can try reconnecting the ports connections.
|
||||||
|
if (!port.IsDynamic && port.direction == staticPort.direction) removedPorts.Add(port.fieldName, port.GetConnections());
|
||||||
port.ClearConnections();
|
port.ClearConnections();
|
||||||
ports.Remove(port.fieldName);
|
ports.Remove(port.fieldName);
|
||||||
}
|
} else port.ValueType = staticPort.ValueType;
|
||||||
// If the port is dynamic and is managed by a dynamic port list, flag it for reference updates
|
|
||||||
else if (IsDynamicListPort(port)) {
|
|
||||||
dynamicListPorts.Add(port);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// Add missing ports
|
// If port doesn't exist anymore, remove it
|
||||||
foreach (NodePort staticPort in staticPorts.Values) {
|
else if (port.IsStatic) {
|
||||||
if (!ports.ContainsKey(staticPort.fieldName)) {
|
//See if the field is tagged with FormerlySerializedAs, if so add the port with its new field name to removedPorts
|
||||||
NodePort port = new NodePort(staticPort, node);
|
// so it can be reconnected in missing ports stage.
|
||||||
//If we just removed the port, try re-adding the connections
|
string newName = null;
|
||||||
List<NodePort> reconnectConnections;
|
if (formerlySerializedAs != null && formerlySerializedAs.TryGetValue(port.fieldName, out newName)) removedPorts.Add(newName, port.GetConnections());
|
||||||
if (removedPorts.TryGetValue(staticPort.fieldName, out reconnectConnections)) {
|
|
||||||
for (int i = 0; i < reconnectConnections.Count; i++) {
|
port.ClearConnections();
|
||||||
NodePort connection = reconnectConnections[i];
|
ports.Remove(port.fieldName);
|
||||||
if (connection == null) continue;
|
|
||||||
// CAVEAT: Ports connected under special conditions defined in graphEditor.CanConnect overrides will not auto-connect.
|
|
||||||
// To fix this, this code would need to be moved to an editor script and call graphEditor.CanConnect instead of port.CanConnectTo.
|
|
||||||
// This is only a problem in the rare edge case where user is using non-standard CanConnect overrides and changes port type of an already connected port
|
|
||||||
if (port.CanConnectTo(connection)) port.Connect(connection);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ports.Add(staticPort.fieldName, port);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
// If the port is dynamic and is managed by a dynamic port list, flag it for reference updates
|
||||||
// Finally, make sure dynamic list port settings correspond to the settings of their "backing port"
|
else if (IsDynamicListPort(port)) {
|
||||||
foreach (NodePort listPort in dynamicListPorts) {
|
dynamicListPorts.Add(port);
|
||||||
// At this point we know that ports here are dynamic list ports
|
|
||||||
// which have passed name/"backing port" checks, ergo we can proceed more safely.
|
|
||||||
string backingPortName = listPort.fieldName.Substring(0, listPort.fieldName.IndexOf(' '));
|
|
||||||
NodePort backingPort = staticPorts[backingPortName];
|
|
||||||
|
|
||||||
// Update port constraints. Creating a new port instead will break the editor, mandating the need for setters.
|
|
||||||
listPort.ValueType = GetBackingValueType(backingPort.ValueType);
|
|
||||||
listPort.direction = backingPort.direction;
|
|
||||||
listPort.connectionType = backingPort.connectionType;
|
|
||||||
listPort.typeConstraint = backingPort.typeConstraint;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Add missing ports
|
||||||
/// <summary>
|
foreach (NodePort staticPort in staticPorts.Values) {
|
||||||
/// Extracts the underlying types from arrays and lists, the only collections for dynamic port lists
|
if (!ports.ContainsKey(staticPort.fieldName)) {
|
||||||
/// currently supported. If the given type is not applicable (i.e. if the dynamic list port was not
|
NodePort port = new NodePort(staticPort, node);
|
||||||
/// defined as an array or a list), returns the given type itself.
|
//If we just removed the port, try re-adding the connections
|
||||||
/// </summary>
|
List<NodePort> reconnectConnections;
|
||||||
private static System.Type GetBackingValueType(System.Type portValType) {
|
if (removedPorts.TryGetValue(staticPort.fieldName, out reconnectConnections)) {
|
||||||
if (portValType.HasElementType) {
|
for (int i = 0; i < reconnectConnections.Count; i++) {
|
||||||
return portValType.GetElementType();
|
NodePort connection = reconnectConnections[i];
|
||||||
}
|
if (connection == null) continue;
|
||||||
if (portValType.IsGenericType && portValType.GetGenericTypeDefinition() == typeof(List<>)) {
|
// CAVEAT: Ports connected under special conditions defined in graphEditor.CanConnect overrides will not auto-connect.
|
||||||
return portValType.GetGenericArguments()[0];
|
// To fix this, this code would need to be moved to an editor script and call graphEditor.CanConnect instead of port.CanConnectTo.
|
||||||
}
|
// This is only a problem in the rare edge case where user is using non-standard CanConnect overrides and changes port type of an already connected port
|
||||||
return portValType;
|
if (port.CanConnectTo(connection)) port.Connect(connection);
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Returns true if the given port is in a dynamic port list.</summary>
|
|
||||||
private static bool IsDynamicListPort(NodePort port) {
|
|
||||||
// Ports flagged as "dynamicPortList = true" end up having a "backing port" and a name with an index, but we have
|
|
||||||
// no guarantee that a dynamic port called "output 0" is an element in a list backed by a static "output" port.
|
|
||||||
// Thus, we need to check for attributes... (but at least we don't need to look at all fields this time)
|
|
||||||
string[] fieldNameParts = port.fieldName.Split(' ');
|
|
||||||
if (fieldNameParts.Length != 2) return false;
|
|
||||||
|
|
||||||
FieldInfo backingPortInfo = port.node.GetType().GetField(fieldNameParts[0]);
|
|
||||||
if (backingPortInfo == null) return false;
|
|
||||||
|
|
||||||
object[] attribs = backingPortInfo.GetCustomAttributes(true);
|
|
||||||
return attribs.Any(x => {
|
|
||||||
Node.InputAttribute inputAttribute = x as Node.InputAttribute;
|
|
||||||
Node.OutputAttribute outputAttribute = x as Node.OutputAttribute;
|
|
||||||
return inputAttribute != null && inputAttribute.dynamicPortList ||
|
|
||||||
outputAttribute != null && outputAttribute.dynamicPortList;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Cache node types </summary>
|
|
||||||
private static void BuildCache() {
|
|
||||||
portDataCache = new PortDataCache();
|
|
||||||
System.Type baseType = typeof(Node);
|
|
||||||
List<System.Type> nodeTypes = new List<System.Type>();
|
|
||||||
System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
|
|
||||||
|
|
||||||
// Loop through assemblies and add node types to list
|
|
||||||
foreach (Assembly assembly in assemblies) {
|
|
||||||
// Skip certain dlls to improve performance
|
|
||||||
string assemblyName = assembly.GetName().Name;
|
|
||||||
int index = assemblyName.IndexOf('.');
|
|
||||||
if (index != -1) assemblyName = assemblyName.Substring(0, index);
|
|
||||||
switch (assemblyName) {
|
|
||||||
// The following assemblies, and sub-assemblies (eg. UnityEngine.UI) are skipped
|
|
||||||
case "UnityEditor":
|
|
||||||
case "UnityEngine":
|
|
||||||
case "Unity":
|
|
||||||
case "System":
|
|
||||||
case "mscorlib":
|
|
||||||
case "Microsoft":
|
|
||||||
continue;
|
|
||||||
default:
|
|
||||||
nodeTypes.AddRange(assembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t)).ToArray());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < nodeTypes.Count; i++) {
|
|
||||||
CachePorts(nodeTypes[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static List<FieldInfo> GetNodeFields(System.Type nodeType) {
|
|
||||||
List<System.Reflection.FieldInfo> fieldInfo = new List<System.Reflection.FieldInfo>(nodeType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance));
|
|
||||||
|
|
||||||
// GetFields doesnt return inherited private fields, so walk through base types and pick those up
|
|
||||||
System.Type tempType = nodeType;
|
|
||||||
while ((tempType = tempType.BaseType) != typeof(XNode.Node)) {
|
|
||||||
FieldInfo[] parentFields = tempType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
|
|
||||||
for (int i = 0; i < parentFields.Length; i++) {
|
|
||||||
// Ensure that we do not already have a member with this type and name
|
|
||||||
FieldInfo parentField = parentFields[i];
|
|
||||||
if (fieldInfo.TrueForAll(x => x.Name != parentField.Name)) {
|
|
||||||
fieldInfo.Add(parentField);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
ports.Add(staticPort.fieldName, port);
|
||||||
return fieldInfo;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void CachePorts(System.Type nodeType) {
|
|
||||||
List<System.Reflection.FieldInfo> fieldInfo = GetNodeFields(nodeType);
|
|
||||||
|
|
||||||
for (int i = 0; i < fieldInfo.Count; i++) {
|
|
||||||
|
|
||||||
//Get InputAttribute and OutputAttribute
|
|
||||||
object[] attribs = fieldInfo[i].GetCustomAttributes(true);
|
|
||||||
Node.InputAttribute inputAttrib = attribs.FirstOrDefault(x => x is Node.InputAttribute) as Node.InputAttribute;
|
|
||||||
Node.OutputAttribute outputAttrib = attribs.FirstOrDefault(x => x is Node.OutputAttribute) as Node.OutputAttribute;
|
|
||||||
UnityEngine.Serialization.FormerlySerializedAsAttribute formerlySerializedAsAttribute = attribs.FirstOrDefault(x => x is UnityEngine.Serialization.FormerlySerializedAsAttribute) as UnityEngine.Serialization.FormerlySerializedAsAttribute;
|
|
||||||
|
|
||||||
if (inputAttrib == null && outputAttrib == null) continue;
|
|
||||||
|
|
||||||
if (inputAttrib != null && outputAttrib != null) Debug.LogError("Field " + fieldInfo[i].Name + " of type " + nodeType.FullName + " cannot be both input and output.");
|
|
||||||
else {
|
|
||||||
if (!portDataCache.ContainsKey(nodeType)) portDataCache.Add(nodeType, new Dictionary<string, NodePort>());
|
|
||||||
NodePort port = new NodePort(fieldInfo[i]);
|
|
||||||
portDataCache[nodeType].Add(port.fieldName, port);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (formerlySerializedAsAttribute != null) {
|
|
||||||
if (formerlySerializedAsCache == null) formerlySerializedAsCache = new Dictionary<System.Type, Dictionary<string, string>>();
|
|
||||||
if (!formerlySerializedAsCache.ContainsKey(nodeType)) formerlySerializedAsCache.Add(nodeType, new Dictionary<string, string>());
|
|
||||||
|
|
||||||
if (formerlySerializedAsCache[nodeType].ContainsKey(formerlySerializedAsAttribute.oldName)) Debug.LogError("Another FormerlySerializedAs with value '" + formerlySerializedAsAttribute.oldName + "' already exist on this node.");
|
|
||||||
else formerlySerializedAsCache[nodeType].Add(formerlySerializedAsAttribute.oldName, fieldInfo[i].Name);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[System.Serializable]
|
// Finally, make sure dynamic list port settings correspond to the settings of their "backing port"
|
||||||
private class PortDataCache : Dictionary<System.Type, Dictionary<string, NodePort>> { }
|
foreach (NodePort listPort in dynamicListPorts) {
|
||||||
|
// At this point we know that ports here are dynamic list ports
|
||||||
|
// which have passed name/"backing port" checks, ergo we can proceed more safely.
|
||||||
|
string backingPortName = listPort.fieldName.Substring(0, listPort.fieldName.IndexOf(' '));
|
||||||
|
NodePort backingPort = staticPorts[backingPortName];
|
||||||
|
|
||||||
|
// Update port constraints. Creating a new port instead will break the editor, mandating the need for setters.
|
||||||
|
listPort.ValueType = GetBackingValueType(backingPort.ValueType);
|
||||||
|
listPort.direction = backingPort.direction;
|
||||||
|
listPort.connectionType = backingPort.connectionType;
|
||||||
|
listPort.typeConstraint = backingPort.typeConstraint;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extracts the underlying types from arrays and lists, the only collections for dynamic port lists
|
||||||
|
/// currently supported. If the given type is not applicable (i.e. if the dynamic list port was not
|
||||||
|
/// defined as an array or a list), returns the given type itself.
|
||||||
|
/// </summary>
|
||||||
|
private static System.Type GetBackingValueType(System.Type portValType) {
|
||||||
|
if (portValType.HasElementType) {
|
||||||
|
return portValType.GetElementType();
|
||||||
|
}
|
||||||
|
if (portValType.IsGenericType && portValType.GetGenericTypeDefinition() == typeof(List<>)) {
|
||||||
|
return portValType.GetGenericArguments()[0];
|
||||||
|
}
|
||||||
|
return portValType;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns true if the given port is in a dynamic port list.</summary>
|
||||||
|
private static bool IsDynamicListPort(NodePort port) {
|
||||||
|
// Ports flagged as "dynamicPortList = true" end up having a "backing port" and a name with an index, but we have
|
||||||
|
// no guarantee that a dynamic port called "output 0" is an element in a list backed by a static "output" port.
|
||||||
|
// Thus, we need to check for attributes... (but at least we don't need to look at all fields this time)
|
||||||
|
string[] fieldNameParts = port.fieldName.Split(' ');
|
||||||
|
if (fieldNameParts.Length != 2) return false;
|
||||||
|
|
||||||
|
FieldInfo backingPortInfo = port.node.GetType().GetField(fieldNameParts[0]);
|
||||||
|
if (backingPortInfo == null) return false;
|
||||||
|
|
||||||
|
object[] attribs = backingPortInfo.GetCustomAttributes(true);
|
||||||
|
return attribs.Any(x => {
|
||||||
|
Node.InputAttribute inputAttribute = x as Node.InputAttribute;
|
||||||
|
Node.OutputAttribute outputAttribute = x as Node.OutputAttribute;
|
||||||
|
return inputAttribute != null && inputAttribute.dynamicPortList ||
|
||||||
|
outputAttribute != null && outputAttribute.dynamicPortList;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Cache node types </summary>
|
||||||
|
private static void BuildCache() {
|
||||||
|
portDataCache = new PortDataCache();
|
||||||
|
System.Type baseType = typeof(Node);
|
||||||
|
List<System.Type> nodeTypes = new List<System.Type>();
|
||||||
|
System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
|
||||||
|
|
||||||
|
// Loop through assemblies and add node types to list
|
||||||
|
foreach (Assembly assembly in assemblies) {
|
||||||
|
// Skip certain dlls to improve performance
|
||||||
|
string assemblyName = assembly.GetName().Name;
|
||||||
|
int index = assemblyName.IndexOf('.');
|
||||||
|
if (index != -1) assemblyName = assemblyName.Substring(0, index);
|
||||||
|
switch (assemblyName) {
|
||||||
|
// The following assemblies, and sub-assemblies (eg. UnityEngine.UI) are skipped
|
||||||
|
case "UnityEditor":
|
||||||
|
case "UnityEngine":
|
||||||
|
case "Unity":
|
||||||
|
case "System":
|
||||||
|
case "mscorlib":
|
||||||
|
case "Microsoft":
|
||||||
|
continue;
|
||||||
|
default:
|
||||||
|
nodeTypes.AddRange(assembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t)).ToArray());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < nodeTypes.Count; i++) {
|
||||||
|
CachePorts(nodeTypes[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<FieldInfo> GetNodeFields(System.Type nodeType) {
|
||||||
|
List<System.Reflection.FieldInfo> fieldInfo = new List<System.Reflection.FieldInfo>(nodeType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance));
|
||||||
|
|
||||||
|
// GetFields doesnt return inherited private fields, so walk through base types and pick those up
|
||||||
|
System.Type tempType = nodeType;
|
||||||
|
while ((tempType = tempType.BaseType) != typeof(Node)) {
|
||||||
|
FieldInfo[] parentFields = tempType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
|
||||||
|
for (int i = 0; i < parentFields.Length; i++) {
|
||||||
|
// Ensure that we do not already have a member with this type and name
|
||||||
|
FieldInfo parentField = parentFields[i];
|
||||||
|
if (fieldInfo.TrueForAll(x => x.Name != parentField.Name)) {
|
||||||
|
fieldInfo.Add(parentField);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fieldInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CachePorts(System.Type nodeType) {
|
||||||
|
List<System.Reflection.FieldInfo> fieldInfo = GetNodeFields(nodeType);
|
||||||
|
|
||||||
|
for (int i = 0; i < fieldInfo.Count; i++) {
|
||||||
|
|
||||||
|
//Get InputAttribute and OutputAttribute
|
||||||
|
object[] attribs = fieldInfo[i].GetCustomAttributes(true);
|
||||||
|
Node.InputAttribute inputAttrib = attribs.FirstOrDefault(x => x is Node.InputAttribute) as Node.InputAttribute;
|
||||||
|
Node.OutputAttribute outputAttrib = attribs.FirstOrDefault(x => x is Node.OutputAttribute) as Node.OutputAttribute;
|
||||||
|
UnityEngine.Serialization.FormerlySerializedAsAttribute formerlySerializedAsAttribute = attribs.FirstOrDefault(x => x is UnityEngine.Serialization.FormerlySerializedAsAttribute) as UnityEngine.Serialization.FormerlySerializedAsAttribute;
|
||||||
|
|
||||||
|
if (inputAttrib == null && outputAttrib == null) continue;
|
||||||
|
|
||||||
|
if (inputAttrib != null && outputAttrib != null) Debug.LogError("Field " + fieldInfo[i].Name + " of type " + nodeType.FullName + " cannot be both input and output.");
|
||||||
|
else {
|
||||||
|
if (!portDataCache.ContainsKey(nodeType)) portDataCache.Add(nodeType, new Dictionary<string, NodePort>());
|
||||||
|
NodePort port = new NodePort(fieldInfo[i]);
|
||||||
|
portDataCache[nodeType].Add(port.fieldName, port);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formerlySerializedAsAttribute != null) {
|
||||||
|
if (formerlySerializedAsCache == null) formerlySerializedAsCache = new Dictionary<System.Type, Dictionary<string, string>>();
|
||||||
|
if (!formerlySerializedAsCache.ContainsKey(nodeType)) formerlySerializedAsCache.Add(nodeType, new Dictionary<string, string>());
|
||||||
|
|
||||||
|
if (formerlySerializedAsCache[nodeType].ContainsKey(formerlySerializedAsAttribute.oldName)) Debug.LogError("Another FormerlySerializedAs with value '" + formerlySerializedAsAttribute.oldName + "' already exist on this node.");
|
||||||
|
else formerlySerializedAsCache[nodeType].Add(formerlySerializedAsAttribute.oldName, fieldInfo[i].Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[System.Serializable]
|
||||||
|
private class PortDataCache : Dictionary<System.Type, Dictionary<string, NodePort>> { }
|
||||||
|
}
|
||||||
@ -2,123 +2,121 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
namespace XNode {
|
/// <summary> Base class for all node graphs </summary>
|
||||||
/// <summary> Base class for all node graphs </summary>
|
[Serializable]
|
||||||
[Serializable]
|
public abstract class NodeGraph : ScriptableObject {
|
||||||
public abstract class NodeGraph : ScriptableObject {
|
|
||||||
|
|
||||||
/// <summary> All nodes in the graph. <para/>
|
/// <summary> All nodes in the graph. <para/>
|
||||||
/// See: <see cref="AddNode{T}"/> </summary>
|
/// See: <see cref="AddNode{T}"/> </summary>
|
||||||
[SerializeField] public List<Node> nodes = new List<Node>();
|
[SerializeField] public List<Node> nodes = new List<Node>();
|
||||||
|
|
||||||
/// <summary> Add a node to the graph by type (convenience method - will call the System.Type version) </summary>
|
/// <summary> Add a node to the graph by type (convenience method - will call the System.Type version) </summary>
|
||||||
public T AddNode<T>() where T : Node {
|
public T AddNode<T>() where T : Node {
|
||||||
return AddNode(typeof(T)) as T;
|
return AddNode(typeof(T)) as T;
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Add a node to the graph by type </summary>
|
|
||||||
public virtual Node AddNode(Type type) {
|
|
||||||
Node.graphHotfix = this;
|
|
||||||
Node node = ScriptableObject.CreateInstance(type) as Node;
|
|
||||||
node.graph = this;
|
|
||||||
nodes.Add(node);
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Creates a copy of the original node in the graph </summary>
|
|
||||||
public virtual Node CopyNode(Node original) {
|
|
||||||
Node.graphHotfix = this;
|
|
||||||
Node node = ScriptableObject.Instantiate(original);
|
|
||||||
node.graph = this;
|
|
||||||
node.ClearConnections();
|
|
||||||
nodes.Add(node);
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Safely remove a node and all its connections </summary>
|
|
||||||
/// <param name="node"> The node to remove </param>
|
|
||||||
public virtual void RemoveNode(Node node) {
|
|
||||||
node.ClearConnections();
|
|
||||||
nodes.Remove(node);
|
|
||||||
if (Application.isPlaying) Destroy(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Remove all nodes and connections from the graph </summary>
|
|
||||||
public virtual void Clear() {
|
|
||||||
if (Application.isPlaying) {
|
|
||||||
for (int i = 0; i < nodes.Count; i++) {
|
|
||||||
if (nodes[i] != null) Destroy(nodes[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
nodes.Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Create a new deep copy of this graph </summary>
|
|
||||||
public virtual 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected virtual void OnDestroy() {
|
|
||||||
// Remove all nodes prior to graph destruction
|
|
||||||
Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
#region Attributes
|
|
||||||
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted. </summary>
|
|
||||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
|
||||||
public class RequireNodeAttribute : Attribute {
|
|
||||||
public Type type0;
|
|
||||||
public Type type1;
|
|
||||||
public Type type2;
|
|
||||||
|
|
||||||
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
|
||||||
public RequireNodeAttribute(Type type) {
|
|
||||||
this.type0 = type;
|
|
||||||
this.type1 = null;
|
|
||||||
this.type2 = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
|
||||||
public RequireNodeAttribute(Type type, Type type2) {
|
|
||||||
this.type0 = type;
|
|
||||||
this.type1 = type2;
|
|
||||||
this.type2 = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
|
||||||
public RequireNodeAttribute(Type type, Type type2, Type type3) {
|
|
||||||
this.type0 = type;
|
|
||||||
this.type1 = type2;
|
|
||||||
this.type2 = type3;
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool Requires(Type type) {
|
|
||||||
if (type == null) return false;
|
|
||||||
if (type == type0) return true;
|
|
||||||
else if (type == type1) return true;
|
|
||||||
else if (type == type2) return true;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endregion
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary> Add a node to the graph by type </summary>
|
||||||
|
public virtual Node AddNode(Type type) {
|
||||||
|
Node.graphHotfix = this;
|
||||||
|
Node node = ScriptableObject.CreateInstance(type) as Node;
|
||||||
|
node.graph = this;
|
||||||
|
nodes.Add(node);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Creates a copy of the original node in the graph </summary>
|
||||||
|
public virtual Node CopyNode(Node original) {
|
||||||
|
Node.graphHotfix = this;
|
||||||
|
Node node = ScriptableObject.Instantiate(original);
|
||||||
|
node.graph = this;
|
||||||
|
node.ClearConnections();
|
||||||
|
nodes.Add(node);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Safely remove a node and all its connections </summary>
|
||||||
|
/// <param name="node"> The node to remove </param>
|
||||||
|
public virtual void RemoveNode(Node node) {
|
||||||
|
node.ClearConnections();
|
||||||
|
nodes.Remove(node);
|
||||||
|
if (Application.isPlaying) Destroy(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Remove all nodes and connections from the graph </summary>
|
||||||
|
public virtual void Clear() {
|
||||||
|
if (Application.isPlaying) {
|
||||||
|
for (int i = 0; i < nodes.Count; i++) {
|
||||||
|
if (nodes[i] != null) Destroy(nodes[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nodes.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Create a new deep copy of this graph </summary>
|
||||||
|
public virtual 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected virtual void OnDestroy() {
|
||||||
|
// Remove all nodes prior to graph destruction
|
||||||
|
Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#region Attributes
|
||||||
|
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted. </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
||||||
|
public class RequireNodeAttribute : Attribute {
|
||||||
|
public Type type0;
|
||||||
|
public Type type1;
|
||||||
|
public Type type2;
|
||||||
|
|
||||||
|
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
||||||
|
public RequireNodeAttribute(Type type) {
|
||||||
|
this.type0 = type;
|
||||||
|
this.type1 = null;
|
||||||
|
this.type2 = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
||||||
|
public RequireNodeAttribute(Type type, Type type2) {
|
||||||
|
this.type0 = type;
|
||||||
|
this.type1 = type2;
|
||||||
|
this.type2 = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Automatically ensures the existance of a certain node type, and prevents it from being deleted </summary>
|
||||||
|
public RequireNodeAttribute(Type type, Type type2, Type type3) {
|
||||||
|
this.type0 = type;
|
||||||
|
this.type1 = type2;
|
||||||
|
this.type2 = type3;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Requires(Type type) {
|
||||||
|
if (type == null) return false;
|
||||||
|
if (type == type0) return true;
|
||||||
|
else if (type == type1) return true;
|
||||||
|
else if (type == type2) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
28
Scripts/NodeGroup.cs
Normal file
28
Scripts/NodeGroup.cs
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using UnityEngine;
|
||||||
|
|
||||||
|
[CreateNodeMenu("Group")]
|
||||||
|
public class NodeGroup : Node {
|
||||||
|
public int width = 400;
|
||||||
|
public int height = 400;
|
||||||
|
public Color color = new Color(1f, 1f, 1f, 0.1f);
|
||||||
|
|
||||||
|
public override object GetValue(NodePort port) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Gets nodes in this group </summary>
|
||||||
|
public List<Node> GetNodes() {
|
||||||
|
List<Node> result = new List<Node>();
|
||||||
|
foreach (Node node in graph.nodes) {
|
||||||
|
if (node == this) continue;
|
||||||
|
if (node == null) continue;
|
||||||
|
if (node.position.x < this.position.x) continue;
|
||||||
|
if (node.position.y < this.position.y) continue;
|
||||||
|
if (node.position.x > this.position.x + width) continue;
|
||||||
|
if (node.position.y > this.position.y + height + 30) continue;
|
||||||
|
result.Add(node);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,422 +1,421 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
using Attributes;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
namespace XNode {
|
[Serializable]
|
||||||
[Serializable]
|
public class NodePort {
|
||||||
public class NodePort {
|
public enum IO { Input, Output }
|
||||||
public enum IO { Input, Output }
|
|
||||||
|
|
||||||
public int ConnectionCount { get { return connections.Count; } }
|
public int ConnectionCount { get { return connections.Count; } }
|
||||||
/// <summary> Return the first non-null connection </summary>
|
/// <summary> Return the first non-null connection </summary>
|
||||||
public NodePort Connection {
|
public NodePort Connection {
|
||||||
get {
|
get {
|
||||||
for (int i = 0; i < connections.Count; i++) {
|
|
||||||
if (connections[i] != null) return connections[i].Port;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public IO direction {
|
|
||||||
get { return _direction; }
|
|
||||||
internal set { _direction = value; }
|
|
||||||
}
|
|
||||||
public Node.ConnectionType connectionType {
|
|
||||||
get { return _connectionType; }
|
|
||||||
internal set { _connectionType = value; }
|
|
||||||
}
|
|
||||||
public Node.TypeConstraint typeConstraint {
|
|
||||||
get { return _typeConstraint; }
|
|
||||||
internal set { _typeConstraint = value; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Is this port connected to anytihng? </summary>
|
|
||||||
public bool IsConnected { get { return connections.Count != 0; } }
|
|
||||||
public bool IsInput { get { return direction == IO.Input; } }
|
|
||||||
public bool IsOutput { get { return direction == IO.Output; } }
|
|
||||||
|
|
||||||
public string fieldName { get { return _fieldName; } }
|
|
||||||
public Node node { get { return _node; } }
|
|
||||||
public bool IsDynamic { get { return _dynamic; } }
|
|
||||||
public bool IsStatic { get { return !_dynamic; } }
|
|
||||||
public Type ValueType {
|
|
||||||
get {
|
|
||||||
if (valueType == null && !string.IsNullOrEmpty(_typeQualifiedName)) valueType = Type.GetType(_typeQualifiedName, false);
|
|
||||||
return valueType;
|
|
||||||
}
|
|
||||||
set {
|
|
||||||
if (valueType == value) return;
|
|
||||||
valueType = value;
|
|
||||||
if (value != null) _typeQualifiedName = NodeDataCache.GetTypeQualifiedName(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private Type valueType;
|
|
||||||
|
|
||||||
[SerializeField] private string _fieldName;
|
|
||||||
[SerializeField] private Node _node;
|
|
||||||
[SerializeField] private string _typeQualifiedName;
|
|
||||||
[SerializeField] private List<PortConnection> connections = new List<PortConnection>();
|
|
||||||
[SerializeField] private IO _direction;
|
|
||||||
[SerializeField] private Node.ConnectionType _connectionType;
|
|
||||||
[SerializeField] private Node.TypeConstraint _typeConstraint;
|
|
||||||
[SerializeField] private bool _dynamic;
|
|
||||||
|
|
||||||
/// <summary> Construct a static targetless nodeport. Used as a template. </summary>
|
|
||||||
public NodePort(FieldInfo fieldInfo) {
|
|
||||||
_fieldName = fieldInfo.Name;
|
|
||||||
ValueType = fieldInfo.FieldType;
|
|
||||||
_dynamic = false;
|
|
||||||
var attribs = fieldInfo.GetCustomAttributes(false);
|
|
||||||
for (int i = 0; i < attribs.Length; i++) {
|
|
||||||
if (attribs[i] is Node.InputAttribute) {
|
|
||||||
_direction = IO.Input;
|
|
||||||
_connectionType = (attribs[i] as Node.InputAttribute).connectionType;
|
|
||||||
_typeConstraint = (attribs[i] as Node.InputAttribute).typeConstraint;
|
|
||||||
} else if (attribs[i] is Node.OutputAttribute) {
|
|
||||||
_direction = IO.Output;
|
|
||||||
_connectionType = (attribs[i] as Node.OutputAttribute).connectionType;
|
|
||||||
_typeConstraint = (attribs[i] as Node.OutputAttribute).typeConstraint;
|
|
||||||
}
|
|
||||||
// Override ValueType of the Port
|
|
||||||
if(attribs[i] is PortTypeOverrideAttribute) {
|
|
||||||
ValueType = (attribs[i] as PortTypeOverrideAttribute).type;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Copy a nodePort but assign it to another node. </summary>
|
|
||||||
public NodePort(NodePort nodePort, Node node) {
|
|
||||||
_fieldName = nodePort._fieldName;
|
|
||||||
ValueType = nodePort.valueType;
|
|
||||||
_direction = nodePort.direction;
|
|
||||||
_dynamic = nodePort._dynamic;
|
|
||||||
_connectionType = nodePort._connectionType;
|
|
||||||
_typeConstraint = nodePort._typeConstraint;
|
|
||||||
_node = node;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Construct a dynamic port. Dynamic ports are not forgotten on reimport, and is ideal for runtime-created ports. </summary>
|
|
||||||
public NodePort(string fieldName, Type type, IO direction, Node.ConnectionType connectionType, Node.TypeConstraint typeConstraint, Node node) {
|
|
||||||
_fieldName = fieldName;
|
|
||||||
this.ValueType = type;
|
|
||||||
_direction = direction;
|
|
||||||
_node = node;
|
|
||||||
_dynamic = true;
|
|
||||||
_connectionType = connectionType;
|
|
||||||
_typeConstraint = typeConstraint;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Checks all connections for invalid references, and removes them. </summary>
|
|
||||||
public void VerifyConnections() {
|
|
||||||
for (int i = connections.Count - 1; i >= 0; i--) {
|
|
||||||
if (connections[i].node != null &&
|
|
||||||
!string.IsNullOrEmpty(connections[i].fieldName) &&
|
|
||||||
connections[i].node.GetPort(connections[i].fieldName) != null)
|
|
||||||
continue;
|
|
||||||
connections.RemoveAt(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Return the output value of this node through its parent nodes GetValue override method. </summary>
|
|
||||||
/// <returns> <see cref="Node.GetValue(NodePort)"/> </returns>
|
|
||||||
public object GetOutputValue() {
|
|
||||||
if (direction == IO.Input) return null;
|
|
||||||
return node.GetValue(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Return the output value of the first connected port. Returns null if none found or invalid.</summary>
|
|
||||||
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
|
||||||
public object GetInputValue() {
|
|
||||||
NodePort connectedPort = Connection;
|
|
||||||
if (connectedPort == null) return null;
|
|
||||||
return connectedPort.GetOutputValue();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Return the output values of all connected ports. </summary>
|
|
||||||
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
|
||||||
public object[] GetInputValues() {
|
|
||||||
object[] objs = new object[ConnectionCount];
|
|
||||||
for (int i = 0; i < ConnectionCount; i++) {
|
|
||||||
NodePort connectedPort = connections[i].Port;
|
|
||||||
if (connectedPort == null) { // if we happen to find a null port, remove it and look again
|
|
||||||
connections.RemoveAt(i);
|
|
||||||
i--;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
objs[i] = connectedPort.GetOutputValue();
|
|
||||||
}
|
|
||||||
return objs;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Return the output value of the first connected port. Returns null if none found or invalid. </summary>
|
|
||||||
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
|
||||||
public T GetInputValue<T>() {
|
|
||||||
object obj = GetInputValue();
|
|
||||||
return obj is T ? (T) obj : default(T);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Return the output values of all connected ports. </summary>
|
|
||||||
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
|
||||||
public T[] GetInputValues<T>() {
|
|
||||||
object[] objs = GetInputValues();
|
|
||||||
T[] ts = new T[objs.Length];
|
|
||||||
for (int i = 0; i < objs.Length; i++) {
|
|
||||||
if (objs[i] is T) ts[i] = (T) objs[i];
|
|
||||||
}
|
|
||||||
return ts;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Return true if port is connected and has a valid input. </summary>
|
|
||||||
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
|
||||||
public bool TryGetInputValue<T>(out T value) {
|
|
||||||
object obj = GetInputValue();
|
|
||||||
if (obj is T) {
|
|
||||||
value = (T) obj;
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
value = default(T);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Return the sum of all inputs. </summary>
|
|
||||||
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
|
||||||
public float GetInputSum(float fallback) {
|
|
||||||
object[] objs = GetInputValues();
|
|
||||||
if (objs.Length == 0) return fallback;
|
|
||||||
float result = 0;
|
|
||||||
for (int i = 0; i < objs.Length; i++) {
|
|
||||||
if (objs[i] is float) result += (float) objs[i];
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Return the sum of all inputs. </summary>
|
|
||||||
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
|
||||||
public int GetInputSum(int fallback) {
|
|
||||||
object[] objs = GetInputValues();
|
|
||||||
if (objs.Length == 0) return fallback;
|
|
||||||
int result = 0;
|
|
||||||
for (int i = 0; i < objs.Length; i++) {
|
|
||||||
if (objs[i] is int) result += (int) objs[i];
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Connect this <see cref="NodePort"/> to another </summary>
|
|
||||||
/// <param name="port">The <see cref="NodePort"/> to connect to</param>
|
|
||||||
public void Connect(NodePort port) {
|
|
||||||
if (connections == null) connections = new List<PortConnection>();
|
|
||||||
if (port == null) { Debug.LogWarning("Cannot connect to null port"); return; }
|
|
||||||
if (port == this) { Debug.LogWarning("Cannot connect port to self."); return; }
|
|
||||||
if (IsConnectedTo(port)) { Debug.LogWarning("Port already connected. "); return; }
|
|
||||||
if (direction == port.direction) { Debug.LogWarning("Cannot connect two " + (direction == IO.Input ? "input" : "output") + " connections"); return; }
|
|
||||||
#if UNITY_EDITOR
|
|
||||||
UnityEditor.Undo.RecordObject(node, "Connect Port");
|
|
||||||
UnityEditor.Undo.RecordObject(port.node, "Connect Port");
|
|
||||||
#endif
|
|
||||||
if (port.connectionType == Node.ConnectionType.Override && port.ConnectionCount != 0) { port.ClearConnections(); }
|
|
||||||
if (connectionType == Node.ConnectionType.Override && ConnectionCount != 0) { ClearConnections(); }
|
|
||||||
connections.Add(new PortConnection(port));
|
|
||||||
if (port.connections == null) port.connections = new List<PortConnection>();
|
|
||||||
if (!port.IsConnectedTo(this)) port.connections.Add(new PortConnection(this));
|
|
||||||
node.OnCreateConnection(this, port);
|
|
||||||
port.node.OnCreateConnection(this, port);
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<NodePort> GetConnections() {
|
|
||||||
List<NodePort> result = new List<NodePort>();
|
|
||||||
for (int i = 0; i < connections.Count; i++) {
|
for (int i = 0; i < connections.Count; i++) {
|
||||||
NodePort port = GetConnection(i);
|
if (connections[i] != null) return connections[i].Port;
|
||||||
if (port != null) result.Add(port);
|
|
||||||
}
|
}
|
||||||
return result;
|
return null;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public NodePort GetConnection(int i) {
|
public IO direction {
|
||||||
//If the connection is broken for some reason, remove it.
|
get { return _direction; }
|
||||||
if (connections[i].node == null || string.IsNullOrEmpty(connections[i].fieldName)) {
|
internal set { _direction = value; }
|
||||||
connections.RemoveAt(i);
|
}
|
||||||
return null;
|
public Node.ConnectionType connectionType {
|
||||||
|
get { return _connectionType; }
|
||||||
|
internal set { _connectionType = value; }
|
||||||
|
}
|
||||||
|
public Node.TypeConstraint typeConstraint {
|
||||||
|
get { return _typeConstraint; }
|
||||||
|
internal set { _typeConstraint = value; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Is this port connected to anytihng? </summary>
|
||||||
|
public bool IsConnected { get { return connections.Count != 0; } }
|
||||||
|
public bool IsInput { get { return direction == IO.Input; } }
|
||||||
|
public bool IsOutput { get { return direction == IO.Output; } }
|
||||||
|
|
||||||
|
public string fieldName { get { return _fieldName; } }
|
||||||
|
public Node node { get { return _node; } }
|
||||||
|
public bool IsDynamic { get { return _dynamic; } }
|
||||||
|
public bool IsStatic { get { return !_dynamic; } }
|
||||||
|
public Type ValueType {
|
||||||
|
get {
|
||||||
|
if (valueType == null && !string.IsNullOrEmpty(_typeQualifiedName)) valueType = Type.GetType(_typeQualifiedName, false);
|
||||||
|
return valueType;
|
||||||
|
}
|
||||||
|
set {
|
||||||
|
if (valueType == value) return;
|
||||||
|
valueType = value;
|
||||||
|
if (value != null) _typeQualifiedName = NodeDataCache.GetTypeQualifiedName(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private Type valueType;
|
||||||
|
|
||||||
|
[SerializeField] private string _fieldName;
|
||||||
|
[SerializeField] private Node _node;
|
||||||
|
[SerializeField] private string _typeQualifiedName;
|
||||||
|
[SerializeField] private List<PortConnection> connections = new List<PortConnection>();
|
||||||
|
[SerializeField] private IO _direction;
|
||||||
|
[SerializeField] private Node.ConnectionType _connectionType;
|
||||||
|
[SerializeField] private Node.TypeConstraint _typeConstraint;
|
||||||
|
[SerializeField] private bool _dynamic;
|
||||||
|
|
||||||
|
/// <summary> Construct a static targetless nodeport. Used as a template. </summary>
|
||||||
|
public NodePort(FieldInfo fieldInfo) {
|
||||||
|
_fieldName = fieldInfo.Name;
|
||||||
|
ValueType = fieldInfo.FieldType;
|
||||||
|
_dynamic = false;
|
||||||
|
var attribs = fieldInfo.GetCustomAttributes(false);
|
||||||
|
for (int i = 0; i < attribs.Length; i++) {
|
||||||
|
if (attribs[i] is Node.InputAttribute) {
|
||||||
|
_direction = IO.Input;
|
||||||
|
_connectionType = (attribs[i] as Node.InputAttribute).connectionType;
|
||||||
|
_typeConstraint = (attribs[i] as Node.InputAttribute).typeConstraint;
|
||||||
|
} else if (attribs[i] is Node.OutputAttribute) {
|
||||||
|
_direction = IO.Output;
|
||||||
|
_connectionType = (attribs[i] as Node.OutputAttribute).connectionType;
|
||||||
|
_typeConstraint = (attribs[i] as Node.OutputAttribute).typeConstraint;
|
||||||
}
|
}
|
||||||
NodePort port = connections[i].node.GetPort(connections[i].fieldName);
|
// Override ValueType of the Port
|
||||||
if (port == null) {
|
if(attribs[i] is PortTypeOverrideAttribute) {
|
||||||
connections.RemoveAt(i);
|
ValueType = (attribs[i] as PortTypeOverrideAttribute).type;
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return port;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Get index of the connection connecting this and specified ports </summary>
|
|
||||||
public int GetConnectionIndex(NodePort port) {
|
|
||||||
for (int i = 0; i < ConnectionCount; i++) {
|
|
||||||
if (connections[i].Port == port) return i;
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool IsConnectedTo(NodePort port) {
|
|
||||||
for (int i = 0; i < connections.Count; i++) {
|
|
||||||
if (connections[i].Port == port) return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Returns true if this port can connect to specified port </summary>
|
|
||||||
public bool CanConnectTo(NodePort port) {
|
|
||||||
// Figure out which is input and which is output
|
|
||||||
NodePort input = null, output = null;
|
|
||||||
if (IsInput) input = this;
|
|
||||||
else output = this;
|
|
||||||
if (port.IsInput) input = port;
|
|
||||||
else output = port;
|
|
||||||
// If there isn't one of each, they can't connect
|
|
||||||
if (input == null || output == null) return false;
|
|
||||||
// Check input type constraints
|
|
||||||
if (input.typeConstraint == XNode.Node.TypeConstraint.Inherited && !input.ValueType.IsAssignableFrom(output.ValueType)) return false;
|
|
||||||
if (input.typeConstraint == XNode.Node.TypeConstraint.Strict && input.ValueType != output.ValueType) return false;
|
|
||||||
if (input.typeConstraint == XNode.Node.TypeConstraint.InheritedInverse && !output.ValueType.IsAssignableFrom(input.ValueType)) return false;
|
|
||||||
if (input.typeConstraint == XNode.Node.TypeConstraint.InheritedAny && !input.ValueType.IsAssignableFrom(output.ValueType) && !output.ValueType.IsAssignableFrom(input.ValueType)) return false;
|
|
||||||
// Check output type constraints
|
|
||||||
if (output.typeConstraint == XNode.Node.TypeConstraint.Inherited && !input.ValueType.IsAssignableFrom(output.ValueType)) return false;
|
|
||||||
if (output.typeConstraint == XNode.Node.TypeConstraint.Strict && input.ValueType != output.ValueType) return false;
|
|
||||||
if (output.typeConstraint == XNode.Node.TypeConstraint.InheritedInverse && !output.ValueType.IsAssignableFrom(input.ValueType)) return false;
|
|
||||||
if (output.typeConstraint == XNode.Node.TypeConstraint.InheritedAny && !input.ValueType.IsAssignableFrom(output.ValueType) && !output.ValueType.IsAssignableFrom(input.ValueType)) return false;
|
|
||||||
// Success
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Disconnect this port from another port </summary>
|
|
||||||
public void Disconnect(NodePort port) {
|
|
||||||
// Remove this ports connection to the other
|
|
||||||
for (int i = connections.Count - 1; i >= 0; i--) {
|
|
||||||
if (connections[i].Port == port) {
|
|
||||||
connections.RemoveAt(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (port != null) {
|
|
||||||
// Remove the other ports connection to this port
|
|
||||||
for (int i = 0; i < port.connections.Count; i++) {
|
|
||||||
if (port.connections[i].Port == this) {
|
|
||||||
port.connections.RemoveAt(i);
|
|
||||||
// Trigger OnRemoveConnection from this side port
|
|
||||||
port.node.OnRemoveConnection(port);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Trigger OnRemoveConnection
|
|
||||||
node.OnRemoveConnection(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Disconnect this port from another port </summary>
|
|
||||||
public void Disconnect(int i) {
|
|
||||||
// Remove the other ports connection to this port
|
|
||||||
NodePort otherPort = connections[i].Port;
|
|
||||||
if (otherPort != null) {
|
|
||||||
otherPort.connections.RemoveAll(it => { return it.Port == this; });
|
|
||||||
}
|
|
||||||
// Remove this ports connection to the other
|
|
||||||
connections.RemoveAt(i);
|
|
||||||
|
|
||||||
// Trigger OnRemoveConnection
|
|
||||||
node.OnRemoveConnection(this);
|
|
||||||
if (otherPort != null) otherPort.node.OnRemoveConnection(otherPort);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void ClearConnections() {
|
|
||||||
while (connections.Count > 0) {
|
|
||||||
Disconnect(connections[0].Port);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Get reroute points for a given connection. This is used for organization </summary>
|
|
||||||
public List<Vector2> GetReroutePoints(int index) {
|
|
||||||
return connections[index].reroutePoints;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Swap connections with another node </summary>
|
|
||||||
public void SwapConnections(NodePort targetPort) {
|
|
||||||
int aConnectionCount = connections.Count;
|
|
||||||
int bConnectionCount = targetPort.connections.Count;
|
|
||||||
|
|
||||||
List<NodePort> portConnections = new List<NodePort>();
|
|
||||||
List<NodePort> targetPortConnections = new List<NodePort>();
|
|
||||||
|
|
||||||
// Cache port connections
|
|
||||||
for (int i = 0; i < aConnectionCount; i++)
|
|
||||||
portConnections.Add(connections[i].Port);
|
|
||||||
|
|
||||||
// Cache target port connections
|
|
||||||
for (int i = 0; i < bConnectionCount; i++)
|
|
||||||
targetPortConnections.Add(targetPort.connections[i].Port);
|
|
||||||
|
|
||||||
ClearConnections();
|
|
||||||
targetPort.ClearConnections();
|
|
||||||
|
|
||||||
// Add port connections to targetPort
|
|
||||||
for (int i = 0; i < portConnections.Count; i++)
|
|
||||||
targetPort.Connect(portConnections[i]);
|
|
||||||
|
|
||||||
// Add target port connections to this one
|
|
||||||
for (int i = 0; i < targetPortConnections.Count; i++)
|
|
||||||
Connect(targetPortConnections[i]);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Copy all connections pointing to a node and add them to this one </summary>
|
|
||||||
public void AddConnections(NodePort targetPort) {
|
|
||||||
int connectionCount = targetPort.ConnectionCount;
|
|
||||||
for (int i = 0; i < connectionCount; i++) {
|
|
||||||
PortConnection connection = targetPort.connections[i];
|
|
||||||
NodePort otherPort = connection.Port;
|
|
||||||
Connect(otherPort);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Move all connections pointing to this node, to another node </summary>
|
|
||||||
public void MoveConnections(NodePort targetPort) {
|
|
||||||
int connectionCount = connections.Count;
|
|
||||||
|
|
||||||
// Add connections to target port
|
|
||||||
for (int i = 0; i < connectionCount; i++) {
|
|
||||||
PortConnection connection = targetPort.connections[i];
|
|
||||||
NodePort otherPort = connection.Port;
|
|
||||||
Connect(otherPort);
|
|
||||||
}
|
|
||||||
ClearConnections();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Swap connected nodes from the old list with nodes from the new list </summary>
|
|
||||||
public void Redirect(List<Node> oldNodes, List<Node> newNodes) {
|
|
||||||
foreach (PortConnection connection in connections) {
|
|
||||||
int index = oldNodes.IndexOf(connection.node);
|
|
||||||
if (index >= 0) connection.node = newNodes[index];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Serializable]
|
|
||||||
private class PortConnection {
|
|
||||||
[SerializeField] public string fieldName;
|
|
||||||
[SerializeField] public Node node;
|
|
||||||
public NodePort Port { get { return port != null ? port : port = GetPort(); } }
|
|
||||||
|
|
||||||
[NonSerialized] private NodePort port;
|
|
||||||
/// <summary> Extra connection path points for organization </summary>
|
|
||||||
[SerializeField] public List<Vector2> reroutePoints = new List<Vector2>();
|
|
||||||
|
|
||||||
public PortConnection(NodePort port) {
|
|
||||||
this.port = port;
|
|
||||||
node = port.node;
|
|
||||||
fieldName = port.fieldName;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Returns the port that this <see cref="PortConnection"/> points to </summary>
|
|
||||||
private NodePort GetPort() {
|
|
||||||
if (node == null || string.IsNullOrEmpty(fieldName)) return null;
|
|
||||||
return node.GetPort(fieldName);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
/// <summary> Copy a nodePort but assign it to another node. </summary>
|
||||||
|
public NodePort(NodePort nodePort, Node node) {
|
||||||
|
_fieldName = nodePort._fieldName;
|
||||||
|
ValueType = nodePort.valueType;
|
||||||
|
_direction = nodePort.direction;
|
||||||
|
_dynamic = nodePort._dynamic;
|
||||||
|
_connectionType = nodePort._connectionType;
|
||||||
|
_typeConstraint = nodePort._typeConstraint;
|
||||||
|
_node = node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Construct a dynamic port. Dynamic ports are not forgotten on reimport, and is ideal for runtime-created ports. </summary>
|
||||||
|
public NodePort(string fieldName, Type type, IO direction, Node.ConnectionType connectionType, Node.TypeConstraint typeConstraint, Node node) {
|
||||||
|
_fieldName = fieldName;
|
||||||
|
this.ValueType = type;
|
||||||
|
_direction = direction;
|
||||||
|
_node = node;
|
||||||
|
_dynamic = true;
|
||||||
|
_connectionType = connectionType;
|
||||||
|
_typeConstraint = typeConstraint;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Checks all connections for invalid references, and removes them. </summary>
|
||||||
|
public void VerifyConnections() {
|
||||||
|
for (int i = connections.Count - 1; i >= 0; i--) {
|
||||||
|
if (connections[i].node != null &&
|
||||||
|
!string.IsNullOrEmpty(connections[i].fieldName) &&
|
||||||
|
connections[i].node.GetPort(connections[i].fieldName) != null)
|
||||||
|
continue;
|
||||||
|
connections.RemoveAt(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Return the output value of this node through its parent nodes GetValue override method. </summary>
|
||||||
|
/// <returns> <see cref="Node.GetValue(NodePort)"/> </returns>
|
||||||
|
public object GetOutputValue() {
|
||||||
|
if (direction == IO.Input) return null;
|
||||||
|
return node.GetValue(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Return the output value of the first connected port. Returns null if none found or invalid.</summary>
|
||||||
|
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
||||||
|
public object GetInputValue() {
|
||||||
|
NodePort connectedPort = Connection;
|
||||||
|
if (connectedPort == null) return null;
|
||||||
|
return connectedPort.GetOutputValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Return the output values of all connected ports. </summary>
|
||||||
|
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
||||||
|
public object[] GetInputValues() {
|
||||||
|
object[] objs = new object[ConnectionCount];
|
||||||
|
for (int i = 0; i < ConnectionCount; i++) {
|
||||||
|
NodePort connectedPort = connections[i].Port;
|
||||||
|
if (connectedPort == null) { // if we happen to find a null port, remove it and look again
|
||||||
|
connections.RemoveAt(i);
|
||||||
|
i--;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
objs[i] = connectedPort.GetOutputValue();
|
||||||
|
}
|
||||||
|
return objs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Return the output value of the first connected port. Returns null if none found or invalid. </summary>
|
||||||
|
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
||||||
|
public T GetInputValue<T>() {
|
||||||
|
object obj = GetInputValue();
|
||||||
|
return obj is T ? (T) obj : default(T);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Return the output values of all connected ports. </summary>
|
||||||
|
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
||||||
|
public T[] GetInputValues<T>() {
|
||||||
|
object[] objs = GetInputValues();
|
||||||
|
T[] ts = new T[objs.Length];
|
||||||
|
for (int i = 0; i < objs.Length; i++) {
|
||||||
|
if (objs[i] is T) ts[i] = (T) objs[i];
|
||||||
|
}
|
||||||
|
return ts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Return true if port is connected and has a valid input. </summary>
|
||||||
|
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
||||||
|
public bool TryGetInputValue<T>(out T value) {
|
||||||
|
object obj = GetInputValue();
|
||||||
|
if (obj is T) {
|
||||||
|
value = (T) obj;
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
value = default(T);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Return the sum of all inputs. </summary>
|
||||||
|
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
||||||
|
public float GetInputSum(float fallback) {
|
||||||
|
object[] objs = GetInputValues();
|
||||||
|
if (objs.Length == 0) return fallback;
|
||||||
|
float result = 0;
|
||||||
|
for (int i = 0; i < objs.Length; i++) {
|
||||||
|
if (objs[i] is float) result += (float) objs[i];
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Return the sum of all inputs. </summary>
|
||||||
|
/// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
|
||||||
|
public int GetInputSum(int fallback) {
|
||||||
|
object[] objs = GetInputValues();
|
||||||
|
if (objs.Length == 0) return fallback;
|
||||||
|
int result = 0;
|
||||||
|
for (int i = 0; i < objs.Length; i++) {
|
||||||
|
if (objs[i] is int) result += (int) objs[i];
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Connect this <see cref="NodePort"/> to another </summary>
|
||||||
|
/// <param name="port">The <see cref="NodePort"/> to connect to</param>
|
||||||
|
public void Connect(NodePort port) {
|
||||||
|
if (connections == null) connections = new List<PortConnection>();
|
||||||
|
if (port == null) { Debug.LogWarning("Cannot connect to null port"); return; }
|
||||||
|
if (port == this) { Debug.LogWarning("Cannot connect port to self."); return; }
|
||||||
|
if (IsConnectedTo(port)) { Debug.LogWarning("Port already connected. "); return; }
|
||||||
|
if (direction == port.direction) { Debug.LogWarning("Cannot connect two " + (direction == IO.Input ? "input" : "output") + " connections"); return; }
|
||||||
|
#if UNITY_EDITOR
|
||||||
|
UnityEditor.Undo.RecordObject(node, "Connect Port");
|
||||||
|
UnityEditor.Undo.RecordObject(port.node, "Connect Port");
|
||||||
|
#endif
|
||||||
|
if (port.connectionType == Node.ConnectionType.Override && port.ConnectionCount != 0) { port.ClearConnections(); }
|
||||||
|
if (connectionType == Node.ConnectionType.Override && ConnectionCount != 0) { ClearConnections(); }
|
||||||
|
connections.Add(new PortConnection(port));
|
||||||
|
if (port.connections == null) port.connections = new List<PortConnection>();
|
||||||
|
if (!port.IsConnectedTo(this)) port.connections.Add(new PortConnection(this));
|
||||||
|
node.OnCreateConnection(this, port);
|
||||||
|
port.node.OnCreateConnection(this, port);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<NodePort> GetConnections() {
|
||||||
|
List<NodePort> result = new List<NodePort>();
|
||||||
|
for (int i = 0; i < connections.Count; i++) {
|
||||||
|
NodePort port = GetConnection(i);
|
||||||
|
if (port != null) result.Add(port);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public NodePort GetConnection(int i) {
|
||||||
|
//If the connection is broken for some reason, remove it.
|
||||||
|
if (connections[i].node == null || string.IsNullOrEmpty(connections[i].fieldName)) {
|
||||||
|
connections.RemoveAt(i);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
NodePort port = connections[i].node.GetPort(connections[i].fieldName);
|
||||||
|
if (port == null) {
|
||||||
|
connections.RemoveAt(i);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Get index of the connection connecting this and specified ports </summary>
|
||||||
|
public int GetConnectionIndex(NodePort port) {
|
||||||
|
for (int i = 0; i < ConnectionCount; i++) {
|
||||||
|
if (connections[i].Port == port) return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsConnectedTo(NodePort port) {
|
||||||
|
for (int i = 0; i < connections.Count; i++) {
|
||||||
|
if (connections[i].Port == port) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Returns true if this port can connect to specified port </summary>
|
||||||
|
public bool CanConnectTo(NodePort port) {
|
||||||
|
// Figure out which is input and which is output
|
||||||
|
NodePort input = null, output = null;
|
||||||
|
if (IsInput) input = this;
|
||||||
|
else output = this;
|
||||||
|
if (port.IsInput) input = port;
|
||||||
|
else output = port;
|
||||||
|
// If there isn't one of each, they can't connect
|
||||||
|
if (input == null || output == null) return false;
|
||||||
|
// Check input type constraints
|
||||||
|
if (input.typeConstraint == Node.TypeConstraint.Inherited && !input.ValueType.IsAssignableFrom(output.ValueType)) return false;
|
||||||
|
if (input.typeConstraint == Node.TypeConstraint.Strict && input.ValueType != output.ValueType) return false;
|
||||||
|
if (input.typeConstraint == Node.TypeConstraint.InheritedInverse && !output.ValueType.IsAssignableFrom(input.ValueType)) return false;
|
||||||
|
if (input.typeConstraint == Node.TypeConstraint.InheritedAny && !input.ValueType.IsAssignableFrom(output.ValueType) && !output.ValueType.IsAssignableFrom(input.ValueType)) return false;
|
||||||
|
// Check output type constraints
|
||||||
|
if (output.typeConstraint == Node.TypeConstraint.Inherited && !input.ValueType.IsAssignableFrom(output.ValueType)) return false;
|
||||||
|
if (output.typeConstraint == Node.TypeConstraint.Strict && input.ValueType != output.ValueType) return false;
|
||||||
|
if (output.typeConstraint == Node.TypeConstraint.InheritedInverse && !output.ValueType.IsAssignableFrom(input.ValueType)) return false;
|
||||||
|
if (output.typeConstraint == Node.TypeConstraint.InheritedAny && !input.ValueType.IsAssignableFrom(output.ValueType) && !output.ValueType.IsAssignableFrom(input.ValueType)) return false;
|
||||||
|
// Success
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Disconnect this port from another port </summary>
|
||||||
|
public void Disconnect(NodePort port) {
|
||||||
|
// Remove this ports connection to the other
|
||||||
|
for (int i = connections.Count - 1; i >= 0; i--) {
|
||||||
|
if (connections[i].Port == port) {
|
||||||
|
connections.RemoveAt(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (port != null) {
|
||||||
|
// Remove the other ports connection to this port
|
||||||
|
for (int i = 0; i < port.connections.Count; i++) {
|
||||||
|
if (port.connections[i].Port == this) {
|
||||||
|
port.connections.RemoveAt(i);
|
||||||
|
// Trigger OnRemoveConnection from this side port
|
||||||
|
port.node.OnRemoveConnection(port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Trigger OnRemoveConnection
|
||||||
|
node.OnRemoveConnection(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Disconnect this port from another port </summary>
|
||||||
|
public void Disconnect(int i) {
|
||||||
|
// Remove the other ports connection to this port
|
||||||
|
NodePort otherPort = connections[i].Port;
|
||||||
|
if (otherPort != null) {
|
||||||
|
otherPort.connections.RemoveAll(it => { return it.Port == this; });
|
||||||
|
}
|
||||||
|
// Remove this ports connection to the other
|
||||||
|
connections.RemoveAt(i);
|
||||||
|
|
||||||
|
// Trigger OnRemoveConnection
|
||||||
|
node.OnRemoveConnection(this);
|
||||||
|
if (otherPort != null) otherPort.node.OnRemoveConnection(otherPort);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ClearConnections() {
|
||||||
|
while (connections.Count > 0) {
|
||||||
|
Disconnect(connections[0].Port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Get reroute points for a given connection. This is used for organization </summary>
|
||||||
|
public List<Vector2> GetReroutePoints(int index) {
|
||||||
|
return connections[index].reroutePoints;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Swap connections with another node </summary>
|
||||||
|
public void SwapConnections(NodePort targetPort) {
|
||||||
|
int aConnectionCount = connections.Count;
|
||||||
|
int bConnectionCount = targetPort.connections.Count;
|
||||||
|
|
||||||
|
List<NodePort> portConnections = new List<NodePort>();
|
||||||
|
List<NodePort> targetPortConnections = new List<NodePort>();
|
||||||
|
|
||||||
|
// Cache port connections
|
||||||
|
for (int i = 0; i < aConnectionCount; i++)
|
||||||
|
portConnections.Add(connections[i].Port);
|
||||||
|
|
||||||
|
// Cache target port connections
|
||||||
|
for (int i = 0; i < bConnectionCount; i++)
|
||||||
|
targetPortConnections.Add(targetPort.connections[i].Port);
|
||||||
|
|
||||||
|
ClearConnections();
|
||||||
|
targetPort.ClearConnections();
|
||||||
|
|
||||||
|
// Add port connections to targetPort
|
||||||
|
for (int i = 0; i < portConnections.Count; i++)
|
||||||
|
targetPort.Connect(portConnections[i]);
|
||||||
|
|
||||||
|
// Add target port connections to this one
|
||||||
|
for (int i = 0; i < targetPortConnections.Count; i++)
|
||||||
|
Connect(targetPortConnections[i]);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Copy all connections pointing to a node and add them to this one </summary>
|
||||||
|
public void AddConnections(NodePort targetPort) {
|
||||||
|
int connectionCount = targetPort.ConnectionCount;
|
||||||
|
for (int i = 0; i < connectionCount; i++) {
|
||||||
|
PortConnection connection = targetPort.connections[i];
|
||||||
|
NodePort otherPort = connection.Port;
|
||||||
|
Connect(otherPort);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Move all connections pointing to this node, to another node </summary>
|
||||||
|
public void MoveConnections(NodePort targetPort) {
|
||||||
|
int connectionCount = connections.Count;
|
||||||
|
|
||||||
|
// Add connections to target port
|
||||||
|
for (int i = 0; i < connectionCount; i++) {
|
||||||
|
PortConnection connection = targetPort.connections[i];
|
||||||
|
NodePort otherPort = connection.Port;
|
||||||
|
Connect(otherPort);
|
||||||
|
}
|
||||||
|
ClearConnections();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Swap connected nodes from the old list with nodes from the new list </summary>
|
||||||
|
public void Redirect(List<Node> oldNodes, List<Node> newNodes) {
|
||||||
|
foreach (PortConnection connection in connections) {
|
||||||
|
int index = oldNodes.IndexOf(connection.node);
|
||||||
|
if (index >= 0) connection.node = newNodes[index];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Serializable]
|
||||||
|
private class PortConnection {
|
||||||
|
[SerializeField] public string fieldName;
|
||||||
|
[SerializeField] public Node node;
|
||||||
|
public NodePort Port { get { return port != null ? port : port = GetPort(); } }
|
||||||
|
|
||||||
|
[NonSerialized] private NodePort port;
|
||||||
|
/// <summary> Extra connection path points for organization </summary>
|
||||||
|
[SerializeField] public List<Vector2> reroutePoints = new List<Vector2>();
|
||||||
|
|
||||||
|
public PortConnection(NodePort port) {
|
||||||
|
this.port = port;
|
||||||
|
node = port.node;
|
||||||
|
fieldName = port.fieldName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary> Returns the port that this <see cref="PortConnection"/> points to </summary>
|
||||||
|
private NodePort GetPort() {
|
||||||
|
if (node == null || string.IsNullOrEmpty(fieldName)) return null;
|
||||||
|
return node.GetPort(fieldName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,23 +1,18 @@
|
|||||||
using System.Collections;
|
using UnityEngine;
|
||||||
using System.Collections.Generic;
|
|
||||||
using UnityEngine;
|
|
||||||
using XNode;
|
|
||||||
|
|
||||||
namespace XNode {
|
/// <summary> Lets you instantiate a node graph in the scene. This allows you to reference in-scene objects. </summary>
|
||||||
/// <summary> Lets you instantiate a node graph in the scene. This allows you to reference in-scene objects. </summary>
|
public class SceneGraph : MonoBehaviour {
|
||||||
public class SceneGraph : MonoBehaviour {
|
public NodeGraph graph;
|
||||||
public NodeGraph graph;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary> Derive from this class to create a SceneGraph with a specific graph type. </summary>
|
/// <summary> Derive from this class to create a SceneGraph with a specific graph type. </summary>
|
||||||
/// <example>
|
/// <example>
|
||||||
/// <code>
|
/// <code>
|
||||||
/// public class MySceneGraph : SceneGraph<MyGraph> {
|
/// public class MySceneGraph : SceneGraph<MyGraph> {
|
||||||
///
|
///
|
||||||
/// }
|
/// }
|
||||||
/// </code>
|
/// </code>
|
||||||
/// </example>
|
/// </example>
|
||||||
public class SceneGraph<T> : SceneGraph where T : NodeGraph {
|
public class SceneGraph<T> : SceneGraph where T : NodeGraph {
|
||||||
public new T graph { get { return base.graph as T; } set { base.graph = value; } }
|
public new T graph { get { return base.graph as T; } set { base.graph = value; } }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user