/// <summary> Draws standard field editors for all public fields </summary>
        public virtual void OnBodyGUI()
        {
            // Unity specifically requires this to save/update any serial object.
            // serializedObject.Update(); must go at the start of an inspector gui, and
            // serializedObject.ApplyModifiedProperties(); goes at the end.
            serializedObject.Update();
            string[] excludes = { "m_Script", "graph", "position", "ports" };

            // Iterate through serialized properties and draw them like the Inspector (But with ports)
            SerializedProperty iterator = serializedObject.GetIterator();
            bool enterChildren          = true;

            EditorGUIUtility.labelWidth = 150;
            while (iterator.NextVisible(enterChildren))
            {
                enterChildren = false;
                if (excludes.Contains(iterator.name))
                {
                    continue;
                }
                NodeEditorGUILayout.PropertyField(iterator, true);
            }

            // Iterate through dynamic ports and draw them in the order in which they are serialized
            foreach (XNode.NodePort dynamicPort in target.DynamicPorts)
            {
                if (NodeEditorGUILayout.IsDynamicPortListPort(dynamicPort))
                {
                    continue;
                }
                NodeEditorGUILayout.PortField(dynamicPort);
            }

            serializedObject.ApplyModifiedProperties();
        }
Ejemplo n.º 2
0
        /// <summary> Like OnBodyGUI(), but only draws ports, ignoring other fields </summary>
        public void OnBodyGUILight()
        {
            // Unity specifically requires this to save/update any serial object.
            // serializedObject.Update(); must go at the start of an inspector gui, and
            // serializedObject.ApplyModifiedProperties(); goes at the end.
            serializedObject.Update();
            string[] excludes = { "m_Script", "graph", "position", "ports" };
            portPositions = new Dictionary <XNode.NodePort, Vector2>();

            SerializedProperty iterator = serializedObject.GetIterator();
            bool enterChildren          = true;

            EditorGUIUtility.labelWidth = 84;
            while (iterator.NextVisible(enterChildren))
            {
                enterChildren = false;
                if (excludes.Contains(iterator.name))
                {
                    continue;
                }
                XNode.Node     node = iterator.serializedObject.targetObject as XNode.Node;
                XNode.NodePort port = node.GetPort(iterator.name);
                if (port == null)
                {
                    continue;
                }

                NodeEditorGUILayout.PropertyField(iterator, true);
            }
            serializedObject.ApplyModifiedProperties();
        }
Ejemplo n.º 3
0
        /// <summary> Draws standard field editors for all public fields </summary>
        public virtual void OnBodyGUI()
        {
#if ODIN_INSPECTOR
            inNodeEditor = true;
#endif

            // Unity specifically requires this to save/update any serial object.
            // serializedObject.Update(); must go at the start of an inspector gui, and
            // serializedObject.ApplyModifiedProperties(); goes at the end.
            serializedObject.Update();
            string[] excludes = { "m_Script", "graph", "position", "ports" };

#if ODIN_INSPECTOR
            InspectorUtilities.BeginDrawPropertyTree(objectTree, true);
            GUIHelper.PushLabelWidth(84);
            objectTree.Draw(true);
            InspectorUtilities.EndDrawPropertyTree(objectTree);
            GUIHelper.PopLabelWidth();
#else
            // Iterate through serialized properties and draw them like the Inspector (But with ports)
            SerializedProperty iterator = serializedObject.GetIterator();
            bool enterChildren          = true;
            while (iterator.NextVisible(enterChildren))
            {
                enterChildren = false;
                if (excludes.Contains(iterator.name))
                {
                    continue;
                }
                NodeEditorGUILayout.PropertyField(iterator, true);
            }
#endif

            // Iterate through dynamic ports and draw them in the order in which they are serialized
            foreach (XNode.NodePort dynamicPort in target.DynamicPorts)
            {
                if (NodeEditorGUILayout.IsDynamicPortListPort(dynamicPort))
                {
                    continue;
                }
                NodeEditorGUILayout.PortField(dynamicPort);
            }

            serializedObject.ApplyModifiedProperties();

#if ODIN_INSPECTOR
            // Call repaint so that the graph window elements respond properly to layout changes coming from Odin
            if (GUIHelper.RepaintRequested)
            {
                GUIHelper.ClearRepaintRequest();
                window.Repaint();
            }
#else
            window.Repaint();
#endif

#if ODIN_INSPECTOR
            inNodeEditor = false;
#endif
        }
