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. 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 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/NodeEditor.cs b/Scripts/Editor/NodeEditor.cs index f38b510..f131f66 100644 --- a/Scripts/Editor/NodeEditor.cs +++ b/Scripts/Editor/NodeEditor.cs @@ -106,6 +106,7 @@ namespace XNodeEditor { } public void Rename(string newName) { + if (newName == null || newName.Trim() == "") newName = UnityEditor.ObjectNames.NicifyVariableName(target.GetType().Name); target.name = newName; AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target)); } diff --git a/Scripts/Editor/NodeEditorAction.cs b/Scripts/Editor/NodeEditorAction.cs index b4d052b..b4f6562 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; @@ -61,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; } @@ -170,7 +169,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; @@ -231,6 +230,7 @@ namespace XNodeEditor { // If click outside node, release field focus if (!isPanning) { EditorGUI.FocusTextInControl(null); + EditorGUIUtility.editingTextField = false; } if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets(); } @@ -241,9 +241,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; } } @@ -287,7 +286,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(); @@ -298,7 +297,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") { @@ -317,6 +316,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 @@ -420,7 +427,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/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/Editor/NodeEditorGUILayout.cs b/Scripts/Editor/NodeEditorGUILayout.cs index 629c594..ee4394d 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; } @@ -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/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]; diff --git a/Scripts/Editor/NodeEditorReflection.cs b/Scripts/Editor/NodeEditorReflection.cs index 04c6484..a2be28e 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,14 +53,23 @@ 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; } + /// 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"); diff --git a/Scripts/Node.cs b/Scripts/Node.cs index 4a9ace9..8785280 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. @@ -63,7 +73,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; @@ -88,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; @@ -111,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; } @@ -206,24 +215,25 @@ 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)] public class InputAttribute : Attribute { 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 +247,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; @@ -255,19 +266,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 +286,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(); 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