From fc0f1983e0ac629bfdad8f94b256487681c7d105 Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Wed, 19 Sep 2018 09:04:58 +0200 Subject: [PATCH 01/73] Suggestion, better looking buttons for InstancePortList --- Scripts/Editor/NodeEditorGUILayout.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 3a90e36..4740819 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -220,7 +220,7 @@ namespace XNodeEditor { for (int i = 0; i < instancePorts.Count(); i++) { GUILayout.BeginHorizontal(); // 'Remove' button - if (GUILayout.Button("-", GUILayout.Width(20))) { + if (GUILayout.Button("-", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { // Clear the removed ports connections instancePorts[i].ClearConnections(); // Move following connections one step up to replace the missing connection @@ -270,7 +270,7 @@ namespace XNodeEditor { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); // 'Add' button - if (GUILayout.Button("+", GUILayout.Width(20))) { + if (GUILayout.Button("+", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { string newName = fieldName + " 0"; int i = 0; From 7ee89ba79c4ba9fad7a5272d71bd65480203700f Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Wed, 19 Sep 2018 23:17:08 +0200 Subject: [PATCH 02/73] Added instancePortList field to Input and Output attributes. --- Scripts/Editor/NodeEditorGUILayout.cs | 32 ++++++++++++++++++++++++--- Scripts/Node.cs | 6 +++-- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 4740819..d0bdc11 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -41,8 +41,18 @@ namespace XNodeEditor { // Get data from [Input] attribute XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected; XNode.Node.InputAttribute inputAttribute; - if (NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out inputAttribute)) showBacking = inputAttribute.backingValue; + bool instancePortList = false; + if (NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out inputAttribute)) { + instancePortList = inputAttribute.instancePortList; + showBacking = inputAttribute.backingValue; + } + if (instancePortList) { + Type type = GetType(property); + XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; + InstancePortList(property.name, type, property.serializedObject, port.direction, connectionType); + return; + } switch (showBacking) { case XNode.Node.ShowBackingValue.Unconnected: // Display a label if port is connected @@ -67,8 +77,18 @@ namespace XNodeEditor { // Get data from [Output] attribute XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected; XNode.Node.OutputAttribute outputAttribute; - if (NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out outputAttribute)) showBacking = outputAttribute.backingValue; + bool instancePortList = false; + if (NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out outputAttribute)) { + instancePortList = outputAttribute.instancePortList; + showBacking = outputAttribute.backingValue; + } + if (instancePortList) { + Type type = GetType(property); + XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; + InstancePortList(property.name, type, property.serializedObject, port.direction, connectionType); + return; + } switch (showBacking) { case XNode.Node.ShowBackingValue.Unconnected: // Display a label if port is connected @@ -105,6 +125,12 @@ namespace XNodeEditor { } } + private static System.Type GetType(SerializedProperty property) { + System.Type parentType = property.serializedObject.targetObject.GetType(); + System.Reflection.FieldInfo fi = parentType.GetField(property.propertyPath); + return fi.FieldType; + } + /// Make a simple port field. public static void PortField(XNode.NodePort port, params GUILayoutOption[] options) { PortField(null, port, options); @@ -259,7 +285,7 @@ namespace XNodeEditor { } else EditorGUILayout.LabelField("[Out of bounds]"); } else { - EditorGUILayout.LabelField(instancePorts[i].fieldName); + EditorGUILayout.LabelField(ObjectNames.NicifyVariableName(instancePorts[i].fieldName)); } GUILayout.EndHorizontal(); diff --git a/Scripts/Node.cs b/Scripts/Node.cs index 90b65e3..5179c32 100644 --- a/Scripts/Node.cs +++ b/Scripts/Node.cs @@ -212,11 +212,12 @@ namespace XNode { public class InputAttribute : Attribute { public ShowBackingValue backingValue; public ConnectionType connectionType; + public bool instancePortList; /// Mark a serializable field as an input port. You can access this through /// Should we display the backing value for this port as an editor field? /// Should we allow multiple connections? - public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnected, ConnectionType connectionType = ConnectionType.Multiple) { + public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnected, ConnectionType connectionType = ConnectionType.Multiple, bool instancePortList = false) { this.backingValue = backingValue; this.connectionType = connectionType; } @@ -227,11 +228,12 @@ namespace XNode { public class OutputAttribute : Attribute { public ShowBackingValue backingValue; public ConnectionType connectionType; + public bool instancePortList; /// Mark a serializable field as an output port. You can access this through /// Should we display the backing value for this port as an editor field? /// Should we allow multiple connections? - public OutputAttribute(ShowBackingValue backingValue = ShowBackingValue.Never, ConnectionType connectionType = ConnectionType.Multiple) { + public OutputAttribute(ShowBackingValue backingValue = ShowBackingValue.Never, ConnectionType connectionType = ConnectionType.Multiple, bool instancePortList = false) { this.backingValue = backingValue; this.connectionType = connectionType; } From 98edbf0c80abc37dd52246af6e09df4154b3bfc3 Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Sat, 22 Sep 2018 11:09:08 +0200 Subject: [PATCH 03/73] Added label before drawing InstancePortList --- Scripts/Editor/NodeEditorGUILayout.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index d0bdc11..301654a 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -50,6 +50,7 @@ namespace XNodeEditor { if (instancePortList) { Type type = GetType(property); XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; + EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName)); InstancePortList(property.name, type, property.serializedObject, port.direction, connectionType); return; } @@ -86,6 +87,7 @@ namespace XNodeEditor { if (instancePortList) { Type type = GetType(property); XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; + EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName)); InstancePortList(property.name, type, property.serializedObject, port.direction, connectionType); return; } From 58d32bfd85de6dd86ee0a32e46cee894b3bbb1ee Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Thu, 27 Sep 2018 21:54:10 +0200 Subject: [PATCH 04/73] OSX does not dispatch SoftDelete (tested on mbp no external keyboard), only Delete. --- Scripts/Editor/NodeEditorAction.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index 9682d17..404b8af 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -279,6 +279,7 @@ namespace XNodeEditor { break; case EventType.ValidateCommand: if (e.commandName == "SoftDelete") RemoveSelectedNodes(); + else if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX && e.commandName == "Delete") RemoveSelectedNodes(); else if (e.commandName == "Duplicate") DublicateSelectedNodes(); Repaint(); break; From 9fe26b29486f7253afe46c4daee25342bf7fc479 Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Wed, 3 Oct 2018 22:20:26 +0200 Subject: [PATCH 05/73] missing assignments in OutputAttribute and InputAttribute --- Scripts/Node.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Scripts/Node.cs b/Scripts/Node.cs index 5179c32..ac62fd6 100644 --- a/Scripts/Node.cs +++ b/Scripts/Node.cs @@ -220,6 +220,7 @@ namespace XNode { public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnected, ConnectionType connectionType = ConnectionType.Multiple, bool instancePortList = false) { this.backingValue = backingValue; this.connectionType = connectionType; + this.instancePortList = instancePortList; } } @@ -236,6 +237,7 @@ namespace XNode { public OutputAttribute(ShowBackingValue backingValue = ShowBackingValue.Never, ConnectionType connectionType = ConnectionType.Multiple, bool instancePortList = false) { this.backingValue = backingValue; this.connectionType = connectionType; + this.instancePortList = instancePortList; } } From f5856f79119514a9d5799eec78b9573c70599bec Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 6 Oct 2018 01:34:34 +0200 Subject: [PATCH 06/73] Fixed #66 Minor bug with noodle --- Scripts/Editor/NodeEditorGUI.cs | 15 ++++++++------- Scripts/Editor/NodeEditorReflection.cs | 12 ++++++++++++ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUI.cs b/Scripts/Editor/NodeEditorGUI.cs index 0cfec5b..9c77033 100644 --- a/Scripts/Editor/NodeEditorGUI.cs +++ b/Scripts/Editor/NodeEditorGUI.cs @@ -10,6 +10,7 @@ namespace XNodeEditor { public NodeGraphEditor graphEditor; private List selectionCache; private List culledNodes; + private int topPadding { get { return isDocked() ? 19 : 22; } } private void OnGUI() { Event e = Event.current; @@ -31,22 +32,22 @@ namespace XNodeEditor { GUI.matrix = m; } - public static void BeginZoomed(Rect rect, float zoom) { + public static void BeginZoomed(Rect rect, float zoom, float topPadding) { GUI.EndClip(); GUIUtility.ScaleAroundPivot(Vector2.one / zoom, rect.size * 0.5f); - Vector4 padding = new Vector4(0, 22, 0, 0); + Vector4 padding = new Vector4(0, topPadding, 0, 0); padding *= zoom; - GUI.BeginClip(new Rect(-((rect.width * zoom) - rect.width) * 0.5f, -(((rect.height * zoom) - rect.height) * 0.5f) + (22 * zoom), + GUI.BeginClip(new Rect(-((rect.width * zoom) - rect.width) * 0.5f, -(((rect.height * zoom) - rect.height) * 0.5f) + (topPadding * zoom), rect.width * zoom, rect.height * zoom)); } - public static void EndZoomed(Rect rect, float zoom) { + public static void EndZoomed(Rect rect, float zoom, float topPadding) { GUIUtility.ScaleAroundPivot(Vector2.one * zoom, rect.size * 0.5f); Vector3 offset = new Vector3( (((rect.width * zoom) - rect.width) * 0.5f), - (((rect.height * zoom) - rect.height) * 0.5f) + (-22 * zoom) + 22, + (((rect.height * zoom) - rect.height) * 0.5f) + (-topPadding * zoom) + topPadding, 0); GUI.matrix = Matrix4x4.TRS(offset, Quaternion.identity, Vector3.one); } @@ -294,7 +295,7 @@ namespace XNodeEditor { if (onValidate != null) nodeHash = Selection.activeObject.GetHashCode(); } - BeginZoomed(position, zoom); + BeginZoomed(position, zoom, topPadding); Vector2 mousePos = Event.current.mousePosition; @@ -425,7 +426,7 @@ namespace XNodeEditor { } if (e.type != EventType.Layout && currentActivity == NodeActivity.DragGrid) Selection.objects = preSelection.ToArray(); - EndZoomed(position, zoom); + EndZoomed(position, zoom, topPadding); //If a change in hash is detected in the selected node, call OnValidate method. //This is done through reflection because OnValidate is only relevant in editor, diff --git a/Scripts/Editor/NodeEditorReflection.cs b/Scripts/Editor/NodeEditorReflection.cs index 7eaec2b..171f3b3 100644 --- a/Scripts/Editor/NodeEditorReflection.cs +++ b/Scripts/Editor/NodeEditorReflection.cs @@ -22,6 +22,18 @@ namespace XNodeEditor { [NonSerialized] private static Type[] _nodeTypes = null; + private Func isDocked { + get { + if (_isDocked == null) { + BindingFlags fullBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; + MethodInfo isDockedMethod = typeof(NodeEditorWindow).GetProperty("docked", fullBinding).GetGetMethod(true); + _isDocked = (Func) Delegate.CreateDelegate(typeof(Func), this, isDockedMethod); + } + return _isDocked; + } + } + private Func _isDocked; + public static Type[] GetNodeTypes() { //Get all classes deriving from Node via reflection return GetDerivedTypes(typeof(XNode.Node)); From 671481f3b1c979dce747b2bc5819b2ab639cca2f Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sun, 14 Oct 2018 19:04:13 +0200 Subject: [PATCH 07/73] Begun working on ReorderableLists --- Scripts/Editor/NodeEditorGUILayout.cs | 31 +++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 301654a..1886295 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -3,12 +3,15 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEditor; +using UnityEditorInternal; using UnityEngine; namespace XNodeEditor { /// xNode-specific version of public static class NodeEditorGUILayout { + private static readonly Dictionary> reorderableListCache = new Dictionary>(); + /// Make a field for a serialized property. Automatically displays relevant node port. public static void PropertyField(SerializedProperty property, bool includeChildren = true, params GUILayoutOption[] options) { PropertyField(property, (GUIContent) null, includeChildren, options); @@ -245,6 +248,34 @@ namespace XNodeEditor { }; List instancePorts = node.InstancePorts.Where(x => isMatchingInstancePort(x.fieldName)).OrderBy(x => x.fieldName).ToList(); + ReorderableList list = null; + Dictionary rlc; + if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) { + if (!rlc.TryGetValue(fieldName, out list)) list = null; + } + if (list == null) { + Debug.Log("Create List"); + list = new ReorderableList(instancePorts, null, true, true, true, true); + if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list); + else reorderableListCache.Add(serializedObject.targetObject, new Dictionary() { { fieldName, list } }); + list.drawElementCallback = + (Rect rect, int index, bool isActive, bool isFocused) => { + XNode.NodePort port = list.list[index] as XNode.NodePort; + //SerializedProperty element = serializedObject.get(index); + if (hasArrayData) { + SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); + EditorGUI.PropertyField(rect, itemData); + } else EditorGUI.LabelField(rect, port.fieldName); + NodeEditorGUILayout.PortField(node.GetPort(instancePorts[index].fieldName)); + }; + list.onReorderCallback = + (ReorderableList rl) => { + + }; + } + list.list = instancePorts; + list.DoLayoutList(); + for (int i = 0; i < instancePorts.Count(); i++) { GUILayout.BeginHorizontal(); // 'Remove' button From 45162932145ba64e89c52828ec19b1a8adbfe9ff Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Thu, 18 Oct 2018 10:07:48 +0200 Subject: [PATCH 08/73] Implemented add, remove. Reordering WIP --- Scripts/Editor/NodeEditorGUILayout.cs | 154 +++++++++++++------------- Scripts/NodePort.cs | 6 + 2 files changed, 80 insertions(+), 80 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 1886295..e47921c 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -53,7 +53,6 @@ namespace XNodeEditor { if (instancePortList) { Type type = GetType(property); XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; - EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName)); InstancePortList(property.name, type, property.serializedObject, port.direction, connectionType); return; } @@ -90,7 +89,6 @@ namespace XNodeEditor { if (instancePortList) { Type type = GetType(property); XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; - EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName)); InstancePortList(property.name, type, property.serializedObject, port.direction, connectionType); return; } @@ -145,7 +143,7 @@ namespace XNodeEditor { public static void PortField(GUIContent label, XNode.NodePort port, params GUILayoutOption[] options) { if (port == null) return; if (options == null) options = new GUILayoutOption[] { GUILayout.MinWidth(30) }; - Rect rect = new Rect(); + Vector2 position = Vector3.zero; 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 @@ -153,18 +151,26 @@ namespace XNodeEditor { // Display a label EditorGUILayout.LabelField(content, options); - rect = GUILayoutUtility.GetLastRect(); - rect.position = rect.position - new Vector2(16, 0); - // 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) { + Rect rect = GUILayoutUtility.GetLastRect(); + position = rect.position - new Vector2(16, 0); + + } + // 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) { // Display a label EditorGUILayout.LabelField(content, NodeEditorResources.OutputPort, options); - rect = GUILayoutUtility.GetLastRect(); - rect.position = rect.position + new Vector2(rect.width, 0); + Rect rect = GUILayoutUtility.GetLastRect(); + position = rect.position + new Vector2(rect.width, 0); } + PortField(position, port); + } - rect.size = new Vector2(16, 16); + /// Make a simple port field. + public static void PortField(Vector2 position, XNode.NodePort port) { + if (port == null) return; + + Rect rect = new Rect(position, new Vector2(16, 16)); Color backgroundColor = new Color32(90, 97, 105, 255); Color tint; @@ -254,7 +260,6 @@ namespace XNodeEditor { if (!rlc.TryGetValue(fieldName, out list)) list = null; } if (list == null) { - Debug.Log("Create List"); list = new ReorderableList(instancePorts, null, true, true, true, true); if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list); else reorderableListCache.Add(serializedObject.targetObject, new Dictionary() { { fieldName, list } }); @@ -266,83 +271,72 @@ namespace XNodeEditor { SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); EditorGUI.PropertyField(rect, itemData); } else EditorGUI.LabelField(rect, port.fieldName); - NodeEditorGUILayout.PortField(node.GetPort(instancePorts[index].fieldName)); + Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); + NodeEditorGUILayout.PortField(pos, node.GetPort(instancePorts[index].fieldName)); + }; + list.drawHeaderCallback = + (Rect rect) => { + EditorGUI.LabelField(rect, serializedObject.FindProperty(fieldName).displayName); }; list.onReorderCallback = (ReorderableList rl) => { + for (int i = 0; i < rl.list.Count; i++) { + XNode.NodePort port = rl.list[i] as XNode.NodePort; + string[] name = port.fieldName.Split(' '); + int newIndex = int.Parse(name[1]); + if (i != newIndex) { + //port.Rename(name[0] + " " + i); + Debug.Log("Switch " + i + " and " + newIndex + "!"); + } + } + }; + list.onAddCallback = + (ReorderableList rl) => { + string newName = fieldName + " 0"; + int i = 0; + while (node.HasPort(newName)) newName = fieldName + " " + (++i); + if (io == XNode.NodePort.IO.Output) node.AddInstanceOutput(type, connectionType, newName); + else node.AddInstanceInput(type, connectionType, newName); + serializedObject.Update(); + EditorUtility.SetDirty(node); + if (hasArrayData) arrayData.InsertArrayElementAtIndex(arraySize); + serializedObject.ApplyModifiedProperties(); + }; + list.onRemoveCallback = + (ReorderableList rl) => { + int index = rl.index; + // Clear the removed ports connections + instancePorts[index].ClearConnections(); + // Move following connections one step up to replace the missing connection + for (int k = index + 1; k < instancePorts.Count(); k++) { + for (int j = 0; j < instancePorts[k].ConnectionCount; j++) { + XNode.NodePort other = instancePorts[k].GetConnection(j); + instancePorts[k].Disconnect(other); + instancePorts[k - 1].Connect(other); + } + } + // Remove the last instance port, to avoid messing up the indexing + node.RemoveInstancePort(instancePorts[instancePorts.Count() - 1].fieldName); + serializedObject.Update(); + EditorUtility.SetDirty(node); + if (hasArrayData) { + arrayData.DeleteArrayElementAtIndex(index); + arraySize--; + // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues + if (instancePorts.Count <= arraySize) { + while (instancePorts.Count <= arraySize) { + arrayData.DeleteArrayElementAtIndex(--arraySize); + } + Debug.LogWarning("Array size exceeded instance ports size. Excess items removed."); + } + serializedObject.ApplyModifiedProperties(); + serializedObject.Update(); + } }; } list.list = instancePorts; list.DoLayoutList(); - - for (int i = 0; i < instancePorts.Count(); i++) { - GUILayout.BeginHorizontal(); - // 'Remove' button - if (GUILayout.Button("-", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { - // Clear the removed ports connections - instancePorts[i].ClearConnections(); - // Move following connections one step up to replace the missing connection - for (int k = i + 1; k < instancePorts.Count(); k++) { - for (int j = 0; j < instancePorts[k].ConnectionCount; j++) { - XNode.NodePort other = instancePorts[k].GetConnection(j); - instancePorts[k].Disconnect(other); - instancePorts[k - 1].Connect(other); - } - } - // Remove the last instance port, to avoid messing up the indexing - node.RemoveInstancePort(instancePorts[instancePorts.Count() - 1].fieldName); - serializedObject.Update(); - EditorUtility.SetDirty(node); - if (hasArrayData) { - arrayData.DeleteArrayElementAtIndex(i); - arraySize--; - // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues - if (instancePorts.Count <= arraySize) { - while (instancePorts.Count <= arraySize) { - arrayData.DeleteArrayElementAtIndex(--arraySize); - } - Debug.LogWarning("Array size exceeded instance ports size. Excess items removed."); - } - serializedObject.ApplyModifiedProperties(); - serializedObject.Update(); - } - i--; - GUILayout.EndHorizontal(); - } else { - if (hasArrayData) { - if (i < arraySize) { - SerializedProperty itemData = arrayData.GetArrayElementAtIndex(i); - if (itemData != null) EditorGUILayout.PropertyField(itemData, new GUIContent(ObjectNames.NicifyVariableName(fieldName) + " " + i), true); - else EditorGUILayout.LabelField("[Missing array data]"); - } else EditorGUILayout.LabelField("[Out of bounds]"); - - } else { - EditorGUILayout.LabelField(ObjectNames.NicifyVariableName(instancePorts[i].fieldName)); - } - - GUILayout.EndHorizontal(); - NodeEditorGUILayout.AddPortField(node.GetPort(instancePorts[i].fieldName)); - } - // GUILayout.EndHorizontal(); - } - GUILayout.BeginHorizontal(); - GUILayout.FlexibleSpace(); - // 'Add' button - if (GUILayout.Button("+", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { - - string newName = fieldName + " 0"; - int i = 0; - while (node.HasPort(newName)) newName = fieldName + " " + (++i); - - if (io == XNode.NodePort.IO.Output) node.AddInstanceOutput(type, connectionType, newName); - else node.AddInstanceInput(type, connectionType, newName); - serializedObject.Update(); - EditorUtility.SetDirty(node); - if (hasArrayData) arrayData.InsertArrayElementAtIndex(arraySize); - serializedObject.ApplyModifiedProperties(); - } - GUILayout.EndHorizontal(); } } } \ No newline at end of file diff --git a/Scripts/NodePort.cs b/Scripts/NodePort.cs index 0ada72d..b74844e 100644 --- a/Scripts/NodePort.cs +++ b/Scripts/NodePort.cs @@ -258,6 +258,12 @@ namespace XNode { } } + /// Potentially dangerous. Use only with instance ports + /// + public void Rename(string fieldName) { + _fieldName = fieldName; + } + /// Get reroute points for a given connection. This is used for organization public List GetReroutePoints(int index) { return connections[index].reroutePoints; From 82627812d607b210986cc67a204d1c7097ac055f Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Fri, 19 Oct 2018 10:12:35 +0200 Subject: [PATCH 09/73] Reordering improved, still WIP --- Scripts/Editor/NodeEditorGUILayout.cs | 41 +++++++++++++++++++++------ Scripts/NodePort.cs | 9 ++++++ 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index e47921c..d271844 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -11,7 +11,7 @@ namespace XNodeEditor { public static class NodeEditorGUILayout { private static readonly Dictionary> reorderableListCache = new Dictionary>(); - + private static int reorderableListIndex = -1; /// Make a field for a serialized property. Automatically displays relevant node port. public static void PropertyField(SerializedProperty property, bool includeChildren = true, params GUILayoutOption[] options) { PropertyField(property, (GUIContent) null, includeChildren, options); @@ -278,17 +278,42 @@ namespace XNodeEditor { (Rect rect) => { EditorGUI.LabelField(rect, serializedObject.FindProperty(fieldName).displayName); }; + list.onSelectCallback = + (ReorderableList rl) => { + reorderableListIndex = rl.index; + }; list.onReorderCallback = (ReorderableList rl) => { - for (int i = 0; i < rl.list.Count; i++) { - XNode.NodePort port = rl.list[i] as XNode.NodePort; - string[] name = port.fieldName.Split(' '); - int newIndex = int.Parse(name[1]); - if (i != newIndex) { - //port.Rename(name[0] + " " + i); - Debug.Log("Switch " + i + " and " + newIndex + "!"); + if (hasArrayData) { + SerializedProperty arrayDataOriginal = arrayData.Copy(); + arrayData.MoveArrayElement(reorderableListIndex, rl.index); + + } + List fromConnections = (rl.list[reorderableListIndex] as XNode.NodePort).GetConnections(); + for (int i = 0; i < rl.list.Count - 1; ++i) { + if (i >= reorderableListIndex) { + XNode.NodePort port = rl.list[i] as XNode.NodePort; + port.ClearConnections(); + List newConnections = (rl.list[i + 1] as XNode.NodePort).GetConnections(); + foreach (var c in newConnections) port.Connect(c); + } + + } + for (int i = rl.list.Count - 1; i > 0; --i) { + if (i > rl.index) { + XNode.NodePort port = rl.list[i] as XNode.NodePort; + port.ClearConnections(); + List newConnections = (rl.list[i - 1] as XNode.NodePort).GetConnections(); + foreach (var c in newConnections) port.Connect(c); } } + XNode.NodePort toPort = rl.list[rl.index] as XNode.NodePort; + toPort.ClearConnections(); + foreach (var c in fromConnections) toPort.Connect(c); + + serializedObject.ApplyModifiedProperties(); + serializedObject.Update(); + NodeEditorWindow.current.Repaint(); }; list.onAddCallback = (ReorderableList rl) => { diff --git a/Scripts/NodePort.cs b/Scripts/NodePort.cs index b74844e..bd0217c 100644 --- a/Scripts/NodePort.cs +++ b/Scripts/NodePort.cs @@ -202,6 +202,15 @@ namespace XNode { port.node.OnCreateConnection(this, port); } + public List GetConnections() { + List result = new List(); + 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)) { From 17ba6a880c2a3523711e610b328d3eb9b76af5ca Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Mon, 22 Oct 2018 00:46:49 +0200 Subject: [PATCH 10/73] Ugh, this isn't easy --- Scripts/Editor/NodeEditorGUILayout.cs | 237 +++++++++++++++----------- Scripts/Node.cs | 9 +- 2 files changed, 141 insertions(+), 105 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index d271844..b8fdd50 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -243,8 +244,6 @@ namespace XNodeEditor { public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple) { XNode.Node node = serializedObject.targetObject as XNode.Node; SerializedProperty arrayData = serializedObject.FindProperty(fieldName); - bool hasArrayData = arrayData != null && arrayData.isArray; - int arraySize = hasArrayData ? arrayData.arraySize : 0; Predicate isMatchingInstancePort = x => { @@ -259,109 +258,149 @@ namespace XNodeEditor { if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) { if (!rlc.TryGetValue(fieldName, out list)) list = null; } + // If a ReorderableList isn't cached for this array, do so. if (list == null) { - list = new ReorderableList(instancePorts, null, true, true, true, true); + string label = serializedObject.FindProperty(fieldName).displayName; + list = CreateReorderableList(instancePorts, arrayData, type, serializedObject, io, label, connectionType); if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list); else reorderableListCache.Add(serializedObject.targetObject, new Dictionary() { { fieldName, list } }); - list.drawElementCallback = - (Rect rect, int index, bool isActive, bool isFocused) => { - XNode.NodePort port = list.list[index] as XNode.NodePort; - //SerializedProperty element = serializedObject.get(index); - if (hasArrayData) { - SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); - EditorGUI.PropertyField(rect, itemData); - } else EditorGUI.LabelField(rect, port.fieldName); - Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); - NodeEditorGUILayout.PortField(pos, node.GetPort(instancePorts[index].fieldName)); - }; - list.drawHeaderCallback = - (Rect rect) => { - EditorGUI.LabelField(rect, serializedObject.FindProperty(fieldName).displayName); - }; - list.onSelectCallback = - (ReorderableList rl) => { - reorderableListIndex = rl.index; - }; - list.onReorderCallback = - (ReorderableList rl) => { - if (hasArrayData) { - SerializedProperty arrayDataOriginal = arrayData.Copy(); - arrayData.MoveArrayElement(reorderableListIndex, rl.index); - - } - List fromConnections = (rl.list[reorderableListIndex] as XNode.NodePort).GetConnections(); - for (int i = 0; i < rl.list.Count - 1; ++i) { - if (i >= reorderableListIndex) { - XNode.NodePort port = rl.list[i] as XNode.NodePort; - port.ClearConnections(); - List newConnections = (rl.list[i + 1] as XNode.NodePort).GetConnections(); - foreach (var c in newConnections) port.Connect(c); - } - - } - for (int i = rl.list.Count - 1; i > 0; --i) { - if (i > rl.index) { - XNode.NodePort port = rl.list[i] as XNode.NodePort; - port.ClearConnections(); - List newConnections = (rl.list[i - 1] as XNode.NodePort).GetConnections(); - foreach (var c in newConnections) port.Connect(c); - } - } - XNode.NodePort toPort = rl.list[rl.index] as XNode.NodePort; - toPort.ClearConnections(); - foreach (var c in fromConnections) toPort.Connect(c); - - serializedObject.ApplyModifiedProperties(); - serializedObject.Update(); - NodeEditorWindow.current.Repaint(); - }; - list.onAddCallback = - (ReorderableList rl) => { - string newName = fieldName + " 0"; - int i = 0; - while (node.HasPort(newName)) newName = fieldName + " " + (++i); - - if (io == XNode.NodePort.IO.Output) node.AddInstanceOutput(type, connectionType, newName); - else node.AddInstanceInput(type, connectionType, newName); - serializedObject.Update(); - EditorUtility.SetDirty(node); - if (hasArrayData) arrayData.InsertArrayElementAtIndex(arraySize); - serializedObject.ApplyModifiedProperties(); - }; - list.onRemoveCallback = - (ReorderableList rl) => { - int index = rl.index; - // Clear the removed ports connections - instancePorts[index].ClearConnections(); - // Move following connections one step up to replace the missing connection - for (int k = index + 1; k < instancePorts.Count(); k++) { - for (int j = 0; j < instancePorts[k].ConnectionCount; j++) { - XNode.NodePort other = instancePorts[k].GetConnection(j); - instancePorts[k].Disconnect(other); - instancePorts[k - 1].Connect(other); - } - } - // Remove the last instance port, to avoid messing up the indexing - node.RemoveInstancePort(instancePorts[instancePorts.Count() - 1].fieldName); - serializedObject.Update(); - EditorUtility.SetDirty(node); - if (hasArrayData) { - arrayData.DeleteArrayElementAtIndex(index); - arraySize--; - // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues - if (instancePorts.Count <= arraySize) { - while (instancePorts.Count <= arraySize) { - arrayData.DeleteArrayElementAtIndex(--arraySize); - } - Debug.LogWarning("Array size exceeded instance ports size. Excess items removed."); - } - serializedObject.ApplyModifiedProperties(); - serializedObject.Update(); - } - }; } list.list = instancePorts; list.DoLayoutList(); } + + private static ReorderableList CreateReorderableList(List instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, string label, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple) { + bool hasArrayData = arrayData != null && arrayData.isArray; + int arraySize = hasArrayData ? arrayData.arraySize : 0; + XNode.Node node = serializedObject.targetObject as XNode.Node; + ReorderableList list = new ReorderableList(instancePorts, null, true, true, true, true); + + list.drawElementCallback = + (Rect rect, int index, bool isActive, bool isFocused) => { + XNode.NodePort port = node.GetPort(arrayData.name + " " + index); + if (hasArrayData) { + SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); + EditorGUI.PropertyField(rect, itemData); + } else EditorGUI.LabelField(rect, port.fieldName); + Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); + NodeEditorGUILayout.PortField(pos, port); + }; + list.drawHeaderCallback = + (Rect rect) => { + EditorGUI.LabelField(rect, label); + }; + list.onSelectCallback = + (ReorderableList rl) => { + reorderableListIndex = rl.index; + }; + list.onReorderCallback = + (ReorderableList rl) => { + // Move array data if there is any + if (hasArrayData) { + SerializedProperty arrayDataOriginal = arrayData.Copy(); + arrayData.MoveArrayElement(reorderableListIndex, rl.index); + } + + XNode.NodePort fromPort = node.GetPort(arrayData.name + " " + reorderableListIndex); + // Move connections + List fromConnections = fromPort.GetConnections(); + for (int i = 0; i < rl.list.Count - 1; ++i) { + if (i >= reorderableListIndex) { + XNode.NodePort port = node.GetPort(arrayData.name + " " + i); + XNode.NodePort targetPort = node.GetPort(arrayData.name + " " + (i + 1)); + port.ClearConnections(); + Debug.Log("Move " + targetPort.fieldName + " to " + port.fieldName); + List newConnections = targetPort.GetConnections(); + foreach (var c in newConnections) port.Connect(c); + } + } + for (int i = rl.list.Count - 1; i > 0; --i) { + if (i > rl.index) { + XNode.NodePort port = node.GetPort(arrayData.name + " " + i); + XNode.NodePort targetPort = node.GetPort(arrayData.name + " " + (i - 1)); + port.ClearConnections(); + Debug.Log("Move " + targetPort.fieldName + " to " + port.fieldName); + List newConnections = targetPort.GetConnections(); + foreach (var c in newConnections) port.Connect(c); + } + } + XNode.NodePort toPort = node.GetPort(arrayData.name + " " + rl.index); + toPort.ClearConnections(); + foreach (var c in fromConnections) toPort.Connect(c); + + // Apply changes + serializedObject.ApplyModifiedProperties(); + serializedObject.Update(); + NodeEditorWindow.current.Repaint(); + EditorApplication.delayCall += NodeEditorWindow.current.Repaint; + }; + list.onAddCallback = + (ReorderableList rl) => { + // Add instance port postfixed with an index number + string newName = arrayData.name + " 0"; + int i = 0; + while (node.HasPort(newName)) newName = arrayData.name + " " + (++i); + + if (io == XNode.NodePort.IO.Output) node.AddInstanceOutput(type, connectionType, newName); + else node.AddInstanceInput(type, connectionType, newName); + serializedObject.Update(); + EditorUtility.SetDirty(node); + if (hasArrayData) arrayData.InsertArrayElementAtIndex(arraySize); + serializedObject.ApplyModifiedProperties(); + }; + list.onRemoveCallback = + (ReorderableList rl) => { + int index = rl.index; + // Clear the removed ports connections + instancePorts[index].ClearConnections(); + // Move following connections one step up to replace the missing connection + for (int k = index + 1; k < instancePorts.Count(); k++) { + for (int j = 0; j < instancePorts[k].ConnectionCount; j++) { + XNode.NodePort other = instancePorts[k].GetConnection(j); + instancePorts[k].Disconnect(other); + instancePorts[k - 1].Connect(other); + } + } + // Remove the last instance port, to avoid messing up the indexing + node.RemoveInstancePort(instancePorts[instancePorts.Count() - 1].fieldName); + serializedObject.Update(); + EditorUtility.SetDirty(node); + if (hasArrayData) { + arrayData.DeleteArrayElementAtIndex(index); + arraySize--; + // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues + if (instancePorts.Count <= arraySize) { + while (instancePorts.Count <= arraySize) { + arrayData.DeleteArrayElementAtIndex(--arraySize); + } + Debug.LogWarning("Array size exceeded instance ports size. Excess items removed."); + } + serializedObject.ApplyModifiedProperties(); + serializedObject.Update(); + } + + }; + + if (hasArrayData) { + int instancePortCount = instancePorts.Count; + while (instancePortCount < arraySize) { + // Add instance port postfixed with an index number + string newName = arrayData.name + " 0"; + int i = 0; + while (node.HasPort(newName)) newName = arrayData.name + " " + (++i); + if (io == XNode.NodePort.IO.Output) node.AddInstanceOutput(type, connectionType, newName); + else node.AddInstanceInput(type, connectionType, newName); + EditorUtility.SetDirty(node); + instancePortCount++; + } + while (arraySize < instancePortCount) { + arrayData.InsertArrayElementAtIndex(arraySize); + arraySize++; + } + serializedObject.ApplyModifiedProperties(); + serializedObject.Update(); + } + return list; + } } } \ No newline at end of file diff --git a/Scripts/Node.cs b/Scripts/Node.cs index ac62fd6..f27af6a 100644 --- a/Scripts/Node.cs +++ b/Scripts/Node.cs @@ -79,24 +79,21 @@ namespace XNode { } #region Instance Ports - /// Convenience function. - /// + /// Convenience function. /// /// public NodePort AddInstanceInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, string fieldName = null) { return AddInstancePort(type, NodePort.IO.Input, connectionType, fieldName); } - /// Convenience function. - /// + /// Convenience function. /// /// public NodePort AddInstanceOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, string fieldName = null) { return AddInstancePort(type, NodePort.IO.Output, connectionType, fieldName); } - /// Add a dynamic, serialized port to this node. - /// + /// Add a dynamic, serialized port to this node. /// /// private NodePort AddInstancePort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, string fieldName = null) { From f00e1e5f2cdc736fd94d8a63ece3e38dc9dcbbaa Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Mon, 22 Oct 2018 09:10:06 +0200 Subject: [PATCH 11/73] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dcaa133..34bb854 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ With a minimal footprint, it is ideal as a base for custom state machines, dialo ### Node example: ```csharp -[System.Serializable] +// public classes deriving from Node are registered as nodes for use within a graph public class MathNode : Node { // Adding [Input] or [Output] is all you need to do to register a field as a valid port on your node [Input] public float a; From b186b7dd345b0bada48a9828c037832c71fe5139 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Fri, 26 Oct 2018 00:17:24 +0200 Subject: [PATCH 12/73] Finished reorderable instance port lists --- Scripts/Editor/NodeEditorGUILayout.cs | 58 ++++++++++---------- Scripts/NodePort.cs | 78 ++++++++++++++++++++++++--- 2 files changed, 103 insertions(+), 33 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index b8fdd50..4720950 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -295,39 +295,43 @@ namespace XNodeEditor { }; list.onReorderCallback = (ReorderableList rl) => { + + // Move up + if (rl.index > reorderableListIndex) { + for (int i = reorderableListIndex; i < rl.index; ++i) { + XNode.NodePort port = node.GetPort(arrayData.name + " " + i); + XNode.NodePort nextPort = node.GetPort(arrayData.name + " " + (i + 1)); + port.SwapConnections(nextPort); + + // Swap cached positions to mitigate twitching + Rect rect = NodeEditorWindow.current.portConnectionPoints[port]; + NodeEditorWindow.current.portConnectionPoints[port] = NodeEditorWindow.current.portConnectionPoints[nextPort]; + NodeEditorWindow.current.portConnectionPoints[nextPort] = rect; + } + } + // Move down + else { + for (int i = reorderableListIndex; i > rl.index; --i) { + XNode.NodePort port = node.GetPort(arrayData.name + " " + i); + XNode.NodePort nextPort = node.GetPort(arrayData.name + " " + (i - 1)); + port.SwapConnections(nextPort); + + // Swap cached positions to mitigate twitching + Rect rect = NodeEditorWindow.current.portConnectionPoints[port]; + NodeEditorWindow.current.portConnectionPoints[port] = NodeEditorWindow.current.portConnectionPoints[nextPort]; + NodeEditorWindow.current.portConnectionPoints[nextPort] = rect; + } + } + // Apply changes + serializedObject.ApplyModifiedProperties(); + serializedObject.Update(); + // Move array data if there is any if (hasArrayData) { SerializedProperty arrayDataOriginal = arrayData.Copy(); arrayData.MoveArrayElement(reorderableListIndex, rl.index); } - XNode.NodePort fromPort = node.GetPort(arrayData.name + " " + reorderableListIndex); - // Move connections - List fromConnections = fromPort.GetConnections(); - for (int i = 0; i < rl.list.Count - 1; ++i) { - if (i >= reorderableListIndex) { - XNode.NodePort port = node.GetPort(arrayData.name + " " + i); - XNode.NodePort targetPort = node.GetPort(arrayData.name + " " + (i + 1)); - port.ClearConnections(); - Debug.Log("Move " + targetPort.fieldName + " to " + port.fieldName); - List newConnections = targetPort.GetConnections(); - foreach (var c in newConnections) port.Connect(c); - } - } - for (int i = rl.list.Count - 1; i > 0; --i) { - if (i > rl.index) { - XNode.NodePort port = node.GetPort(arrayData.name + " " + i); - XNode.NodePort targetPort = node.GetPort(arrayData.name + " " + (i - 1)); - port.ClearConnections(); - Debug.Log("Move " + targetPort.fieldName + " to " + port.fieldName); - List newConnections = targetPort.GetConnections(); - foreach (var c in newConnections) port.Connect(c); - } - } - XNode.NodePort toPort = node.GetPort(arrayData.name + " " + rl.index); - toPort.ClearConnections(); - foreach (var c in fromConnections) toPort.Connect(c); - // Apply changes serializedObject.ApplyModifiedProperties(); serializedObject.Update(); diff --git a/Scripts/NodePort.cs b/Scripts/NodePort.cs index bd0217c..35ba41f 100644 --- a/Scripts/NodePort.cs +++ b/Scripts/NodePort.cs @@ -261,23 +261,89 @@ namespace XNode { if (port != null) port.node.OnRemoveConnection(port); } + /// Disconnect this port from another port + public void Disconnect(int i) { + // Remove the other ports connection to this port + NodePort otherPort = connections[i].Port; + if (otherPort != null) { + for (int k = 0; k < otherPort.connections.Count; k++) { + if (otherPort.connections[k].Port == this) { + otherPort.connections.RemoveAt(i); + } + } + } + // 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); } } - /// Potentially dangerous. Use only with instance ports - /// - public void Rename(string fieldName) { - _fieldName = fieldName; - } - /// Get reroute points for a given connection. This is used for organization public List GetReroutePoints(int index) { return connections[index].reroutePoints; } + /// Swap connections with another node + public void SwapConnections(NodePort targetPort) { + int aConnectionCount = connections.Count; + int bConnectionCount = targetPort.connections.Count; + + // Add target port connections to this one + for (int i = 0; i < aConnectionCount; i++) { + PortConnection connection = connections[i]; + NodePort otherPort = connection.Port; + targetPort.Connect(otherPort); + } + + // Add connections to target port + for (int i = 0; i < bConnectionCount; i++) { + PortConnection connection = targetPort.connections[i]; + NodePort otherPort = connection.Port; + Connect(otherPort); + } + + // Remove starting connections on this port + for (int i = aConnectionCount - 1; i >= 0; i--) { + Disconnect(i); + } + + // Remove starting connections on target port + for (int i = bConnectionCount - 1; i >= 0; i--) { + targetPort.Disconnect(i); + } + } + + /// Copy all connections pointing to a node and add them to this one + 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); + } + } + + /// Move all connections pointing to this node, to another node + 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(); + } + /// Swap connected nodes from the old list with nodes from the new list public void Redirect(List oldNodes, List newNodes) { foreach (PortConnection connection in connections) { From 0b008c77ebe65c749a053e24b60dadbb3260e87d Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Fri, 26 Oct 2018 00:31:53 +0200 Subject: [PATCH 13/73] Fixed edge case where swapping connections connected to the same port would cause a "port is already connected" error --- Scripts/NodePort.cs | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/Scripts/NodePort.cs b/Scripts/NodePort.cs index 35ba41f..3f55795 100644 --- a/Scripts/NodePort.cs +++ b/Scripts/NodePort.cs @@ -296,29 +296,28 @@ namespace XNode { int aConnectionCount = connections.Count; int bConnectionCount = targetPort.connections.Count; + List portConnections = new List(); + List targetPortConnections = new List(); + + // 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 < aConnectionCount; i++) { - PortConnection connection = connections[i]; - NodePort otherPort = connection.Port; - targetPort.Connect(otherPort); - } + for (int i = 0; i < targetPortConnections.Count; i++) + Connect(targetPortConnections[i]); - // Add connections to target port - for (int i = 0; i < bConnectionCount; i++) { - PortConnection connection = targetPort.connections[i]; - NodePort otherPort = connection.Port; - Connect(otherPort); - } - - // Remove starting connections on this port - for (int i = aConnectionCount - 1; i >= 0; i--) { - Disconnect(i); - } - - // Remove starting connections on target port - for (int i = bConnectionCount - 1; i >= 0; i--) { - targetPort.Disconnect(i); - } } /// Copy all connections pointing to a node and add them to this one From bad05a6e64305b1032c80a975fb57d95d594b706 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Fri, 26 Oct 2018 18:42:16 +0200 Subject: [PATCH 14/73] InstancePortList custom PropertyHeight supported --- Scripts/Editor/NodeEditorGUILayout.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 4720950..df8d918 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -285,6 +285,10 @@ namespace XNodeEditor { Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); NodeEditorGUILayout.PortField(pos, port); }; + list.elementHeightCallback = (int index) => { + SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); + return EditorGUI.GetPropertyHeight(itemData); + }; list.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, label); From 16992c39722e1d43666aec21aa7451cc281d7dee Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 27 Oct 2018 18:41:13 +0200 Subject: [PATCH 15/73] Added NodeEditor.GetBodyStyle, allowing per-node body styles --- Scripts/Editor/NodeEditor.cs | 4 ++++ Scripts/Editor/NodeEditorGUI.cs | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index 1469e2d..46c13bf 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -75,6 +75,10 @@ namespace XNodeEditor { else return Color.white; } + public virtual GUIStyle GetBodyStyle() { + return NodeEditorResources.styles.nodeBody; + } + public void InitiateRename() { renaming = 1; } diff --git a/Scripts/Editor/NodeEditorGUI.cs b/Scripts/Editor/NodeEditorGUI.cs index 9c77033..70cd76e 100644 --- a/Scripts/Editor/NodeEditorGUI.cs +++ b/Scripts/Editor/NodeEditorGUI.cs @@ -348,18 +348,18 @@ namespace XNodeEditor { bool selected = selectionCache.Contains(graph.nodes[n]); if (selected) { - GUIStyle style = new GUIStyle(NodeEditorResources.styles.nodeBody); + GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle()); GUIStyle highlightStyle = new GUIStyle(NodeEditorResources.styles.nodeHighlight); highlightStyle.padding = style.padding; style.padding = new RectOffset(); GUI.color = nodeEditor.GetTint(); - GUILayout.BeginVertical(new GUIStyle(style)); + GUILayout.BeginVertical(style); GUI.color = NodeEditorPreferences.GetSettings().highlightColor; GUILayout.BeginVertical(new GUIStyle(highlightStyle)); } else { - GUIStyle style = NodeEditorResources.styles.nodeBody; + GUIStyle style = new GUIStyle(nodeEditor.GetBodyStyle()); GUI.color = nodeEditor.GetTint(); - GUILayout.BeginVertical(new GUIStyle(style)); + GUILayout.BeginVertical(style); } GUI.color = guiColor; From e9c6b6f2212483bbc811347b0b2df9187e734849 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 27 Oct 2018 19:57:13 +0200 Subject: [PATCH 16/73] Removed middleman function --- Scripts/Editor/NodeEditor.cs | 7 ------- Scripts/Editor/NodeEditorGUI.cs | 3 ++- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index 46c13bf..2de8c02 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -15,13 +15,6 @@ namespace XNodeEditor { public static Dictionary portPositions; public static int renaming; - /// Draws the node GUI. - /// Port handle positions need to be returned to the NodeEditorWindow - public void OnNodeGUI() { - OnHeaderGUI(); - OnBodyGUI(); - } - public virtual void OnHeaderGUI() { string title = target.name; if (renaming != 0 && Selection.Contains(target)) { diff --git a/Scripts/Editor/NodeEditorGUI.cs b/Scripts/Editor/NodeEditorGUI.cs index 70cd76e..dd74a01 100644 --- a/Scripts/Editor/NodeEditorGUI.cs +++ b/Scripts/Editor/NodeEditorGUI.cs @@ -366,7 +366,8 @@ namespace XNodeEditor { EditorGUI.BeginChangeCheck(); //Draw node contents - nodeEditor.OnNodeGUI(); + nodeEditor.OnHeaderGUI(); + nodeEditor.OnBodyGUI(); //If user changed a value, notify other scripts through onUpdateNode if (EditorGUI.EndChangeCheck()) { From ba6938063801bf4b406500681383aa7942485c3d Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Mon, 29 Oct 2018 21:20:22 +0100 Subject: [PATCH 17/73] Fixed error on instanceportlists that aren't arrays --- Scripts/Editor/NodeEditorGUILayout.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index df8d918..7ee43a6 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -285,10 +285,13 @@ namespace XNodeEditor { Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); NodeEditorGUILayout.PortField(pos, port); }; - list.elementHeightCallback = (int index) => { - SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); - return EditorGUI.GetPropertyHeight(itemData); - }; + list.elementHeightCallback = + (int index) => { + if (hasArrayData) { + SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); + return EditorGUI.GetPropertyHeight(itemData); + } else return EditorGUIUtility.singleLineHeight; + }; list.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, label); From b9bd67bd28df602520c600d3c08564f2fa61cac1 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Tue, 30 Oct 2018 09:38:44 +0100 Subject: [PATCH 18/73] Cleanup Removed unused code, added/fixed comments --- Scripts/Editor/NodeEditor.cs | 1 - Scripts/Editor/NodeEditorBase.cs | 5 ++++- Scripts/Editor/NodeEditorGUILayout.cs | 1 - Scripts/Editor/NodeEditorReflection.cs | 10 ---------- Scripts/Editor/NodeGraphEditor.cs | 2 +- 5 files changed, 5 insertions(+), 14 deletions(-) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index 2de8c02..fa4e110 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -87,7 +87,6 @@ namespace XNodeEditor { private Type inspectedType; /// Tells a NodeEditor which Node type it is an editor for /// Type that this editor can edit - /// Path to the node public CustomNodeEditorAttribute(Type inspectedType) { this.inspectedType = inspectedType; } diff --git a/Scripts/Editor/NodeEditorBase.cs b/Scripts/Editor/NodeEditorBase.cs index 2a16f18..b94f290 100644 --- a/Scripts/Editor/NodeEditorBase.cs +++ b/Scripts/Editor/NodeEditorBase.cs @@ -7,7 +7,10 @@ using UnityEngine; namespace XNodeEditor.Internal { /// Handles caching of custom editor classes and their target types. Accessible with GetEditor(Type type) - public class NodeEditorBase where A : Attribute, NodeEditorBase.INodeEditorAttrib where T : NodeEditorBase where K : ScriptableObject { + /// Editor Type. Should be the type of the deriving script itself (eg. NodeEditor) + /// Attribute Type. The attribute used to connect with the runtime type (eg. CustomNodeEditorAttribute) + /// Runtime Type. The ScriptableObject this can be an editor for (eg. Node) + public abstract class NodeEditorBase where A : Attribute, NodeEditorBase.INodeEditorAttrib where T : NodeEditorBase where K : ScriptableObject { /// Custom editors defined with [CustomNodeEditor] private static Dictionary editorTypes; private static Dictionary editors = new Dictionary(); diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 7ee43a6..bcc142b 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -335,7 +335,6 @@ namespace XNodeEditor { // Move array data if there is any if (hasArrayData) { - SerializedProperty arrayDataOriginal = arrayData.Copy(); arrayData.MoveArrayElement(reorderableListIndex, rl.index); } diff --git a/Scripts/Editor/NodeEditorReflection.cs b/Scripts/Editor/NodeEditorReflection.cs index 171f3b3..5601951 100644 --- a/Scripts/Editor/NodeEditorReflection.cs +++ b/Scripts/Editor/NodeEditorReflection.cs @@ -71,16 +71,6 @@ namespace XNodeEditor { return types.ToArray(); } - public static object ObjectFromType(Type type) { - return Activator.CreateInstance(type); - } - - public static object ObjectFromFieldName(object obj, string fieldName) { - Type type = obj.GetType(); - FieldInfo fieldInfo = type.GetField(fieldName); - return fieldInfo.GetValue(obj); - } - public static KeyValuePair[] GetContextMenuMethods(object obj) { Type type = obj.GetType(); MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); diff --git a/Scripts/Editor/NodeGraphEditor.cs b/Scripts/Editor/NodeGraphEditor.cs index bcb95e1..1c32a6e 100644 --- a/Scripts/Editor/NodeGraphEditor.cs +++ b/Scripts/Editor/NodeGraphEditor.cs @@ -65,7 +65,7 @@ namespace XNodeEditor { public string editorPrefsKey; /// Tells a NodeGraphEditor which Graph type it is an editor for /// Type that this editor can edit - /// Define unique key for unique layout settings instance + /// Define unique key for unique layout settings instance public CustomNodeGraphEditorAttribute(Type inspectedType, string editorPrefsKey = "xNode.Settings") { this.inspectedType = inspectedType; this.editorPrefsKey = editorPrefsKey; From dc608a3d1ba6cf8de2c8ff3571ecf308d8b71c3b Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Thu, 1 Nov 2018 00:46:38 +0100 Subject: [PATCH 19/73] Added NodeEditorGUILayout.onCreateReorderableList action for reorderablelist customization --- Scripts/Editor/NodeEditorGUILayout.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index bcc142b..c1c1665 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -11,8 +11,11 @@ namespace XNodeEditor { /// xNode-specific version of public static class NodeEditorGUILayout { + /// Listen for this event if you want to alter the default ReorderableList + public static Action onCreateReorderableList; private static readonly Dictionary> reorderableListCache = new Dictionary>(); private static int reorderableListIndex = -1; + /// Make a field for a serialized property. Automatically displays relevant node port. public static void PropertyField(SerializedProperty property, bool includeChildren = true, params GUILayoutOption[] options) { PropertyField(property, (GUIContent) null, includeChildren, options); @@ -410,6 +413,7 @@ namespace XNodeEditor { serializedObject.ApplyModifiedProperties(); serializedObject.Update(); } + if (onCreateReorderableList != null) onCreateReorderableList(list); return list; } } From 604365ce67b9441d6749aa4bef44f63abc4ee82b Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Wed, 7 Nov 2018 20:20:14 +0100 Subject: [PATCH 20/73] Unity 2018.3 support --- Scripts/Editor/NodeEditorReflection.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Scripts/Editor/NodeEditorReflection.cs b/Scripts/Editor/NodeEditorReflection.cs index 5601951..0afd307 100644 --- a/Scripts/Editor/NodeEditorReflection.cs +++ b/Scripts/Editor/NodeEditorReflection.cs @@ -101,6 +101,16 @@ namespace XNodeEditor { /// Very crude. Uses a lot of reflection. public static void OpenPreferences() { try { +#if UNITY_2018_3_OR_NEWER + SettingsProvider[] providers = SettingsService.FetchSettingsProviders(); + + foreach (SettingsProvider settingsProvider in providers) { + if (settingsProvider.name == "Node Editor") { + EditorPrefs.SetString("SettingsWindow_Settings_current_provider", settingsProvider.settingsPath); + EditorApplication.ExecuteMenuItem("Edit/Preferences..."); + } + } +#else //Open preferences window Assembly assembly = Assembly.GetAssembly(typeof(UnityEditor.EditorWindow)); Type type = assembly.GetType("UnityEditor.PreferencesWindow"); @@ -132,6 +142,7 @@ namespace XNodeEditor { return; } } +#endif } catch (Exception e) { Debug.LogError(e); Debug.LogWarning("Unity has changed around internally. Can't open properties through reflection. Please contact xNode developer and supply unity version number."); From 6979333eb1981bde2a4e020a01626ff12555ddec Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sun, 11 Nov 2018 22:38:48 +0100 Subject: [PATCH 21/73] Added [NodeEnum] which fixes enum positions. #28 --- Scripts/Attributes.meta | 10 ++++ Scripts/Attributes/NodeEnum.cs | 4 ++ Scripts/Attributes/NodeEnum.cs.meta | 13 +++++ Scripts/Editor/Drawers.meta | 10 ++++ Scripts/Editor/Drawers/NodeEnumDrawer.cs | 56 +++++++++++++++++++ Scripts/Editor/Drawers/NodeEnumDrawer.cs.meta | 13 +++++ Scripts/Editor/NodeEditorGUI.cs | 8 +++ 7 files changed, 114 insertions(+) create mode 100644 Scripts/Attributes.meta create mode 100644 Scripts/Attributes/NodeEnum.cs create mode 100644 Scripts/Attributes/NodeEnum.cs.meta create mode 100644 Scripts/Editor/Drawers.meta create mode 100644 Scripts/Editor/Drawers/NodeEnumDrawer.cs create mode 100644 Scripts/Editor/Drawers/NodeEnumDrawer.cs.meta diff --git a/Scripts/Attributes.meta b/Scripts/Attributes.meta new file mode 100644 index 0000000..c0be849 --- /dev/null +++ b/Scripts/Attributes.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 5644dfc7eed151045af664a9d4fd1906 +folderAsset: yes +timeCreated: 1541633926 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Attributes/NodeEnum.cs b/Scripts/Attributes/NodeEnum.cs new file mode 100644 index 0000000..9a5c12a --- /dev/null +++ b/Scripts/Attributes/NodeEnum.cs @@ -0,0 +1,4 @@ +using UnityEngine; + +/// Draw enums correctly within nodes. Without it, enums show up at the wrong positions. +public class NodeEnumAttribute : PropertyAttribute { } \ No newline at end of file diff --git a/Scripts/Attributes/NodeEnum.cs.meta b/Scripts/Attributes/NodeEnum.cs.meta new file mode 100644 index 0000000..813a80b --- /dev/null +++ b/Scripts/Attributes/NodeEnum.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: 10a8338f6c985854697b35459181af0a +timeCreated: 1541633942 +licenseType: Free +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Editor/Drawers.meta b/Scripts/Editor/Drawers.meta new file mode 100644 index 0000000..b69e0ac --- /dev/null +++ b/Scripts/Editor/Drawers.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7adf21edfb51f514fa991d7556ecd0ef +folderAsset: yes +timeCreated: 1541971984 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Editor/Drawers/NodeEnumDrawer.cs b/Scripts/Editor/Drawers/NodeEnumDrawer.cs new file mode 100644 index 0000000..cdb6511 --- /dev/null +++ b/Scripts/Editor/Drawers/NodeEnumDrawer.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +using XNode; +using XNodeEditor; + +namespace XNodeEditor { + [CustomPropertyDrawer(typeof(NodeEnumAttribute))] + public class NodeEnumDrawer : PropertyDrawer { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { + EditorGUI.BeginProperty(position, label, property); + + // Throw error on wrong type + if (property.propertyType != SerializedPropertyType.Enum) { + throw new ArgumentException("Parameter selected must be of type System.Enum"); + } + + // Add label + position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); + + // Get current enum name + string enumName = ""; + if (property.enumValueIndex >= 0 && property.enumValueIndex < property.enumDisplayNames.Length) enumName = property.enumDisplayNames[property.enumValueIndex]; + + // Display dropdown + if (EditorGUI.DropdownButton(position, new GUIContent(enumName), FocusType.Passive)) { + // Position is all wrong if we show the dropdown during the node draw phase. + // Instead, add it to onLateGUI to display it later. + NodeEditorWindow.current.onLateGUI += () => ShowContextMenuAtMouse(property); + } + EditorGUI.EndProperty(); + } + + private void ShowContextMenuAtMouse(SerializedProperty property) { + // Initialize menu + GenericMenu menu = new GenericMenu(); + + // Add all enum display names to menu + for (int i = 0; i < property.enumDisplayNames.Length; i++) { + int index = i; + menu.AddItem(new GUIContent(property.enumDisplayNames[i]), false, () => SetEnum(property, index)); + } + + // Display at cursor position + Rect r = new Rect(Event.current.mousePosition, new Vector2(0, 0)); + menu.DropDown(r); + } + + private void SetEnum(SerializedProperty property, int index) { + property.enumValueIndex = index; + property.serializedObject.ApplyModifiedProperties(); + } + } +} \ No newline at end of file diff --git a/Scripts/Editor/Drawers/NodeEnumDrawer.cs.meta b/Scripts/Editor/Drawers/NodeEnumDrawer.cs.meta new file mode 100644 index 0000000..beacf6b --- /dev/null +++ b/Scripts/Editor/Drawers/NodeEnumDrawer.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: 83db81f92abadca439507e25d517cabe +timeCreated: 1541633798 +licenseType: Free +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Editor/NodeEditorGUI.cs b/Scripts/Editor/NodeEditorGUI.cs index dd74a01..34fa6a7 100644 --- a/Scripts/Editor/NodeEditorGUI.cs +++ b/Scripts/Editor/NodeEditorGUI.cs @@ -11,6 +11,8 @@ namespace XNodeEditor { private List selectionCache; private List culledNodes; private int topPadding { get { return isDocked() ? 19 : 22; } } + /// Executed after all other window GUI. Useful if Zoom is ruining your day. Automatically resets after being run. + public event Action onLateGUI; private void OnGUI() { Event e = Event.current; @@ -29,6 +31,12 @@ namespace XNodeEditor { DrawTooltip(); graphEditor.OnGUI(); + // Run and reset onLateGUI + if (onLateGUI != null) { + onLateGUI(); + onLateGUI = null; + } + GUI.matrix = m; } From 35861d20c69bf0e1dd67e37b738980616aaa5718 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Tue, 13 Nov 2018 00:04:00 +0100 Subject: [PATCH 22/73] Focus xNode in preferences window in >= 2018.3 --- Scripts/Editor/NodeEditorReflection.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Scripts/Editor/NodeEditorReflection.cs b/Scripts/Editor/NodeEditorReflection.cs index 0afd307..42e583c 100644 --- a/Scripts/Editor/NodeEditorReflection.cs +++ b/Scripts/Editor/NodeEditorReflection.cs @@ -102,11 +102,9 @@ namespace XNodeEditor { public static void OpenPreferences() { try { #if UNITY_2018_3_OR_NEWER - SettingsProvider[] providers = SettingsService.FetchSettingsProviders(); - - foreach (SettingsProvider settingsProvider in providers) { + foreach (SettingsProvider settingsProvider in SettingsService.FetchSettingsProviders()) { if (settingsProvider.name == "Node Editor") { - EditorPrefs.SetString("SettingsWindow_Settings_current_provider", settingsProvider.settingsPath); + EditorPrefs.SetString("SettingsWindow_Preferences_current_provider", settingsProvider.settingsPath); EditorApplication.ExecuteMenuItem("Edit/Preferences..."); } } From 11c8f29672e98b7f9f9da6acb2dee55bd9c5731d Mon Sep 17 00:00:00 2001 From: Thomas Morgner Date: Fri, 16 Nov 2018 12:01:34 +0000 Subject: [PATCH 23/73] Clear edit-mode when reselecting node while renaming node --- Scripts/Editor/NodeEditor.cs | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index fa4e110..8b06c26 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -13,19 +13,28 @@ namespace XNodeEditor { /// Fires every whenever a node was modified through the editor public static Action onUpdateNode; public static Dictionary portPositions; - public static int renaming; + public int renaming; public virtual void OnHeaderGUI() { string title = target.name; - if (renaming != 0 && Selection.Contains(target)) { - int controlID = EditorGUIUtility.GetControlID(FocusType.Keyboard) + 1; - if (renaming == 1) { - EditorGUIUtility.keyboardControl = controlID; - EditorGUIUtility.editingTextField = true; - renaming = 2; + if (renaming != 0) { + if (Selection.Contains(target)) { + int controlID = EditorGUIUtility.GetControlID(FocusType.Keyboard) + 1; + if (renaming == 1) { + EditorGUIUtility.keyboardControl = controlID; + EditorGUIUtility.editingTextField = true; + renaming = 2; + } + target.name = EditorGUILayout.TextField(target.name, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); + if (!EditorGUIUtility.editingTextField) { + Debug.Log("Finish renaming"); + Rename(target.name); + renaming = 0; + } } - target.name = EditorGUILayout.TextField(target.name, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); - if (!EditorGUIUtility.editingTextField) { + else { + // Selection changed, so stop renaming. + GUILayout.Label(title, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); Rename(target.name); renaming = 0; } From b138388c290f2babe0e386e681d8d73a45b2eb8f Mon Sep 17 00:00:00 2001 From: Thomas Morgner Date: Fri, 16 Nov 2018 12:14:04 +0000 Subject: [PATCH 24/73] Allow to trigger renames via F2 key --- Scripts/Editor/NodeEditor.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index fa4e110..3a3c490 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -31,9 +31,20 @@ namespace XNodeEditor { } } else { GUILayout.Label(title, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); + if (HasFocus() && IsRenameKeyPressed()) { + InitiateRename(); + } } } + bool HasFocus() { + return Selection.activeObject == this.target; + } + + bool IsRenameKeyPressed() { + return (Event.current != null && Event.current.isKey && Event.current.keyCode == KeyCode.F2); + } + /// Draws standard field editors for all public fields public virtual void OnBodyGUI() { // Unity specifically requires this to save/update any serial object. From 5803ae45ba9e5929729254b756a4fa0693f59fd5 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Fri, 16 Nov 2018 14:06:59 +0100 Subject: [PATCH 25/73] Revert "Allow to trigger renames via F2 key" --- Scripts/Editor/NodeEditor.cs | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index bdcb384..8b06c26 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -40,20 +40,9 @@ namespace XNodeEditor { } } else { GUILayout.Label(title, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); - if (HasFocus() && IsRenameKeyPressed()) { - InitiateRename(); - } } } - bool HasFocus() { - return Selection.activeObject == this.target; - } - - bool IsRenameKeyPressed() { - return (Event.current != null && Event.current.isKey && Event.current.keyCode == KeyCode.F2); - } - /// Draws standard field editors for all public fields public virtual void OnBodyGUI() { // Unity specifically requires this to save/update any serial object. From 6c1af6f4cda16d50b80a970b803ebdd0549a448e Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Mon, 10 Dec 2018 23:33:25 +0100 Subject: [PATCH 26/73] Fix/error on duplicate (#82) * Pressing CTRL+D (duplicate) threw editorgui exception "Getting control 0s position in a group with only 3 controls when doing ValidateCommand". comparing to https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/SceneHierarchyWindow.cs : row 211, the proper use of the event was not made. also fixed spelling of Dublicate to Duplicate. * Braces on wrong lines. * Something got wrong with the comments. --- Scripts/Editor/NodeEditorAction.cs | 18 +++++++++++++----- Scripts/Editor/NodeEditorGUI.cs | 2 +- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index 404b8af..b5315f8 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -278,9 +278,17 @@ namespace XNodeEditor { } break; case EventType.ValidateCommand: - if (e.commandName == "SoftDelete") RemoveSelectedNodes(); - else if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX && e.commandName == "Delete") RemoveSelectedNodes(); - else if (e.commandName == "Duplicate") DublicateSelectedNodes(); + case EventType.ExecuteCommand: + if (e.commandName == "SoftDelete") { + if (e.type == EventType.ExecuteCommand) RemoveSelectedNodes(); + e.Use(); + } else if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX && e.commandName == "Delete") { + if (e.type == EventType.ExecuteCommand) RemoveSelectedNodes(); + e.Use(); + } else if (e.commandName == "Duplicate") { + if (e.type == EventType.ExecuteCommand) DuplicateSelectedNodes(); + e.Use(); + } Repaint(); break; case EventType.Ignore: @@ -357,8 +365,8 @@ namespace XNodeEditor { } } - /// Dublicate selected nodes and select the dublicates - public void DublicateSelectedNodes() { + /// Duplicate selected nodes and select the duplicates + public void DuplicateSelectedNodes() { UnityEngine.Object[] newNodes = new UnityEngine.Object[Selection.objects.Length]; Dictionary substitutes = new Dictionary(); for (int i = 0; i < Selection.objects.Length; i++) { diff --git a/Scripts/Editor/NodeEditorGUI.cs b/Scripts/Editor/NodeEditorGUI.cs index 34fa6a7..8d7b95a 100644 --- a/Scripts/Editor/NodeEditorGUI.cs +++ b/Scripts/Editor/NodeEditorGUI.cs @@ -126,7 +126,7 @@ namespace XNodeEditor { contextMenu.AddItem(new GUIContent("Rename"), false, RenameSelectedNode); } - contextMenu.AddItem(new GUIContent("Duplicate"), false, DublicateSelectedNodes); + contextMenu.AddItem(new GUIContent("Duplicate"), false, DuplicateSelectedNodes); contextMenu.AddItem(new GUIContent("Remove"), false, RemoveSelectedNodes); // If only one node is selected From a0eee5b9caabe641e507954959d4f87683e14c51 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Wed, 12 Dec 2018 00:57:31 +0100 Subject: [PATCH 27/73] Fix misconfigured node.graph reference during node instantiation and graph cloning (#85) * Attempting to fix #81 in a cleaner way. Still not perfect * Fixed setting to null during OnEnable * Fixed spelling --- Scripts/Node.cs | 8 +++++++- Scripts/NodeGraph.cs | 7 +++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Scripts/Node.cs b/Scripts/Node.cs index f27af6a..881a297 100644 --- a/Scripts/Node.cs +++ b/Scripts/Node.cs @@ -60,7 +60,13 @@ namespace XNode { /// It is recommended not to modify these at hand. Instead, see and [SerializeField] private NodePortDictionary ports = new NodePortDictionary(); + /// Used during node instantiation to fix null/misconfigured graph during OnEnable/Init. Set it before instantiating a node. Will automatically be unset during OnEnable + public static NodeGraph graphHotfix; + + protected void OnEnable() { + if (graphHotfix != null) graph = graphHotfix; + graphHotfix = null; UpdateStaticPorts(); Init(); } @@ -308,4 +314,4 @@ namespace XNode { } } } -} \ No newline at end of file +} diff --git a/Scripts/NodeGraph.cs b/Scripts/NodeGraph.cs index d6d766c..6b95fc2 100644 --- a/Scripts/NodeGraph.cs +++ b/Scripts/NodeGraph.cs @@ -18,18 +18,20 @@ namespace XNode { /// Add a node to the graph by type public virtual Node AddNode(Type type) { + Node.graphHotfix = this; Node node = ScriptableObject.CreateInstance(type) as Node; - nodes.Add(node); node.graph = this; + nodes.Add(node); return node; } /// Creates a copy of the original node in the graph public virtual Node CopyNode(Node original) { + Node.graphHotfix = this; Node node = ScriptableObject.Instantiate(original); + node.graph = this; node.ClearConnections(); nodes.Add(node); - node.graph = this; return node; } @@ -58,6 +60,7 @@ namespace XNode { // 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; From 5b11e8102781cf7f24a91a70c872ee8b7be59087 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 15 Dec 2018 12:40:16 +0100 Subject: [PATCH 28/73] Move context menu functions around to allow more customization (#87) Moved NodeEditorWindow.ShowNodeContextMenu to NodeEditor.AddContextMenuItems Moved NodeEditorWindow.ShowGraphContextMenu to NodeGraphEditor.AddContextMenuItems Moved NodeEditorWindow.CreateNode to NodeGraphEditor.CreateNode --- Scripts/Editor/NodeEditor.cs | 20 ++++++++++ Scripts/Editor/NodeEditorAction.cs | 17 +++----- Scripts/Editor/NodeEditorGUI.cs | 54 -------------------------- Scripts/Editor/NodeEditorReflection.cs | 11 ++++++ Scripts/Editor/NodeGraphEditor.cs | 29 ++++++++++++++ 5 files changed, 66 insertions(+), 65 deletions(-) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index 8b06c26..f38b510 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -81,6 +81,26 @@ namespace XNodeEditor { return NodeEditorResources.styles.nodeBody; } + /// Add items for the context menu when right-clicking this node. Override to add custom menu items. + public virtual void AddContextMenuItems(GenericMenu menu) { + // Actions if only one node is selected + if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { + XNode.Node node = Selection.activeObject as XNode.Node; + menu.AddItem(new GUIContent("Move To Top"), false, () => NodeEditorWindow.current.MoveNodeToTop(node)); + menu.AddItem(new GUIContent("Rename"), false, NodeEditorWindow.current.RenameSelectedNode); + } + + // Add actions to any number of selected nodes + menu.AddItem(new GUIContent("Duplicate"), false, NodeEditorWindow.current.DuplicateSelectedNodes); + menu.AddItem(new GUIContent("Remove"), false, NodeEditorWindow.current.RemoveSelectedNodes); + + // Custom sctions if only one node is selected + if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { + XNode.Node node = Selection.activeObject as XNode.Node; + NodeEditorWindow.AddCustomContextMenuItems(menu, node); + } + } + public void InitiateRename() { renaming = 1; } diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index b5315f8..d8d36cb 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -260,9 +260,13 @@ namespace XNodeEditor { ShowPortContextMenu(hoveredPort); } else if (IsHoveringNode && IsHoveringTitle(hoveredNode)) { if (!Selection.Contains(hoveredNode)) SelectNode(hoveredNode, false); - ShowNodeContextMenu(); + GenericMenu menu = new GenericMenu(); + NodeEditor.GetEditor(hoveredNode).AddContextMenuItems(menu); + menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); } else if (!IsHoveringNode) { - ShowGraphContextMenu(); + GenericMenu menu = new GenericMenu(); + graphEditor.AddContextMenuItems(menu); + menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); } } isPanning = false; @@ -323,15 +327,6 @@ namespace XNodeEditor { panOffset = Vector2.zero; } - public void CreateNode(Type type, Vector2 position) { - XNode.Node node = graph.AddNode(type); - node.position = position; - node.name = UnityEditor.ObjectNames.NicifyVariableName(type.Name); - AssetDatabase.AddObjectToAsset(node, graph); - if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); - Repaint(); - } - /// Remove nodes in the graph in Selection.objects public void RemoveSelectedNodes() { // We need to delete reroutes starting at the highest point index to avoid shifting indices diff --git a/Scripts/Editor/NodeEditorGUI.cs b/Scripts/Editor/NodeEditorGUI.cs index 8d7b95a..9f48f0e 100644 --- a/Scripts/Editor/NodeEditorGUI.cs +++ b/Scripts/Editor/NodeEditorGUI.cs @@ -116,60 +116,6 @@ namespace XNodeEditor { if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); } - /// Show right-click context menu for selected nodes - public void ShowNodeContextMenu() { - GenericMenu contextMenu = new GenericMenu(); - // If only one node is selected - if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { - XNode.Node node = Selection.activeObject as XNode.Node; - contextMenu.AddItem(new GUIContent("Move To Top"), false, () => MoveNodeToTop(node)); - contextMenu.AddItem(new GUIContent("Rename"), false, RenameSelectedNode); - } - - contextMenu.AddItem(new GUIContent("Duplicate"), false, DuplicateSelectedNodes); - contextMenu.AddItem(new GUIContent("Remove"), false, RemoveSelectedNodes); - - // If only one node is selected - if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { - XNode.Node node = Selection.activeObject as XNode.Node; - AddCustomContextMenuItems(contextMenu, node); - } - - contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); - } - - /// Show right-click context menu for current graph - void ShowGraphContextMenu() { - GenericMenu contextMenu = new GenericMenu(); - Vector2 pos = WindowToGridPosition(Event.current.mousePosition); - for (int i = 0; i < nodeTypes.Length; i++) { - Type type = nodeTypes[i]; - - //Get node context menu path - string path = graphEditor.GetNodeMenuName(type); - if (string.IsNullOrEmpty(path)) continue; - - contextMenu.AddItem(new GUIContent(path), false, () => { - CreateNode(type, pos); - }); - } - contextMenu.AddSeparator(""); - contextMenu.AddItem(new GUIContent("Preferences"), false, () => OpenPreferences()); - AddCustomContextMenuItems(contextMenu, graph); - contextMenu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); - } - - void AddCustomContextMenuItems(GenericMenu contextMenu, object obj) { - KeyValuePair[] items = GetContextMenuMethods(obj); - if (items.Length != 0) { - contextMenu.AddSeparator(""); - for (int i = 0; i < items.Length; i++) { - KeyValuePair kvp = items[i]; - contextMenu.AddItem(new GUIContent(kvp.Key.menuItem), false, () => kvp.Value.Invoke(obj, null)); - } - } - } - /// Draw a bezier from startpoint to endpoint, both in grid coordinates public void DrawConnection(Vector2 startPoint, Vector2 endPoint, Color col) { startPoint = GridToWindowPosition(startPoint); diff --git a/Scripts/Editor/NodeEditorReflection.cs b/Scripts/Editor/NodeEditorReflection.cs index 42e583c..bfe8307 100644 --- a/Scripts/Editor/NodeEditorReflection.cs +++ b/Scripts/Editor/NodeEditorReflection.cs @@ -71,6 +71,17 @@ namespace XNodeEditor { return types.ToArray(); } + public static void AddCustomContextMenuItems(GenericMenu contextMenu, object obj) { + KeyValuePair[] items = GetContextMenuMethods(obj); + if (items.Length != 0) { + contextMenu.AddSeparator(""); + for (int i = 0; i < items.Length; i++) { + KeyValuePair kvp = items[i]; + contextMenu.AddItem(new GUIContent(kvp.Key.menuItem), false, () => kvp.Value.Invoke(obj, null)); + } + } + } + public static KeyValuePair[] GetContextMenuMethods(object obj) { Type type = obj.GetType(); MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); diff --git a/Scripts/Editor/NodeGraphEditor.cs b/Scripts/Editor/NodeGraphEditor.cs index 1c32a6e..20f5657 100644 --- a/Scripts/Editor/NodeGraphEditor.cs +++ b/Scripts/Editor/NodeGraphEditor.cs @@ -38,10 +38,39 @@ namespace XNodeEditor { return ObjectNames.NicifyVariableName(type.ToString().Replace('.', '/')); } + /// Add items for the context menu when right-clicking this node. Override to add custom menu items. + public virtual void AddContextMenuItems(GenericMenu menu) { + Vector2 pos = NodeEditorWindow.current.WindowToGridPosition(Event.current.mousePosition); + for (int i = 0; i < NodeEditorWindow.nodeTypes.Length; i++) { + Type type = NodeEditorWindow.nodeTypes[i]; + + //Get node context menu path + string path = GetNodeMenuName(type); + if (string.IsNullOrEmpty(path)) continue; + + menu.AddItem(new GUIContent(path), false, () => { + CreateNode(type, pos); + }); + } + menu.AddSeparator(""); + menu.AddItem(new GUIContent("Preferences"), false, () => NodeEditorWindow.OpenPreferences()); + NodeEditorWindow.AddCustomContextMenuItems(menu, target); + } + public virtual Color GetTypeColor(Type type) { return NodeEditorPreferences.GetTypeColor(type); } + /// Create a node and save it in the graph asset + public virtual void CreateNode(Type type, Vector2 position) { + XNode.Node node = target.AddNode(type); + node.position = position; + node.name = UnityEditor.ObjectNames.NicifyVariableName(type.Name); + AssetDatabase.AddObjectToAsset(node, target); + if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); + NodeEditorWindow.RepaintAll(); + } + /// Creates a copy of the original node in the graph public XNode.Node CopyNode(XNode.Node original) { XNode.Node node = target.CopyNode(original); From 3b18ca9b02bfd9ac6a52177e954f40eb12a708fc Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Sat, 15 Dec 2018 14:33:34 +0100 Subject: [PATCH 29/73] FetchSettingsProviders has been removed in 2018.3.0f2. Now preferences is opened like this. --- Scripts/Editor/NodeEditorReflection.cs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/Scripts/Editor/NodeEditorReflection.cs b/Scripts/Editor/NodeEditorReflection.cs index bfe8307..04c6484 100644 --- a/Scripts/Editor/NodeEditorReflection.cs +++ b/Scripts/Editor/NodeEditorReflection.cs @@ -113,12 +113,7 @@ namespace XNodeEditor { public static void OpenPreferences() { try { #if UNITY_2018_3_OR_NEWER - foreach (SettingsProvider settingsProvider in SettingsService.FetchSettingsProviders()) { - if (settingsProvider.name == "Node Editor") { - EditorPrefs.SetString("SettingsWindow_Preferences_current_provider", settingsProvider.settingsPath); - EditorApplication.ExecuteMenuItem("Edit/Preferences..."); - } - } + SettingsService.OpenUserPreferences("Preferences/Node Editor"); #else //Open preferences window Assembly assembly = Assembly.GetAssembly(typeof(UnityEditor.EditorWindow)); From fe2b7a9684e27286f8cd70e097d12b90de9660b2 Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Tue, 18 Dec 2018 10:00:10 +0100 Subject: [PATCH 30/73] Fix for [Space] attribute (#90) * Fix for [Space] attribute. Code is a bit messy. * Exchanged EditorGUILayout.Space() to GUILayout.Space() that takes a parameter height, for custom space distances. * Changed where implementation is added to not messy up the rest of the code. --- Scripts/Editor/NodeEditorGUILayout.cs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index c1c1665..b17fea3 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -43,6 +43,10 @@ namespace XNodeEditor { else { Rect rect = new Rect(); + float spacePadding = 0; + SpaceAttribute spaceAttribute; + if(NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out spaceAttribute)) spacePadding = spaceAttribute.height; + // 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) { // Get data from [Input] attribute @@ -54,6 +58,15 @@ namespace XNodeEditor { showBacking = inputAttribute.backingValue; } + //Call GUILayout.Space if Space attribute is set and we are NOT drawing a PropertyField + bool useLayoutSpace = instancePortList + || showBacking == XNode.Node.ShowBackingValue.Never + || (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected); + if (spacePadding > 0 && useLayoutSpace) { + GUILayout.Space(spacePadding); + spacePadding = 0; + } + if (instancePortList) { Type type = GetType(property); XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; @@ -78,7 +91,7 @@ namespace XNodeEditor { } rect = GUILayoutUtility.GetLastRect(); - rect.position = rect.position - new Vector2(16, 0); + rect.position = rect.position - new Vector2(16, -spacePadding); // 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) { // Get data from [Output] attribute @@ -90,6 +103,16 @@ namespace XNodeEditor { showBacking = outputAttribute.backingValue; } + //Call GUILayout.Space if Space attribute is set and we are NOT drawing a PropertyField + bool useLayoutSpace = instancePortList + || showBacking == XNode.Node.ShowBackingValue.Never + || (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected); + if (spacePadding > 0 && useLayoutSpace) + { + GUILayout.Space(spacePadding); + spacePadding = 0; + } + if (instancePortList) { Type type = GetType(property); XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; @@ -114,7 +137,7 @@ namespace XNodeEditor { } rect = GUILayoutUtility.GetLastRect(); - rect.position = rect.position + new Vector2(rect.width, 0); + rect.position = rect.position + new Vector2(rect.width, spacePadding); } rect.size = new Vector2(16, 16); From e6530d87d6f4e2c3bef9d02506383c48a1d4341c Mon Sep 17 00:00:00 2001 From: Patrik Lindberg Date: Fri, 21 Dec 2018 11:44:15 +0100 Subject: [PATCH 31/73] Zooming is now centered around the mouse position. --- Scripts/Editor/NodeEditorAction.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index d8d36cb..e43ec7b 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -52,8 +52,10 @@ namespace XNodeEditor { case EventType.MouseMove: break; case EventType.ScrollWheel: + var oldZoom = zoom; if (e.delta.y > 0) zoom += 0.1f * zoom; else zoom -= 0.1f * zoom; + panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset); break; case EventType.MouseDrag: if (e.button == 0) { From 842101720e3c39e35ddb0f35da6d845086a486cb Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Fri, 21 Dec 2018 13:39:52 +0100 Subject: [PATCH 32/73] Changed so Dictionary now uses Type as key. Uses PrettyName less. Also changed to TryGetValue instead of ContainsKey in GetTypeColor() --- Scripts/Editor/NodeEditorPreferences.cs | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/Scripts/Editor/NodeEditorPreferences.cs b/Scripts/Editor/NodeEditorPreferences.cs index 210a619..35c39a1 100644 --- a/Scripts/Editor/NodeEditorPreferences.cs +++ b/Scripts/Editor/NodeEditorPreferences.cs @@ -12,7 +12,7 @@ namespace XNodeEditor { /// The last key we checked. This should be the one we modify private static string lastKey = "xNode.Settings"; - private static Dictionary typeColors = new Dictionary(); + private static Dictionary typeColors = new Dictionary(); private static Dictionary settings = new Dictionary(); [System.Serializable] @@ -134,15 +134,16 @@ namespace XNodeEditor { EditorGUILayout.LabelField("Types", EditorStyles.boldLabel); //Display type colors. Save them if they are edited by the user - List typeColorKeys = new List(typeColors.Keys); - foreach (string typeColorKey in typeColorKeys) { - Color col = typeColors[typeColorKey]; + foreach (var typeColor in typeColors) { + Type type = typeColor.Key; + string typeColorKey = NodeEditorUtilities.PrettyName(type); + Color col = typeColor.Value; EditorGUI.BeginChangeCheck(); EditorGUILayout.BeginHorizontal(); col = EditorGUILayout.ColorField(typeColorKey, col); EditorGUILayout.EndHorizontal(); if (EditorGUI.EndChangeCheck()) { - typeColors[typeColorKey] = col; + typeColors[type] = col; if (settings.typeColors.ContainsKey(typeColorKey)) settings.typeColors[typeColorKey] = col; else settings.typeColors.Add(typeColorKey, col); SavePrefs(typeColorKey, settings); @@ -165,7 +166,7 @@ namespace XNodeEditor { public static void ResetPrefs() { if (EditorPrefs.HasKey(lastKey)) EditorPrefs.DeleteKey(lastKey); if (settings.ContainsKey(lastKey)) settings.Remove(lastKey); - typeColors = new Dictionary(); + typeColors = new Dictionary(); VerifyLoaded(); NodeEditorWindow.RepaintAll(); } @@ -184,19 +185,21 @@ namespace XNodeEditor { public static Color GetTypeColor(System.Type type) { VerifyLoaded(); if (type == null) return Color.gray; - string typeName = type.PrettyName(); - if (!typeColors.ContainsKey(typeName)) { - if (settings[lastKey].typeColors.ContainsKey(typeName)) typeColors.Add(typeName, settings[lastKey].typeColors[typeName]); + Color col; + if (!typeColors.TryGetValue(type, out col)) { + string typeName = type.PrettyName(); + if (settings[lastKey].typeColors.ContainsKey(typeName)) typeColors.Add(type, settings[lastKey].typeColors[typeName]); else { #if UNITY_5_4_OR_NEWER UnityEngine.Random.InitState(typeName.GetHashCode()); #else UnityEngine.Random.seed = typeName.GetHashCode(); #endif - typeColors.Add(typeName, new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value)); + col = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); + typeColors.Add(type, col); } } - return typeColors[typeName]; + return col; } } } \ No newline at end of file From 3d1da00652bafe5850fa1fee66be0389b6dec51c Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Fri, 21 Dec 2018 14:54:12 +0100 Subject: [PATCH 33/73] Caches attributes, generates no garbage after first fetch. Cache gets reset on recompilation of code. --- Scripts/Editor/NodeEditorGUILayout.cs | 6 +++--- Scripts/Editor/NodeEditorUtilities.cs | 31 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index b17fea3..8089265 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -45,7 +45,7 @@ namespace XNodeEditor { float spacePadding = 0; SpaceAttribute spaceAttribute; - if(NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out spaceAttribute)) spacePadding = spaceAttribute.height; + if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out spaceAttribute)) spacePadding = spaceAttribute.height; // 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) { @@ -53,7 +53,7 @@ namespace XNodeEditor { XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected; XNode.Node.InputAttribute inputAttribute; bool instancePortList = false; - if (NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out inputAttribute)) { + if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute)) { instancePortList = inputAttribute.instancePortList; showBacking = inputAttribute.backingValue; } @@ -98,7 +98,7 @@ namespace XNodeEditor { XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected; XNode.Node.OutputAttribute outputAttribute; bool instancePortList = false; - if (NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out outputAttribute)) { + if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute)) { instancePortList = outputAttribute.instancePortList; showBacking = outputAttribute.backingValue; } diff --git a/Scripts/Editor/NodeEditorUtilities.cs b/Scripts/Editor/NodeEditorUtilities.cs index 0d98420..828207f 100644 --- a/Scripts/Editor/NodeEditorUtilities.cs +++ b/Scripts/Editor/NodeEditorUtilities.cs @@ -15,6 +15,9 @@ namespace XNodeEditor { /// C#'s Script Icon [The one MonoBhevaiour Scripts have]. private static Texture2D scriptIcon = (EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D); + /// Saves Attribute from Type+Field for faster lookup. Resets on recompiles. + private static Dictionary>> typeAttributes = new Dictionary>>(); + public static bool GetAttrib(Type classType, out T attribOut) where T : Attribute { object[] attribs = classType.GetCustomAttributes(typeof(T), false); return GetAttrib(attribs, out attribOut); @@ -45,6 +48,34 @@ namespace XNodeEditor { return false; } + public static bool GetCachedAttrib(Type classType, string fieldName, out T attribOut) where T : Attribute { + Dictionary> typeFields; + if (!typeAttributes.TryGetValue(classType, out typeFields)) { + typeFields = new Dictionary>(); + typeAttributes.Add(classType, typeFields); + } + + Dictionary typeTypes; + if(!typeFields.TryGetValue(fieldName, out typeTypes)) { + typeTypes = new Dictionary(); + typeFields.Add(fieldName, typeTypes); + } + + Attribute attr; + if (!typeTypes.TryGetValue(typeof(T), out attr)) { + if (GetAttrib(classType, fieldName, out attribOut)) typeTypes.Add(typeof(T), attribOut); + else typeTypes.Add(typeof(T), null); + } + + if(attr == null) { + attribOut = null; + return false; + } + + attribOut = attr as T; + return true; + } + /// Returns true if this can be casted to public static bool IsCastableTo(this Type from, Type to) { if (to.IsAssignableFrom(from)) return true; From 3ced922ce6c7c778f309efa8e3aaa9f3d663f737 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sun, 23 Dec 2018 10:21:03 +0100 Subject: [PATCH 34/73] Add zoomToMouse setting in preferences --- Scripts/Editor/NodeEditorAction.cs | 4 ++-- Scripts/Editor/NodeEditorPreferences.cs | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index e43ec7b..f3ebde4 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -52,10 +52,10 @@ namespace XNodeEditor { case EventType.MouseMove: break; case EventType.ScrollWheel: - var oldZoom = zoom; + float oldZoom = zoom; if (e.delta.y > 0) zoom += 0.1f * zoom; else zoom -= 0.1f * zoom; - panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset); + if (NodeEditorPreferences.GetSettings().zoomToMouse) panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset); break; case EventType.MouseDrag: if (e.button == 0) { diff --git a/Scripts/Editor/NodeEditorPreferences.cs b/Scripts/Editor/NodeEditorPreferences.cs index 210a619..b3a8d83 100644 --- a/Scripts/Editor/NodeEditorPreferences.cs +++ b/Scripts/Editor/NodeEditorPreferences.cs @@ -26,6 +26,7 @@ namespace XNodeEditor { public Color32 highlightColor = new Color32(255, 255, 255, 255); public bool gridSnap = true; public bool autoSave = true; + public bool zoomToMouse = true; [SerializeField] private string typeColorsData = ""; [NonSerialized] public Dictionary typeColors = new Dictionary(); public NoodleType noodleType = NoodleType.Curve; @@ -98,6 +99,7 @@ namespace XNodeEditor { //Label EditorGUILayout.LabelField("Grid", EditorStyles.boldLabel); settings.gridSnap = EditorGUILayout.Toggle(new GUIContent("Snap", "Hold CTRL in editor to invert"), settings.gridSnap); + settings.zoomToMouse = EditorGUILayout.Toggle(new GUIContent("Zoom to Mouse", "Zooms towards mouse position"), settings.zoomToMouse); settings.gridLineColor = EditorGUILayout.ColorField("Color", settings.gridLineColor); settings.gridBgColor = EditorGUILayout.ColorField(" ", settings.gridBgColor); From 8d445fa3f49e58ed29f2cf6fa0143e7a06e690b5 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Thu, 27 Dec 2018 02:47:15 +0100 Subject: [PATCH 35/73] Fixed formatting --- Scripts/Editor/NodeEditorPreferences.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Scripts/Editor/NodeEditorPreferences.cs b/Scripts/Editor/NodeEditorPreferences.cs index 35c39a1..fd5ddfd 100644 --- a/Scripts/Editor/NodeEditorPreferences.cs +++ b/Scripts/Editor/NodeEditorPreferences.cs @@ -135,9 +135,9 @@ namespace XNodeEditor { //Display type colors. Save them if they are edited by the user foreach (var typeColor in typeColors) { - Type type = typeColor.Key; - string typeColorKey = NodeEditorUtilities.PrettyName(type); - Color col = typeColor.Value; + Type type = typeColor.Key; + string typeColorKey = NodeEditorUtilities.PrettyName(type); + Color col = typeColor.Value; EditorGUI.BeginChangeCheck(); EditorGUILayout.BeginHorizontal(); col = EditorGUILayout.ColorField(typeColorKey, col); @@ -185,9 +185,9 @@ namespace XNodeEditor { public static Color GetTypeColor(System.Type type) { VerifyLoaded(); if (type == null) return Color.gray; - Color col; + Color col; if (!typeColors.TryGetValue(type, out col)) { - string typeName = type.PrettyName(); + string typeName = type.PrettyName(); if (settings[lastKey].typeColors.ContainsKey(typeName)) typeColors.Add(type, settings[lastKey].typeColors[typeName]); else { #if UNITY_5_4_OR_NEWER @@ -195,8 +195,8 @@ namespace XNodeEditor { #else UnityEngine.Random.seed = typeName.GetHashCode(); #endif - col = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); - typeColors.Add(type, col); + col = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); + typeColors.Add(type, col); } } return col; From c321c276d186714e19096a374e71a8d5dea21679 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Thu, 27 Dec 2018 02:55:09 +0100 Subject: [PATCH 36/73] Fixed formatting --- Scripts/Editor/NodeEditorGUILayout.cs | 17 ++++++++--------- Scripts/Editor/NodeEditorUtilities.cs | 4 ++-- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 8089265..30f6426 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -45,7 +45,7 @@ namespace XNodeEditor { float spacePadding = 0; SpaceAttribute spaceAttribute; - if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out spaceAttribute)) spacePadding = spaceAttribute.height; + if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out spaceAttribute)) spacePadding = spaceAttribute.height; // 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) { @@ -59,9 +59,9 @@ namespace XNodeEditor { } //Call GUILayout.Space if Space attribute is set and we are NOT drawing a PropertyField - bool useLayoutSpace = instancePortList - || showBacking == XNode.Node.ShowBackingValue.Never - || (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected); + bool useLayoutSpace = instancePortList || + showBacking == XNode.Node.ShowBackingValue.Never || + (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected); if (spacePadding > 0 && useLayoutSpace) { GUILayout.Space(spacePadding); spacePadding = 0; @@ -104,11 +104,10 @@ namespace XNodeEditor { } //Call GUILayout.Space if Space attribute is set and we are NOT drawing a PropertyField - bool useLayoutSpace = instancePortList - || showBacking == XNode.Node.ShowBackingValue.Never - || (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected); - if (spacePadding > 0 && useLayoutSpace) - { + bool useLayoutSpace = instancePortList || + showBacking == XNode.Node.ShowBackingValue.Never || + (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected); + if (spacePadding > 0 && useLayoutSpace) { GUILayout.Space(spacePadding); spacePadding = 0; } diff --git a/Scripts/Editor/NodeEditorUtilities.cs b/Scripts/Editor/NodeEditorUtilities.cs index 828207f..ebc7bd4 100644 --- a/Scripts/Editor/NodeEditorUtilities.cs +++ b/Scripts/Editor/NodeEditorUtilities.cs @@ -56,7 +56,7 @@ namespace XNodeEditor { } Dictionary typeTypes; - if(!typeFields.TryGetValue(fieldName, out typeTypes)) { + if (!typeFields.TryGetValue(fieldName, out typeTypes)) { typeTypes = new Dictionary(); typeFields.Add(fieldName, typeTypes); } @@ -67,7 +67,7 @@ namespace XNodeEditor { else typeTypes.Add(typeof(T), null); } - if(attr == null) { + if (attr == null) { attribOut = null; return false; } From 96d73bcb81afff60da58259481f34e12b4c07ce2 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 5 Jan 2019 22:00:57 +0100 Subject: [PATCH 37/73] Better error handling for InstancePortLists --- Scripts/Editor/NodeEditorGUILayout.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 30f6426..6129dd8 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -304,6 +304,10 @@ namespace XNodeEditor { (Rect rect, int index, bool isActive, bool isFocused) => { XNode.NodePort port = node.GetPort(arrayData.name + " " + index); if (hasArrayData) { + if (arrayData.arraySize <= index) { + EditorGUI.LabelField(rect, "Invalid element " + index); + return; + } SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); EditorGUI.PropertyField(rect, itemData); } else EditorGUI.LabelField(rect, port.fieldName); @@ -313,6 +317,7 @@ namespace XNodeEditor { list.elementHeightCallback = (int index) => { if (hasArrayData) { + if (arrayData.arraySize <= index) return EditorGUIUtility.singleLineHeight; SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); return EditorGUI.GetPropertyHeight(itemData); } else return EditorGUIUtility.singleLineHeight; From b08d706e0d2a194ec444bedf902a0861056012d7 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Thu, 10 Jan 2019 18:15:16 +0100 Subject: [PATCH 38/73] Changed custom InstancePortList API. See: NodeEditorGUILayout.InstancePortList --- Scripts/Editor/NodeEditorGUILayout.cs | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 6129dd8..7c5800e 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -11,8 +11,6 @@ namespace XNodeEditor { /// xNode-specific version of public static class NodeEditorGUILayout { - /// Listen for this event if you want to alter the default ReorderableList - public static Action onCreateReorderableList; private static readonly Dictionary> reorderableListCache = new Dictionary>(); private static int reorderableListIndex = -1; @@ -256,17 +254,13 @@ namespace XNodeEditor { GUI.color = col; } - [Obsolete("Use InstancePortList(string, Type, SerializedObject, NodePort.IO, Node.ConnectionType) instead")] - public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple) { - InstancePortList(fieldName, type, serializedObject, XNode.NodePort.IO.Output, connectionType); - } - /// Draw an editable list of instance ports. Port names are named as "[fieldName] [index]" /// Supply a list for editable values /// Value type of added instance ports /// The serializedObject of the node /// Connection type of added instance ports - public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple) { + /// Called on the list on creation. Use this if you want to customize the created ReorderableList + public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple, Action onCreation = null) { XNode.Node node = serializedObject.targetObject as XNode.Node; SerializedProperty arrayData = serializedObject.FindProperty(fieldName); @@ -286,7 +280,7 @@ namespace XNodeEditor { // If a ReorderableList isn't cached for this array, do so. if (list == null) { string label = serializedObject.FindProperty(fieldName).displayName; - list = CreateReorderableList(instancePorts, arrayData, type, serializedObject, io, label, connectionType); + list = CreateReorderableList(instancePorts, arrayData, type, serializedObject, io, label, connectionType, onCreation); if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list); else reorderableListCache.Add(serializedObject.targetObject, new Dictionary() { { fieldName, list } }); } @@ -294,7 +288,7 @@ namespace XNodeEditor { list.DoLayoutList(); } - private static ReorderableList CreateReorderableList(List instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, string label, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple) { + private static ReorderableList CreateReorderableList(List instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, string label, XNode.Node.ConnectionType connectionType, Action onCreation) { bool hasArrayData = arrayData != null && arrayData.isArray; int arraySize = hasArrayData ? arrayData.arraySize : 0; XNode.Node node = serializedObject.targetObject as XNode.Node; @@ -324,7 +318,7 @@ namespace XNodeEditor { }; list.drawHeaderCallback = (Rect rect) => { - EditorGUI.LabelField(rect, label); + EditorGUI.LabelField(rect, label + "(" + serializedObject.targetObject.name + ")"); }; list.onSelectCallback = (ReorderableList rl) => { @@ -413,7 +407,7 @@ namespace XNodeEditor { while (instancePorts.Count <= arraySize) { arrayData.DeleteArrayElementAtIndex(--arraySize); } - Debug.LogWarning("Array size exceeded instance ports size. Excess items removed."); + UnityEngine.Debug.LogWarning("Array size exceeded instance ports size. Excess items removed."); } serializedObject.ApplyModifiedProperties(); serializedObject.Update(); @@ -440,7 +434,7 @@ namespace XNodeEditor { serializedObject.ApplyModifiedProperties(); serializedObject.Update(); } - if (onCreateReorderableList != null) onCreateReorderableList(list); + if (onCreation != null) onCreation(list); return list; } } From d397e3a2084404e8308a55227dadedbce73d6705 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Thu, 10 Jan 2019 19:54:11 +0100 Subject: [PATCH 39/73] Improved NodeEnumDrawer serialization --- Scripts/Attributes/NodeEnum.cs | 1 + Scripts/Editor/Drawers/NodeEnumDrawer.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/Scripts/Attributes/NodeEnum.cs b/Scripts/Attributes/NodeEnum.cs index 9a5c12a..9cdaef4 100644 --- a/Scripts/Attributes/NodeEnum.cs +++ b/Scripts/Attributes/NodeEnum.cs @@ -1,4 +1,5 @@ using UnityEngine; /// Draw enums correctly within nodes. Without it, enums show up at the wrong positions. +/// Enums with this attribute are not detected by EditorGui.ChangeCheck due to waiting before executing public class NodeEnumAttribute : PropertyAttribute { } \ No newline at end of file diff --git a/Scripts/Editor/Drawers/NodeEnumDrawer.cs b/Scripts/Editor/Drawers/NodeEnumDrawer.cs index cdb6511..3e770f2 100644 --- a/Scripts/Editor/Drawers/NodeEnumDrawer.cs +++ b/Scripts/Editor/Drawers/NodeEnumDrawer.cs @@ -51,6 +51,7 @@ namespace XNodeEditor { private void SetEnum(SerializedProperty property, int index) { property.enumValueIndex = index; property.serializedObject.ApplyModifiedProperties(); + property.serializedObject.Update(); } } } \ No newline at end of file From 432ca092749ac8ea73a5a9671d5f1456a716d945 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Fri, 11 Jan 2019 18:38:54 +0100 Subject: [PATCH 40/73] Removed debug info --- Scripts/Editor/NodeEditorGUILayout.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 7c5800e..dcb7099 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -318,7 +318,7 @@ namespace XNodeEditor { }; list.drawHeaderCallback = (Rect rect) => { - EditorGUI.LabelField(rect, label + "(" + serializedObject.targetObject.name + ")"); + EditorGUI.LabelField(rect, label); }; list.onSelectCallback = (ReorderableList rl) => { From 5ee63d3ee59f804d2de43a49409d2ac5c6b8d848 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Fri, 11 Jan 2019 18:54:44 +0100 Subject: [PATCH 41/73] Fixed #96 InstancePortLists no longer need to point to a serialized property --- Scripts/Editor/NodeEditorGUILayout.cs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index dcb7099..d021655 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -262,7 +262,6 @@ namespace XNodeEditor { /// Called on the list on creation. Use this if you want to customize the created ReorderableList public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple, Action onCreation = null) { XNode.Node node = serializedObject.targetObject as XNode.Node; - SerializedProperty arrayData = serializedObject.FindProperty(fieldName); Predicate isMatchingInstancePort = x => { @@ -279,8 +278,8 @@ namespace XNodeEditor { } // If a ReorderableList isn't cached for this array, do so. if (list == null) { - string label = serializedObject.FindProperty(fieldName).displayName; - list = CreateReorderableList(instancePorts, arrayData, type, serializedObject, io, label, connectionType, onCreation); + SerializedProperty arrayData = serializedObject.FindProperty(fieldName); + list = CreateReorderableList(fieldName, instancePorts, arrayData, type, serializedObject, io, connectionType, onCreation); if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list); else reorderableListCache.Add(serializedObject.targetObject, new Dictionary() { { fieldName, list } }); } @@ -288,15 +287,16 @@ namespace XNodeEditor { list.DoLayoutList(); } - private static ReorderableList CreateReorderableList(List instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, string label, XNode.Node.ConnectionType connectionType, Action onCreation) { + private static ReorderableList CreateReorderableList(string fieldName, List instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType, Action onCreation) { bool hasArrayData = arrayData != null && arrayData.isArray; int arraySize = hasArrayData ? arrayData.arraySize : 0; XNode.Node node = serializedObject.targetObject as XNode.Node; ReorderableList list = new ReorderableList(instancePorts, null, true, true, true, true); + string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName); list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { - XNode.NodePort port = node.GetPort(arrayData.name + " " + index); + XNode.NodePort port = node.GetPort(fieldName + " " + index); if (hasArrayData) { if (arrayData.arraySize <= index) { EditorGUI.LabelField(rect, "Invalid element " + index); @@ -330,8 +330,8 @@ namespace XNodeEditor { // Move up if (rl.index > reorderableListIndex) { for (int i = reorderableListIndex; i < rl.index; ++i) { - XNode.NodePort port = node.GetPort(arrayData.name + " " + i); - XNode.NodePort nextPort = node.GetPort(arrayData.name + " " + (i + 1)); + XNode.NodePort port = node.GetPort(fieldName + " " + i); + XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i + 1)); port.SwapConnections(nextPort); // Swap cached positions to mitigate twitching @@ -343,8 +343,8 @@ namespace XNodeEditor { // Move down else { for (int i = reorderableListIndex; i > rl.index; --i) { - XNode.NodePort port = node.GetPort(arrayData.name + " " + i); - XNode.NodePort nextPort = node.GetPort(arrayData.name + " " + (i - 1)); + XNode.NodePort port = node.GetPort(fieldName + " " + i); + XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i - 1)); port.SwapConnections(nextPort); // Swap cached positions to mitigate twitching @@ -371,9 +371,9 @@ namespace XNodeEditor { list.onAddCallback = (ReorderableList rl) => { // Add instance port postfixed with an index number - string newName = arrayData.name + " 0"; + string newName = fieldName + " 0"; int i = 0; - while (node.HasPort(newName)) newName = arrayData.name + " " + (++i); + while (node.HasPort(newName)) newName = fieldName + " " + (++i); if (io == XNode.NodePort.IO.Output) node.AddInstanceOutput(type, connectionType, newName); else node.AddInstanceInput(type, connectionType, newName); From c9a4a81c31fc4595d200b0c6e609523bebb93541 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 12 Jan 2019 02:23:00 +0100 Subject: [PATCH 42/73] InstandePortLists draw element include children --- Scripts/Editor/NodeEditorGUILayout.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index d021655..629c594 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -303,7 +303,7 @@ namespace XNodeEditor { return; } SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); - EditorGUI.PropertyField(rect, itemData); + EditorGUI.PropertyField(rect, itemData, true); } else EditorGUI.LabelField(rect, port.fieldName); Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); NodeEditorGUILayout.PortField(pos, port); From 4c9264fed5e02754ecf221c78b033a7ea60bd366 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sun, 20 Jan 2019 22:01:26 +0100 Subject: [PATCH 43/73] Fixed #100 --- Scripts/Editor/NodeEditorUtilities.cs | 2 +- Scripts/NodeDataCache.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Scripts/Editor/NodeEditorUtilities.cs b/Scripts/Editor/NodeEditorUtilities.cs index ebc7bd4..e85631b 100644 --- a/Scripts/Editor/NodeEditorUtilities.cs +++ b/Scripts/Editor/NodeEditorUtilities.cs @@ -35,7 +35,7 @@ namespace XNodeEditor { } public static bool GetAttrib(Type classType, string fieldName, out T attribOut) where T : Attribute { - object[] attribs = classType.GetField(fieldName).GetCustomAttributes(typeof(T), false); + object[] attribs = classType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetCustomAttributes(typeof(T), false); return GetAttrib(attribs, out attribOut); } diff --git a/Scripts/NodeDataCache.cs b/Scripts/NodeDataCache.cs index 283cc9d..415ac21 100644 --- a/Scripts/NodeDataCache.cs +++ b/Scripts/NodeDataCache.cs @@ -69,7 +69,7 @@ namespace XNode { } private static void CachePorts(System.Type nodeType) { - System.Reflection.FieldInfo[] fieldInfo = nodeType.GetFields(); + System.Reflection.FieldInfo[] fieldInfo = nodeType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); for (int i = 0; i < fieldInfo.Length; i++) { //Get InputAttribute and OutputAttribute From 8c731a99478760cbe126c91749c599d58a65081f Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Mon, 21 Jan 2019 21:07:07 +0100 Subject: [PATCH 44/73] Fixed #100 again --- Scripts/Editor/NodeEditorUtilities.cs | 12 +++++++++++- Scripts/NodeDataCache.cs | 18 +++++++++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/Scripts/Editor/NodeEditorUtilities.cs b/Scripts/Editor/NodeEditorUtilities.cs index e85631b..c0eeeb3 100644 --- a/Scripts/Editor/NodeEditorUtilities.cs +++ b/Scripts/Editor/NodeEditorUtilities.cs @@ -35,7 +35,17 @@ namespace XNodeEditor { } public static bool GetAttrib(Type classType, string fieldName, out T attribOut) where T : Attribute { - object[] attribs = classType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetCustomAttributes(typeof(T), false); + // If we can't find field in the first run, it's probably a private field in a base class. + FieldInfo field = classType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + // Search base classes for private fields only. Public fields are found above + while (field == null && (classType = classType.BaseType) != typeof(XNode.Node)) field = classType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); + // This shouldn't happen. Ever. + if (field == null) { + Debug.LogWarning("Field " + fieldName + " couldnt be found"); + attribOut = null; + return false; + } + object[] attribs = field.GetCustomAttributes(typeof(T), false); return GetAttrib(attribs, out attribOut); } diff --git a/Scripts/NodeDataCache.cs b/Scripts/NodeDataCache.cs index 415ac21..8d96146 100644 --- a/Scripts/NodeDataCache.cs +++ b/Scripts/NodeDataCache.cs @@ -68,12 +68,24 @@ namespace XNode { } } + public static List GetNodeFields(System.Type nodeType) { + List fieldInfo = new List(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.AddRange(tempType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)); + } + return fieldInfo; + } + private static void CachePorts(System.Type nodeType) { - System.Reflection.FieldInfo[] fieldInfo = nodeType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - for (int i = 0; i < fieldInfo.Length; i++) { + List fieldInfo = GetNodeFields(nodeType); + + for (int i = 0; i < fieldInfo.Count; i++) { //Get InputAttribute and OutputAttribute - object[] attribs = fieldInfo[i].GetCustomAttributes(false); + 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; From 3972ac5abf8996a6e72c34b59bc73667e24fc698 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Mon, 21 Jan 2019 22:25:05 +0100 Subject: [PATCH 45/73] Allow naming nodes in Init --- Scripts/Editor/NodeGraphEditor.cs | 2 +- Scripts/Node.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Scripts/Editor/NodeGraphEditor.cs b/Scripts/Editor/NodeGraphEditor.cs index 20f5657..81a53c8 100644 --- a/Scripts/Editor/NodeGraphEditor.cs +++ b/Scripts/Editor/NodeGraphEditor.cs @@ -65,7 +65,7 @@ namespace XNodeEditor { public virtual void CreateNode(Type type, Vector2 position) { XNode.Node node = target.AddNode(type); node.position = position; - node.name = UnityEditor.ObjectNames.NicifyVariableName(type.Name); + if (string.IsNullOrEmpty(node.name)) node.name = UnityEditor.ObjectNames.NicifyVariableName(type.Name); AssetDatabase.AddObjectToAsset(node, target); if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); NodeEditorWindow.RepaintAll(); diff --git a/Scripts/Node.cs b/Scripts/Node.cs index 881a297..4a9ace9 100644 --- a/Scripts/Node.cs +++ b/Scripts/Node.cs @@ -76,7 +76,7 @@ namespace XNode { NodeDataCache.UpdatePorts(this, ports); } - /// Initialize node. Called on creation. + /// Initialize node. Called on enable. protected virtual void Init() { } /// Checks all connections for invalid references, and removes them. From 50002a1f6a0abfe2df5810e32ecbbcfa77e597e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=2E=20Tar=C4=B1k=20=C3=87etin?= Date: Thu, 31 Jan 2019 12:40:44 +0300 Subject: [PATCH 46/73] Update README.md Appended qAI project at the end of "Projects using xNode" section of Readme. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 34bb854..904e146 100644 --- a/README.md +++ b/README.md @@ -71,3 +71,4 @@ Feel free to also leave suggestions/requests in the [issues](https://github.com/ Projects using xNode: * [Graphmesh](https://github.com/Siccity/Graphmesh "Go to github page") * [Dialogue](https://github.com/Siccity/Dialogue "Go to github page") +* [qAI](https://github.com/jlreymendez/qAI "Go to github page") From 0f5539e077be5bc2895d14491dc1cd41b53daa82 Mon Sep 17 00:00:00 2001 From: NoiseCrime Date: Wed, 13 Feb 2019 16:17:25 +0000 Subject: [PATCH 47/73] Support for DoubleClick on node to center it. Added support for double clciking on Node header to center that node within the editor window. --- Scripts/Editor/NodeEditorAction.cs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index f3ebde4..5add067 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -22,11 +22,12 @@ namespace XNodeEditor { [NonSerialized] private List draggedOutputReroutes = new List(); private RerouteReference hoveredReroute = new RerouteReference(); private List selectedReroutes = new List(); - private Rect nodeRects; + private Rect nodeRects; // Is this used? private Vector2 dragBoxStart; private UnityEngine.Object[] preBoxSelection; private RerouteReference[] preBoxSelectionReroute; private Rect selectionBox; + private bool isDoubleClick = false; private struct RerouteReference { public XNode.NodePort port; @@ -172,6 +173,10 @@ namespace XNodeEditor { SelectNode(hoveredNode, e.control || e.shift); if (!e.control && !e.shift) selectedReroutes.Clear(); } else if (e.control || e.shift) DeselectNode(hoveredNode); + + // Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown. + isDoubleClick = ( e.clickCount == 2 ); + e.Use(); currentActivity = NodeActivity.HoldNode; } else if (IsHoveringReroute) { @@ -239,6 +244,13 @@ namespace XNodeEditor { if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift)) { selectedReroutes.Clear(); SelectNode(hoveredNode, false); + + // Double click to center node + if ( isDoubleClick ) + { + Vector2 nodeDimension = nodeSizes.ContainsKey( hoveredNode ) ? nodeSizes[ hoveredNode ] / 2 : new Vector2(0f, 0f); + panOffset = -hoveredNode.position - nodeDimension; + } } // If click reroute, select it. @@ -273,6 +285,8 @@ namespace XNodeEditor { } isPanning = false; } + // Reset DoubleClick + isDoubleClick = false; break; case EventType.KeyDown: if (EditorGUIUtility.editingTextField) break; From 2dfe6d3a91ad55d1c0ef055ab898df0bb1e7181c Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Wed, 13 Feb 2019 21:06:56 +0100 Subject: [PATCH 48/73] Fixed formatting --- Scripts/Editor/NodeEditorAction.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index 5add067..dd49a06 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -22,12 +22,11 @@ namespace XNodeEditor { [NonSerialized] private List draggedOutputReroutes = new List(); private RerouteReference hoveredReroute = new RerouteReference(); private List selectedReroutes = new List(); - private Rect nodeRects; // Is this used? private Vector2 dragBoxStart; private UnityEngine.Object[] preBoxSelection; private RerouteReference[] preBoxSelectionReroute; private Rect selectionBox; - private bool isDoubleClick = false; + private bool isDoubleClick = false; private struct RerouteReference { public XNode.NodePort port; @@ -175,7 +174,7 @@ namespace XNodeEditor { } else if (e.control || e.shift) DeselectNode(hoveredNode); // Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown. - isDoubleClick = ( e.clickCount == 2 ); + isDoubleClick = (e.clickCount == 2); e.Use(); currentActivity = NodeActivity.HoldNode; @@ -246,9 +245,8 @@ namespace XNodeEditor { SelectNode(hoveredNode, false); // Double click to center node - if ( isDoubleClick ) - { - Vector2 nodeDimension = nodeSizes.ContainsKey( hoveredNode ) ? nodeSizes[ hoveredNode ] / 2 : new Vector2(0f, 0f); + if (isDoubleClick) { + Vector2 nodeDimension = nodeSizes.ContainsKey(hoveredNode) ? nodeSizes[hoveredNode] / 2 : Vector2.zero; panOffset = -hoveredNode.position - nodeDimension; } } From cda19862e544cedd5db2b9458bc7694c0bd76b6b Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Fri, 15 Feb 2019 08:22:35 +0100 Subject: [PATCH 49/73] Update CONTRIBUTING.md --- CONTRIBUTING.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b96a660..8638230 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,6 +18,14 @@ If your feature aims to cover something not related to editing nodes, it general Skim through the code and you'll get the hang of it quickly. * Methods, Types and properties PascalCase * Variables camelCase -* Public methods XML commented +* Public methods XML commented. Params described if not obvious +* Explicit usage of brackets when doing multiple math operations on the same line + +## Formatting +I use VSCode with the C# FixFormat extension and the following setting overrides: +```json +"csharpfixformat.style.spaces.beforeParenthesis": false, +"csharpfixformat.style.indent.regionIgnored": true +``` * Open braces on same line as condition * 4 spaces for indentation. From d0104f24203526557f20d440339f193e9795340f Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Fri, 15 Feb 2019 09:05:33 +0100 Subject: [PATCH 50/73] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 904e146..16d51b4 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ With a minimal footprint, it is ideal as a base for custom state machines, dialo * No runtime reflection (unless you need to edit/build node graphs at runtime. In this case, all reflection is cached.) * Does not rely on any 3rd party plugins * Custom node inspector code is very similar to regular custom inspector code +* Supported from Unity 5.3 and up ### Wiki * [Getting started](https://github.com/Siccity/xNode/wiki/Getting%20Started) - create your very first node node and graph From 973f9beb1d33ffe1cb7177b1810f1b1f9a024ec9 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 16 Feb 2019 01:22:05 +0100 Subject: [PATCH 51/73] Added support for new SettingsProvider system #109 --- Scripts/Editor/NodeEditorPreferences.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Scripts/Editor/NodeEditorPreferences.cs b/Scripts/Editor/NodeEditorPreferences.cs index e4213ec..e896f34 100644 --- a/Scripts/Editor/NodeEditorPreferences.cs +++ b/Scripts/Editor/NodeEditorPreferences.cs @@ -81,7 +81,20 @@ namespace XNodeEditor { return settings[lastKey]; } +#if UNITY_2019_1_OR_NEWER + [SettingsProvider] + public static SettingsProvider CreateXNodeSettingsProvider() { + SettingsProvider provider = new SettingsProvider("Preferences/Node Editor", SettingsScope.User) { + guiHandler = (searchContext) => { XNodeEditor.NodeEditorPreferences.PreferencesGUI(); }, + keywords = new HashSet(new [] { "xNode", "node", "editor", "graph", "connections", "noodles", "ports" }) + }; + return provider; + } +#endif + +#if !UNITY_2019_1_OR_NEWER [PreferenceItem("Node Editor")] +#endif private static void PreferencesGUI() { VerifyLoaded(); Settings settings = NodeEditorPreferences.settings[lastKey]; From 84e2af7916303cbc205017ce5ca0af0ffe9f4c75 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 16 Feb 2019 01:32:52 +0100 Subject: [PATCH 52/73] Cleanup Postfixed attribute classes with Attribute Added Attributes region --- Scripts/Editor/NodeEditorReflection.cs | 8 ++++---- Scripts/Node.cs | 15 ++++++++------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/Scripts/Editor/NodeEditorReflection.cs b/Scripts/Editor/NodeEditorReflection.cs index 04c6484..21dbf7a 100644 --- a/Scripts/Editor/NodeEditorReflection.cs +++ b/Scripts/Editor/NodeEditorReflection.cs @@ -42,9 +42,9 @@ namespace XNodeEditor { public static Dictionary GetNodeTint() { Dictionary tints = new Dictionary(); for (int i = 0; i < nodeTypes.Length; i++) { - var attribs = nodeTypes[i].GetCustomAttributes(typeof(XNode.Node.NodeTint), true); + var attribs = nodeTypes[i].GetCustomAttributes(typeof(XNode.Node.NodeTintAttribute), true); if (attribs == null || attribs.Length == 0) continue; - XNode.Node.NodeTint attrib = attribs[0] as XNode.Node.NodeTint; + XNode.Node.NodeTintAttribute attrib = attribs[0] as XNode.Node.NodeTintAttribute; tints.Add(nodeTypes[i], attrib.color); } return tints; @@ -53,9 +53,9 @@ namespace XNodeEditor { public static Dictionary GetNodeWidth() { Dictionary widths = new Dictionary(); for (int i = 0; i < nodeTypes.Length; i++) { - var attribs = nodeTypes[i].GetCustomAttributes(typeof(XNode.Node.NodeWidth), true); + var attribs = nodeTypes[i].GetCustomAttributes(typeof(XNode.Node.NodeWidthAttribute), true); if (attribs == null || attribs.Length == 0) continue; - XNode.Node.NodeWidth attrib = attribs[0] as XNode.Node.NodeWidth; + XNode.Node.NodeWidthAttribute attrib = attribs[0] as XNode.Node.NodeWidthAttribute; widths.Add(nodeTypes[i], attrib.width); } return widths; diff --git a/Scripts/Node.cs b/Scripts/Node.cs index 4a9ace9..43d716e 100644 --- a/Scripts/Node.cs +++ b/Scripts/Node.cs @@ -63,7 +63,6 @@ namespace XNode { /// Used during node instantiation to fix null/misconfigured graph during OnEnable/Init. Set it before instantiating a node. Will automatically be unset during OnEnable public static NodeGraph graphHotfix; - protected void OnEnable() { if (graphHotfix != null) graph = graphHotfix; graphHotfix = null; @@ -210,6 +209,7 @@ namespace XNode { return JsonUtility.ToJson(this).GetHashCode(); } +#region Attributes /// Mark a serializable field as an input port. You can access this through [AttributeUsage(AttributeTargets.Field, AllowMultiple = true)] public class InputAttribute : Attribute { @@ -255,19 +255,19 @@ namespace XNode { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class NodeTint : Attribute { + public class NodeTintAttribute : Attribute { public Color color; /// Specify a color for this node type /// Red [0.0f .. 1.0f] /// Green [0.0f .. 1.0f] /// Blue [0.0f .. 1.0f] - public NodeTint(float r, float g, float b) { + public NodeTintAttribute(float r, float g, float b) { color = new Color(r, g, b); } /// Specify a color for this node type /// HEX color value - public NodeTint(string hex) { + public NodeTintAttribute(string hex) { ColorUtility.TryParseHtmlString(hex, out color); } @@ -275,20 +275,21 @@ namespace XNode { /// Red [0 .. 255] /// Green [0 .. 255] /// Blue [0 .. 255] - public NodeTint(byte r, byte g, byte b) { + public NodeTintAttribute(byte r, byte g, byte b) { color = new Color32(r, g, b, byte.MaxValue); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class NodeWidth : Attribute { + public class NodeWidthAttribute : Attribute { public int width; /// Specify a width for this node type /// Width - public NodeWidth(int width) { + public NodeWidthAttribute(int width) { this.width = width; } } +#endregion [Serializable] private class NodePortDictionary : Dictionary, ISerializationCallbackReceiver { [SerializeField] private List keys = new List(); From 71defcbdd5b74996e2604676bdc2001b9143e191 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 16 Feb 2019 02:36:42 +0100 Subject: [PATCH 53/73] Implemented typeConstraint in InputAttribute --- Scripts/Editor/NodeEditorAction.cs | 4 ++-- Scripts/Editor/NodeEditorGUILayout.cs | 14 ++++++------- Scripts/Node.cs | 29 ++++++++++++++++++++------- Scripts/NodeDataCache.cs | 2 +- Scripts/NodePort.cs | 24 +++++++++++++++++++++- 5 files changed, 55 insertions(+), 18 deletions(-) diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index dd49a06..315f23b 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -60,7 +60,7 @@ namespace XNodeEditor { case EventType.MouseDrag: if (e.button == 0) { if (IsDraggingPort) { - if (IsHoveringPort && hoveredPort.IsInput) { + if (IsHoveringPort && hoveredPort.IsInput && draggedOutput.CanConnectTo(hoveredPort)) { if (!draggedOutput.IsConnectedTo(hoveredPort)) { draggedOutputTarget = hoveredPort; } @@ -422,7 +422,7 @@ namespace XNodeEditor { Rect fromRect; if (!_portConnectionPoints.TryGetValue(draggedOutput, out fromRect)) return; Vector2 from = fromRect.center; - col.a = 0.6f; + col.a = draggedOutputTarget != null ? 1.0f : 0.6f; Vector2 to = Vector2.zero; for (int i = 0; i < draggedOutputReroutes.Count; i++) { to = draggedOutputReroutes[i]; diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 629c594..b136dc9 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -260,7 +260,7 @@ namespace XNodeEditor { /// The serializedObject of the node /// Connection type of added instance ports /// Called on the list on creation. Use this if you want to customize the created ReorderableList - public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple, Action onCreation = null) { + 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 onCreation = null) { XNode.Node node = serializedObject.targetObject as XNode.Node; Predicate isMatchingInstancePort = @@ -279,7 +279,7 @@ namespace XNodeEditor { // If a ReorderableList isn't cached for this array, do so. if (list == null) { SerializedProperty arrayData = serializedObject.FindProperty(fieldName); - list = CreateReorderableList(fieldName, instancePorts, arrayData, type, serializedObject, io, connectionType, onCreation); + list = CreateReorderableList(fieldName, instancePorts, arrayData, type, serializedObject, io, connectionType, typeConstraint, onCreation); if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list); else reorderableListCache.Add(serializedObject.targetObject, new Dictionary() { { fieldName, list } }); } @@ -287,7 +287,7 @@ namespace XNodeEditor { list.DoLayoutList(); } - private static ReorderableList CreateReorderableList(string fieldName, List instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType, Action onCreation) { + private static ReorderableList CreateReorderableList(string fieldName, List instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType, XNode.Node.TypeConstraint typeConstraint, Action onCreation) { bool hasArrayData = arrayData != null && arrayData.isArray; int arraySize = hasArrayData ? arrayData.arraySize : 0; XNode.Node node = serializedObject.targetObject as XNode.Node; @@ -375,8 +375,8 @@ namespace XNodeEditor { int i = 0; while (node.HasPort(newName)) newName = fieldName + " " + (++i); - if (io == XNode.NodePort.IO.Output) node.AddInstanceOutput(type, connectionType, newName); - else node.AddInstanceInput(type, connectionType, newName); + if (io == XNode.NodePort.IO.Output) node.AddInstanceOutput(type, connectionType, XNode.Node.TypeConstraint.None, newName); + else node.AddInstanceInput(type, connectionType, typeConstraint, newName); serializedObject.Update(); EditorUtility.SetDirty(node); if (hasArrayData) arrayData.InsertArrayElementAtIndex(arraySize); @@ -422,8 +422,8 @@ namespace XNodeEditor { string newName = arrayData.name + " 0"; int i = 0; while (node.HasPort(newName)) newName = arrayData.name + " " + (++i); - if (io == XNode.NodePort.IO.Output) node.AddInstanceOutput(type, connectionType, newName); - else node.AddInstanceInput(type, connectionType, newName); + if (io == XNode.NodePort.IO.Output) node.AddInstanceOutput(type, connectionType, typeConstraint, newName); + else node.AddInstanceInput(type, connectionType, typeConstraint, newName); EditorUtility.SetDirty(node); instancePortCount++; } diff --git a/Scripts/Node.cs b/Scripts/Node.cs index 43d716e..7c06f92 100644 --- a/Scripts/Node.cs +++ b/Scripts/Node.cs @@ -41,6 +41,16 @@ namespace XNode { Override, } + /// Tells which types of input to allow + public enum TypeConstraint { + /// Allow all types of input + None, + /// Allow similar and inherited types + Inherited, + /// Allow only similar types + Strict, + } + /// Iterate over all ports on this node. public IEnumerable Ports { get { foreach (NodePort port in ports.Values) yield return port; } } /// Iterate over all outputs on this node. @@ -87,21 +97,21 @@ namespace XNode { /// Convenience function. /// /// - public NodePort AddInstanceInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, string fieldName = null) { - return AddInstancePort(type, NodePort.IO.Input, connectionType, fieldName); + public NodePort AddInstanceInput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { + return AddInstancePort(type, NodePort.IO.Input, connectionType, typeConstraint, fieldName); } /// Convenience function. /// /// - public NodePort AddInstanceOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, string fieldName = null) { - return AddInstancePort(type, NodePort.IO.Output, connectionType, fieldName); + public NodePort AddInstanceOutput(Type type, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { + return AddInstancePort(type, NodePort.IO.Output, connectionType, typeConstraint, fieldName); } /// Add a dynamic, serialized port to this node. /// /// - private NodePort AddInstancePort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, string fieldName = null) { + private NodePort AddInstancePort(Type type, NodePort.IO direction, Node.ConnectionType connectionType = Node.ConnectionType.Multiple, Node.TypeConstraint typeConstraint = TypeConstraint.None, string fieldName = null) { if (fieldName == null) { fieldName = "instanceInput_0"; int i = 0; @@ -110,7 +120,7 @@ namespace XNode { Debug.LogWarning("Port '" + fieldName + "' already exists in " + name, this); return ports[fieldName]; } - NodePort port = new NodePort(fieldName, type, direction, connectionType, this); + NodePort port = new NodePort(fieldName, type, direction, connectionType, typeConstraint, this); ports.Add(fieldName, port); return port; } @@ -216,14 +226,18 @@ namespace XNode { public ShowBackingValue backingValue; public ConnectionType connectionType; public bool instancePortList; + public TypeConstraint typeConstraint; /// Mark a serializable field as an input port. You can access this through /// Should we display the backing value for this port as an editor field? /// Should we allow multiple connections? - public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnected, ConnectionType connectionType = ConnectionType.Multiple, bool instancePortList = false) { + /// Constrains which input connections can be made to this port + /// If true, will display a reorderable list of inputs instead of a single port. Will automatically add and display values for lists and arrays + public InputAttribute(ShowBackingValue backingValue = ShowBackingValue.Unconnected, ConnectionType connectionType = ConnectionType.Multiple, TypeConstraint typeConstraint = TypeConstraint.None, bool instancePortList = false) { this.backingValue = backingValue; this.connectionType = connectionType; this.instancePortList = instancePortList; + this.typeConstraint = typeConstraint; } } @@ -237,6 +251,7 @@ namespace XNode { /// Mark a serializable field as an output port. You can access this through /// Should we display the backing value for this port as an editor field? /// Should we allow multiple connections? + /// If true, will display a reorderable list of outputs instead of a single port. Will automatically add and display values for lists and arrays public OutputAttribute(ShowBackingValue backingValue = ShowBackingValue.Never, ConnectionType connectionType = ConnectionType.Multiple, bool instancePortList = false) { this.backingValue = backingValue; this.connectionType = connectionType; diff --git a/Scripts/NodeDataCache.cs b/Scripts/NodeDataCache.cs index 8d96146..434ffc5 100644 --- a/Scripts/NodeDataCache.cs +++ b/Scripts/NodeDataCache.cs @@ -30,7 +30,7 @@ namespace XNode { NodePort staticPort; if (staticPorts.TryGetValue(port.fieldName, out staticPort)) { // If port exists but with wrong settings, remove it. Re-add it later. - if (port.connectionType != staticPort.connectionType || port.IsDynamic || port.direction != staticPort.direction) ports.Remove(port.fieldName); + if (port.connectionType != staticPort.connectionType || port.IsDynamic || port.direction != staticPort.direction || port.typeConstraint != staticPort.typeConstraint) ports.Remove(port.fieldName); else port.ValueType = staticPort.ValueType; } // If port doesn't exist anymore, remove it diff --git a/Scripts/NodePort.cs b/Scripts/NodePort.cs index 3f55795..24e4941 100644 --- a/Scripts/NodePort.cs +++ b/Scripts/NodePort.cs @@ -21,6 +21,7 @@ namespace XNode { public IO direction { get { return _direction; } } public Node.ConnectionType connectionType { get { return _connectionType; } } + public Node.TypeConstraint typeConstraint { get { return _typeConstraint; } } /// Is this port connected to anytihng? public bool IsConnected { get { return connections.Count != 0; } } @@ -49,6 +50,7 @@ namespace XNode { [SerializeField] private List connections = new List(); [SerializeField] private IO _direction; [SerializeField] private Node.ConnectionType _connectionType; + [SerializeField] private Node.TypeConstraint _typeConstraint; [SerializeField] private bool _dynamic; /// Construct a static targetless nodeport. Used as a template. @@ -61,6 +63,7 @@ namespace XNode { 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; @@ -75,17 +78,19 @@ namespace XNode { _direction = nodePort.direction; _dynamic = nodePort._dynamic; _connectionType = nodePort._connectionType; + _typeConstraint = nodePort._typeConstraint; _node = node; } /// Construct a dynamic port. Dynamic ports are not forgotten on reimport, and is ideal for runtime-created ports. - public NodePort(string fieldName, Type type, IO direction, Node.ConnectionType connectionType, Node node) { + 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; } /// Checks all connections for invalid references, and removes them. @@ -240,6 +245,23 @@ namespace XNode { return false; } + /// Returns true if this port can connect to specified port + 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 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; + // Success + return true; + } + /// Disconnect this port from another port public void Disconnect(NodePort port) { // Remove this ports connection to the other From 3a8ae366f2eae2122c86df9e694e8c388b56d131 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 16 Feb 2019 03:06:25 +0100 Subject: [PATCH 54/73] Fixed #103 Similar issue as #100 GetField was not returning private fields. The method now not only looks for private fields, but also fields inside inherited classes --- Scripts/Editor/NodeEditorGUILayout.cs | 2 +- Scripts/Editor/NodeEditorReflection.cs | 9 +++++++++ Scripts/Editor/NodeEditorUtilities.cs | 4 +--- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 629c594..3330caa 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -154,7 +154,7 @@ namespace XNodeEditor { private static System.Type GetType(SerializedProperty property) { System.Type parentType = property.serializedObject.targetObject.GetType(); - System.Reflection.FieldInfo fi = parentType.GetField(property.propertyPath); + System.Reflection.FieldInfo fi = NodeEditorWindow.GetFieldInfo(property.serializedObject.targetObject.GetType(), property.name); return fi.FieldType; } diff --git a/Scripts/Editor/NodeEditorReflection.cs b/Scripts/Editor/NodeEditorReflection.cs index 21dbf7a..a2be28e 100644 --- a/Scripts/Editor/NodeEditorReflection.cs +++ b/Scripts/Editor/NodeEditorReflection.cs @@ -61,6 +61,15 @@ namespace XNodeEditor { return widths; } + /// Get FieldInfo of a field, including those that are private and/or inherited + public static FieldInfo GetFieldInfo(Type type, string fieldName) { + // 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); + // 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); + return field; + } + /// Get all classes deriving from baseType via reflection public static Type[] GetDerivedTypes(Type baseType) { List types = new List(); diff --git a/Scripts/Editor/NodeEditorUtilities.cs b/Scripts/Editor/NodeEditorUtilities.cs index c0eeeb3..24dff06 100644 --- a/Scripts/Editor/NodeEditorUtilities.cs +++ b/Scripts/Editor/NodeEditorUtilities.cs @@ -36,9 +36,7 @@ namespace XNodeEditor { public static bool GetAttrib(Type classType, string fieldName, out T attribOut) where T : Attribute { // If we can't find field in the first run, it's probably a private field in a base class. - FieldInfo field = classType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - // Search base classes for private fields only. Public fields are found above - while (field == null && (classType = classType.BaseType) != typeof(XNode.Node)) field = classType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); + FieldInfo field = NodeEditorWindow.GetFieldInfo(classType, fieldName); // This shouldn't happen. Ever. if (field == null) { Debug.LogWarning("Field " + fieldName + " couldnt be found"); From 57d3a03a91d38f722d16c988e72d5cd5dffe489c Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 16 Feb 2019 12:21:21 +0100 Subject: [PATCH 55/73] Removed GetHashCode override. This should improve performance, but has previously caused a slew of bugs. Bugtest thoroughly before merging --- Scripts/Editor/NodeEditorGUI.cs | 10 +++------- Scripts/Node.cs | 4 ---- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUI.cs b/Scripts/Editor/NodeEditorGUI.cs index 9f48f0e..e22a0b4 100644 --- a/Scripts/Editor/NodeEditorGUI.cs +++ b/Scripts/Editor/NodeEditorGUI.cs @@ -241,12 +241,10 @@ namespace XNodeEditor { selectionCache = new List(Selection.objects); } - //Active node is hashed before and after node GUI to detect changes - int nodeHash = 0; System.Reflection.MethodInfo onValidate = null; if (Selection.activeObject != null && Selection.activeObject is XNode.Node) { onValidate = Selection.activeObject.GetType().GetMethod("OnValidate"); - if (onValidate != null) nodeHash = Selection.activeObject.GetHashCode(); + if (onValidate != null) EditorGUI.BeginChangeCheck(); } BeginZoomed(position, zoom, topPadding); @@ -383,12 +381,10 @@ namespace XNodeEditor { if (e.type != EventType.Layout && currentActivity == NodeActivity.DragGrid) Selection.objects = preSelection.ToArray(); EndZoomed(position, zoom, topPadding); - //If a change in hash is detected in the selected node, call OnValidate method. + //If a change in is detected in the selected node, call OnValidate method. //This is done through reflection because OnValidate is only relevant in editor, //and thus, the code should not be included in build. - if (nodeHash != 0) { - if (onValidate != null && nodeHash != Selection.activeObject.GetHashCode()) onValidate.Invoke(Selection.activeObject, null); - } + if (onValidate != null && EditorGUI.EndChangeCheck()) onValidate.Invoke(Selection.activeObject, null); } private bool ShouldBeCulled(XNode.Node node) { diff --git a/Scripts/Node.cs b/Scripts/Node.cs index 43d716e..da04d86 100644 --- a/Scripts/Node.cs +++ b/Scripts/Node.cs @@ -205,10 +205,6 @@ namespace XNode { foreach (NodePort port in Ports) port.ClearConnections(); } - public override int GetHashCode() { - return JsonUtility.ToJson(this).GetHashCode(); - } - #region Attributes /// Mark a serializable field as an input port. You can access this through [AttributeUsage(AttributeTargets.Field, AllowMultiple = true)] From f6404e9d9df75592b5bee8bc607a28343a23589c Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sun, 17 Feb 2019 03:18:49 +0100 Subject: [PATCH 56/73] Unity 5.3 support --- Scripts/Editor/Drawers/NodeEnumDrawer.cs | 9 +++++++++ Scripts/Editor/NodeEditorAction.cs | 12 ++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/Scripts/Editor/Drawers/NodeEnumDrawer.cs b/Scripts/Editor/Drawers/NodeEnumDrawer.cs index 3e770f2..7478f94 100644 --- a/Scripts/Editor/Drawers/NodeEnumDrawer.cs +++ b/Scripts/Editor/Drawers/NodeEnumDrawer.cs @@ -24,12 +24,21 @@ namespace XNodeEditor { string enumName = ""; if (property.enumValueIndex >= 0 && property.enumValueIndex < property.enumDisplayNames.Length) enumName = property.enumDisplayNames[property.enumValueIndex]; +#if UNITY_2017_1_OR_NEWER // Display dropdown if (EditorGUI.DropdownButton(position, new GUIContent(enumName), FocusType.Passive)) { // Position is all wrong if we show the dropdown during the node draw phase. // Instead, add it to onLateGUI to display it later. NodeEditorWindow.current.onLateGUI += () => ShowContextMenuAtMouse(property); } +#else + // Display dropdown + if (GUI.Button(position, new GUIContent(enumName), "MiniPopup")) { + // Position is all wrong if we show the dropdown during the node draw phase. + // Instead, add it to onLateGUI to display it later. + NodeEditorWindow.current.onLateGUI += () => ShowContextMenuAtMouse(property); + } +#endif EditorGUI.EndProperty(); } diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index 315f23b..c436d33 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -289,7 +289,7 @@ namespace XNodeEditor { case EventType.KeyDown: if (EditorGUIUtility.editingTextField) break; else if (e.keyCode == KeyCode.F) Home(); - if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX) { + if (IsMac()) { if (e.keyCode == KeyCode.Return) RenameSelectedNode(); } else { if (e.keyCode == KeyCode.F2) RenameSelectedNode(); @@ -300,7 +300,7 @@ namespace XNodeEditor { if (e.commandName == "SoftDelete") { if (e.type == EventType.ExecuteCommand) RemoveSelectedNodes(); e.Use(); - } else if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX && e.commandName == "Delete") { + } else if (IsMac() && e.commandName == "Delete") { if (e.type == EventType.ExecuteCommand) RemoveSelectedNodes(); e.Use(); } else if (e.commandName == "Duplicate") { @@ -319,6 +319,14 @@ namespace XNodeEditor { } } + public bool IsMac() { +#if UNITY_2017_1_OR_NEWER + return SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX; +#else + return SystemInfo.operatingSystem.StartsWith("Mac"); +#endif + } + private void RecalculateDragOffsets(Event current) { dragOffset = new Vector2[Selection.objects.Length + selectedReroutes.Count]; // Selected nodes From 662e919aaabf205d825515ed976a093d5353b110 Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Sun, 17 Feb 2019 11:57:17 +0100 Subject: [PATCH 57/73] Renaming node to nothing (#112) When the name is empty or just whitespaces, it reverts to the original node type name --- Scripts/Editor/NodeEditor.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index f38b510..44594f0 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -106,6 +106,7 @@ namespace XNodeEditor { } public void Rename(string newName) { + if (string.IsNullOrWhiteSpace(newName)) newName = UnityEditor.ObjectNames.NicifyVariableName(target.GetType().Name); target.name = newName; AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target)); } From 8cb647734a7959d9f91317bdb669db4da7b448b6 Mon Sep 17 00:00:00 2001 From: Simon Rodriguez Date: Sun, 17 Feb 2019 12:00:11 +0100 Subject: [PATCH 58/73] EditorGUI.FocusTextInControl(null) sets editingTextField to true even if null is being sent in. (#113) Then the editor won't listen to keyboard input. --- Scripts/Editor/NodeEditorAction.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index c436d33..efc1cb6 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -235,6 +235,7 @@ namespace XNodeEditor { // If click outside node, release field focus if (!isPanning) { EditorGUI.FocusTextInControl(null); + EditorGUIUtility.editingTextField = false; } if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); } From c3067018535dbe228c2c374fc1f0911f0bbdb3cb Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sun, 17 Feb 2019 12:24:58 +0100 Subject: [PATCH 59/73] .Net 2.0 compatability --- Scripts/Editor/NodeEditor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index 44594f0..f131f66 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -106,7 +106,7 @@ namespace XNodeEditor { } public void Rename(string newName) { - if (string.IsNullOrWhiteSpace(newName)) newName = UnityEditor.ObjectNames.NicifyVariableName(target.GetType().Name); + if (newName == null || newName.Trim() == "") newName = UnityEditor.ObjectNames.NicifyVariableName(target.GetType().Name); target.name = newName; AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target)); } From 5acb7e4ba85df35918af610be0e5f9d63cbeb1a4 Mon Sep 17 00:00:00 2001 From: NoiseCrime Date: Mon, 18 Feb 2019 12:28:35 +0000 Subject: [PATCH 60/73] UI Sharpness complete fix (#115) Complete fix to address bluriness of the UI in the Node Editor Window. Previous fixes were not all encompassing and failed to account for now even dimensions of Editor Window. --- Scripts/Editor/NodeEditorAction.cs | 8 ++------ Scripts/Editor/NodeEditorWindow.cs | 5 +++-- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index efc1cb6..b4f6562 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -136,12 +136,7 @@ namespace XNodeEditor { Repaint(); } } else if (e.button == 1 || e.button == 2) { - Vector2 tempOffset = panOffset; - tempOffset += e.delta * zoom; - // Round value to increase crispyness of UI text - tempOffset.x = Mathf.Round(tempOffset.x); - tempOffset.y = Mathf.Round(tempOffset.y); - panOffset = tempOffset; + panOffset += e.delta * zoom; isPanning = true; } break; @@ -276,6 +271,7 @@ namespace XNodeEditor { GenericMenu menu = new GenericMenu(); NodeEditor.GetEditor(hoveredNode).AddContextMenuItems(menu); menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); + e.Use(); // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places. } else if (!IsHoveringNode) { GenericMenu menu = new GenericMenu(); graphEditor.AddContextMenuItems(menu); diff --git a/Scripts/Editor/NodeEditorWindow.cs b/Scripts/Editor/NodeEditorWindow.cs index 72fd4ce..740fd20 100644 --- a/Scripts/Editor/NodeEditorWindow.cs +++ b/Scripts/Editor/NodeEditorWindow.cs @@ -123,8 +123,9 @@ namespace XNodeEditor { public Vector2 GridToWindowPositionNoClipped(Vector2 gridPosition) { Vector2 center = position.size * 0.5f; - float xOffset = (center.x * zoom + (panOffset.x + gridPosition.x)); - float yOffset = (center.y * zoom + (panOffset.y + gridPosition.y)); + // UI Sharpness complete fix - Round final offset not panOffset + float xOffset = Mathf.Round(center.x * zoom + (panOffset.x + gridPosition.x)); + float yOffset = Mathf.Round(center.y * zoom + (panOffset.y + gridPosition.y)); return new Vector2(xOffset, yOffset); } From 43038cfcc1d5c592bdd2288ef0be41cdbf37a9e4 Mon Sep 17 00:00:00 2001 From: Sergi Tortosa Ortiz-Villajos Date: Tue, 19 Feb 2019 22:50:45 +0100 Subject: [PATCH 61/73] Support inherited attributes (#116) --- Scripts/Editor/NodeEditorUtilities.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Scripts/Editor/NodeEditorUtilities.cs b/Scripts/Editor/NodeEditorUtilities.cs index 24dff06..18e295f 100644 --- a/Scripts/Editor/NodeEditorUtilities.cs +++ b/Scripts/Editor/NodeEditorUtilities.cs @@ -25,7 +25,7 @@ namespace XNodeEditor { public static bool GetAttrib(object[] attribs, out T attribOut) where T : Attribute { for (int i = 0; i < attribs.Length; i++) { - if (attribs[i].GetType() == typeof(T)) { + if (attribs[i] is T){ attribOut = attribs[i] as T; return true; } @@ -43,7 +43,7 @@ namespace XNodeEditor { attribOut = null; return false; } - object[] attribs = field.GetCustomAttributes(typeof(T), false); + object[] attribs = field.GetCustomAttributes(typeof(T), true); return GetAttrib(attribs, out attribOut); } From 2939fe49353900d37835fd21710a31382a09a84d Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 2 Mar 2019 11:53:48 +0100 Subject: [PATCH 62/73] Added automatic drawing of instance ports Fixed minor issue getting parentType twice --- Scripts/Editor/NodeEditor.cs | 7 +++++++ Scripts/Editor/NodeEditorGUILayout.cs | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index f131f66..d222f9e 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -52,6 +52,7 @@ namespace XNodeEditor { string[] excludes = { "m_Script", "graph", "position", "ports" }; portPositions = new Dictionary(); + // Iterate through serialized properties and draw them like the Inspector (But with ports) SerializedProperty iterator = serializedObject.GetIterator(); bool enterChildren = true; EditorGUIUtility.labelWidth = 84; @@ -60,6 +61,12 @@ namespace XNodeEditor { if (excludes.Contains(iterator.name)) continue; NodeEditorGUILayout.PropertyField(iterator, true); } + + // Iterate through instance ports and draw them in the order in which they are serialized + foreach(XNode.NodePort instancePort in target.InstancePorts) { + NodeEditorGUILayout.PortField(instancePort); + } + serializedObject.ApplyModifiedProperties(); } diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index ee4394d..7cc1a21 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -154,7 +154,7 @@ namespace XNodeEditor { private static System.Type GetType(SerializedProperty property) { System.Type parentType = property.serializedObject.targetObject.GetType(); - System.Reflection.FieldInfo fi = NodeEditorWindow.GetFieldInfo(property.serializedObject.targetObject.GetType(), property.name); + System.Reflection.FieldInfo fi = NodeEditorWindow.GetFieldInfo(parentType, property.name); return fi.FieldType; } From 29acbf63489d58b2573ff327723c7651dc458fab Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sun, 3 Mar 2019 00:51:06 +0100 Subject: [PATCH 63/73] Update README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 16d51b4..2b59422 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![alt text](https://user-images.githubusercontent.com/37786733/41541140-71602302-731a-11e8-9434-79b3a57292b6.png) + [![Discord](https://img.shields.io/discord/361769369404964864.svg)](https://discord.gg/qgPrHv4) [![GitHub issues](https://img.shields.io/github/issues/Siccity/xNode.svg)](https://github.com/Siccity/xNode/issues) @@ -15,7 +15,9 @@ Thinking of developing a node-based plugin? Then this is for you. You can downlo xNode is super userfriendly, intuitive and will help you reap the benefits of node graphs in no time. With a minimal footprint, it is ideal as a base for custom state machines, dialogue systems, decision makers etc. -![editor](https://user-images.githubusercontent.com/6402525/33150712-01d60602-cfd5-11e7-83b4-eb008fd9d711.png) +

+ +

### Key features * Lightweight in runtime From 6783324018c231710e5898d3c3e5d40acef7f152 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Mon, 4 Mar 2019 18:29:43 +0100 Subject: [PATCH 64/73] Fix drawing instance twice for instanceportlists --- Scripts/Editor/NodeEditor.cs | 1 + Scripts/Editor/NodeEditorGUILayout.cs | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index d222f9e..1fffc66 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -64,6 +64,7 @@ namespace XNodeEditor { // Iterate through instance ports and draw them in the order in which they are serialized foreach(XNode.NodePort instancePort in target.InstancePorts) { + if (NodeEditorGUILayout.IsInstancePortListPort(instancePort)) continue; NodeEditorGUILayout.PortField(instancePort); } diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 7cc1a21..b2ac5e8 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -254,6 +254,18 @@ namespace XNodeEditor { GUI.color = col; } + /// Is this port part of an InstancePortList? + public static bool IsInstancePortListPort(XNode.NodePort port) { + string[] parts = port.fieldName.Split(' '); + if (parts.Length != 2) return false; + Dictionary cache; + if (reorderableListCache.TryGetValue(port.node, out cache)) { + ReorderableList list; + if (cache.TryGetValue(parts[0], out list)) return true; + } + return false; + } + /// Draw an editable list of instance ports. Port names are named as "[fieldName] [index]" /// Supply a list for editable values /// Value type of added instance ports From 01d7f782e41e145cb52bf9bd7bea8f4a7cf2e927 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Mon, 4 Mar 2019 19:04:00 +0100 Subject: [PATCH 65/73] Fixed issues relating to InstancePortList --- Scripts/Editor/NodeEditorGUILayout.cs | 35 +++++++++++++++++---------- Scripts/Node.cs | 2 ++ 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index b2ac5e8..4eca18c 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -301,7 +301,6 @@ namespace XNodeEditor { private static ReorderableList CreateReorderableList(string fieldName, List instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType, XNode.Node.TypeConstraint typeConstraint, Action onCreation) { bool hasArrayData = arrayData != null && arrayData.isArray; - int arraySize = hasArrayData ? arrayData.arraySize : 0; XNode.Node node = serializedObject.targetObject as XNode.Node; ReorderableList list = new ReorderableList(instancePorts, null, true, true, true, true); string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName); @@ -317,8 +316,10 @@ namespace XNodeEditor { SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); EditorGUI.PropertyField(rect, itemData, true); } else EditorGUI.LabelField(rect, port.fieldName); - Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); - NodeEditorGUILayout.PortField(pos, port); + if (port != null) { + Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); + NodeEditorGUILayout.PortField(pos, port); + } }; list.elementHeightCallback = (int index) => { @@ -391,11 +392,22 @@ namespace XNodeEditor { else node.AddInstanceInput(type, connectionType, typeConstraint, newName); serializedObject.Update(); EditorUtility.SetDirty(node); - if (hasArrayData) arrayData.InsertArrayElementAtIndex(arraySize); + if (hasArrayData) { + arrayData.InsertArrayElementAtIndex(arrayData.arraySize); + } serializedObject.ApplyModifiedProperties(); }; list.onRemoveCallback = (ReorderableList rl) => { + + Predicate isMatchingInstancePort = + x => { + string[] split = x.Split(' '); + if (split != null && split.Length == 2) return split[0] == fieldName; + else return false; + }; + instancePorts = node.InstancePorts.Where(x => isMatchingInstancePort(x.fieldName)).OrderBy(x => x.fieldName).ToList(); + int index = rl.index; // Clear the removed ports connections instancePorts[index].ClearConnections(); @@ -413,23 +425,21 @@ namespace XNodeEditor { EditorUtility.SetDirty(node); if (hasArrayData) { arrayData.DeleteArrayElementAtIndex(index); - arraySize--; // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues - if (instancePorts.Count <= arraySize) { - while (instancePorts.Count <= arraySize) { - arrayData.DeleteArrayElementAtIndex(--arraySize); + if (instancePorts.Count <= arrayData.arraySize) { + while (instancePorts.Count <= arrayData.arraySize) { + arrayData.DeleteArrayElementAtIndex(arrayData.arraySize - 1); } UnityEngine.Debug.LogWarning("Array size exceeded instance ports size. Excess items removed."); } serializedObject.ApplyModifiedProperties(); serializedObject.Update(); } - }; if (hasArrayData) { int instancePortCount = instancePorts.Count; - while (instancePortCount < arraySize) { + while (instancePortCount < arrayData.arraySize) { // Add instance port postfixed with an index number string newName = arrayData.name + " 0"; int i = 0; @@ -439,9 +449,8 @@ namespace XNodeEditor { EditorUtility.SetDirty(node); instancePortCount++; } - while (arraySize < instancePortCount) { - arrayData.InsertArrayElementAtIndex(arraySize); - arraySize++; + while (arrayData.arraySize < instancePortCount) { + arrayData.InsertArrayElementAtIndex(arrayData.arraySize); } serializedObject.ApplyModifiedProperties(); serializedObject.Update(); diff --git a/Scripts/Node.cs b/Scripts/Node.cs index 8785280..74eb309 100644 --- a/Scripts/Node.cs +++ b/Scripts/Node.cs @@ -127,6 +127,8 @@ namespace XNode { /// Remove an instance port from the node public void RemoveInstancePort(string fieldName) { + NodePort instancePort = GetPort(fieldName); + if (instancePort == null) throw new ArgumentException("port " + fieldName + " doesn't exist"); RemoveInstancePort(GetPort(fieldName)); } From 4263e45b2482229dab42ba4613d60a8f90874f92 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Fri, 8 Mar 2019 19:50:31 +0100 Subject: [PATCH 66/73] Rework node renaming Renaming now happens on a separate popup. --- Scripts/Editor/NodeEditor.cs | 34 ++------------- Scripts/Editor/NodeEditorAction.cs | 7 +++- Scripts/Editor/RenamePopup.cs | 66 ++++++++++++++++++++++++++++++ Scripts/Editor/RenamePopup.cs.meta | 13 ++++++ 4 files changed, 88 insertions(+), 32 deletions(-) create mode 100644 Scripts/Editor/RenamePopup.cs create mode 100644 Scripts/Editor/RenamePopup.cs.meta diff --git a/Scripts/Editor/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index 1fffc66..a6d1748 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -13,34 +13,9 @@ namespace XNodeEditor { /// Fires every whenever a node was modified through the editor public static Action onUpdateNode; public static Dictionary portPositions; - public int renaming; public virtual void OnHeaderGUI() { - string title = target.name; - if (renaming != 0) { - if (Selection.Contains(target)) { - int controlID = EditorGUIUtility.GetControlID(FocusType.Keyboard) + 1; - if (renaming == 1) { - EditorGUIUtility.keyboardControl = controlID; - EditorGUIUtility.editingTextField = true; - renaming = 2; - } - target.name = EditorGUILayout.TextField(target.name, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); - if (!EditorGUIUtility.editingTextField) { - Debug.Log("Finish renaming"); - Rename(target.name); - renaming = 0; - } - } - else { - // Selection changed, so stop renaming. - GUILayout.Label(title, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); - Rename(target.name); - renaming = 0; - } - } else { - GUILayout.Label(title, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); - } + GUILayout.Label(target.name, NodeEditorResources.styles.nodeHeader, GUILayout.Height(30)); } /// Draws standard field editors for all public fields @@ -63,7 +38,7 @@ namespace XNodeEditor { } // Iterate through instance ports and draw them in the order in which they are serialized - foreach(XNode.NodePort instancePort in target.InstancePorts) { + foreach (XNode.NodePort instancePort in target.InstancePorts) { if (NodeEditorGUILayout.IsInstancePortListPort(instancePort)) continue; NodeEditorGUILayout.PortField(instancePort); } @@ -109,10 +84,7 @@ namespace XNodeEditor { } } - public void InitiateRename() { - renaming = 1; - } - + /// Rename the node asset. This will trigger a reimport of the node. public void Rename(string newName) { if (newName == null || newName.Trim() == "") newName = UnityEditor.ObjectNames.NicifyVariableName(target.GetType().Name); target.name = newName; diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index b4f6562..211f3cc 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -366,7 +366,12 @@ namespace XNodeEditor { public void RenameSelectedNode() { if (Selection.objects.Length == 1 && Selection.activeObject is XNode.Node) { XNode.Node node = Selection.activeObject as XNode.Node; - NodeEditor.GetEditor(node).InitiateRename(); + Vector2 size; + if (nodeSizes.TryGetValue(node, out size)) { + RenamePopup.Show(Selection.activeObject, size.x); + } else { + RenamePopup.Show(Selection.activeObject); + } } } diff --git a/Scripts/Editor/RenamePopup.cs b/Scripts/Editor/RenamePopup.cs new file mode 100644 index 0000000..a49a948 --- /dev/null +++ b/Scripts/Editor/RenamePopup.cs @@ -0,0 +1,66 @@ +using UnityEditor; +using UnityEngine; + +namespace XNodeEditor { + /// Utility for renaming assets + public class RenamePopup : EditorWindow { + public static RenamePopup current { get; private set; } + public Object target; + public string input; + + private bool firstFrame = true; + + /// Show a rename popup for an asset at mouse position. Will trigger reimport of the asset on apply. + public static RenamePopup Show(Object target, float width = 200) { + RenamePopup window = EditorWindow.GetWindow(true, "Rename " + target.name, true); + if (current != null) current.Close(); + current = window; + window.target = target; + window.input = target.name; + window.minSize = new Vector2(100, 44); + window.position = new Rect(0, 0, width, 44); + GUI.FocusControl("ClearAllFocus"); + window.UpdatePositionToMouse(); + return window; + } + + private void UpdatePositionToMouse() { + if (Event.current == null) return; + Vector3 mousePoint = GUIUtility.GUIToScreenPoint(Event.current.mousePosition); + Rect pos = position; + pos.x = mousePoint.x - position.width * 0.5f; + pos.y = mousePoint.y - 10; + position = pos; + } + + private void OnLostFocus() { + // Make the popup close on lose focus + Close(); + } + + private void OnGUI() { + if (firstFrame) { + UpdatePositionToMouse(); + firstFrame = false; + } + input = EditorGUILayout.TextField(input); + Event e = Event.current; + // If input is empty, revert name to default instead + if (input == null || input.Trim() == "") { + if (GUILayout.Button("Revert to default") || (e.isKey && e.keyCode == KeyCode.Return)) { + target.name = UnityEditor.ObjectNames.NicifyVariableName(target.GetType().Name); + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target)); + Close(); + } + } + // Rename asset to input text + else { + if (GUILayout.Button("Apply") || (e.isKey && e.keyCode == KeyCode.Return)) { + target.name = input; + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target)); + Close(); + } + } + } + } +} \ No newline at end of file diff --git a/Scripts/Editor/RenamePopup.cs.meta b/Scripts/Editor/RenamePopup.cs.meta new file mode 100644 index 0000000..5c40a02 --- /dev/null +++ b/Scripts/Editor/RenamePopup.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: 4ef3ddc25518318469bce838980c64be +timeCreated: 1552067957 +licenseType: Free +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 2f4adadb72b01c522b82b765b6db43955c89a7f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mert=20K=C4=B1r=C4=B1mgeri?= Date: Wed, 20 Mar 2019 12:42:47 +0300 Subject: [PATCH 67/73] Zoom out limit feature (#122) Zoom out limit added --- Scripts/Editor/NodeEditorPreferences.cs | 3 ++- Scripts/Editor/NodeEditorWindow.cs | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Scripts/Editor/NodeEditorPreferences.cs b/Scripts/Editor/NodeEditorPreferences.cs index e896f34..bd2cb55 100644 --- a/Scripts/Editor/NodeEditorPreferences.cs +++ b/Scripts/Editor/NodeEditorPreferences.cs @@ -23,6 +23,7 @@ namespace XNodeEditor { [SerializeField] private Color32 _gridBgColor = new Color(0.18f, 0.18f, 0.18f); public Color32 gridBgColor { get { return _gridBgColor; } set { _gridBgColor = value; _gridTexture = null; } } + public float zoomOutLimit = 5f; public Color32 highlightColor = new Color32(255, 255, 255, 255); public bool gridSnap = true; public bool autoSave = true; @@ -113,7 +114,7 @@ namespace XNodeEditor { EditorGUILayout.LabelField("Grid", EditorStyles.boldLabel); settings.gridSnap = EditorGUILayout.Toggle(new GUIContent("Snap", "Hold CTRL in editor to invert"), settings.gridSnap); settings.zoomToMouse = EditorGUILayout.Toggle(new GUIContent("Zoom to Mouse", "Zooms towards mouse position"), settings.zoomToMouse); - + settings.zoomOutLimit = EditorGUILayout.FloatField(new GUIContent("Zoom out Limit", "Upper limit to zoom"), settings.zoomOutLimit); settings.gridLineColor = EditorGUILayout.ColorField("Color", settings.gridLineColor); settings.gridBgColor = EditorGUILayout.ColorField(" ", settings.gridBgColor); if (GUI.changed) { diff --git a/Scripts/Editor/NodeEditorWindow.cs b/Scripts/Editor/NodeEditorWindow.cs index 740fd20..08b0a56 100644 --- a/Scripts/Editor/NodeEditorWindow.cs +++ b/Scripts/Editor/NodeEditorWindow.cs @@ -61,7 +61,7 @@ namespace XNodeEditor { public XNode.NodeGraph graph; public Vector2 panOffset { get { return _panOffset; } set { _panOffset = value; Repaint(); } } private Vector2 _panOffset; - public float zoom { get { return _zoom; } set { _zoom = Mathf.Clamp(value, 1f, 5f); Repaint(); } } + public float zoom { get { return _zoom; } set { _zoom = Mathf.Clamp(value, 1f, NodeEditorPreferences.GetSettings().zoomOutLimit); Repaint(); } } private float _zoom = 1; void OnFocus() { @@ -163,4 +163,4 @@ namespace XNodeEditor { } } } -} \ No newline at end of file +} From af0523db2d5311401f4033ae40ebb71477d9da65 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Mon, 1 Apr 2019 19:16:54 +0200 Subject: [PATCH 68/73] Fixed #124 - Errors on DynamicPortList with >10 items Was using OrderBy(x => x.fieldName). The resulting order would then be 1, 10, 11, .. , 2, 3, 4, etc. Fixed by parsing the indices as ints, and ordering by that value instead --- Scripts/Editor/NodeEditorGUILayout.cs | 36 ++++++++++++++++----------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 4eca18c..32e527f 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -275,13 +275,17 @@ namespace XNodeEditor { 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 onCreation = null) { XNode.Node node = serializedObject.targetObject as XNode.Node; - Predicate isMatchingInstancePort = - x => { - string[] split = x.Split(' '); - if (split != null && split.Length == 2) return split[0] == fieldName; - else return false; - }; - List instancePorts = node.InstancePorts.Where(x => isMatchingInstancePort(x.fieldName)).OrderBy(x => x.fieldName).ToList(); + var indexedPorts = node.InstancePorts.Select(x => { + string[] split = x.fieldName.Split(' '); + if (split != null && split.Length == 2 && split[0] == fieldName) { + int i = -1; + if (int.TryParse(split[1], out i)) { + return new { index = i, port = x }; + } + } + return new { index = -1, port = (XNode.NodePort) null }; + }); + List instancePorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList(); ReorderableList list = null; Dictionary rlc; @@ -400,13 +404,17 @@ namespace XNodeEditor { list.onRemoveCallback = (ReorderableList rl) => { - Predicate isMatchingInstancePort = - x => { - string[] split = x.Split(' '); - if (split != null && split.Length == 2) return split[0] == fieldName; - else return false; - }; - instancePorts = node.InstancePorts.Where(x => isMatchingInstancePort(x.fieldName)).OrderBy(x => x.fieldName).ToList(); + var indexedPorts = node.InstancePorts.Select(x => { + string[] split = x.fieldName.Split(' '); + if (split != null && split.Length == 2 && split[0] == fieldName) { + int i = -1; + if (int.TryParse(split[1], out i)) { + return new { index = i, port = x }; + } + } + return new { index = -1, port = (XNode.NodePort) null }; + }); + instancePorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList(); int index = rl.index; // Clear the removed ports connections From d8a4a41a8f57007dc3931a44e1ddd58070051e48 Mon Sep 17 00:00:00 2001 From: Robin Neal Date: Wed, 3 Apr 2019 19:39:21 +0100 Subject: [PATCH 69/73] Open non-persistent graphs on double-click (#126) --- Scripts/Editor/NodeEditorWindow.cs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/Scripts/Editor/NodeEditorWindow.cs b/Scripts/Editor/NodeEditorWindow.cs index 08b0a56..24bd8f5 100644 --- a/Scripts/Editor/NodeEditorWindow.cs +++ b/Scripts/Editor/NodeEditorWindow.cs @@ -70,6 +70,20 @@ namespace XNodeEditor { if (graphEditor != null && NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); } + [InitializeOnLoadMethod] + private static void OnLoad() { + Selection.selectionChanged -= OnSelectionChanged; + Selection.selectionChanged += OnSelectionChanged; + } + + /// Handle Selection Change events + private static void OnSelectionChanged() { + XNode.NodeGraph nodeGraph = Selection.activeObject as XNode.NodeGraph; + if (nodeGraph && !AssetDatabase.Contains(nodeGraph)) { + Open(nodeGraph); + } + } + /// Create editor window public static NodeEditorWindow Init() { NodeEditorWindow w = CreateInstance(); @@ -147,14 +161,21 @@ namespace XNodeEditor { public static bool OnOpen(int instanceID, int line) { XNode.NodeGraph nodeGraph = EditorUtility.InstanceIDToObject(instanceID) as XNode.NodeGraph; if (nodeGraph != null) { - NodeEditorWindow w = GetWindow(typeof(NodeEditorWindow), false, "xNode", true) as NodeEditorWindow; - w.wantsMouseMove = true; - w.graph = nodeGraph; + Open(nodeGraph); return true; } return false; } + /// Open the provided graph in the NodeEditor + public static void Open(XNode.NodeGraph graph) { + if (!graph) return; + + NodeEditorWindow w = GetWindow(typeof(NodeEditorWindow), false, "xNode", true) as NodeEditorWindow; + w.wantsMouseMove = true; + w.graph = graph; + } + /// Repaint all open NodeEditorWindows. public static void RepaintAll() { NodeEditorWindow[] windows = Resources.FindObjectsOfTypeAll(); From f6e0e3bc4d839b41ce792c161229d530117b29da Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Wed, 3 Apr 2019 21:50:29 +0200 Subject: [PATCH 70/73] Added NodeGraphEditor.GetPortColor --- Scripts/Editor/NodeEditorGUI.cs | 2 +- Scripts/Editor/NodeEditorGUILayout.cs | 6 +++--- Scripts/Editor/NodeGraphEditor.cs | 4 ++++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Scripts/Editor/NodeEditorGUI.cs b/Scripts/Editor/NodeEditorGUI.cs index e22a0b4..b26b9ba 100644 --- a/Scripts/Editor/NodeEditorGUI.cs +++ b/Scripts/Editor/NodeEditorGUI.cs @@ -184,7 +184,7 @@ namespace XNodeEditor { Rect fromRect; if (!_portConnectionPoints.TryGetValue(output, out fromRect)) continue; - Color connectionColor = graphEditor.GetTypeColor(output.ValueType); + Color connectionColor = graphEditor.GetPortColor(output); for (int k = 0; k < output.ConnectionCount; k++) { XNode.NodePort input = output.GetConnection(k); diff --git a/Scripts/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 32e527f..e3f7c60 100644 --- a/Scripts/Editor/NodeEditorGUILayout.cs +++ b/Scripts/Editor/NodeEditorGUILayout.cs @@ -142,7 +142,7 @@ namespace XNodeEditor { Color backgroundColor = new Color32(90, 97, 105, 255); Color tint; if (NodeEditorWindow.nodeTint.TryGetValue(port.node.GetType(), out tint)) backgroundColor *= tint; - Color col = NodeEditorWindow.current.graphEditor.GetTypeColor(port.ValueType); + Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port); DrawPortHandle(rect, backgroundColor, col); // Register the handle position @@ -199,7 +199,7 @@ namespace XNodeEditor { Color backgroundColor = new Color32(90, 97, 105, 255); Color tint; if (NodeEditorWindow.nodeTint.TryGetValue(port.node.GetType(), out tint)) backgroundColor *= tint; - Color col = NodeEditorWindow.current.graphEditor.GetTypeColor(port.ValueType); + Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port); DrawPortHandle(rect, backgroundColor, col); // Register the handle position @@ -228,7 +228,7 @@ namespace XNodeEditor { Color backgroundColor = new Color32(90, 97, 105, 255); Color tint; if (NodeEditorWindow.nodeTint.TryGetValue(port.node.GetType(), out tint)) backgroundColor *= tint; - Color col = NodeEditorWindow.current.graphEditor.GetTypeColor(port.ValueType); + Color col = NodeEditorWindow.current.graphEditor.GetPortColor(port); DrawPortHandle(rect, backgroundColor, col); // Register the handle position diff --git a/Scripts/Editor/NodeGraphEditor.cs b/Scripts/Editor/NodeGraphEditor.cs index 81a53c8..1286f7a 100644 --- a/Scripts/Editor/NodeGraphEditor.cs +++ b/Scripts/Editor/NodeGraphEditor.cs @@ -57,6 +57,10 @@ namespace XNodeEditor { NodeEditorWindow.AddCustomContextMenuItems(menu, target); } + public virtual Color GetPortColor(XNode.NodePort port) { + return GetTypeColor(port.ValueType); + } + public virtual Color GetTypeColor(Type type) { return NodeEditorPreferences.GetTypeColor(type); } From 8adc4fd459a103dcd5cf51c28d8b168136901a51 Mon Sep 17 00:00:00 2001 From: Thor Brigsted Date: Sat, 6 Apr 2019 13:27:44 +0200 Subject: [PATCH 71/73] Fixed #128, #127, #64 - Added NodeEditorBase.OnCreate, OnGraphEditor.OnOpen, and NodeEditorBase.window --- Scripts/Editor/NodeEditorAction.cs | 2 +- Scripts/Editor/NodeEditorBase.cs | 9 ++++++++- Scripts/Editor/NodeEditorGUI.cs | 6 ++---- Scripts/Editor/NodeEditorWindow.cs | 11 ++++++++++- Scripts/Editor/NodeGraphEditor.cs | 7 +++++-- 5 files changed, 26 insertions(+), 9 deletions(-) diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index 211f3cc..0570777 100644 --- a/Scripts/Editor/NodeEditorAction.cs +++ b/Scripts/Editor/NodeEditorAction.cs @@ -269,7 +269,7 @@ namespace XNodeEditor { } else if (IsHoveringNode && IsHoveringTitle(hoveredNode)) { if (!Selection.Contains(hoveredNode)) SelectNode(hoveredNode, false); GenericMenu menu = new GenericMenu(); - NodeEditor.GetEditor(hoveredNode).AddContextMenuItems(menu); + NodeEditor.GetEditor(hoveredNode, this).AddContextMenuItems(menu); menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero)); e.Use(); // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places. } else if (!IsHoveringNode) { diff --git a/Scripts/Editor/NodeEditorBase.cs b/Scripts/Editor/NodeEditorBase.cs index b94f290..ab463e6 100644 --- a/Scripts/Editor/NodeEditorBase.cs +++ b/Scripts/Editor/NodeEditorBase.cs @@ -14,10 +14,11 @@ namespace XNodeEditor.Internal { /// Custom editors defined with [CustomNodeEditor] private static Dictionary editorTypes; private static Dictionary editors = new Dictionary(); + public NodeEditorWindow window; public K target; public SerializedObject serializedObject; - public static T GetEditor(K target) { + public static T GetEditor(K target, NodeEditorWindow window) { if (target == null) return null; T editor; if (!editors.TryGetValue(target, out editor)) { @@ -26,9 +27,12 @@ namespace XNodeEditor.Internal { editor = Activator.CreateInstance(editorType) as T; editor.target = target; editor.serializedObject = new SerializedObject(target); + editor.window = window; + editor.OnCreate(); editors.Add(target, editor); } if (editor.target == null) editor.target = target; + if (editor.window != window) editor.window = window; if (editor.serializedObject == null) editor.serializedObject = new SerializedObject(target); return editor; } @@ -56,6 +60,9 @@ namespace XNodeEditor.Internal { } } + /// Called on creation, after references have been set + public virtual void OnCreate() { } + public interface INodeEditorAttrib { Type GetInspectedType(); } diff --git a/Scripts/Editor/NodeEditorGUI.cs b/Scripts/Editor/NodeEditorGUI.cs index b26b9ba..509f871 100644 --- a/Scripts/Editor/NodeEditorGUI.cs +++ b/Scripts/Editor/NodeEditorGUI.cs @@ -18,9 +18,7 @@ namespace XNodeEditor { Event e = Event.current; Matrix4x4 m = GUI.matrix; if (graph == null) return; - graphEditor = NodeGraphEditor.GetEditor(graph); - graphEditor.position = position; - + ValidateGraphEditor(); Controls(); DrawGrid(position, zoom, panOffset); @@ -288,7 +286,7 @@ namespace XNodeEditor { _portConnectionPoints = _portConnectionPoints.Where(x => x.Key.node != node).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); } - NodeEditor nodeEditor = NodeEditor.GetEditor(node); + NodeEditor nodeEditor = NodeEditor.GetEditor(node, this); NodeEditor.portPositions = new Dictionary(); diff --git a/Scripts/Editor/NodeEditorWindow.cs b/Scripts/Editor/NodeEditorWindow.cs index 24bd8f5..a575c8d 100644 --- a/Scripts/Editor/NodeEditorWindow.cs +++ b/Scripts/Editor/NodeEditorWindow.cs @@ -66,7 +66,7 @@ namespace XNodeEditor { void OnFocus() { current = this; - graphEditor = NodeGraphEditor.GetEditor(graph); + ValidateGraphEditor(); if (graphEditor != null && NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); } @@ -84,6 +84,15 @@ namespace XNodeEditor { } } + /// Make sure the graph editor is assigned and to the right object + private void ValidateGraphEditor() { + NodeGraphEditor graphEditor = NodeGraphEditor.GetEditor(graph, this); + if (this.graphEditor != graphEditor) { + this.graphEditor = graphEditor; + graphEditor.OnOpen(); + } + } + /// Create editor window public static NodeEditorWindow Init() { NodeEditorWindow w = CreateInstance(); diff --git a/Scripts/Editor/NodeGraphEditor.cs b/Scripts/Editor/NodeGraphEditor.cs index 1286f7a..8a9d2f0 100644 --- a/Scripts/Editor/NodeGraphEditor.cs +++ b/Scripts/Editor/NodeGraphEditor.cs @@ -8,13 +8,16 @@ namespace XNodeEditor { /// Base class to derive custom Node Graph editors from. Use this to override how graphs are drawn in the editor. [CustomNodeGraphEditor(typeof(XNode.NodeGraph))] public class NodeGraphEditor : XNodeEditor.Internal.NodeEditorBase { - /// The position of the window in screen space. - public Rect position; + [Obsolete("Use window.position instead")] + public Rect position { get { return window.position; } set { window.position = value; } } /// Are we currently renaming a node? protected bool isRenaming; public virtual void OnGUI() { } + /// Called when opened by NodeEditorWindow + public virtual void OnOpen() { } + public virtual Texture2D GetGridTexture() { return NodeEditorPreferences.GetSettings().gridTexture; } From 32fa3d7c9f12ebfb2ef6cfb334f8e0d604d49c51 Mon Sep 17 00:00:00 2001 From: Woland Date: Thu, 11 Apr 2019 12:27:56 +0200 Subject: [PATCH 72/73] gitignore: Ignore meta files for git dot files --- .gitignore | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 68af404..1460751 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,8 @@ sysinfo.txt /Examples/ README.md.meta LICENSE.md.meta -CONTRIBUTING.md.meta \ No newline at end of file +CONTRIBUTING.md.meta + +.git.meta +.gitignore.meta +.gitattributes.meta From 7eaa15af4a70aea49267fb39da81a8c317916b51 Mon Sep 17 00:00:00 2001 From: Woland Date: Sun, 14 Apr 2019 03:21:29 +0200 Subject: [PATCH 73/73] NodeEditorReflection: Catch ReflectionTypeLoadException (#131) * NodeEditorReflection: Catch ReflectionTypeLoadException Can happen if dll can not be loaded for some reason * Removed unnecessary editor precompile tags --- Scripts/Editor/NodeEditorReflection.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Scripts/Editor/NodeEditorReflection.cs b/Scripts/Editor/NodeEditorReflection.cs index a2be28e..18b72fa 100644 --- a/Scripts/Editor/NodeEditorReflection.cs +++ b/Scripts/Editor/NodeEditorReflection.cs @@ -75,7 +75,9 @@ namespace XNodeEditor { List types = new List(); System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { - types.AddRange(assembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t)).ToArray()); + try { + types.AddRange(assembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsAssignableFrom(t)).ToArray()); + } catch(ReflectionTypeLoadException) {} } return types.ToArray(); } @@ -162,4 +164,4 @@ namespace XNodeEditor { } } } -} \ No newline at end of file +}