Ejemplo n.º 4
0
 /// <summary> Draws an input and an output port on the same line </summary>
 public static void PortPair(XNode.NodePort input, XNode.NodePort output)
 {
     GUILayout.BeginHorizontal();
     NodeEditorGUILayout.PortField(input, GUILayout.MinWidth(0));
     NodeEditorGUILayout.PortField(output, GUILayout.MinWidth(0));
     GUILayout.EndHorizontal();
 }
Ejemplo n.º 5
0
        /// <summary> Safely remove a node and all its connections. </summary>
        public virtual void RemoveNode(XNode.Node node)
        {
            if (!CanRemove(node))
            {
                return;
            }

            // Remove the node
            Undo.RecordObject(node, "Delete Node");
            Undo.RecordObject(target, "Delete Node");
            foreach (var port in node.Ports)
            {
                foreach (var conn in port.GetConnections())
                {
                    Undo.RecordObject(conn.node, "Delete Node");
                }
            }
            target.RemoveNode(node);

            //Remove NodeEdotpr cachedata ,otherwise ,delete node will throw error (odin)
            NodeEditor.GetEditor(node, NodeEditorWindow.current).RemoveEditor();
            //Remove dynamicPort cachedata ,otherwise ,delete node will throw error
            NodeEditorGUILayout.RemoveTargetreorderableList(node);

            Undo.DestroyObjectImmediate(node);
            if (NodeEditorPreferences.GetSettings().autoSave)
            {
                AssetDatabase.SaveAssets();
            }
        }
Ejemplo n.º 6
0
        /// <summary> Draws an input and an output port on the same line </summary>
        public static void PortPair(XNode.NodePort input, GUIContent label, XNode.NodePort output)
        {
            GUILayout.BeginHorizontal();
            NodeEditorGUILayout.PortField(new GUIContent(""), input, GUILayout.MinWidth(0));
            GUIStyle style = new GUIStyle(EditorStyles.label);

            style.alignment = TextAnchor.MiddleCenter;
            EditorGUILayout.LabelField(label, style, GUILayout.MinWidth(0));
            NodeEditorGUILayout.PortField(new GUIContent(""), output, GUILayout.MinWidth(0));
            GUILayout.EndHorizontal();
        }
