Exemple #1
0
 /// <summary> Make a simple port field. </summary>
 public static void PortField(XNode.NodePort port, params GUILayoutOption[] options)
 {
     PortField(null, port, options);
 }
Exemple #2
0
 public override object GetValue(XNode.NodePort port)
 {
     return(HolderInput);
 }
Exemple #3
0
 public static bool IsInstancePortListPort(XNode.NodePort port)
 {
     return(IsDynamicPortListPort(port));
 }
Exemple #4
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 && arrayData.propertyType != SerializedPropertyType.String)
                {
                    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) => {
                bool hasRect    = false;
                bool hasNewRect = false;
                Rect rect       = Rect.zero;
                Rect newRect    = Rect.zero;
                // 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
                        hasRect    = NodeEditorWindow.current.portConnectionPoints.TryGetValue(port, out rect);
                        hasNewRect = NodeEditorWindow.current.portConnectionPoints.TryGetValue(nextPort, out newRect);
                        NodeEditorWindow.current.portConnectionPoints[port]     = hasNewRect ? newRect : rect;
                        NodeEditorWindow.current.portConnectionPoints[nextPort] = hasRect ? rect : newRect;
                    }
                }
                // 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
                        hasRect    = NodeEditorWindow.current.portConnectionPoints.TryGetValue(port, out rect);
                        hasNewRect = NodeEditorWindow.current.portConnectionPoints.TryGetValue(nextPort, out newRect);
                        NodeEditorWindow.current.portConnectionPoints[port]     = hasNewRect ? newRect : rect;
                        NodeEditorWindow.current.portConnectionPoints[nextPort] = hasRect ? rect : newRect;
                    }
                }
                // 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 && arrayData.propertyType != SerializedPropertyType.String)
                {
                    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);
        }
Exemple #5
0
 public RerouteReference(XNode.NodePort port, int connectionIndex, int pointIndex)
 {
     this.port            = port;
     this.connectionIndex = connectionIndex;
     this.pointIndex      = pointIndex;
 }
        /// <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)
        {
            if (property == null)
            {
                throw new NullReferenceException();
            }

            // If property is not a port, display a regular property field
            if (port == null)
            {
                EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
            }
            else
            {
                Rect rect = new Rect();

                float          spacePadding = 0;
                SpaceAttribute spaceAttribute;
                if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out spaceAttribute))
                {
                    spacePadding = spaceAttribute.height;
                }

                // If property is an input, display a regular property field and put a port handle on the left side
                if (port.direction == XNode.NodePort.IO.Input)
                {
                    // Get data from [Input] attribute
                    XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
                    XNode.Node.InputAttribute   inputAttribute;
                    bool dynamicPortList = false;
                    if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute))
                    {
                        dynamicPortList = inputAttribute.dynamicPortList;
                        showBacking     = inputAttribute.backingValue;
                    }

                    //Call GUILayout.Space if Space attribute is set and we are NOT drawing a PropertyField
                    bool useLayoutSpace = dynamicPortList ||
                                          showBacking == XNode.Node.ShowBackingValue.Never ||
                                          (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected);
                    if (spacePadding > 0 && useLayoutSpace)
                    {
                        GUILayout.Space(spacePadding);
                        spacePadding = 0;
                    }

                    if (dynamicPortList)
                    {
                        Type type = GetType(property);
                        XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
                        DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
                        return;
                    }
                    switch (showBacking)
                    {
                    case XNode.Node.ShowBackingValue.Unconnected:
                        // Display a label if port is connected
                        if (port.IsConnected)
                        {
                            EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case XNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName));
                        break;

                    case XNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect          = GUILayoutUtility.GetLastRect();
                    rect.position = rect.position - new Vector2(16, -spacePadding);
                    // If property is an output, display a text label and put a port handle on the right side
                }
                else if (port.direction == XNode.NodePort.IO.Output)
                {
                    // Get data from [Output] attribute
                    XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
                    XNode.Node.OutputAttribute  outputAttribute;
                    bool dynamicPortList = false;
                    if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute))
                    {
                        dynamicPortList = outputAttribute.dynamicPortList;
                        showBacking     = outputAttribute.backingValue;
                    }

                    //Call GUILayout.Space if Space attribute is set and we are NOT drawing a PropertyField
                    bool useLayoutSpace = dynamicPortList ||
                                          showBacking == XNode.Node.ShowBackingValue.Never ||
                                          (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected);
                    if (spacePadding > 0 && useLayoutSpace)
                    {
                        GUILayout.Space(spacePadding);
                        spacePadding = 0;
                    }

                    if (dynamicPortList)
                    {
                        Type type = GetType(property);
                        XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
                        DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
                        return;
                    }
                    switch (showBacking)
                    {
                    case XNode.Node.ShowBackingValue.Unconnected:
                        // Display a label if port is connected
                        if (port.IsConnected)
                        {
                            EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case XNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
                        break;

                    case XNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect          = GUILayoutUtility.GetLastRect();
                    rect.position = rect.position + new Vector2(rect.width, spacePadding);
                }

                rect.size = new Vector2(16, 16);

                NodeEditor editor          = NodeEditor.GetEditor(port.node, NodeEditorWindow.current);
                Color      backgroundColor = editor.GetTint();
                Color      col             = NodeEditorWindow.current.graphEditor.GetPortColor(port);
                DrawPortHandle(rect, backgroundColor, col);

                // Register the handle position
                Vector2 portPos = rect.center;
                NodeEditor.portPositions[port] = portPos;
            }
        }
Exemple #7
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.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--;
                        // 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--;
                }
                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);
                    }
                    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);
                }

                node.AddInstanceOutput(type, connectionType, newName);
                serializedObject.Update();
                EditorUtility.SetDirty(node);
                if (hasArrayData)
                {
                    arrayData.InsertArrayElementAtIndex(arraySize);
                }
                serializedObject.ApplyModifiedProperties();
            }
            GUILayout.EndHorizontal();
        }
Exemple #8
0
 /// <summary> Returned color is used to color ports </summary>
 public virtual Color GetPortColor(XNode.NodePort port)
 {
     return(GetTypeColor(port.ValueType));
 }
 /// <summary> Draws an input and an output port on the same line </summary>
 public static void PortPair(GUIContent inputLabel, XNode.NodePort input, GUIContent outputLabel, XNode.NodePort output)
 {
     GUILayout.BeginHorizontal();
     NodeEditorGUILayout.PortField(inputLabel, input, GUILayout.MinWidth(0));
     NodeEditorGUILayout.PortField(outputLabel, output, GUILayout.MinWidth(0));
     GUILayout.EndHorizontal();
 }
