def addNodes(self):
        node1 = Node(self.scene,
                     "My Awesome Node 1",
                     inputs=[0, 0, 0],
                     outputs=[1])
        node2 = Node(self.scene,
                     "My Awesome Node 2",
                     inputs=[3, 3, 3],
                     outputs=[1])
        node3 = Node(self.scene,
                     "My Awesome Node 3",
                     inputs=[2, 2, 2],
                     outputs=[1])
        node1.setPos(-350, -250)
        node2.setPos(-75, 0)
        node3.setPos(200, -150)

        edge1 = Edge(self.scene,
                     node1.outputs[0],
                     node2.inputs[0],
                     edge_type=EDGE_TYPE_BEZIER)
        edge2 = Edge(self.scene,
                     node2.outputs[0],
                     node3.inputs[0],
                     edge_type=EDGE_TYPE_BEZIER)

        self.scene.history.storeInitialHistoryStamp()
Exemplo n.º 2
0
    def addNodes(self):
        node1 = Node(self.scene,
                     "My Awesome Node 1",
                     inputs=[0, 2, 3],
                     outputs=[1])
        node2 = Node(self.scene,
                     "My Awesome Node 2",
                     inputs=[1, 4, 5],
                     outputs=[1])
        node3 = Node(self.scene,
                     "My Awesome Node 3",
                     inputs=[4, 0, 2],
                     outputs=[1])
        node1.setPos(-350, -250)
        node2.setPos(-75, 0)
        node3.setPos(200, -150)

        edge1 = Edge(self.scene,
                     node1.outputs[0],
                     node2.inputs[0],
                     edge_type=EDGE_TYPE_BEZIER)
        edge2 = Edge(self.scene,
                     node2.outputs[0],
                     node3.inputs[1],
                     edge_type=EDGE_TYPE_BEZIER)
    def addNodes(self):
        """Testing method to create 3 `Nodes` with 3 `Edges` connecting them"""
        node1 = Node(self.scene,
                     "My Awesome Node 1",
                     inputs=[0, 0, 0],
                     outputs=[1, 5])
        node2 = Node(self.scene,
                     "My Awesome Node 2",
                     inputs=[3, 3, 3],
                     outputs=[1])
        node3 = Node(self.scene,
                     "My Awesome Node 3",
                     inputs=[2, 2, 2],
                     outputs=[1])
        node1.setPos(-350, -250)
        node2.setPos(-75, 0)
        node3.setPos(200, -200)

        edge1 = Edge(self.scene,
                     node1.outputs[0],
                     node2.inputs[0],
                     edge_type=EDGE_TYPE_BEZIER)
        edge2 = Edge(self.scene,
                     node2.outputs[0],
                     node3.inputs[0],
                     edge_type=EDGE_TYPE_BEZIER)
        edge3 = Edge(self.scene,
                     node1.outputs[0],
                     node3.inputs[2],
                     edge_type=EDGE_TYPE_BEZIER)

        self.scene.history.storeInitialHistoryStamp()
Exemplo n.º 4
0
 def edgeDragStart(self, item):
     if DEBUG: print('View::edgeDragStart - Start dragging edge')
     if DEBUG: print('View::edgeDragStart - Assign Start Socket to:', item.socket)
     #self.previousEdge = item.socket.edge
     self.drag_start_socket = item.socket
     self.drag_edge = Edge(self.grScene.scene, item.socket, None, EDGE_TYPE_BEZIER)
     if DEBUG: print('View::edgeDragStart -  dragEdge:', self.drag_edge)