Ejemplo n.º 7
0
        /// <summary> Draw a connection as we are dragging it </summary>
        public void DrawDraggedConnection()
        {
            if (IsDraggingPort)
            {
                Color col = NodeEditorPreferences.GetTypeColor(draggedPort.ValueType);
                col.a = draggedPortTarget != null ? 1.0f : 0.6f;

                Rect fromRect;
                if (!_portConnectionPoints.TryGetValue(draggedPort, out fromRect))
                {
                    return;
                }
                List <Vector2> gridPoints = new List <Vector2>();
                gridPoints.Add(fromRect.center);
                for (int i = 0; i < draggedOutputReroutes.Count; i++)
                {
                    gridPoints.Add(draggedOutputReroutes[i]);
                }
                if (draggedPortTarget != null)
                {
                    gridPoints.Add(portConnectionPoints[draggedPortTarget].center);
                }
                else
                {
                    gridPoints.Add(WindowToGridPosition(Event.current.mousePosition));
                }

                if (draggedPort.IsInput)
                {
                    gridPoints.Reverse();
                }
                DrawNoodle(col, gridPoints);

                Color bgcol = Color.black;
                Color frcol = col;
                bgcol.a = 0.6f;
                frcol.a = 0.6f;

                // Loop through reroute points again and draw the points
                for (int i = 0; i < draggedOutputReroutes.Count; i++)
                {
                    // Draw reroute point at position
                    Rect rect = new Rect(draggedOutputReroutes[i], new Vector2(16, 16));
                    rect.position = new Vector2(rect.position.x - 8, rect.position.y - 8);
                    rect          = GridToWindowRect(rect);

                    NodeEditorGUILayout.DrawPortHandle(rect, bgcol, frcol);
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary> Draw a connection as we are dragging it </summary>
        public void DrawDraggedConnection()
        {
            if (IsDraggingPort)
            {
                Gradient     gradient  = graphEditor.GetNoodleGradient(draggedOutput, null);
                float        thickness = graphEditor.GetNoodleThickness(draggedOutput, null);
                NoodlePath   path      = graphEditor.GetNoodlePath(draggedOutput, null);
                NoodleStroke stroke    = graphEditor.GetNoodleStroke(draggedOutput, null);

                Rect fromRect;
                if (!_portConnectionPoints.TryGetValue(draggedOutput, out fromRect))
                {
                    return;
                }
                List <Vector2> gridPoints = new List <Vector2>();
                gridPoints.Add(fromRect.center);
                for (int i = 0; i < draggedOutputReroutes.Count; i++)
                {
                    gridPoints.Add(draggedOutputReroutes[i]);
                }
                if (draggedOutputTarget != null)
                {
                    gridPoints.Add(portConnectionPoints[draggedOutputTarget].center);
                }
                else
                {
                    gridPoints.Add(WindowToGridPosition(Event.current.mousePosition));
                }

                DrawNoodle(gradient, path, stroke, thickness, gridPoints);

                GUIStyle portStyle = NodeEditorWindow.current.graphEditor.GetPortStyle(draggedOutput);
                Color    bgcol     = Color.black;
                Color    frcol     = gradient.colorKeys[0].color;
                bgcol.a = 0.6f;
                frcol.a = 0.6f;

                // Loop through reroute points again and draw the points
                for (int i = 0; i < draggedOutputReroutes.Count; i++)
                {
                    // Draw reroute point at position
                    Rect rect = new Rect(draggedOutputReroutes[i], new Vector2(16, 16));
                    rect.position = new Vector2(rect.position.x - 8, rect.position.y - 8);
                    rect          = GridToWindowRect(rect);

                    NodeEditorGUILayout.DrawPortHandle(rect, bgcol, frcol, portStyle.normal.background, portStyle.active.background);
                }
            }
        }
Ejemplo n.º 9
0
        protected override void DrawPropertyLayout(GUIContent label)
        {
            Node     node = Property.Tree.WeakTargets[0] as Node;
            NodePort port = node.GetInputPort(Property.Name);

            if (!NodeEditor.inNodeEditor)
            {
                if (Attribute.backingValue == xNode.Node.ShowBackingValue.Always || Attribute.backingValue == xNode.Node.ShowBackingValue.Unconnected && !port.IsConnected)
                {
                    CallNextDrawer(label);
                }
                return;
            }

            if (Property.Tree.WeakTargets.Count > 1)
            {
                SirenixEditorGUI.WarningMessageBox("Cannot draw ports with multiple nodes selected");
                return;
            }

            if (port != null)
            {
                var portPropoerty = Property.Tree.GetUnityPropertyForPath(Property.UnityPropertyPath);
                if (portPropoerty == null)
                {
                    SirenixEditorGUI.ErrorMessageBox("Port property missing at: " + Property.UnityPropertyPath);
                    return;
                }
                else
                {
                    var labelWidth = Property.GetAttribute <LabelWidthAttribute>();
                    if (labelWidth != null)
                    {
                        GUIHelper.PushLabelWidth(labelWidth.Width);
                    }

                    NodeEditorGUILayout.PropertyField(portPropoerty, label == null ? GUIContent.none : label, true, GUILayout.MinWidth(30));

                    if (labelWidth != null)
                    {
                        GUIHelper.PopLabelWidth();
                    }
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary> Draws standard field editors for all public fields </summary>
        public virtual void OnBodyGUI()
        {
            string[] excludes = { "m_Script", "graph", "position", "ports" };
            portPositions = new Dictionary <XNode.NodePort, Vector2>();

            SerializedProperty iterator = serializedObject.GetIterator();
            bool enterChildren          = true;

            EditorGUIUtility.labelWidth = 84;
            while (iterator.NextVisible(enterChildren))
            {
                enterChildren = false;
                if (excludes.Contains(iterator.name))
                {
                    continue;
                }
                NodeEditorGUILayout.PropertyField(iterator, true);
            }
        }
Ejemplo n.º 11
0
        /// <summary> Like OnBodyGUI(), but only draws fields whose name is in selected[], ignoring other fields </summary>
        public void OnBodyGUISelected(string[] selected)
        {
            serializedObject.Update();
            portPositions = new Dictionary <XNode.NodePort, Vector2>();

            SerializedProperty iterator = serializedObject.GetIterator();
            bool enterChildren          = true;

            EditorGUIUtility.labelWidth = 84;
            while (iterator.NextVisible(enterChildren))
            {
                if (!selected.Contains(iterator.name))
                {
                    continue;
                }
                NodeEditorGUILayout.PropertyField(iterator, true);
            }
            serializedObject.ApplyModifiedProperties();
        }
Ejemplo n.º 12
0
        /// <summary> Draw a connection as we are dragging it </summary>
        public void DrawDraggedConnection()
        {
            if (IsDraggingPort)
            {
                Color col = NodeEditorPreferences.GetTypeColor(draggedOutput.ValueType);

                Rect fromRect;
                if (!_portConnectionPoints.TryGetValue(draggedOutput, out fromRect))
                {
                    return;
                }
                Vector2 from = fromRect.center;
                col.a = draggedOutputTarget != null ? 1.0f : 0.6f;
                Vector2 to = Vector2.zero;
                for (int i = 0; i < draggedOutputReroutes.Count; i++)
                {
                    to = draggedOutputReroutes[i];
                    DrawConnection(from, to, col);
                    from = to;
                }
                to = draggedOutputTarget != null ? portConnectionPoints[draggedOutputTarget].center : WindowToGridPosition(Event.current.mousePosition);
                DrawConnection(from, to, col);

                Color bgcol = Color.black;
                Color frcol = col;
                bgcol.a = 0.6f;
                frcol.a = 0.6f;

                // Loop through reroute points again and draw the points
                for (int i = 0; i < draggedOutputReroutes.Count; i++)
                {
                    // Draw reroute point at position
                    Rect rect = new Rect(draggedOutputReroutes[i], new Vector2(16, 16));
                    rect.position = new Vector2(rect.position.x - 8, rect.position.y - 8);
                    rect          = GridToWindowRect(rect);

                    NodeEditorGUILayout.DrawPortHandle(rect, bgcol, frcol);
                }
            }
        }
Ejemplo n.º 13
0
        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;

            XNode.Node      node  = serializedObject.targetObject as XNode.Node;
            ReorderableList list  = new ReorderableList(dynamicPorts, 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(fieldName + " " + index);
                if (hasArrayData)
                {
                    if (arrayData.arraySize <= index)
                    {
                        EditorGUI.LabelField(rect, "Array[" + index + "] data out of range");
                        return;
                    }
                    SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
                    EditorGUI.PropertyField(rect, itemData, true);
                }
                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));
                    NodeEditorGUILayout.PortField(pos, port);
                }
            };
            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);
                }
            };
            list.drawHeaderCallback =
                (Rect rect) => {
                EditorGUI.LabelField(rect, label);
            };
            list.onSelectCallback =
                (ReorderableList rl) => {
                reorderableListIndex = rl.index;
            };
            list.onReorderCallback =
                (ReorderableList rl) => {
                // Move up
                if (rl.index > reorderableListIndex)
                {
                    for (int i = reorderableListIndex; i < rl.index; ++i)
                    {
                        XNode.NodePort port     = node.GetPort(fieldName + " " + i);
                        XNode.NodePort nextPort = node.GetPort(fieldName + " " + (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(fieldName + " " + i);
                        XNode.NodePort nextPort = node.GetPort(fieldName + " " + (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)
                {
                    arrayData.MoveArrayElement(reorderableListIndex, rl.index);
                }

                // Apply changes
                serializedObject.ApplyModifiedProperties();
                serializedObject.Update();
                NodeEditorWindow.current.Repaint();
                EditorApplication.delayCall += NodeEditorWindow.current.Repaint;
            };
            list.onAddCallback =
                (ReorderableList rl) => {
                // Add dynamic port postfixed with an index number
                string newName = fieldName + " 0";
                int    i       = 0;
                while (node.HasPort(newName))
                {
                    newName = fieldName + " " + (++i);
                }

                if (io == XNode.NodePort.IO.Output)
                {
                    node.AddDynamicOutput(type, connectionType, XNode.Node.TypeConstraint.None, newName);
                }
                else
                {
                    node.AddDynamicInput(type, connectionType, typeConstraint, newName);
                }
                serializedObject.Update();
                EditorUtility.SetDirty(node);
                if (hasArrayData)
                {
                    arrayData.InsertArrayElementAtIndex(arrayData.arraySize);
                }
                serializedObject.ApplyModifiedProperties();
            };
            list.onRemoveCallback =
                (ReorderableList rl) => {
                var indexedPorts = node.DynamicPorts.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 });
                }).Where(x => x.port != null);
                dynamicPorts = indexedPorts.OrderBy(x => x.index).Select(x => x.port).ToList();

                int index = rl.index;

                if (dynamicPorts[index] == null)
                {
                    Debug.LogWarning("No port found at index " + index + " - Skipped");
                }
                else if (dynamicPorts.Count <= index)
                {
                    Debug.LogWarning("DynamicPorts[" + index + "] out of range. Length was " + dynamicPorts.Count + " - Skipped");
                }
                else
                {
                    // Clear the removed ports connections
                    dynamicPorts[index].ClearConnections();
                    // Move following connections one step up to replace the missing connection
                    for (int k = index + 1; k < dynamicPorts.Count(); k++)
                    {
                        for (int j = 0; j < dynamicPorts[k].ConnectionCount; j++)
                        {
                            XNode.NodePort other = dynamicPorts[k].GetConnection(j);
                            dynamicPorts[k].Disconnect(other);
                            dynamicPorts[k - 1].Connect(other);
                        }
                    }
                    // Remove the last dynamic port, to avoid messing up the indexing
                    node.RemoveDynamicPort(dynamicPorts[dynamicPorts.Count() - 1].fieldName);
                    serializedObject.Update();
                    EditorUtility.SetDirty(node);
                }

                if (hasArrayData)
                {
                    if (arrayData.arraySize <= index)
                    {
                        Debug.LogWarning("Attempted to remove array index " + index + " where only " + arrayData.arraySize + " exist - Skipped");
                        Debug.Log(rl.list[0]);
                        return;
                    }
                    arrayData.DeleteArrayElementAtIndex(index);
                    // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues
                    if (dynamicPorts.Count <= arrayData.arraySize)
                    {
                        while (dynamicPorts.Count <= arrayData.arraySize)
                        {
                            arrayData.DeleteArrayElementAtIndex(arrayData.arraySize - 1);
                        }
                        UnityEngine.Debug.LogWarning("Array size exceeded dynamic ports size. Excess items removed.");
                    }
                    serializedObject.ApplyModifiedProperties();
                    serializedObject.Update();
                }
            };

            if (hasArrayData)
            {
                int dynamicPortCount = dynamicPorts.Count;
                while (dynamicPortCount < arrayData.arraySize)
                {
                    // Add dynamic 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.AddDynamicOutput(type, connectionType, typeConstraint, newName);
                    }
                    else
                    {
                        node.AddDynamicInput(type, connectionType, typeConstraint, newName);
                    }
                    EditorUtility.SetDirty(node);
                    dynamicPortCount++;
                }
                while (arrayData.arraySize < dynamicPortCount)
                {
                    arrayData.InsertArrayElementAtIndex(arrayData.arraySize);
                }
                serializedObject.ApplyModifiedProperties();
                serializedObject.Update();
            }
            if (onCreation != null)
            {
                onCreation(list);
            }
            return(list);
        }
        /// <summary> Draw an editable list of instance ports. Port names are named as "[fieldName] [index]" </summary>
        /// <param name="fieldName">Supply a list for editable values</param>
        /// <param name="type">Value type of added instance ports</param>
        /// <param name="serializedObject">The serializedObject of the node</param>
        /// <param name="connectionType">Connection type of added instance ports</param>
        public static void InstancePortList(string fieldName, Type type, SerializedObject serializedObject, 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;

            List <XNode.NodePort> instancePorts = node.InstancePorts.Where(x => x.fieldName.StartsWith(fieldName)).OrderBy(x => x.fieldName).ToList();

            for (int i = 0; i < instancePorts.Count(); i++)
            {
                GUILayout.BeginHorizontal();
                if (GUILayout.Button("-", GUILayout.Width(30)))
                {
                    // 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--;
                    }
                    i--;
                }
                else
                {
                    if (hasArrayData)
                    {
                        if (i < arraySize)
                        {
                            SerializedProperty itemData = arrayData.GetArrayElementAtIndex(i);
                            if (itemData != null)
                            {
                                EditorGUILayout.PropertyField(itemData, new GUIContent(ObjectNames.NicifyVariableName(fieldName) + " " + i));
                            }
                            else
                            {
                                EditorGUILayout.LabelField("[Missing array data]");
                            }
                        }
                        else
                        {
                            EditorGUILayout.LabelField("[Out of bounds]");
                        }
                    }
                    else
                    {
                        EditorGUILayout.LabelField(instancePorts[i].fieldName);
                    }
                    NodeEditorGUILayout.PortField(new GUIContent(), node.GetPort(instancePorts[i].fieldName), GUILayout.Width(-4));
                }
                GUILayout.EndHorizontal();
            }
            GUILayout.BeginHorizontal();
            EditorGUILayout.Space();
            if (GUILayout.Button("+", GUILayout.Width(30)))
            {
                string newName = fieldName + " 0";
                int    i       = 0;
                while (node.HasPort(newName))
                {
                    newName = fieldName + " " + (++i);
                }

                instancePorts.Add(node.AddInstanceOutput(type, connectionType, newName));
                serializedObject.Update();
                EditorUtility.SetDirty(node);
                if (hasArrayData)
                {
                    arrayData.InsertArrayElementAtIndex(arraySize);
                }
            }
            GUILayout.EndHorizontal();
        }