Exemple #10
0
        public static void PropertyAndPortPair(SerializedObject so, XNode.NodePort input, XNode.NodePort output)
        {
            XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
            XNode.Node.InputAttribute   inputAttribute;
            bool dynamicPortList = false;

            if (NodeEditorUtilities.GetCachedAttrib(input.node.GetType(), input.fieldName, out inputAttribute))
            {
                dynamicPortList = inputAttribute.dynamicPortList;
                showBacking     = inputAttribute.backingValue;
            }

            bool usePropertyAttributes = dynamicPortList ||
                                         showBacking == XNode.Node.ShowBackingValue.Never ||
                                         (showBacking == XNode.Node.ShowBackingValue.Unconnected && input.IsConnected);


            if (!usePropertyAttributes)
            {
                PropertyField(so.FindProperty(input.fieldName));
                PortField(output);
            }
            else
            {
                PortPair(input, output);
            }
        }
Exemple #11
0
 public NodePortReference(XNode.NodePort nodePort)
 {
     _node = nodePort.node as UnityEngine.Object;
     _name = nodePort.fieldName;
 }
Exemple #12
0
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

            switch (e.type)
            {
            case EventType.MouseMove:
                break;

            case EventType.ScrollWheel:
                if (e.delta.y > 0)
                {
                    zoom += 0.1f * zoom;
                }
                else
                {
                    zoom -= 0.1f * zoom;
                }
                break;

            case EventType.MouseDrag:
                if (e.button == 0)
                {
                    if (IsDraggingPort)
                    {
                        if (IsHoveringPort && hoveredPort.IsInput)
                        {
                            if (!draggedOutput.IsConnectedTo(hoveredPort))
                            {
                                draggedOutputTarget = hoveredPort;
                            }
                        }
                        else
                        {
                            draggedOutputTarget = null;
                        }
                        Repaint();
                    }
                    else if (IsDraggingNode)
                    {
                        draggedNode.position = WindowToGridPosition(e.mousePosition) + dragOffset;
                        if (NodeEditorPreferences.gridSnap)
                        {
                            draggedNode.position.x = (Mathf.Round((draggedNode.position.x + 8) / 16) * 16) - 8;
                            draggedNode.position.y = (Mathf.Round((draggedNode.position.y + 8) / 16) * 16) - 8;
                        }
                        Repaint();
                    }
                }
                else if (e.button == 1)
                {
                    panOffset += e.delta * zoom;
                    isPanning  = true;
                }
                break;

            case EventType.MouseDown:
                Repaint();
                if (e.button == 0)
                {
                    SelectNode(hoveredNode);
                    if (IsHoveringPort)
                    {
                        if (hoveredPort.IsOutput)
                        {
                            draggedOutput = hoveredPort;
                        }
                        else
                        {
                            hoveredPort.VerifyConnections();
                            if (hoveredPort.IsConnected)
                            {
                                XNode.Node     node   = hoveredPort.node;
                                XNode.NodePort output = hoveredPort.Connection;
                                hoveredPort.Disconnect(output);
                                draggedOutput       = output;
                                draggedOutputTarget = hoveredPort;
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                            }
                        }
                    }
                    else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                    {
                        draggedNode = hoveredNode;
                        dragOffset  = hoveredNode.position - WindowToGridPosition(e.mousePosition);
                    }
                }
                break;

            case EventType.MouseUp:
                if (e.button == 0)
                {
                    //Port drag release
                    if (IsDraggingPort)
                    {
                        //If connection is valid, save it
                        if (draggedOutputTarget != null)
                        {
                            XNode.Node node = draggedOutputTarget.node;
                            if (graph.nodes.Count != 0)
                            {
                                draggedOutput.Connect(draggedOutputTarget);
                            }
                            if (NodeEditor.onUpdateNode != null)
                            {
                                NodeEditor.onUpdateNode(node);
                            }
                            EditorUtility.SetDirty(graph);
                        }
                        //Release dragged connection
                        draggedOutput       = null;
                        draggedOutputTarget = null;
                        EditorUtility.SetDirty(graph);
                        Repaint();
                        AssetDatabase.SaveAssets();
                    }
                    else if (IsDraggingNode)
                    {
                        draggedNode = null;
                        AssetDatabase.SaveAssets();
                    }
                    else if (GUIUtility.hotControl != 0)
                    {
                        AssetDatabase.SaveAssets();
                    }
                }
                else if (e.button == 1)
                {
                    if (!isPanning)
                    {
                        if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                        {
                            ShowNodeContextMenu(hoveredNode);
                        }
                        else if (!IsHoveringNode)
                        {
                            ShowGraphContextMenu();
                        }
                    }
                    isPanning = false;
                }
                break;
            }
        }
Exemple #13
0
 public static bool IsInstancePortListPort(XNode.NodePort port) => IsDynamicPortListPort(port);