Exemplo n.º 5
0
    def edgeDragEnd(self, item):
        """ return True if skip the rest of the code """
        self.mode = MODE_NOOP

        if DEBUG: print('View::edgeDragEnd ~ End dragging edge')
        self.drag_edge.remove()
        self.drag_edge = None

        if type(item) is QDMGraphicsSocket:
            if item.socket != self.drag_start_socket:
                # if we released dragging on a socket (other then the beginning socket)

                # we wanna keep all the edges comming from target socket
                if not item.socket.is_multi_edges:
                    item.socket.removeAllEdges()

                # we wanna keep all the edges comming from start socket
                if not self.drag_start_socket.is_multi_edges:
                    self.drag_start_socket.removeAllEdges()

                new_edge = Edge(self.grScene.scene,
                                self.drag_start_socket,
                                item.socket,
                                edge_type=EDGE_TYPE_BEZIER)
                if DEBUG:
                    print("View::edgeDragEnd ~  created new edge:", new_edge,
                          "connecting", new_edge.start_socket, "<-->",
                          new_edge.end_socket)

                self.grScene.scene.history.storeHistory(
                    "Created new edge by dragging", setModified=True)
                return True

        if DEBUG: print('View::edgeDragEnd ~ everything done.')
        return False
Exemplo n.º 6
0
 def edgeDragStart(self, item):
     try:
         if DEBUG: print('View::edgeDragStart ~ Start dragging edge')
         if DEBUG: print('View::edgeDragStart ~   assign Start Socket to:', item.socket)
         self.drag_start_socket = item.socket
         self.drag_edge = Edge(self.grScene.scene, item.socket, None, EDGE_TYPE_BEZIER)
         if DEBUG: print('View::edgeDragStart ~   dragEdge:', self.drag_edge)
     except Exception as e: dumpException(e)
Exemplo n.º 7
0
    def dropNode(self, node: "Node", scene_pos_x: float, scene_pos_y: float):
        """
        Code handling the dropping of a node on an existing edge.

        :param scene_pos_x: scene position x
        :type scene_pos_x: `float`
        :param scene_pos_y: scene position y
        :type scene_pos_y: `float`
        """

        node_box = self.hotZoneRect(node)

        # check if the node is dropped on an existing edge
        edge = self.intersect(node_box)
        if edge is None: return

        if self.isConnected(node): return

        # determine the order of start and end
        if edge.start_socket.is_output:
            socket_start = edge.start_socket
            socket_end = edge.end_socket
        else:
            socket_start = edge.end_socket
            socket_end = edge.start_socket

        # The new edges will have the same edge_type as the intersected edge
        edge_type = edge.edge_type
        edge.remove()
        self.grView.grScene.scene.history.storeHistory('Delete existing edge',
                                                       setModified=True)

        new_node_socket_in = node.inputs[0]
        Edge(self.grScene.scene,
             socket_start,
             new_node_socket_in,
             edge_type=edge_type)
        new_node_socket_out = node.outputs[0]
        Edge(self.grScene.scene,
             new_node_socket_out,
             socket_end,
             edge_type=edge_type)

        self.grView.grScene.scene.history.storeHistory(
            'Created new edges by dropping node', setModified=True)