Ejemplo n.º 15
0
        /// <summary> Draw an editable list of instance ports. Port names are named as "[fieldName] [index]" </summary>
        /// <param name="fieldName">Supply a list for editable values</param>
        /// <param name="type">Value type of added instance ports</param>
        /// <param name="serializedObject">The serializedObject of the node</param>
        /// <param name="connectionType">Connection type of added instance ports</param>
        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 <string> isMatchingInstancePort =
                x => {
                string[] split = x.Split(' ');
                if (split != null && split.Length == 2)
                {
                    return(split[0] == fieldName);
                }
                else
                {
                    return(false);
                }
            };
            List <XNode.NodePort> instancePorts = node.InstancePorts.Where(x => isMatchingInstancePort(x.fieldName)).OrderBy(x => x.fieldName).ToList();

            for (int i = 0; i < instancePorts.Count(); i++)
            {
                GUILayout.BeginHorizontal();
                // 'Remove' button
                if (GUILayout.Button("-", GUILayout.Width(20)))
                {
                    // 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(instancePorts[i].fieldName);
                    }

                    GUILayout.EndHorizontal();
                    NodeEditorGUILayout.AddPortField(node.GetPort(instancePorts[i].fieldName));
                }
                // GUILayout.EndHorizontal();
            }
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            // 'Add' button
            if (GUILayout.Button("+", GUILayout.Width(20)))
            {
                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();
        }