Exemple #14
0
 /// <summary> Returned float is used for noodle thickness </summary>
 /// <param name="output"> The output this noodle comes from. Never null. </param>
 /// <param name="input"> The output this noodle comes from. Can be null if we are dragging the noodle. </param>
 public virtual float GetNoodleThickness(XNode.NodePort output, XNode.NodePort input)
 {
     return(NodeEditorPreferences.GetSettings().noodleThickness);
 }
        private static ReorderableList CreateReorderableList(List <XNode.NodePort> instancePorts, SerializedProperty arrayData, Type type, SerializedObject serializedObject, XNode.NodePort.IO io, string label, XNode.Node.ConnectionType connectionType = XNode.Node.ConnectionType.Multiple)
        {
            bool hasArrayData = arrayData != null && arrayData.isArray;
            int  arraySize    = hasArrayData ? arrayData.arraySize : 0;

            XNode.Node      node = serializedObject.targetObject as XNode.Node;
            ReorderableList list = new ReorderableList(instancePorts, null, true, true, true, true);

            list.drawElementCallback =
                (Rect rect, int index, bool isActive, bool isFocused) => {
                XNode.NodePort port = node.GetPort(arrayData.name + " " + index);
                if (hasArrayData)
                {
                    SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
                    EditorGUI.PropertyField(rect, itemData);
                }
                else
                {
                    EditorGUI.LabelField(rect, port.fieldName);
                }
                Vector2 pos = rect.position + (port.IsOutput?new Vector2(rect.width + 6, 0) : new Vector2(-36, 0));
                NodeEditorGUILayout.PortField(pos, port);
            };
            list.elementHeightCallback =
                (int index) => {
                if (hasArrayData)
                {
                    SerializedProperty itemData = arrayData.GetArrayElementAtIndex(index);
                    return(EditorGUI.GetPropertyHeight(itemData));
                }
                else
                {
                    return(EditorGUIUtility.singleLineHeight);
                }
            };
            list.drawHeaderCallback =
                (Rect rect) => {
                EditorGUI.LabelField(rect, label);
            };
            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);
                if (hasArrayData)
                {
                    arrayData.InsertArrayElementAtIndex(arraySize);
                }
                serializedObject.ApplyModifiedProperties();
            };
            list.onRemoveCallback =
                (ReorderableList rl) => {
                int index = rl.index;
                // Clear the removed ports connections
                instancePorts[index].ClearConnections();
                // Move following connections one step up to replace the missing connection
                for (int k = index + 1; k < instancePorts.Count(); k++)
                {
                    for (int j = 0; j < instancePorts[k].ConnectionCount; j++)
                    {
                        XNode.NodePort other = instancePorts[k].GetConnection(j);
                        instancePorts[k].Disconnect(other);
                        instancePorts[k - 1].Connect(other);
                    }
                }
                // Remove the last instance port, to avoid messing up the indexing
                node.RemoveInstancePort(instancePorts[instancePorts.Count() - 1].fieldName);
                serializedObject.Update();
                EditorUtility.SetDirty(node);
                if (hasArrayData)
                {
                    arrayData.DeleteArrayElementAtIndex(index);
                    arraySize--;
                    // Error handling. If the following happens too often, file a bug report at https://github.com/Siccity/xNode/issues
                    if (instancePorts.Count <= arraySize)
                    {
                        while (instancePorts.Count <= arraySize)
                        {
                            arrayData.DeleteArrayElementAtIndex(--arraySize);
                        }
                        Debug.LogWarning("Array size exceeded instance ports size. Excess items removed.");
                    }
                    serializedObject.ApplyModifiedProperties();
                    serializedObject.Update();
                }
            };

            if (hasArrayData)
            {
                int instancePortCount = instancePorts.Count;
                while (instancePortCount < arraySize)
                {
                    // Add instance port postfixed with an index number
                    string newName = arrayData.name + " 0";
                    int    i       = 0;
                    while (node.HasPort(newName))
                    {
                        newName = arrayData.name + " " + (++i);
                    }
                    if (io == XNode.NodePort.IO.Output)
                    {
                        node.AddInstanceOutput(type, connectionType, newName);
                    }
                    else
                    {
                        node.AddInstanceInput(type, connectionType, newName);
                    }
                    EditorUtility.SetDirty(node);
                    instancePortCount++;
                }
                while (arraySize < instancePortCount)
                {
                    arrayData.InsertArrayElementAtIndex(arraySize);
                    arraySize++;
                }
                serializedObject.ApplyModifiedProperties();
                serializedObject.Update();
            }
            if (onCreateReorderableList != null)
            {
                onCreateReorderableList(list);
            }
            return(list);
        }