Exemplo n.º 8
0
    def edgeDragEnd(self, item):
        # return true if to skip the rest of the code
        self.mode = NODE_NOOP

        if DEBUG: print("View::edgeDragEnd - End dragging edge")
        self.drag_edge.remove()
        self.drag_edge = None

        if type(item) is QDMGraphicsSocket:
            if item.socket != self.drag_start_socket:
                # If we released draging on a socket (other than the beginning socket)
                # if DEBUG: print('View::edgeDragEnd - previous edge', self.previousEdge)

                # if item.socket.hasEdge():
                #     item.socket.edges.remove()

                # for edge in item.socket.edges:
                #     if DEBUG: print("View::edgeDragEnd - cleanup edges IN target", edge)
                #     edge.remove()
                #     if DEBUG: print("View::edgeDragEnd - cleanup edges IN target", edge, "removed")

                # we wanna keep all the edges coming from target socket
                if not item.socket.is_multi_edges:
                    item.socket.removeAllEdges()
                # we wanna keep all the edges coming from start socket

                if not self.drag_start_socket.is_multi_edges:
                    self.drag_start_socket.removeAllEdges()

                # if DEBUG: print("View::edgeDragEnd - assign End Socket", item.socket)
                # if self.previousEdge is not None: self.previousEdge.remove()
                # if DEBUG: print('View::edgeDragEnd - previous edge remove')
                # self.drag_edge.start_socket = self.drag_last_start_socket
                # self.drag_edge.end_socket = item.socket
                # self.drag_edge.start_socket.addEdge(self.drag_edge)
                # self.drag_edge.end_socket.addEdge(self.drag_edge)
                # if DEBUG: print('View:: edgeDragEnd -   assigned start & end sockets to drag edge')
                # self.drag_edge.updatePositions()
                new_edge = Edge(self.grScene.scene, self.drag_start_socket, item.socket, EDGE_TYPE_BEZIER)
                if DEBUG: print("View::edgeDragEnd -   created new edge:", new_edge, "connecting", new_edge.start_socket, "<--->", new_edge.end_socket)

                self.grScene.scene.history.storeHistory("Created new edge by dragging")
                return True



        # if DEBUG: print('View::edgeDragEnd - about to set socket to previous edge:', self.previousEdge)
        # if self.previousEdge is not None:
        #     self.previousEdge.start_socket.edge = self.previousEdge

        if DEBUG: print('View::edgeDragEnd - everything done.')
        return False
Exemplo n.º 9
0
 def edgeDragStart(self, item):
     try:
         logging.debug('View::edgeDragStart ~ Start dragging edge')
         logging.debug(
             'View::edgeDragStart ~   assign Start Socket to: {item.socket}'
         )
         self.drag_start_socket = item.socket
         self.drag_edge = Edge(self.grScene.scene, item.socket, None,
                               EDGE_TYPE_BEZIER)
         logging.debug(
             f'View::edgeDragStart ~   dragEdge: {self.drag_edge}')
     except Exception as e:
         dumpException(e)
Exemplo n.º 10
0
    def edgeDragEnd(self, item: 'QGraphicsItem'):
        """Code handling the end of dragging an `Edge` operation. In this code return True if skip the
        rest of the mouse event processing

        :param item: Item in the `Graphics Scene` where we ended dragging an `Edge`
        :type item: ``QGraphicsItem``
        """
        self.mode = MODE_NOOP

        if DEBUG: print('View::edgeDragEnd ~ End dragging edge')
        self.drag_edge.remove(
            silent=True)  # don't notify sockets about removing drag_edge
        self.drag_edge = None

        try:
            if isinstance(item, QDMGraphicsSocket):
                if item.socket != self.drag_start_socket:
                    # if we released dragging on a socket (other then the beginning socket)

                    # we wanna keep all the edges comming from target socket
                    if not item.socket.is_multi_edges:
                        item.socket.removeAllEdges()

                    # we wanna keep all the edges comming from start socket
                    if not self.drag_start_socket.is_multi_edges:
                        self.drag_start_socket.removeAllEdges()

                    ## Create new Edge
                    new_edge = Edge(self.grScene.scene,
                                    self.drag_start_socket,
                                    item.socket,
                                    edge_type=EDGE_TYPE_BEZIER)
                    if DEBUG:
                        print("View::edgeDragEnd ~  created new edge:",
                              new_edge, "connecting", new_edge.start_socket,
                              "<-->", new_edge.end_socket)

                    ## Send notifications for the new edge
                    for socket in [self.drag_start_socket, item.socket]:
                        # @TODO: Add possibility (ie when an input edge was replaced) to be silent and don't trigger change
                        socket.node.onEdgeConnectionChanged(new_edge)
                        if socket.is_input: socket.node.onInputChanged(socket)

                    self.grScene.scene.history.storeHistory(
                        "Created new edge by dragging", setModified=True)
                    return True
        except Exception as e:
            dumpException(e)

        if DEBUG: print('View::edgeDragEnd ~ everything done.')
        return False