Ejemplo n.º 16
0
 protected virtual void PropertyField(SerializedProperty property, bool includeChildren = true, params GUILayoutOption[] options)
 {
     NodeEditorGUILayout.PropertyField(property, includeChildren, options);
 }
Ejemplo n.º 17
0
        private static ReorderableList CreateReorderableList(List <XNode.NodePort> instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, string label, XNode.ConnectionType connectionType = XNode.ConnectionType.Multiple)
        {
            bool            hasArrayData = arrayData != null && arrayData.isArray;
            int             arraySize    = hasArrayData ? arrayData.arraySize : 0;
            var             node         = serializedObject.targetObject as XNode.INode;
            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)
                {
                    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);
                }
                Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0));
                NodeEditorGUILayout.PortField(pos, port);
            };
            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);
                }
            };
            list.drawHeaderCallback =
                (Rect rect) => {
                EditorGUI.LabelField(rect, label);
            };
            list.onSelectCallback =
                (ReorderableList rl) => {
                reorderableListIndex = rl.index;
            };
            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)
                {
                    arrayData.MoveArrayElement(reorderableListIndex, rl.index);
                }

                // 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 as UnityEngine.Object);
                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 as UnityEngine.Object);
                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 as UnityEngine.Object);
                    instancePortCount++;
                }
                while (arraySize < instancePortCount)
                {
                    arrayData.InsertArrayElementAtIndex(arraySize);
                    arraySize++;
                }
                serializedObject.ApplyModifiedProperties();
                serializedObject.Update();
            }
            if (onCreateReorderableList != null)
            {
                onCreateReorderableList(list);
            }
            return(list);
        }