Exemple #16
0
 public virtual NoodleStroke GetNoodleStroke(XNode.NodePort output, XNode.NodePort input)
 {
     return(NodeEditorPreferences.GetSettings().noodleStroke);
 }
        /// <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)
        {
            if (property == null)
            {
                throw new NullReferenceException();
            }

            // If property is not a port, display a regular property field
            if (port == null)
            {
                EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
            }
            else
            {
                Rect rect = new Rect();

                // If property is an input, display a regular property field and put a port handle on the left side
                if (port.direction == XNode.NodePort.IO.Input)
                {
                    // Get data from [Input] attribute
                    XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
                    XNode.Node.InputAttribute   inputAttribute;
                    bool instancePortList = false;
                    if (NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out inputAttribute))
                    {
                        instancePortList = inputAttribute.instancePortList;
                        showBacking      = inputAttribute.backingValue;
                    }

                    if (instancePortList)
                    {
                        Type type = GetType(property);
                        XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
                        InstancePortList(property.name, type, property.serializedObject, port.direction, connectionType);
                        return;
                    }
                    switch (showBacking)
                    {
                    case XNode.Node.ShowBackingValue.Unconnected:
                        // Display a label if port is connected
                        if (port.IsConnected)
                        {
                            EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case XNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName));
                        break;

                    case XNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect          = GUILayoutUtility.GetLastRect();
                    rect.position = rect.position - new Vector2(18, 0);
                    // If property is an output, display a text label and put a port handle on the right side
                }
                else if (port.direction == XNode.NodePort.IO.Output)
                {
                    // Get data from [Output] attribute
                    XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
                    XNode.Node.OutputAttribute  outputAttribute;
                    bool instancePortList = false;
                    if (NodeEditorUtilities.GetAttrib(port.node.GetType(), property.name, out outputAttribute))
                    {
                        instancePortList = outputAttribute.instancePortList;
                        showBacking      = outputAttribute.backingValue;
                    }

                    if (instancePortList)
                    {
                        Type type = GetType(property);
                        XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
                        InstancePortList(property.name, type, property.serializedObject, port.direction, connectionType);
                        return;
                    }
                    switch (showBacking)
                    {
                    case XNode.Node.ShowBackingValue.Unconnected:
                        // Display a label if port is connected
                        if (port.IsConnected)
                        {
                            EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case XNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
                        break;

                    case XNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect          = GUILayoutUtility.GetLastRect();
                    rect.position = rect.position + new Vector2(rect.width, 0);
                }

                rect.size = new Vector2(16, 16);

                Color backgroundColor = new Color32(90, 97, 105, 255);
                Color tint;
                if (NodeEditorWindow.nodeTint.TryGetValue(port.node.GetType(), out tint))
                {
                    backgroundColor *= tint;
                }
                Color col = NodeEditorWindow.current.graphEditor.GetTypeColor(port.ValueType);
                DrawPortHandle(rect, backgroundColor, col);

                // Register the handle position
                Vector2 portPos = rect.center;
                if (NodeEditor.portPositions.ContainsKey(port))
                {
                    NodeEditor.portPositions[port] = portPos;
                }
                else
                {
                    NodeEditor.portPositions.Add(port, portPos);
                }
            }
        }
Exemple #18
0
 /// <summary> The returned color is used to color the background of the door.
 /// Usually used for outer edge effect </summary>
 public virtual Color GetPortBackgroundColor(XNode.NodePort port)
 {
     return(Color.gray);
 }
Exemple #19
0
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

            switch (e.type)
            {
            case EventType.MouseMove:
                break;

            case EventType.ScrollWheel:
                if (e.delta.y > 0)
                {
                    zoom += 0.1f * zoom;
                }
                else
                {
                    zoom -= 0.1f * zoom;
                }
                break;

            case EventType.MouseDrag:
                if (e.button == 0)
                {
                    if (IsDraggingPort)
                    {
                        if (IsHoveringPort && hoveredPort.IsInput)
                        {
                            if (!draggedOutput.IsConnectedTo(hoveredPort))
                            {
                                draggedOutputTarget = hoveredPort;
                            }
                        }
                        else
                        {
                            draggedOutputTarget = null;
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldHeader || currentActivity == NodeActivity.DragHeader)
                    {
                        for (int i = 0; i < Selection.objects.Length; i++)
                        {
                            if (Selection.objects[i] is XNode.Node)
                            {
                                XNode.Node node = Selection.objects[i] as XNode.Node;
                                node.position = WindowToGridPosition(e.mousePosition) + dragOffset[i];
                                if (NodeEditorPreferences.GridSnap)
                                {
                                    node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8;
                                    node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8;
                                }
                            }
                        }
                        currentActivity = NodeActivity.DragHeader;
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldGrid)
                    {
                        currentActivity = NodeActivity.DragGrid;
                        preBoxSelection = Selection.objects;
                        dragBoxStart    = WindowToGridPosition(e.mousePosition);
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.DragGrid)
                    {
                        foreach (XNode.Node node in graph.nodes)
                        {
                        }
                        Repaint();
                    }
                }
                else if (e.button == 1 || e.button == 2)
                {
                    Vector2 tempOffset = panOffset;
                    tempOffset += e.delta * zoom;
                    // Round value to increase crispyness of UI text
                    tempOffset.x = Mathf.Round(tempOffset.x);
                    tempOffset.y = Mathf.Round(tempOffset.y);
                    panOffset    = tempOffset;
                    isPanning    = true;
                }
                break;

            case EventType.MouseDown:
                Repaint();
                if (e.button == 0)
                {
                    if (IsHoveringPort)
                    {
                        if (hoveredPort.IsOutput)
                        {
                            draggedOutput = hoveredPort;
                        }
                        else
                        {
                            hoveredPort.VerifyConnections();
                            if (hoveredPort.IsConnected)
                            {
                                XNode.Node     node   = hoveredPort.node;
                                XNode.NodePort output = hoveredPort.Connection;
                                hoveredPort.Disconnect(output);
                                draggedOutput       = output;
                                draggedOutputTarget = hoveredPort;
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                            }
                        }
                    }
                    else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                    {
                        // If mousedown on node header, select or deselect
                        if (!Selection.Contains(hoveredNode))
                        {
                            SelectNode(hoveredNode, e.control || e.shift);
                        }
                        else if (e.control || e.shift)
                        {
                            DeselectNode(hoveredNode);
                        }
                        e.Use();
                        currentActivity = NodeActivity.HoldHeader;
                        dragOffset      = new Vector2[Selection.objects.Length];
                        for (int i = 0; i < dragOffset.Length; i++)
                        {
                            if (Selection.objects[i] is XNode.Node)
                            {
                                XNode.Node node = Selection.objects[i] as XNode.Node;
                                dragOffset[i] = node.position - WindowToGridPosition(e.mousePosition);
                            }
                        }
                    }
                    // If mousedown on grid background, deselect all
                    else if (!IsHoveringNode)
                    {
                        currentActivity = NodeActivity.HoldGrid;
                        if (!e.control && !e.shift)
                        {
                            Selection.activeObject = null;
                        }
                    }
                }
                break;

            case EventType.MouseUp:
                if (e.button == 0)
                {
                    //Port drag release
                    if (IsDraggingPort)
                    {
                        //If connection is valid, save it
                        if (draggedOutputTarget != null)
                        {
                            XNode.Node node = draggedOutputTarget.node;
                            if (graph.nodes.Count != 0)
                            {
                                draggedOutput.Connect(draggedOutputTarget);
                            }
                            if (NodeEditor.onUpdateNode != null)
                            {
                                NodeEditor.onUpdateNode(node);
                            }
                            EditorUtility.SetDirty(graph);
                        }
                        //Release dragged connection
                        draggedOutput       = null;
                        draggedOutputTarget = null;
                        EditorUtility.SetDirty(graph);
                        AssetDatabase.SaveAssets();
                    }
                    else if (currentActivity == NodeActivity.DragHeader)
                    {
                        AssetDatabase.SaveAssets();
                    }
                    else if (!IsHoveringNode)
                    {
                        // If click outside node, release field focus
                        if (!isPanning)
                        {
                            GUIUtility.hotControl      = 0;
                            GUIUtility.keyboardControl = 0;
                        }
                        AssetDatabase.SaveAssets();
                    }

                    // If click node header, select single node.
                    if (currentActivity == NodeActivity.HoldHeader && !(e.control || e.shift))
                    {
                        SelectNode(hoveredNode, false);
                    }

                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                else if (e.button == 1)
                {
                    if (!isPanning)
                    {
                        if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                        {
                            if (!Selection.Contains(hoveredNode))
                            {
                                SelectNode(hoveredNode, false);
                            }
                            ShowNodeContextMenu();
                        }
                        else if (!IsHoveringNode)
                        {
                            ShowGraphContextMenu();
                        }
                    }
                    isPanning = false;
                }
                break;

            case EventType.KeyDown:
                if (e.keyCode == KeyCode.Delete)
                {
                    RemoveSelectedNodes();
                }
                else if (e.keyCode == KeyCode.D && e.control)
                {
                    DublicateSelectedNodes();
                }
                Repaint();
                break;

            case EventType.Ignore:
                // If release mouse outside window
                if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid)
                {
                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                break;
            }
        }
Exemple #20
0
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

            switch (e.type)
            {
            case EventType.MouseMove:
                break;

            case EventType.ScrollWheel:
                if (e.delta.y > 0)
                {
                    zoom += 0.1f * zoom;
                }
                else
                {
                    zoom -= 0.1f * zoom;
                }
                break;

            case EventType.MouseDrag:
                if (e.button == 0)
                {
                    if (IsDraggingPort)
                    {
                        if (IsHoveringPort && hoveredPort.IsInput)
                        {
                            if (!draggedOutput.IsConnectedTo(hoveredPort))
                            {
                                draggedOutputTarget = hoveredPort;
                            }
                        }
                        else
                        {
                            draggedOutputTarget = null;
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldNode)
                    {
                        RecalculateDragOffsets(e);
                        currentActivity = NodeActivity.DragNode;
                        Repaint();
                    }
                    if (currentActivity == NodeActivity.DragNode)
                    {
                        // Holding ctrl inverts grid snap
                        bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap;
                        if (e.control)
                        {
                            gridSnap = !gridSnap;
                        }

                        Vector2 mousePos = WindowToGridPosition(e.mousePosition);
                        // Move selected nodes with offset
                        for (int i = 0; i < Selection.objects.Length; i++)
                        {
                            if (Selection.objects[i] is XNode.Node)
                            {
                                XNode.Node node    = Selection.objects[i] as XNode.Node;
                                Vector2    initial = node.position;
                                node.position = mousePos + dragOffset[i];
                                if (gridSnap)
                                {
                                    node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8;
                                    node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8;
                                }

                                // Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame.
                                Vector2 offset = node.position - initial;
                                if (offset.sqrMagnitude > 0)
                                {
                                    foreach (XNode.NodePort output in node.Outputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(output, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[output] = rect;
                                        }
                                    }

                                    foreach (XNode.NodePort input in node.Inputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(input, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[input] = rect;
                                        }
                                    }
                                }
                            }
                        }
                        // Move selected reroutes with offset
                        for (int i = 0; i < selectedReroutes.Count; i++)
                        {
                            Vector2 pos = mousePos + dragOffset[Selection.objects.Length + i];
                            pos.x -= 8;
                            pos.y -= 8;
                            if (gridSnap)
                            {
                                pos.x = (Mathf.Round((pos.x + 8) / 16) * 16);
                                pos.y = (Mathf.Round((pos.y + 8) / 16) * 16);
                            }
                            selectedReroutes[i].SetPoint(pos);
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldGrid)
                    {
                        currentActivity        = NodeActivity.DragGrid;
                        preBoxSelection        = Selection.objects;
                        preBoxSelectionReroute = selectedReroutes.ToArray();
                        dragBoxStart           = WindowToGridPosition(e.mousePosition);
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.DragGrid)
                    {
                        Vector2 boxStartPos = GridToWindowPosition(dragBoxStart);
                        Vector2 boxSize     = e.mousePosition - boxStartPos;
                        if (boxSize.x < 0)
                        {
                            boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x);
                        }
                        if (boxSize.y < 0)
                        {
                            boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y);
                        }
                        selectionBox = new Rect(boxStartPos, boxSize);
                        Repaint();
                    }
                }
                else if (e.button == 1 || e.button == 2)
                {
                    Vector2 tempOffset = panOffset;
                    tempOffset += e.delta * zoom;
                    // Round value to increase crispyness of UI text
                    tempOffset.x = Mathf.Round(tempOffset.x);
                    tempOffset.y = Mathf.Round(tempOffset.y);
                    panOffset    = tempOffset;
                    isPanning    = true;
                }
                break;

            case EventType.MouseDown:
                Repaint();
                if (e.button == 0)
                {
                    draggedOutputReroutes.Clear();

                    if (IsHoveringPort)
                    {
                        if (hoveredPort.IsOutput)
                        {
                            draggedOutput = hoveredPort;
                        }
                        else
                        {
                            hoveredPort.VerifyConnections();
                            if (hoveredPort.IsConnected)
                            {
                                XNode.Node     node   = hoveredPort.node;
                                XNode.NodePort output = hoveredPort.Connection;
                                int            outputConnectionIndex = output.GetConnectionIndex(hoveredPort);
                                draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex);
                                hoveredPort.Disconnect(output);
                                draggedOutput       = output;
                                draggedOutputTarget = hoveredPort;
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                            }
                        }
                    }
                    else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                    {
                        // If mousedown on node header, select or deselect
                        if (!Selection.Contains(hoveredNode))
                        {
                            SelectNode(hoveredNode, e.control || e.shift);
                            if (!e.control && !e.shift)
                            {
                                selectedReroutes.Clear();
                            }
                        }
                        else if (e.control || e.shift)
                        {
                            DeselectNode(hoveredNode);
                        }
                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    else if (IsHoveringReroute)
                    {
                        // If reroute isn't selected
                        if (!selectedReroutes.Contains(hoveredReroute))
                        {
                            // Add it
                            if (e.control || e.shift)
                            {
                                selectedReroutes.Add(hoveredReroute);
                            }
                            // Select it
                            else
                            {
                                selectedReroutes = new List <RerouteReference>()
                                {
                                    hoveredReroute
                                };
                                Selection.activeObject = null;
                            }
                        }
                        // Deselect
                        else if (e.control || e.shift)
                        {
                            selectedReroutes.Remove(hoveredReroute);
                        }
                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    // If mousedown on grid background, deselect all
                    else if (!IsHoveringNode)
                    {
                        currentActivity = NodeActivity.HoldGrid;
                        if (!e.control && !e.shift)
                        {
                            selectedReroutes.Clear();
                            Selection.activeObject = null;
                        }
                    }
                }
                break;

            case EventType.MouseUp:
                if (e.button == 0)
                {
                    //Port drag release
                    if (IsDraggingPort)
                    {
                        //If connection is valid, save it
                        if (draggedOutputTarget != null)
                        {
                            XNode.Node node = draggedOutputTarget.node;
                            if (graph.nodes.Count != 0)
                            {
                                draggedOutput.Connect(draggedOutputTarget);
                            }

                            // ConnectionIndex can be -1 if the connection is removed instantly after creation
                            int connectionIndex = draggedOutput.GetConnectionIndex(draggedOutputTarget);
                            if (connectionIndex != -1)
                            {
                                draggedOutput.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes);
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                                EditorUtility.SetDirty(graph);
                            }
                        }
                        //Release dragged connection
                        draggedOutput       = null;
                        draggedOutputTarget = null;
                        EditorUtility.SetDirty(graph);
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (currentActivity == NodeActivity.DragNode)
                    {
                        IEnumerable <XNode.Node> nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node);
                        foreach (XNode.Node node in nodes)
                        {
                            EditorUtility.SetDirty(node);
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (!IsHoveringNode)
                    {
                        // If click outside node, release field focus
                        if (!isPanning)
                        {
                            EditorGUI.FocusTextInControl(null);
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }

                    // If click node header, select it.
                    if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift))
                    {
                        selectedReroutes.Clear();
                        SelectNode(hoveredNode, false);
                    }

                    // If click reroute, select it.
                    if (IsHoveringReroute && !(e.control || e.shift))
                    {
                        selectedReroutes = new List <RerouteReference>()
                        {
                            hoveredReroute
                        };
                        Selection.activeObject = null;
                    }

                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                else if (e.button == 1 || e.button == 2)
                {
                    if (!isPanning)
                    {
                        if (IsDraggingPort)
                        {
                            draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition));
                        }
                        else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1)
                        {
                            selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint());
                            selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1);
                        }
                        else if (IsHoveringReroute)
                        {
                            ShowRerouteContextMenu(hoveredReroute);
                        }
                        else if (IsHoveringPort)
                        {
                            ShowPortContextMenu(hoveredPort);
                        }
                        else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                        {
                            if (!Selection.Contains(hoveredNode))
                            {
                                SelectNode(hoveredNode, false);
                            }
                            ShowNodeContextMenu();
                        }
                        else if (!IsHoveringNode)
                        {
                            ShowGraphContextMenu();
                        }
                    }
                    isPanning = false;
                }
                break;

            case EventType.KeyDown:
                if (EditorGUIUtility.editingTextField)
                {
                    break;
                }
                else if (e.keyCode == KeyCode.F)
                {
                    Home();
                }
                if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX)
                {
                    if (e.keyCode == KeyCode.Return)
                    {
                        RenameSelectedNode();
                    }
                }
                else
                {
                    if (e.keyCode == KeyCode.F2)
                    {
                        RenameSelectedNode();
                    }
                }
                break;

            case EventType.ValidateCommand:
                if (e.commandName == "SoftDelete")
                {
                    RemoveSelectedNodes();
                }
                else if (e.commandName == "Duplicate")
                {
                    DublicateSelectedNodes();
                }
                Repaint();
                break;

            case EventType.Ignore:
                // If release mouse outside window
                if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid)
                {
                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                break;
            }
        }
        private void InsertDuplicateNodes(XNode.Node[] nodes, Vector2 topLeft)
        {
            if (nodes == null || nodes.Length == 0)
            {
                return;
            }

            // Get top-left node
            Vector2 topLeftNode = nodes.Select(x => x.position).Aggregate((x, y) => new Vector2(Mathf.Min(x.x, y.x), Mathf.Min(x.y, y.y)));
            Vector2 offset      = topLeft - topLeftNode;

            UnityEngine.Object[] newNodes = new UnityEngine.Object[nodes.Length];
            Dictionary <XNode.Node, XNode.Node> substitutes = new Dictionary <XNode.Node, XNode.Node>();

            for (int i = 0; i < nodes.Length; i++)
            {
                XNode.Node srcNode = nodes[i];
                if (srcNode == null)
                {
                    continue;
                }

                // Check if user is allowed to add more of given node type
                XNode.Node.DisallowMultipleNodesAttribute disallowAttrib;
                Type nodeType = srcNode.GetType();
                if (NodeEditorUtilities.GetAttrib(nodeType, out disallowAttrib))
                {
                    int typeCount = graph.nodes.Count(x => x.GetType() == nodeType);
                    if (typeCount >= disallowAttrib.max)
                    {
                        continue;
                    }
                }

                XNode.Node newNode = graphEditor.CopyNode(srcNode);
                substitutes.Add(srcNode, newNode);
                newNode.position = srcNode.position + offset;
                newNodes[i]      = newNode;
            }

            // Walk through the selected nodes again, recreate connections, using the new nodes
            for (int i = 0; i < nodes.Length; i++)
            {
                XNode.Node srcNode = nodes[i];
                if (srcNode == null)
                {
                    continue;
                }
                foreach (XNode.NodePort port in srcNode.Ports)
                {
                    for (int c = 0; c < port.ConnectionCount; c++)
                    {
                        XNode.NodePort inputPort  = port.direction == XNode.NodePort.IO.Input ? port : port.GetConnection(c);
                        XNode.NodePort outputPort = port.direction == XNode.NodePort.IO.Output ? port : port.GetConnection(c);

                        XNode.Node newNodeIn, newNodeOut;
                        if (substitutes.TryGetValue(inputPort.node, out newNodeIn) && substitutes.TryGetValue(outputPort.node, out newNodeOut))
                        {
                            newNodeIn.UpdatePorts();
                            newNodeOut.UpdatePorts();
                            inputPort  = newNodeIn.GetInputPort(inputPort.fieldName);
                            outputPort = newNodeOut.GetOutputPort(outputPort.fieldName);
                        }
                        if (!inputPort.IsConnectedTo(outputPort))
                        {
                            inputPort.Connect(outputPort);
                        }
                    }
                }
            }
            // Select the new nodes
            Selection.objects = newNodes;
        }