Exemplo n.º 11
0
 def edgeDragStart(self, item: 'QGraphicsItem'):
     """Code handling the start of dragging an `Edge` operation"""
     try:
         if DEBUG: print('View::edgeDragStart ~ Start dragging edge')
         if DEBUG:
             print('View::edgeDragStart ~   assign Start Socket to:',
                   item.socket)
         self.drag_start_socket = item.socket
         self.drag_edge = Edge(self.grScene.scene, item.socket, None,
                               EDGE_TYPE_BEZIER)
         if DEBUG:
             print('View::edgeDragStart ~   dragEdge:', self.drag_edge)
     except Exception as e:
         dumpException(e)
Exemplo n.º 12
0
    def deserializeFromClipboard(self, data: dict):
        """
        Deserializes data from Clipboard.

        :param data: ``dict`` data for deserialization to the :class:`nodeeditor.node_scene.Scene`.
        :type data: ``dict``
        """

        hashmap = {}

        # calculate mouse pointer - scene position
        view = self.scene.getView()
        mouse_scene_pos = view.last_scene_mouse_position

        # calculate selected objects bbox and center
        minx, maxx, miny, maxy = 0, 0, 0, 0
        for node_data in data['nodes']:
            x, y = node_data['pos_x'], node_data['pos_y']
            if x < minx: minx = x
            if x > maxx: maxx = x
            if y < miny: miny = y
            if y > maxy: maxy = y
        bbox_center_x = (minx + maxx) / 2
        bbox_center_y = (miny + maxy) / 2

        # center = view.mapToScene(view.rect().center())

        # calculate tehe offset of the newly creating nodes
        offset_x = mouse_scene_pos.x() - bbox_center_x
        offset_y = mouse_scene_pos.y() - bbox_center_y

        # create each node
        for node_data in data['nodes']:
            new_node = self.scene.getNodeClassFromData(node_data)(self.scene)
            new_node.deserialize(node_data, hashmap, restore_id=False)

            # readjust the new node's position
            pos = new_node.pos
            new_node.setPos(pos.x() + offset_x, pos.y() + offset_y)

        # create each edge
        if 'edges' in data:
            for edge_data in data['edges']:
                new_edge = Edge(self.scene)
                new_edge.deserialize(edge_data, hashmap, restore_id=False)

        # store history
        self.scene.history.storeHistory("Pasted elements in scene",
                                        setModified=True)
Exemplo n.º 13
0
    def deserialize(self, data, hashmap={}, restore_id=True):
        self.clear()
        hashmap = {}

        if restore_id: self.id = data['id']

        # create nodes
        for node_data in data['nodes']:
            Node(self).deserialize(node_data, hashmap, restore_id)

        # create edges
        for edge_data in data['edges']:
            Edge(self).deserialize(edge_data, hashmap, restore_id)

        return True
Exemplo n.º 14
0
    def deserialize(self,
                    data: dict,
                    hashmap: dict = {},
                    restore_id: bool = True) -> bool:
        self.clear()
        hashmap = {}

        if restore_id: self.id = data['id']

        # create nodes
        for node_data in data['nodes']:
            self.getNodeClassFromData(node_data)(self).deserialize(
                node_data, hashmap, restore_id)

        # create edges
        for edge_data in data['edges']:
            Edge(self).deserialize(edge_data, hashmap, restore_id)

        return True
