1
0
mirror of https://github.com/Siccity/xNode.git synced 2025-12-20 09:16:01 +08:00

Port Padding BugFIX

Added the separate port padding to control the port's offset position in relation to the node content padding

Currently, if I try to create a custom theme for node, i will be stuck with the port padding, because currently there are not separate padding from the node,
This commit is contained in:
juliocp 2020-10-07 16:33:10 -03:00
parent e820157fad
commit 72c7ca9d04
2 changed files with 203 additions and 102 deletions

View File

@ -7,20 +7,24 @@ using UnityEditor;
using UnityEditorInternal; using UnityEditorInternal;
using UnityEngine; using UnityEngine;
namespace XNodeEditor { namespace XNodeEditor
{
/// <summary> xNode-specific version of <see cref="EditorGUILayout"/> </summary> /// <summary> xNode-specific version of <see cref="EditorGUILayout"/> </summary>
public static class NodeEditorGUILayout { public static class NodeEditorGUILayout
{
private static readonly Dictionary<UnityEngine.Object, Dictionary<string, ReorderableList>> reorderableListCache = new Dictionary<UnityEngine.Object, Dictionary<string, ReorderableList>>(); private static readonly Dictionary<UnityEngine.Object, Dictionary<string, ReorderableList>> reorderableListCache = new Dictionary<UnityEngine.Object, Dictionary<string, ReorderableList>>();
private static int reorderableListIndex = -1; private static int reorderableListIndex = -1;
/// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary> /// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary>
public static void PropertyField(SerializedProperty property, bool includeChildren = true, params GUILayoutOption[] options) { public static void PropertyField(SerializedProperty property, bool includeChildren = true, params GUILayoutOption[] options)
{
PropertyField(property, (GUIContent)null, includeChildren, options); PropertyField(property, (GUIContent)null, includeChildren, options);
} }
/// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary> /// <summary> Make a field for a serialized property. Automatically displays relevant node port. </summary>
public static void PropertyField(SerializedProperty property, GUIContent label, bool includeChildren = true, params GUILayoutOption[] options) { public static void PropertyField(SerializedProperty property, GUIContent label, bool includeChildren = true, params GUILayoutOption[] options)
{
if (property == null) throw new NullReferenceException(); if (property == null) throw new NullReferenceException();
XNode.Node node = property.serializedObject.targetObject as XNode.Node; XNode.Node node = property.serializedObject.targetObject as XNode.Node;
XNode.NodePort port = node.GetPort(property.name); XNode.NodePort port = node.GetPort(property.name);
@ -28,28 +32,33 @@ namespace XNodeEditor {
} }
/// <summary> Make a field for a serialized property. Manual node port override. </summary> /// <summary> Make a field for a serialized property. Manual node port override. </summary>
public static void PropertyField(SerializedProperty property, XNode.NodePort port, bool includeChildren = true, params GUILayoutOption[] options) { public static void PropertyField(SerializedProperty property, XNode.NodePort port, bool includeChildren = true, params GUILayoutOption[] options)
{
PropertyField(property, null, port, includeChildren, options); PropertyField(property, null, port, includeChildren, options);
} }
/// <summary> Make a field for a serialized property. Manual node port override. </summary> /// <summary> Make a field for a serialized property. Manual node port override. </summary>
public static void PropertyField(SerializedProperty property, GUIContent label, XNode.NodePort port, bool includeChildren = true, params GUILayoutOption[] options) { public static void PropertyField(SerializedProperty property, GUIContent label, XNode.NodePort port, bool includeChildren = true, params GUILayoutOption[] options)
{
if (property == null) throw new NullReferenceException(); if (property == null) throw new NullReferenceException();
// If property is not a port, display a regular property field // If property is not a port, display a regular property field
if (port == null) EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30)); if (port == null) EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
else { else
{
Rect rect = new Rect(); Rect rect = new Rect();
List<PropertyAttribute> propertyAttributes = NodeEditorUtilities.GetCachedPropertyAttribs(port.node.GetType(), property.name); List<PropertyAttribute> propertyAttributes = NodeEditorUtilities.GetCachedPropertyAttribs(port.node.GetType(), property.name);
// If property is an input, display a regular property field and put a port handle on the left side // If property is an input, display a regular property field and put a port handle on the left side
if (port.direction == XNode.NodePort.IO.Input) { if (port.direction == XNode.NodePort.IO.Input)
{
// Get data from [Input] attribute // Get data from [Input] attribute
XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected; XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
XNode.Node.InputAttribute inputAttribute; XNode.Node.InputAttribute inputAttribute;
bool dynamicPortList = false; bool dynamicPortList = false;
if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute)) { if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute))
{
dynamicPortList = inputAttribute.dynamicPortList; dynamicPortList = inputAttribute.dynamicPortList;
showBacking = inputAttribute.backingValue; showBacking = inputAttribute.backingValue;
} }
@ -60,30 +69,40 @@ namespace XNodeEditor {
float spacePadding = 0; float spacePadding = 0;
string tooltip = null; string tooltip = null;
foreach (var attr in propertyAttributes) { foreach (var attr in propertyAttributes)
if (attr is SpaceAttribute) { {
if (attr is SpaceAttribute)
{
if (usePropertyAttributes) GUILayout.Space((attr as SpaceAttribute).height); if (usePropertyAttributes) GUILayout.Space((attr as SpaceAttribute).height);
else spacePadding += (attr as SpaceAttribute).height; else spacePadding += (attr as SpaceAttribute).height;
} else if (attr is HeaderAttribute) { }
if (usePropertyAttributes) { else if (attr is HeaderAttribute)
{
if (usePropertyAttributes)
{
//GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs //GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs
Rect position = GUILayoutUtility.GetRect(0, (EditorGUIUtility.singleLineHeight * 1.5f) - EditorGUIUtility.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it. Rect position = GUILayoutUtility.GetRect(0, (EditorGUIUtility.singleLineHeight * 1.5f) - EditorGUIUtility.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it.
position.yMin += EditorGUIUtility.singleLineHeight * 0.5f; position.yMin += EditorGUIUtility.singleLineHeight * 0.5f;
position = EditorGUI.IndentedRect(position); position = EditorGUI.IndentedRect(position);
GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel); GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
} else spacePadding += EditorGUIUtility.singleLineHeight * 1.5f; }
} else if (attr is TooltipAttribute) { else spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
}
else if (attr is TooltipAttribute)
{
tooltip = (attr as TooltipAttribute).tooltip; tooltip = (attr as TooltipAttribute).tooltip;
} }
} }
if (dynamicPortList) { if (dynamicPortList)
{
Type type = GetType(property); Type type = GetType(property);
XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType); DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
return; return;
} }
switch (showBacking) { switch (showBacking)
{
case XNode.Node.ShowBackingValue.Unconnected: case XNode.Node.ShowBackingValue.Unconnected:
// Display a label if port is connected // Display a label if port is connected
if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip)); if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
@ -101,14 +120,18 @@ namespace XNodeEditor {
} }
rect = GUILayoutUtility.GetLastRect(); rect = GUILayoutUtility.GetLastRect();
rect.position = rect.position - new Vector2(16, -spacePadding); float paddingLeft = NodeEditorResources.styles.inputPort.padding.left;
rect.position = rect.position - new Vector2(16 + paddingLeft, -spacePadding);
// If property is an output, display a text label and put a port handle on the right side // If property is an output, display a text label and put a port handle on the right side
} else if (port.direction == XNode.NodePort.IO.Output) { }
else if (port.direction == XNode.NodePort.IO.Output)
{
// Get data from [Output] attribute // Get data from [Output] attribute
XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected; XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
XNode.Node.OutputAttribute outputAttribute; XNode.Node.OutputAttribute outputAttribute;
bool dynamicPortList = false; bool dynamicPortList = false;
if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute)) { if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute))
{
dynamicPortList = outputAttribute.dynamicPortList; dynamicPortList = outputAttribute.dynamicPortList;
showBacking = outputAttribute.backingValue; showBacking = outputAttribute.backingValue;
} }
@ -119,30 +142,40 @@ namespace XNodeEditor {
float spacePadding = 0; float spacePadding = 0;
string tooltip = null; string tooltip = null;
foreach (var attr in propertyAttributes) { foreach (var attr in propertyAttributes)
if (attr is SpaceAttribute) { {
if (attr is SpaceAttribute)
{
if (usePropertyAttributes) GUILayout.Space((attr as SpaceAttribute).height); if (usePropertyAttributes) GUILayout.Space((attr as SpaceAttribute).height);
else spacePadding += (attr as SpaceAttribute).height; else spacePadding += (attr as SpaceAttribute).height;
} else if (attr is HeaderAttribute) { }
if (usePropertyAttributes) { else if (attr is HeaderAttribute)
{
if (usePropertyAttributes)
{
//GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs //GUI Values are from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs
Rect position = GUILayoutUtility.GetRect(0, (EditorGUIUtility.singleLineHeight * 1.5f) - EditorGUIUtility.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it. Rect position = GUILayoutUtility.GetRect(0, (EditorGUIUtility.singleLineHeight * 1.5f) - EditorGUIUtility.standardVerticalSpacing); //Layout adds standardVerticalSpacing after rect so we subtract it.
position.yMin += EditorGUIUtility.singleLineHeight * 0.5f; position.yMin += EditorGUIUtility.singleLineHeight * 0.5f;
position = EditorGUI.IndentedRect(position); position = EditorGUI.IndentedRect(position);
GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel); GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
} else spacePadding += EditorGUIUtility.singleLineHeight * 1.5f; }
} else if (attr is TooltipAttribute) { else spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
}
else if (attr is TooltipAttribute)
{
tooltip = (attr as TooltipAttribute).tooltip; tooltip = (attr as TooltipAttribute).tooltip;
} }
} }
if (dynamicPortList) { if (dynamicPortList)
{
Type type = GetType(property); Type type = GetType(property);
XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple; XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType); DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
return; return;
} }
switch (showBacking) { switch (showBacking)
{
case XNode.Node.ShowBackingValue.Unconnected: case XNode.Node.ShowBackingValue.Unconnected:
// Display a label if port is connected // Display a label if port is connected
if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30)); if (port.IsConnected) EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
@ -160,6 +193,7 @@ namespace XNodeEditor {
} }
rect = GUILayoutUtility.GetLastRect(); rect = GUILayoutUtility.GetLastRect();
rect.width += NodeEditorResources.styles.outputPort.padding.right;
rect.position = rect.position + new Vector2(rect.width, spacePadding); rect.position = rect.position + new Vector2(rect.width, spacePadding);
} }
@ -175,45 +209,53 @@ namespace XNodeEditor {
} }
} }
private static System.Type GetType(SerializedProperty property) { private static System.Type GetType(SerializedProperty property)
{
System.Type parentType = property.serializedObject.targetObject.GetType(); System.Type parentType = property.serializedObject.targetObject.GetType();
System.Reflection.FieldInfo fi = parentType.GetFieldInfo(property.name); System.Reflection.FieldInfo fi = parentType.GetFieldInfo(property.name);
return fi.FieldType; return fi.FieldType;
} }
/// <summary> Make a simple port field. </summary> /// <summary> Make a simple port field. </summary>
public static void PortField(XNode.NodePort port, params GUILayoutOption[] options) { public static void PortField(XNode.NodePort port, params GUILayoutOption[] options)
{
PortField(null, port, options); PortField(null, port, options);
} }
/// <summary> Make a simple port field. </summary> /// <summary> Make a simple port field. </summary>
public static void PortField(GUIContent label, XNode.NodePort port, params GUILayoutOption[] options) { public static void PortField(GUIContent label, XNode.NodePort port, params GUILayoutOption[] options)
{
if (port == null) return; if (port == null) return;
if (options == null) options = new GUILayoutOption[] { GUILayout.MinWidth(30) }; if (options == null) options = new GUILayoutOption[] { GUILayout.MinWidth(30) };
Vector2 position = Vector3.zero; Vector2 position = Vector3.zero;
GUIContent content = label != null ? label : new GUIContent(ObjectNames.NicifyVariableName(port.fieldName)); GUIContent content = label != null ? label : new GUIContent(ObjectNames.NicifyVariableName(port.fieldName));
// If property is an input, display a regular property field and put a port handle on the left side // If property is an input, display a regular property field and put a port handle on the left side
if (port.direction == XNode.NodePort.IO.Input) { if (port.direction == XNode.NodePort.IO.Input)
{
// Display a label // Display a label
EditorGUILayout.LabelField(content, options); EditorGUILayout.LabelField(content, options);
Rect rect = GUILayoutUtility.GetLastRect(); Rect rect = GUILayoutUtility.GetLastRect();
position = rect.position - new Vector2(16, 0); float paddingLeft = NodeEditorResources.styles.inputPort.padding.left;
position = rect.position - new Vector2(16 + paddingLeft, 0);
} }
// If property is an output, display a text label and put a port handle on the right side // If property is an output, display a text label and put a port handle on the right side
else if (port.direction == XNode.NodePort.IO.Output) { else if (port.direction == XNode.NodePort.IO.Output)
{
// Display a label // Display a label
EditorGUILayout.LabelField(content, NodeEditorResources.OutputPort, options); EditorGUILayout.LabelField(content, NodeEditorResources.OutputPort, options);
Rect rect = GUILayoutUtility.GetLastRect(); Rect rect = GUILayoutUtility.GetLastRect();
rect.width += NodeEditorResources.styles.outputPort.padding.right;
position = rect.position + new Vector2(rect.width, 0); position = rect.position + new Vector2(rect.width, 0);
} }
PortField(position, port); PortField(position, port);
} }
/// <summary> Make a simple port field. </summary> /// <summary> Make a simple port field. </summary>
public static void PortField(Vector2 position, XNode.NodePort port) { public static void PortField(Vector2 position, XNode.NodePort port)
{
if (port == null) return; if (port == null) return;
Rect rect = new Rect(position, new Vector2(16, 16)); Rect rect = new Rect(position, new Vector2(16, 16));
@ -228,17 +270,23 @@ namespace XNodeEditor {
} }
/// <summary> Add a port field to previous layout element. </summary> /// <summary> Add a port field to previous layout element. </summary>
public static void AddPortField(XNode.NodePort port) { public static void AddPortField(XNode.NodePort port)
{
if (port == null) return; if (port == null) return;
Rect rect = new Rect(); Rect rect = new Rect();
// If property is an input, display a regular property field and put a port handle on the left side // If property is an input, display a regular property field and put a port handle on the left side
if (port.direction == XNode.NodePort.IO.Input) { if (port.direction == XNode.NodePort.IO.Input)
{
rect = GUILayoutUtility.GetLastRect(); rect = GUILayoutUtility.GetLastRect();
rect.position = rect.position - new Vector2(16, 0); float paddingLeft = NodeEditorResources.styles.inputPort.padding.left;
rect.position = rect.position - new Vector2(16 + paddingLeft, 0);
// If property is an output, display a text label and put a port handle on the right side // If property is an output, display a text label and put a port handle on the right side
} else if (port.direction == XNode.NodePort.IO.Output) { }
else if (port.direction == XNode.NodePort.IO.Output)
{
rect = GUILayoutUtility.GetLastRect(); rect = GUILayoutUtility.GetLastRect();
rect.width += NodeEditorResources.styles.outputPort.padding.right;
rect.position = rect.position + new Vector2(rect.width, 0); rect.position = rect.position + new Vector2(rect.width, 0);
} }
@ -254,14 +302,16 @@ namespace XNodeEditor {
} }
/// <summary> Draws an input and an output port on the same line </summary> /// <summary> Draws an input and an output port on the same line </summary>
public static void PortPair(XNode.NodePort input, XNode.NodePort output) { public static void PortPair(XNode.NodePort input, XNode.NodePort output)
{
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
NodeEditorGUILayout.PortField(input, GUILayout.MinWidth(0)); NodeEditorGUILayout.PortField(input, GUILayout.MinWidth(0));
NodeEditorGUILayout.PortField(output, GUILayout.MinWidth(0)); NodeEditorGUILayout.PortField(output, GUILayout.MinWidth(0));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
public static void DrawPortHandle(Rect rect, Color backgroundColor, Color typeColor) { public static void DrawPortHandle(Rect rect, Color backgroundColor, Color typeColor)
{
Color col = GUI.color; Color col = GUI.color;
GUI.color = backgroundColor; GUI.color = backgroundColor;
GUI.DrawTexture(rect, NodeEditorResources.dotOuter); GUI.DrawTexture(rect, NodeEditorResources.dotOuter);
@ -272,22 +322,26 @@ namespace XNodeEditor {
#region Obsolete #region Obsolete
[Obsolete("Use IsDynamicPortListPort instead")] [Obsolete("Use IsDynamicPortListPort instead")]
public static bool IsInstancePortListPort(XNode.NodePort port) { public static bool IsInstancePortListPort(XNode.NodePort port)
{
return IsDynamicPortListPort(port); return IsDynamicPortListPort(port);
} }
[Obsolete("Use DynamicPortList instead")] [Obsolete("Use DynamicPortList instead")]
public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple, XNode.Node.TypeConstraint typeConstraint = XNode.Node.TypeConstraint.None, Action<ReorderableList> onCreation = null) { public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple, XNode.Node.TypeConstraint typeConstraint = XNode.Node.TypeConstraint.None, Action<ReorderableList> onCreation = null)
{
DynamicPortList(fieldName, type, serializedObject, io, connectionType, typeConstraint, onCreation); DynamicPortList(fieldName, type, serializedObject, io, connectionType, typeConstraint, onCreation);
} }
#endregion #endregion
/// <summary> Is this port part of a DynamicPortList? </summary> /// <summary> Is this port part of a DynamicPortList? </summary>
public static bool IsDynamicPortListPort(XNode.NodePort port) { public static bool IsDynamicPortListPort(XNode.NodePort port)
{
string[] parts = port.fieldName.Split(' '); string[] parts = port.fieldName.Split(' ');
if (parts.Length != 2) return false; if (parts.Length != 2) return false;
Dictionary<string, ReorderableList> cache; Dictionary<string, ReorderableList> cache;
if (reorderableListCache.TryGetValue(port.node, out cache)) { if (reorderableListCache.TryGetValue(port.node, out cache))
{
ReorderableList list; ReorderableList list;
if (cache.TryGetValue(parts[0], out list)) return true; if (cache.TryGetValue(parts[0], out list)) return true;
} }
@ -300,14 +354,18 @@ namespace XNodeEditor {
/// <param name="serializedObject">The serializedObject of the node</param> /// <param name="serializedObject">The serializedObject of the node</param>
/// <param name="connectionType">Connection type of added dynamic ports</param> /// <param name="connectionType">Connection type of added dynamic ports</param>
/// <param name="onCreation">Called on the list on creation. Use this if you want to customize the created ReorderableList</param> /// <param name="onCreation">Called on the list on creation. Use this if you want to customize the created ReorderableList</param>
public static void DynamicPortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple, XNode.Node.TypeConstraint typeConstraint = XNode.Node.TypeConstraint.None, Action<ReorderableList> onCreation = null) { public static void DynamicPortList(string fieldName, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple, XNode.Node.TypeConstraint typeConstraint = XNode.Node.TypeConstraint.None, Action<ReorderableList> onCreation = null)
{
XNode.Node node = serializedObject.targetObject as XNode.Node; XNode.Node node = serializedObject.targetObject as XNode.Node;
var indexedPorts = node.DynamicPorts.Select(x => { var indexedPorts = node.DynamicPorts.Select(x =>
{
string[] split = x.fieldName.Split(' '); string[] split = x.fieldName.Split(' ');
if (split != null && split.Length == 2 && split[0] == fieldName) { if (split != null && split.Length == 2 && split[0] == fieldName)
{
int i = -1; int i = -1;
if (int.TryParse(split[1], out i)) { if (int.TryParse(split[1], out i))
{
return new { index = i, port = x }; return new { index = i, port = x };
} }
} }
@ -319,11 +377,13 @@ namespace XNodeEditor {
ReorderableList list = null; ReorderableList list = null;
Dictionary<string, ReorderableList> rlc; Dictionary<string, ReorderableList> rlc;
if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) { if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc))
{
if (!rlc.TryGetValue(fieldName, out list)) list = null; if (!rlc.TryGetValue(fieldName, out list)) list = null;
} }
// If a ReorderableList isn't cached for this array, do so. // If a ReorderableList isn't cached for this array, do so.
if (list == null) { if (list == null)
{
SerializedProperty arrayData = serializedObject.FindProperty(fieldName); SerializedProperty arrayData = serializedObject.FindProperty(fieldName);
list = CreateReorderableList(fieldName, dynamicPorts, arrayData, type, serializedObject, io, connectionType, typeConstraint, onCreation); list = CreateReorderableList(fieldName, dynamicPorts, arrayData, type, serializedObject, io, connectionType, typeConstraint, onCreation);
if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list); if (reorderableListCache.TryGetValue(serializedObject.targetObject, out rlc)) rlc.Add(fieldName, list);
@ -334,53 +394,67 @@ namespace XNodeEditor {
} }
private static ReorderableList CreateReorderableList(string fieldName, List<XNode.NodePort> dynamicPorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType, XNode.Node.TypeConstraint typeConstraint, Action<ReorderableList> onCreation) { private static ReorderableList CreateReorderableList(string fieldName, List<XNode.NodePort> dynamicPorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, XNode.Node.ConnectionType connectionType, XNode.Node.TypeConstraint typeConstraint, Action<ReorderableList> onCreation)
{
bool hasArrayData = arrayData != null && arrayData.isArray; bool hasArrayData = arrayData != null && arrayData.isArray;
XNode.Node node = serializedObject.targetObject as XNode.Node; XNode.Node node = serializedObject.targetObject as XNode.Node;
ReorderableList list = new ReorderableList(dynamicPorts, null, true, true, true, true); ReorderableList list = new ReorderableList(dynamicPorts, null, true, true, true, true);
string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName); string label = arrayData != null ? arrayData.displayName : ObjectNames.NicifyVariableName(fieldName);
list.drawElementCallback = list.drawElementCallback =
(Rect rect, int index, bool isActive, bool isFocused) => { (Rect rect, int index, bool isActive, bool isFocused) =>
{
XNode.NodePort port = node.GetPort(fieldName + " " + index); XNode.NodePort port = node.GetPort(fieldName + " " + index);
if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String) { if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String)
if (arrayData.arraySize <= index) { {
if (arrayData.arraySize <= index)
{
EditorGUI.LabelField(rect, "Array[" + index + "] data out of range"); EditorGUI.LabelField(rect, "Array[" + index + "] data out of range");
return; return;
} }
SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
EditorGUI.PropertyField(rect, itemData, true); EditorGUI.PropertyField(rect, itemData, true);
} else EditorGUI.LabelField(rect, port != null ? port.fieldName : ""); }
if (port != null) { else EditorGUI.LabelField(rect, port != null ? port.fieldName : "");
if (port != null)
{
Vector2 pos = rect.position + (port.IsOutput ? new Vector2(rect.width + 6, 0) : new Vector2(-36, 0)); Vector2 pos = rect.position + (port.IsOutput ? new Vector2(rect.width + 6, 0) : new Vector2(-36, 0));
NodeEditorGUILayout.PortField(pos, port); NodeEditorGUILayout.PortField(pos, port);
} }
}; };
list.elementHeightCallback = list.elementHeightCallback =
(int index) => { (int index) =>
if (hasArrayData) { {
if (hasArrayData)
{
if (arrayData.arraySize <= index) return EditorGUIUtility.singleLineHeight; if (arrayData.arraySize <= index) return EditorGUIUtility.singleLineHeight;
SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index); SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
return EditorGUI.GetPropertyHeight(itemData); return EditorGUI.GetPropertyHeight(itemData);
} else return EditorGUIUtility.singleLineHeight; }
else return EditorGUIUtility.singleLineHeight;
}; };
list.drawHeaderCallback = list.drawHeaderCallback =
(Rect rect) => { (Rect rect) =>
{
EditorGUI.LabelField(rect, label); EditorGUI.LabelField(rect, label);
}; };
list.onSelectCallback = list.onSelectCallback =
(ReorderableList rl) => { (ReorderableList rl) =>
{
reorderableListIndex = rl.index; reorderableListIndex = rl.index;
}; };
list.onReorderCallback = list.onReorderCallback =
(ReorderableList rl) => { (ReorderableList rl) =>
{
bool hasRect = false; bool hasRect = false;
bool hasNewRect = false; bool hasNewRect = false;
Rect rect = Rect.zero; Rect rect = Rect.zero;
Rect newRect = Rect.zero; Rect newRect = Rect.zero;
// Move up // Move up
if (rl.index > reorderableListIndex) { if (rl.index > reorderableListIndex)
for (int i = reorderableListIndex; i < rl.index; ++i) { {
for (int i = reorderableListIndex; i < rl.index; ++i)
{
XNode.NodePort port = node.GetPort(fieldName + " " + i); XNode.NodePort port = node.GetPort(fieldName + " " + i);
XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i + 1)); XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i + 1));
port.SwapConnections(nextPort); port.SwapConnections(nextPort);
@ -393,8 +467,10 @@ namespace XNodeEditor {
} }
} }
// Move down // Move down
else { else
for (int i = reorderableListIndex; i > rl.index; --i) { {
for (int i = reorderableListIndex; i > rl.index; --i)
{
XNode.NodePort port = node.GetPort(fieldName + " " + i); XNode.NodePort port = node.GetPort(fieldName + " " + i);
XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i - 1)); XNode.NodePort nextPort = node.GetPort(fieldName + " " + (i - 1));
port.SwapConnections(nextPort); port.SwapConnections(nextPort);
@ -411,7 +487,8 @@ namespace XNodeEditor {
serializedObject.Update(); serializedObject.Update();
// Move array data if there is any // Move array data if there is any
if (hasArrayData) { if (hasArrayData)
{
arrayData.MoveArrayElement(reorderableListIndex, rl.index); arrayData.MoveArrayElement(reorderableListIndex, rl.index);
} }
@ -422,7 +499,8 @@ namespace XNodeEditor {
EditorApplication.delayCall += NodeEditorWindow.current.Repaint; EditorApplication.delayCall += NodeEditorWindow.current.Repaint;
}; };
list.onAddCallback = list.onAddCallback =
(ReorderableList rl) => { (ReorderableList rl) =>
{
// Add dynamic port postfixed with an index number // Add dynamic port postfixed with an index number
string newName = fieldName + " 0"; string newName = fieldName + " 0";
int i = 0; int i = 0;
@ -432,19 +510,24 @@ namespace XNodeEditor {
else node.AddDynamicInput(type, connectionType, typeConstraint, newName); else node.AddDynamicInput(type, connectionType, typeConstraint, newName);
serializedObject.Update(); serializedObject.Update();
EditorUtility.SetDirty(node); EditorUtility.SetDirty(node);
if (hasArrayData) { if (hasArrayData)
{
arrayData.InsertArrayElementAtIndex(arrayData.arraySize); arrayData.InsertArrayElementAtIndex(arrayData.arraySize);
} }
serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties();
}; };
list.onRemoveCallback = list.onRemoveCallback =
(ReorderableList rl) => { (ReorderableList rl) =>
{
var indexedPorts = node.DynamicPorts.Select(x => { var indexedPorts = node.DynamicPorts.Select(x =>
{
string[] split = x.fieldName.Split(' '); string[] split = x.fieldName.Split(' ');
if (split != null && split.Length == 2 && split[0] == fieldName) { if (split != null && split.Length == 2 && split[0] == fieldName)
{
int i = -1; int i = -1;
if (int.TryParse(split[1], out i)) { if (int.TryParse(split[1], out i))
{
return new { index = i, port = x }; return new { index = i, port = x };
} }
} }
@ -454,17 +537,24 @@ namespace XNodeEditor {
int index = rl.index; int index = rl.index;
if (dynamicPorts[index] == null) { if (dynamicPorts[index] == null)
{
Debug.LogWarning("No port found at index " + index + " - Skipped"); Debug.LogWarning("No port found at index " + index + " - Skipped");
} else if (dynamicPorts.Count <= index) { }
else if (dynamicPorts.Count <= index)
{
Debug.LogWarning("DynamicPorts[" + index + "] out of range. Length was " + dynamicPorts.Count + " - Skipped"); Debug.LogWarning("DynamicPorts[" + index + "] out of range. Length was " + dynamicPorts.Count + " - Skipped");
} else { }
else
{
// Clear the removed ports connections // Clear the removed ports connections
dynamicPorts[index].ClearConnections(); dynamicPorts[index].ClearConnections();
// Move following connections one step up to replace the missing connection // Move following connections one step up to replace the missing connection
for (int k = index + 1; k < dynamicPorts.Count(); k++) { for (int k = index + 1; k < dynamicPorts.Count(); k++)
for (int j = 0; j < dynamicPorts[k].ConnectionCount; j++) { {
for (int j = 0; j < dynamicPorts[k].ConnectionCount; j++)
{
XNode.NodePort other = dynamicPorts[k].GetConnection(j); XNode.NodePort other = dynamicPorts[k].GetConnection(j);
dynamicPorts[k].Disconnect(other); dynamicPorts[k].Disconnect(other);
dynamicPorts[k - 1].Connect(other); dynamicPorts[k - 1].Connect(other);
@ -476,16 +566,20 @@ namespace XNodeEditor {
EditorUtility.SetDirty(node); EditorUtility.SetDirty(node);
} }
if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String) { if (hasArrayData && arrayData.propertyType != SerializedPropertyType.String)
if (arrayData.arraySize <= index) { {
if (arrayData.arraySize <= index)
{
Debug.LogWarning("Attempted to remove array index " + index + " where only " + arrayData.arraySize + " exist - Skipped"); Debug.LogWarning("Attempted to remove array index " + index + " where only " + arrayData.arraySize + " exist - Skipped");
Debug.Log(rl.list[0]); Debug.Log(rl.list[0]);
return; return;
} }
arrayData.DeleteArrayElementAtIndex(index); arrayData.DeleteArrayElementAtIndex(index);
// Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues
if (dynamicPorts.Count <= arrayData.arraySize) { if (dynamicPorts.Count <= arrayData.arraySize)
while (dynamicPorts.Count <= arrayData.arraySize) { {
while (dynamicPorts.Count <= arrayData.arraySize)
{
arrayData.DeleteArrayElementAtIndex(arrayData.arraySize - 1); arrayData.DeleteArrayElementAtIndex(arrayData.arraySize - 1);
} }
UnityEngine.Debug.LogWarning("Array size exceeded dynamic ports size. Excess items removed."); UnityEngine.Debug.LogWarning("Array size exceeded dynamic ports size. Excess items removed.");
@ -495,9 +589,11 @@ namespace XNodeEditor {
} }
}; };
if (hasArrayData) { if (hasArrayData)
{
int dynamicPortCount = dynamicPorts.Count; int dynamicPortCount = dynamicPorts.Count;
while (dynamicPortCount < arrayData.arraySize) { while (dynamicPortCount < arrayData.arraySize)
{
// Add dynamic port postfixed with an index number // Add dynamic port postfixed with an index number
string newName = arrayData.name + " 0"; string newName = arrayData.name + " 0";
int i = 0; int i = 0;
@ -507,7 +603,8 @@ namespace XNodeEditor {
EditorUtility.SetDirty(node); EditorUtility.SetDirty(node);
dynamicPortCount++; dynamicPortCount++;
} }
while (arrayData.arraySize < dynamicPortCount) { while (arrayData.arraySize < dynamicPortCount)
{
arrayData.InsertArrayElementAtIndex(arrayData.arraySize); arrayData.InsertArrayElementAtIndex(arrayData.arraySize);
} }
serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties();

View File

@ -18,7 +18,7 @@ namespace XNodeEditor {
public static Styles _styles = null; public static Styles _styles = null;
public static GUIStyle OutputPort { get { return new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperRight }; } } public static GUIStyle OutputPort { get { return new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperRight }; } }
public class Styles { public class Styles {
public GUIStyle inputPort, nodeHeader, nodeBody, tooltip, nodeHighlight; public GUIStyle inputPort, outputPort, nodeHeader, nodeBody, tooltip, nodeHighlight;
public Styles() { public Styles() {
GUIStyle baseStyle = new GUIStyle("Label"); GUIStyle baseStyle = new GUIStyle("Label");
@ -26,7 +26,11 @@ namespace XNodeEditor {
inputPort = new GUIStyle(baseStyle); inputPort = new GUIStyle(baseStyle);
inputPort.alignment = TextAnchor.UpperLeft; inputPort.alignment = TextAnchor.UpperLeft;
inputPort.padding.left = 10; inputPort.padding.left = 0;
outputPort = new GUIStyle(baseStyle);
outputPort.alignment = TextAnchor.UpperRight;
outputPort.padding.right = 0;
nodeHeader = new GUIStyle(); nodeHeader = new GUIStyle();
nodeHeader.alignment = TextAnchor.MiddleCenter; nodeHeader.alignment = TextAnchor.MiddleCenter;