Exemple #22
0
 public NodePortReference(XNode.NodePort nodePort) {
     _node = nodePort.node;
     _name = nodePort.fieldName;
 }
Exemple #23
0
 /// <summary> Returned float is used for noodle thickness </summary>
 /// <param name="output"> The output this noodle comes from. Never null. </param>
 /// <param name="input"> The output this noodle comes from. Can be null if we are dragging the noodle. </param>
 public virtual float GetNoodleThickness(XNode.NodePort output, XNode.NodePort input)
 {
     return(5f);
 }
Exemple #24
0
        /// <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)
        {
            if (property == null)
            {
                throw new NullReferenceException();
            }

            // If property is not a port, display a regular property field
            if (port == null)
            {
                EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
            }
            else
            {
                Rect rect = new Rect();

                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 (port.direction == XNode.NodePort.IO.Input)
                {
                    // Get data from [Input] attribute
                    XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
                    XNode.Node.InputAttribute   inputAttribute;
                    bool dynamicPortList = false;
                    if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out inputAttribute))
                    {
                        dynamicPortList = inputAttribute.dynamicPortList;
                        showBacking     = inputAttribute.backingValue;
                    }

                    bool usePropertyAttributes = dynamicPortList ||
                                                 showBacking == XNode.Node.ShowBackingValue.Never ||
                                                 (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected);

                    float  spacePadding = 0;
                    string tooltip      = null;
                    foreach (var attr in propertyAttributes)
                    {
                        if (attr is SpaceAttribute)
                        {
                            if (usePropertyAttributes)
                            {
                                GUILayout.Space((attr as SpaceAttribute).height);
                            }
                            else
                            {
                                spacePadding += (attr as SpaceAttribute).height;
                            }
                        }
                        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
                                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       = EditorGUI.IndentedRect(position);
                                GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
                            }
                            else
                            {
                                spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
                            }
                        }
                        else if (attr is TooltipAttribute)
                        {
                            tooltip = (attr as TooltipAttribute).tooltip;
                        }
                    }

                    if (dynamicPortList)
                    {
                        Type type = GetType(property);
                        XNode.Node.ConnectionType connectionType = inputAttribute != null ? inputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
                        DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
                        return;
                    }
                    switch (showBacking)
                    {
                    case XNode.Node.ShowBackingValue.Unconnected:
                        // Display a label if port is connected
                        if (port.IsConnected)
                        {
                            EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case XNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip));
                        break;

                    case XNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect = GUILayoutUtility.GetLastRect();
                    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
                }
                else if (port.direction == XNode.NodePort.IO.Output)
                {
                    // Get data from [Output] attribute
                    XNode.Node.ShowBackingValue showBacking = XNode.Node.ShowBackingValue.Unconnected;
                    XNode.Node.OutputAttribute  outputAttribute;
                    bool dynamicPortList = false;
                    if (NodeEditorUtilities.GetCachedAttrib(port.node.GetType(), property.name, out outputAttribute))
                    {
                        dynamicPortList = outputAttribute.dynamicPortList;
                        showBacking     = outputAttribute.backingValue;
                    }

                    bool usePropertyAttributes = dynamicPortList ||
                                                 showBacking == XNode.Node.ShowBackingValue.Never ||
                                                 (showBacking == XNode.Node.ShowBackingValue.Unconnected && port.IsConnected);

                    float  spacePadding = 0;
                    string tooltip      = null;
                    foreach (var attr in propertyAttributes)
                    {
                        if (attr is SpaceAttribute)
                        {
                            if (usePropertyAttributes)
                            {
                                GUILayout.Space((attr as SpaceAttribute).height);
                            }
                            else
                            {
                                spacePadding += (attr as SpaceAttribute).height;
                            }
                        }
                        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
                                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       = EditorGUI.IndentedRect(position);
                                GUI.Label(position, (attr as HeaderAttribute).header, EditorStyles.boldLabel);
                            }
                            else
                            {
                                spacePadding += EditorGUIUtility.singleLineHeight * 1.5f;
                            }
                        }
                        else if (attr is TooltipAttribute)
                        {
                            tooltip = (attr as TooltipAttribute).tooltip;
                        }
                    }

                    if (dynamicPortList)
                    {
                        Type type = GetType(property);
                        XNode.Node.ConnectionType connectionType = outputAttribute != null ? outputAttribute.connectionType : XNode.Node.ConnectionType.Multiple;
                        DynamicPortList(property.name, type, property.serializedObject, port.direction, connectionType);
                        return;
                    }
                    switch (showBacking)
                    {
                    case XNode.Node.ShowBackingValue.Unconnected:
                        // 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));
                        }
                        // Display an editable property field if port is not connected
                        else
                        {
                            EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        }
                        break;

                    case XNode.Node.ShowBackingValue.Never:
                        // Display a label
                        EditorGUILayout.LabelField(label != null ? label : new GUIContent(property.displayName, tooltip), NodeEditorResources.OutputPort, GUILayout.MinWidth(30));
                        break;

                    case XNode.Node.ShowBackingValue.Always:
                        // Display an editable property field
                        EditorGUILayout.PropertyField(property, label, includeChildren, GUILayout.MinWidth(30));
                        break;
                    }

                    rect          = GUILayoutUtility.GetLastRect();
                    rect.width   += NodeEditorResources.styles.outputPort.padding.right;
                    rect.position = rect.position + new Vector2(rect.width, spacePadding);
                }

                rect.size = new Vector2(16, 16);

                Color backgroundColor = NodeEditorWindow.current.graphEditor.GetPortBackgroundColor(port);
                Color col             = NodeEditorWindow.current.graphEditor.GetPortColor(port);
                if (!port.IsConnected)
                {
                    col = new Color(col.r, col.g, col.b, 0.5f);
                }
                DrawPortHandle(rect, backgroundColor, col);

                // Register the handle position
                Vector2 portPos = rect.center;
                NodeEditor.portPositions[port] = portPos;
            }
        }
 public virtual void AddPortContextMenu(GenericMenu menu, XNode.NodePort port)
 {
 }