Exemplo n.º 15
0
    def deserializeFromClipboard(self, data):

        hashmap = {}

        # calculate mouse pointer - scene position
        view = self.scene.grScene.views()[0]

        mouse_scene_pos = view.last_scene_mouse_position

        # calculate selected objects bbox and center
        minx, maxx, miny, maxy = 0, 0, 0, 0
        for node_data in data['nodes']:
            x, y = node_data['pos_x'], node_data['pos_y']
            if x < minx: minx = x
            if x > maxx: maxx = x
            if y < miny: miny = y
            if y > maxy: maxy = y
        bbox_center_x = (minx + maxx) / 2
        bbox_center_y = (miny + maxy) / 2

        #center = view.mapToScene(view.rect().center())

        # calculate the offset of the newly creating nodes
        offset_x = mouse_scene_pos.x() - bbox_center_x
        offset_y = mouse_scene_pos.y() - bbox_center_y

        # create each node
        for node_data in data['nodes']:
            new_node = Node(self.scene)
            new_node.deserialize(node_data, hashmap, restore_id=False)

            # readjust the new node's position
            pos = new_node.pos
            new_node.setPos(pos.x() + offset_x, pos.y() + offset_y)

        # create each edge
        if 'edges' in data:
            for edge_data in data['edges']:
                new_edge = Edge(self.scene)
                new_edge.deserialize(edge_data, hashmap, restore_id=False)

        # store history
        self.scene.history.storeHistory("Pasted elements in scene")
Exemplo n.º 16
0
    def edgeDragEnd(self, item):
        """ return True if skip the rest of the code """
        self.mode = MODE_NOOP

        logging.debug('View::edgeDragEnd ~ End dragging edge')
        self.drag_edge.remove()
        self.drag_edge = None

        try:
            if type(item) is QDMGraphicsSocket:
                if item.socket != self.drag_start_socket:
                    # if we released dragging on a socket (other then the beginning socket)

                    # we wanna keep all the edges comming from target socket
                    if not item.socket.is_multi_edges:
                        item.socket.removeAllEdges()

                    # we wanna keep all the edges comming from start socket
                    if not self.drag_start_socket.is_multi_edges:
                        self.drag_start_socket.removeAllEdges()

                    new_edge = Edge(self.grScene.scene,
                                    self.drag_start_socket,
                                    item.socket,
                                    edge_type=EDGE_TYPE_BEZIER)
                    logging.debug(
                        f"View::edgeDragEnd ~ created new edge: {new_edge}, "
                        f"connecting {new_edge.start_socket} <--> {new_edge.end_socket}"
                    )

                    for socket in [self.drag_start_socket, item.socket]:
                        socket.node.onEdgeConnectionChanged(new_edge)
                        if socket.is_input:
                            socket.node.onInputChanged(new_edge)

                    self.grScene.scene.history.storeHistory(
                        "Created new edge by dragging", setModified=True)
                    return True
        except Exception as e:
            dumpException(e)

        logging.debug('View::edgeDragEnd ~ everything done.')
        return False
Exemplo n.º 17
0
    def deserialize(self, data, hashmap={}, restore_id=True):
        self.clear()
        hashmap = {}

        if restore_id: self.id = data['id']

        # create nodes
        for node_data in data['nodes']:
            #classtype = self.getNodeClassFromData(node_data)
            #c = classtype(self)
            #c.deserialize(node_data, hashmap, restore_id)
            #self.addNode(c)

            try:
                self.getNodeClassFromData(node_data)(self).deserialize(node_data, hashmap, restore_id)
            except Exception as e:
                logging.error(e)
                traceback.print_tb(e.__traceback__)

        # create edges
        for edge_data in data['edges']:
            Edge(self).deserialize(edge_data, hashmap, restore_id)

        return True