Ejemplo n.º 18
0
        /// <summary> Draws all connections </summary>
        public void DrawConnections()
        {
            Vector2 mousePos = Event.current.mousePosition;
            List <RerouteReference> selection = preBoxSelectionReroute != null ? new List <RerouteReference>(preBoxSelectionReroute) : new List <RerouteReference>();

            hoveredReroute = new RerouteReference();

            foreach (XNode.Node node in graph.nodes)
            {
                //If a null node is found, return. This can happen if the nodes associated script is deleted. It is currently not possible in Unity to delete a null asset.
                if (node == null)
                {
                    continue;
                }

                // Draw full connections and output > reroute
                foreach (XNode.NodePort output in node.Outputs)
                {
                    //Needs cleanup. Null checks are ugly
                    if (!portConnectionPoints.ContainsKey(output))
                    {
                        continue;
                    }

                    Color connectionColor = graphEditor.GetTypeColor(output.ValueType);

                    for (int k = 0; k < output.ConnectionCount; k++)
                    {
                        XNode.NodePort input = output.GetConnection(k);

                        // Error handling
                        if (input == null)
                        {
                            continue;                //If a script has been updated and the port doesn't exist, it is removed and null is returned. If this happens, return.
                        }
                        if (!input.IsConnectedTo(output))
                        {
                            input.Connect(output);
                        }
                        if (!_portConnectionPoints.ContainsKey(input))
                        {
                            continue;
                        }

                        Vector2        from          = _portConnectionPoints[output].center;
                        Vector2        to            = Vector2.zero;
                        List <Vector2> reroutePoints = output.GetReroutePoints(k);
                        // Loop through reroute points and draw the path
                        for (int i = 0; i < reroutePoints.Count; i++)
                        {
                            to = reroutePoints[i];
                            DrawConnection(from, to, connectionColor);
                            from = to;
                        }
                        to = _portConnectionPoints[input].center;
                        DrawConnection(from, to, connectionColor);

                        // Loop through reroute points again and draw the points
                        for (int i = 0; i < reroutePoints.Count; i++)
                        {
                            // Draw reroute point at position
                            Rect rect = new Rect(reroutePoints[i], new Vector2(16, 16));
                            rect.position = new Vector2(rect.position.x - 8, rect.position.y - 8);
                            rect          = GridToWindowRect(rect);
                            Color bgcol = new Color32(90, 97, 105, 255);;
                            if (selectedReroutes.Contains(new RerouteReference(output, k, i)))
                            {
                                bgcol = Color.yellow;
                            }
                            NodeEditorGUILayout.DrawPortHandle(rect, bgcol, connectionColor);

                            if (rect.Overlaps(selectionBox))
                            {
                                selection.Add(new RerouteReference(output, k, i));
                            }
                            if (rect.Contains(mousePos))
                            {
                                hoveredReroute = new RerouteReference(output, k, i);
                            }
                        }
                    }
                }
            }
            if (Event.current.type != EventType.Layout && currentActivity == NodeActivity.DragGrid)
            {
                selectedReroutes = selection;
            }
        }