Exemple #26
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();

            Color col = GUI.color;

            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
                    Rect fromRect;
                    if (!_portConnectionPoints.TryGetValue(output, out fromRect))
                    {
                        continue;
                    }

                    Color connectionColor = graphEditor.GetPortColor(output);

                    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);
                        }
                        Rect toRect;
                        if (!_portConnectionPoints.TryGetValue(input, out toRect))
                        {
                            continue;
                        }

                        List <Vector2> reroutePoints = output.GetReroutePoints(k);

                        List <Vector2> gridPoints = new List <Vector2>();
                        gridPoints.Add(fromRect.center);
                        gridPoints.AddRange(reroutePoints);
                        gridPoints.Add(toRect.center);
                        DrawNoodle(connectionColor, gridPoints);

                        // Loop through reroute points again and draw the points
                        for (int i = 0; i < reroutePoints.Count; i++)
                        {
                            RerouteReference rerouteRef = new RerouteReference(output, k, i);
                            // Draw reroute point at position
                            Rect rect = new Rect(reroutePoints[i], new Vector2(12, 12));
                            rect.position = new Vector2(rect.position.x - 6, rect.position.y - 6);
                            rect          = GridToWindowRect(rect);

                            // Draw selected reroute points with an outline
                            if (selectedReroutes.Contains(rerouteRef))
                            {
                                GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
                                GUI.DrawTexture(rect, NodeEditorResources.dotOuter);
                            }

                            GUI.color = connectionColor;
                            GUI.DrawTexture(rect, NodeEditorResources.dot);
                            if (rect.Overlaps(selectionBox))
                            {
                                selection.Add(rerouteRef);
                            }
                            if (rect.Contains(mousePos))
                            {
                                hoveredReroute = rerouteRef;
                            }
                        }
                    }
                }
            }
            GUI.color = col;
            if (Event.current.type != EventType.Layout && currentActivity == NodeActivity.DragGrid)
            {
                selectedReroutes = selection;
            }
        }
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

            switch (e.type)
            {
            case EventType.MouseMove:
                break;

            case EventType.ScrollWheel:
                float oldZoom = zoom;
                if (e.delta.y > 0)
                {
                    zoom += 0.1f * zoom;
                }
                else
                {
                    zoom -= 0.1f * zoom;
                }
                if (NodeEditorPreferences.GetSettings().zoomToMouse)
                {
                    panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset);
                }
                break;

            case EventType.MouseDrag:
                if (e.button == 0)
                {
                    if (IsDraggingPort)
                    {
                        if (IsHoveringPort && hoveredPort.IsInput && draggedOutput.CanConnectTo(hoveredPort))
                        {
                            if (!draggedOutput.IsConnectedTo(hoveredPort))
                            {
                                draggedOutputTarget = hoveredPort;
                            }
                        }
                        else
                        {
                            draggedOutputTarget = null;
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldNode)
                    {
                        RecalculateDragOffsets(e);
                        currentActivity = NodeActivity.DragNode;
                        Repaint();
                    }
                    if (currentActivity == NodeActivity.DragNode)
                    {
                        // Holding ctrl inverts grid snap
                        bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap;
                        if (e.control)
                        {
                            gridSnap = !gridSnap;
                        }

                        Vector2 mousePos = WindowToGridPosition(e.mousePosition);
                        // Move selected nodes with offset
                        for (int i = 0; i < Selection.objects.Length; i++)
                        {
                            if (Selection.objects[i] is XNode.Node)
                            {
                                XNode.Node node    = Selection.objects[i] as XNode.Node;
                                Vector2    initial = node.position;
                                node.position = mousePos + dragOffset[i];
                                if (gridSnap)
                                {
                                    node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8;
                                    node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8;
                                }

                                // Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame.
                                Vector2 offset = node.position - initial;
                                if (offset.sqrMagnitude > 0)
                                {
                                    foreach (XNode.NodePort output in node.Outputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(output, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[output] = rect;
                                        }
                                    }

                                    foreach (XNode.NodePort input in node.Inputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(input, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[input] = rect;
                                        }
                                    }
                                }
                            }
                        }
                        // Move selected reroutes with offset
                        for (int i = 0; i < selectedReroutes.Count; i++)
                        {
                            Vector2 pos = mousePos + dragOffset[Selection.objects.Length + i];
                            if (gridSnap)
                            {
                                pos.x = (Mathf.Round(pos.x / 16) * 16);
                                pos.y = (Mathf.Round(pos.y / 16) * 16);
                            }
                            selectedReroutes[i].SetPoint(pos);
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldGrid)
                    {
                        currentActivity        = NodeActivity.DragGrid;
                        preBoxSelection        = Selection.objects;
                        preBoxSelectionReroute = selectedReroutes.ToArray();
                        dragBoxStart           = WindowToGridPosition(e.mousePosition);
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.DragGrid)
                    {
                        Vector2 boxStartPos = GridToWindowPosition(dragBoxStart);
                        Vector2 boxSize     = e.mousePosition - boxStartPos;
                        if (boxSize.x < 0)
                        {
                            boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x);
                        }
                        if (boxSize.y < 0)
                        {
                            boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y);
                        }
                        selectionBox = new Rect(boxStartPos, boxSize);
                        Repaint();
                    }
                }
                else if (e.button == 1 || e.button == 2)
                {
                    panOffset += e.delta * zoom;
                    isPanning  = true;
                }
                break;

            case EventType.MouseDown:
                Repaint();
                if (e.button == 0)
                {
                    draggedOutputReroutes.Clear();

                    if (IsHoveringPort)
                    {
                        if (hoveredPort.IsOutput)
                        {
                            draggedOutput = hoveredPort;
                        }
                        else
                        {
                            hoveredPort.VerifyConnections();
                            if (hoveredPort.IsConnected)
                            {
                                XNode.Node     node   = hoveredPort.node;
                                XNode.NodePort output = hoveredPort.Connection;
                                int            outputConnectionIndex = output.GetConnectionIndex(hoveredPort);
                                draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex);
                                hoveredPort.Disconnect(output);
                                draggedOutput       = output;
                                draggedOutputTarget = hoveredPort;
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                            }
                        }
                    }
                    else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                    {
                        // If mousedown on node header, select or deselect
                        if (!Selection.Contains(hoveredNode))
                        {
                            SelectNode(hoveredNode, e.control || e.shift);
                            if (!e.control && !e.shift)
                            {
                                selectedReroutes.Clear();
                            }
                        }
                        else if (e.control || e.shift)
                        {
                            DeselectNode(hoveredNode);
                        }

                        // Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown.
                        isDoubleClick = (e.clickCount == 2);

                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    else if (IsHoveringReroute)
                    {
                        // If reroute isn't selected
                        if (!selectedReroutes.Contains(hoveredReroute))
                        {
                            // Add it
                            if (e.control || e.shift)
                            {
                                selectedReroutes.Add(hoveredReroute);
                            }
                            // Select it
                            else
                            {
                                selectedReroutes = new List <RerouteReference>()
                                {
                                    hoveredReroute
                                };
                                Selection.activeObject = null;
                            }
                        }
                        // Deselect
                        else if (e.control || e.shift)
                        {
                            selectedReroutes.Remove(hoveredReroute);
                        }
                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    // If mousedown on grid background, deselect all
                    else if (!IsHoveringNode)
                    {
                        currentActivity = NodeActivity.HoldGrid;
                        if (!e.control && !e.shift)
                        {
                            selectedReroutes.Clear();
                            Selection.activeObject = null;
                        }
                    }
                }
                break;

            case EventType.MouseUp:
                if (e.button == 0)
                {
                    //Port drag release
                    if (IsDraggingPort)
                    {
                        //If connection is valid, save it
                        if (draggedOutputTarget != null)
                        {
                            XNode.Node node = draggedOutputTarget.node;
                            if (graph.nodes.Count != 0)
                            {
                                draggedOutput.Connect(draggedOutputTarget);
                            }

                            // ConnectionIndex can be -1 if the connection is removed instantly after creation
                            int connectionIndex = draggedOutput.GetConnectionIndex(draggedOutputTarget);
                            if (connectionIndex != -1)
                            {
                                draggedOutput.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes);
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                                EditorUtility.SetDirty(graph);
                            }
                        }
                        //Release dragged connection
                        draggedOutput       = null;
                        draggedOutputTarget = null;
                        EditorUtility.SetDirty(graph);
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (currentActivity == NodeActivity.DragNode)
                    {
                        IEnumerable <XNode.Node> nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node);
                        foreach (XNode.Node node in nodes)
                        {
                            EditorUtility.SetDirty(node);
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (!IsHoveringNode)
                    {
                        // If click outside node, release field focus
                        if (!isPanning)
                        {
                            EditorGUI.FocusTextInControl(null);
                            EditorGUIUtility.editingTextField = false;
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }

                    // If click node header, select it.
                    if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift))
                    {
                        selectedReroutes.Clear();
                        SelectNode(hoveredNode, false);

                        // Double click to center node
                        if (isDoubleClick)
                        {
                            Vector2 nodeDimension = nodeSizes.ContainsKey(hoveredNode) ? nodeSizes[hoveredNode] / 2 : Vector2.zero;
                            panOffset = -hoveredNode.position - nodeDimension;
                        }
                    }

                    // If click reroute, select it.
                    if (IsHoveringReroute && !(e.control || e.shift))
                    {
                        selectedReroutes = new List <RerouteReference>()
                        {
                            hoveredReroute
                        };
                        Selection.activeObject = null;
                    }

                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                else if (e.button == 1 || e.button == 2)
                {
                    if (!isPanning)
                    {
                        if (IsDraggingPort)
                        {
                            draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition));
                        }
                        else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1)
                        {
                            selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint());
                            selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1);
                        }
                        else if (IsHoveringReroute)
                        {
                            ShowRerouteContextMenu(hoveredReroute);
                        }
                        else if (IsHoveringPort)
                        {
                            ShowPortContextMenu(hoveredPort);
                        }
                        else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                        {
                            if (!Selection.Contains(hoveredNode))
                            {
                                SelectNode(hoveredNode, false);
                            }
                            GenericMenu menu = new GenericMenu();
                            NodeEditor.GetEditor(hoveredNode).AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                            e.Use();     // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places.
                        }
                        else if (!IsHoveringNode)
                        {
                            GenericMenu menu = new GenericMenu();
                            graphEditor.AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                        }
                    }
                    isPanning = false;
                }
                // Reset DoubleClick
                isDoubleClick = false;
                break;

            case EventType.KeyDown:
                if (EditorGUIUtility.editingTextField)
                {
                    break;
                }
                else if (e.keyCode == KeyCode.F)
                {
                    Home();
                }
                if (IsMac())
                {
                    if (e.keyCode == KeyCode.Return)
                    {
                        RenameSelectedNode();
                    }
                }
                else
                {
                    if (e.keyCode == KeyCode.F2)
                    {
                        RenameSelectedNode();
                    }
                }
                break;

            case EventType.ValidateCommand:
            case EventType.ExecuteCommand:
                if (e.commandName == "SoftDelete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (IsMac() && e.commandName == "Delete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Duplicate")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        DuplicateSelectedNodes();
                    }
                    e.Use();
                }
                Repaint();
                break;

            case EventType.Ignore:
                // If release mouse outside window
                if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid)
                {
                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                break;
            }
        }
Exemple #28
0
 /// <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)
 {
     PropertyField(property, null, port, includeChildren, options);
 }
Exemple #29
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;
            }
        }