Exemplo n.º 18
0
    def deserializeFromClipboard(self, data:dict, *args, **kwargs):
        """
        Deserializes data from Clipboard.

        :param data: ``dict`` data for deserialization to the :class:`nodeeditor.node_scene.Scene`.
        :type data: ``dict``
        """

        hashmap = {}

        # calculate mouse pointer - scene position
        view = self.scene.getView()
        mouse_scene_pos = view.last_scene_mouse_position

        # calculate selected objects bbox and center
        minx, maxx, miny, maxy = 10000000,-10000000, 10000000,-10000000
        for node_data in data['nodes']:
            x, y = node_data['pos_x'], node_data['pos_y']
            if x < minx: minx = x
            if x > maxx: maxx = x
            if y < miny: miny = y
            if y > maxy: maxy = y

        # add width and height of a node
        maxx -= 180
        maxy += 100

        relbboxcenterx = (minx + maxx) / 2 - minx
        relbboxcentery = (miny + maxy) / 2 - miny

        if DEBUG_PASTING:
            print (" *** PASTA:")
            print("Copied boudaries:\n\tX:", minx, maxx, "   Y:", miny, maxy)
            print("\tbbox_center:", relbboxcenterx, relbboxcentery)

        # calculate the offset of the newly creating nodes
        mousex, mousey = mouse_scene_pos.x(), mouse_scene_pos.y()

        # create each node
        created_nodes = []

        self.scene.setSilentSelectionEvents()

        self.scene.doDeselectItems()

        for node_data in data['nodes']:
            new_node = self.scene.getNodeClassFromData(node_data)(self.scene)
            new_node.deserialize(node_data, hashmap, restore_id=False, *args, **kwargs)
            created_nodes.append(new_node)

            # readjust the new nodeeditor's position

            # new node's current position
            posx, posy = new_node.pos.x(), new_node.pos.y()
            newx, newy = mousex + posx - minx, mousey + posy - miny

            new_node.setPos(newx, newy)

            new_node.doSelect()

            if DEBUG_PASTING:
                print("** PASTA SUM:")
                print("\tMouse pos:", mousex, mousey)
                print("\tnew node pos:", posx, posy)
                print("\tFINAL:", newx, newy)

        # create each edge
        if 'edges' in data:
            for edge_data in data['edges']:
                new_edge = Edge(self.scene)
                new_edge.deserialize(edge_data, hashmap, restore_id=False, *args, **kwargs)


        self.scene.setSilentSelectionEvents(False)

        # store history
        self.scene.history.storeHistory("Pasted elements in scene", setModified=True)

        return created_nodes
Exemplo n.º 19
0
    def deserialize(self,
                    data: dict,
                    hashmap: dict = {},
                    restore_id: bool = True,
                    *args,
                    **kwargs) -> bool:
        hashmap = {}

        if restore_id: self.id = data['id']

        # -- deserialize NODES

        ## Instead of recreating all the nodes, reuse existing ones...
        # get list of all current nodes:
        all_nodes = self.nodes.copy()

        # go through deserialized nodes:
        for node_data in data['nodes']:
            # can we find this node in the scene?
            found = False
            for node in all_nodes:
                if node.id == node_data['id']:
                    found = node
                    break

            if not found:
                try:
                    new_node = self.getNodeClassFromData(node_data)(self)
                    new_node.deserialize(node_data, hashmap, restore_id, *args,
                                         **kwargs)
                    new_node.onDeserialized(node_data)
                    # print("New node for", node_data['title'])
                except:
                    dumpException()
            else:
                try:
                    found.deserialize(node_data, hashmap, restore_id, *args,
                                      **kwargs)
                    found.onDeserialized(node_data)
                    all_nodes.remove(found)
                    # print("Reused", node_data['title'])
                except:
                    dumpException()

        # remove nodes which are left in the scene and were NOT in the serialized data!
        # that means they were not in the graph before...
        while all_nodes != []:
            node = all_nodes.pop()
            node.remove()

        # -- deserialize EDGES

        ## Instead of recreating all the edges, reuse existing ones...
        # get list of all current edges:
        all_edges = self.edges.copy()

        # go through deserialized edges:
        for edge_data in data['edges']:
            # can we find this node in the scene?
            found = False
            for edge in all_edges:
                if edge.id == edge_data['id']:
                    found = edge
                    break

            if not found:
                new_edge = Edge(self).deserialize(edge_data, hashmap,
                                                  restore_id, *args, **kwargs)
                # print("New edge for", edge_data)
            else:
                found.deserialize(edge_data, hashmap, restore_id, *args,
                                  **kwargs)
                all_edges.remove(found)

        # remove nodes which are left in the scene and were NOT in the serialized data!
        # that means they were not in the graph before...
        while all_edges != []:
            edge = all_edges.pop()
            edge.remove()

        return True