Skip to content

load_backdrop

LoadBackdropNodes

Bases: LoaderPlugin

Loading published .nk files to backdrop nodes

Source code in client/ayon_nuke/plugins/load/load_backdrop.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
class LoadBackdropNodes(load.LoaderPlugin):
    """Loading published .nk files to backdrop nodes"""

    product_base_types = {"*"}
    product_types = product_base_types
    representations = {"*"}
    extensions = {"nk"}

    settings_category = "nuke"

    label = "Import Nuke Nodes"
    order = 0
    icon = "eye"
    color = "white"
    node_color = "0x7533c1ff"
    remove_nodes_from_backdrop = False

    def load(self, context, name, namespace, data):
        """
        Loading function to import .nk file into script and wrap
        it on backdrop

        Arguments:
            context (dict): context of version
            name (str): name of the version
            namespace (str): namespace name
            data (dict): compulsory attribute > not used

        Returns:
            nuke node: containerised nuke node object
        """

        # get main variables
        namespace = namespace or context["folder"]["name"]
        version_entity = context["version"]

        version_attributes = version_entity["attrib"]
        colorspace = version_attributes.get("colorSpace")

        object_name = "{}_{}".format(name, namespace)

        # prepare data for imprinting
        data_imprint = {
            "version": version_entity["version"],
            "colorspaceInput": colorspace
        }

        # add attributes from the version to imprint to metadata knob
        for k in ["source", "fps"]:
            data_imprint[k] = version_attributes[k]

        # getting file path
        file = self.filepath_from_context(context).replace("\\", "/")

        # adding nodes to node graph
        # just in case we are in group lets jump out of it
        nuke.endGroup()

        # Get mouse position
        n = nuke.createNode("NoOp")
        xcursor, ycursor = (n.xpos(), n.ypos())
        reset_selection()
        nuke.delete(n)

        bdn_frame = 50

        with maintained_selection():

            # add group from nk
            nuke.nodePaste(file)

            # get all pasted nodes
            new_nodes = list()
            nodes = nuke.selectedNodes()

            # get pointer position in DAG
            xpointer, ypointer = find_free_space_to_paste_nodes(
                nodes, direction="right", offset=200 + bdn_frame
            )

            # reset position to all nodes and replace inputs and output
            for n in nodes:
                reset_selection()
                xpos = (n.xpos() - xcursor) + xpointer
                ypos = (n.ypos() - ycursor) + ypointer
                n.setXYpos(xpos, ypos)

                # replace Input nodes for dots
                if n.Class() in "Input":
                    dot = nuke.createNode("Dot")
                    new_name = n.name().replace("INP", "DOT")
                    dot.setName(new_name)
                    dot["label"].setValue(new_name)
                    dot.setXYpos(xpos, ypos)
                    new_nodes.append(dot)

                    # rewire
                    dep = n.dependent()
                    for d in dep:
                        index = next((i for i, dpcy in enumerate(
                                      d.dependencies())
                                      if n is dpcy), 0)
                        d.setInput(index, dot)

                    # remove Input node
                    reset_selection()
                    nuke.delete(n)
                    continue

                # replace Input nodes for dots
                elif n.Class() in "Output":
                    dot = nuke.createNode("Dot")
                    new_name = n.name() + "_DOT"
                    dot.setName(new_name)
                    dot["label"].setValue(new_name)
                    dot.setXYpos(xpos, ypos)
                    new_nodes.append(dot)

                    # rewire
                    dep = next((d for d in n.dependencies()), None)
                    if dep:
                        dot.setInput(0, dep)

                    # remove Input node
                    reset_selection()
                    nuke.delete(n)
                    continue
                else:
                    new_nodes.append(n)

            # reselect nodes with new Dot instead of Inputs and Output
            reset_selection()
            select_nodes(new_nodes)
            # place on backdrop
            bdn = self.set_autobackdrop(xpos, ypos, object_name)
            return containerise(
                node=bdn,
                name=name,
                namespace=namespace,
                context=context,
                loader=self.__class__.__name__,
                data=data_imprint)

    def update(self, container, context):
        """Update the Loader's path

        Nuke automatically tries to reset some variables when changing
        the loader's path to a new file. These automatic changes are to its
        inputs:

        """

        # get main variables
        # Get version from io
        project_name = context["project"]["name"]
        version_entity = context["version"]
        repre_entity = context["representation"]

        # get corresponding node
        GN = container["node"]

        file = self.filepath_from_context(context).replace("\\", "/")

        name = container["name"]
        namespace = container["namespace"]
        object_name = "{}_{}".format(name, namespace)

        version_attributes = version_entity["attrib"]
        colorspace = version_attributes.get("colorSpace")

        data_imprint = {
            "representation": repre_entity["id"],
            "version": version_entity["version"],
            "colorspaceInput": colorspace,
        }

        for k in ["source", "fps"]:
            data_imprint[k] = version_attributes[k]

        # adding nodes to node graph
        # just in case we are in group lets jump out of it
        nuke.endGroup()

        xpos = GN.xpos()
        ypos = GN.ypos()
        avalon_data = get_avalon_knob_data(GN)

        # Preserve external connections (to/from outside the backdrop)
        backdrop_nodes = GN.getNodes()
        with restore_node_connections(backdrop_nodes):
            for node in backdrop_nodes:
                # Delete old backdrop nodes
                nuke.delete(node)
            nuke.delete(GN)

            with maintained_selection():
                # add group from nk
                nuke.nodePaste(file)
                # create new backdrop so that the nodes can be
                # filled within it
                GN = self.set_autobackdrop(xpos, ypos, object_name)
                set_avalon_knob_data(GN, avalon_data)

        # get all versions in list
        last_version_entity = ayon_api.get_last_version_by_product_id(
            project_name, version_entity["productId"], fields={"id"}
        )

        # change color of node
        if version_entity["id"] == last_version_entity["id"]:
            color_value = self.node_color
        else:
            color_value = "0xd88467ff"
        GN["tile_color"].setValue(int(color_value, 16))

        self.log.info(
            "updated to version: {}".format(version_entity["version"])
        )

        return update_container(GN, data_imprint)

    def switch(self, container, context):
        self.update(container, context)

    def remove(self, container):
        node = container["node"]
        with viewer_update_and_undo_stop():
            if self.remove_nodes_from_backdrop:
                for child_node in node.getNodes():
                    nuke.delete(child_node)
            nuke.delete(node)

    def set_autobackdrop(self, xpos, ypos, object_name, bdn_frame=50):
        """Set auto backdrop around selected nodes

        Args:
            xpos (int): x position
            ypos (int): y position
            object_name (str): name of the object
            bdn_frame (int, optional): frame size around the backdrop. Defaults to 50.

        Returns:
            nuke.BackdropNode: the created backdrop node
        """
        # place on backdrop
        bdn = nukescripts.autoBackdrop()

        # add frame offset
        xpos = bdn.xpos() - bdn_frame
        ypos = bdn.ypos() - bdn_frame
        bdwidth = bdn["bdwidth"].value() + (bdn_frame*2)
        bdheight = bdn["bdheight"].value() + (bdn_frame*2)

        bdn["xpos"].setValue(xpos)
        bdn["ypos"].setValue(ypos)
        bdn["bdwidth"].setValue(bdwidth)
        bdn["bdheight"].setValue(bdheight)

        bdn["name"].setValue(object_name)
        bdn["label"].setValue("Version tracked frame: \n`{}`\n\nPLEASE DO NOT REMOVE OR MOVE \nANYTHING FROM THIS FRAME!".format(object_name))
        bdn["note_font_size"].setValue(20)

        return bdn

load(context, name, namespace, data)

Loading function to import .nk file into script and wrap it on backdrop

Parameters:

Name Type Description Default
context dict

context of version

required
name str

name of the version

required
namespace str

namespace name

required
data dict

compulsory attribute > not used

required

Returns:

Type Description

nuke node: containerised nuke node object

Source code in client/ayon_nuke/plugins/load/load_backdrop.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def load(self, context, name, namespace, data):
    """
    Loading function to import .nk file into script and wrap
    it on backdrop

    Arguments:
        context (dict): context of version
        name (str): name of the version
        namespace (str): namespace name
        data (dict): compulsory attribute > not used

    Returns:
        nuke node: containerised nuke node object
    """

    # get main variables
    namespace = namespace or context["folder"]["name"]
    version_entity = context["version"]

    version_attributes = version_entity["attrib"]
    colorspace = version_attributes.get("colorSpace")

    object_name = "{}_{}".format(name, namespace)

    # prepare data for imprinting
    data_imprint = {
        "version": version_entity["version"],
        "colorspaceInput": colorspace
    }

    # add attributes from the version to imprint to metadata knob
    for k in ["source", "fps"]:
        data_imprint[k] = version_attributes[k]

    # getting file path
    file = self.filepath_from_context(context).replace("\\", "/")

    # adding nodes to node graph
    # just in case we are in group lets jump out of it
    nuke.endGroup()

    # Get mouse position
    n = nuke.createNode("NoOp")
    xcursor, ycursor = (n.xpos(), n.ypos())
    reset_selection()
    nuke.delete(n)

    bdn_frame = 50

    with maintained_selection():

        # add group from nk
        nuke.nodePaste(file)

        # get all pasted nodes
        new_nodes = list()
        nodes = nuke.selectedNodes()

        # get pointer position in DAG
        xpointer, ypointer = find_free_space_to_paste_nodes(
            nodes, direction="right", offset=200 + bdn_frame
        )

        # reset position to all nodes and replace inputs and output
        for n in nodes:
            reset_selection()
            xpos = (n.xpos() - xcursor) + xpointer
            ypos = (n.ypos() - ycursor) + ypointer
            n.setXYpos(xpos, ypos)

            # replace Input nodes for dots
            if n.Class() in "Input":
                dot = nuke.createNode("Dot")
                new_name = n.name().replace("INP", "DOT")
                dot.setName(new_name)
                dot["label"].setValue(new_name)
                dot.setXYpos(xpos, ypos)
                new_nodes.append(dot)

                # rewire
                dep = n.dependent()
                for d in dep:
                    index = next((i for i, dpcy in enumerate(
                                  d.dependencies())
                                  if n is dpcy), 0)
                    d.setInput(index, dot)

                # remove Input node
                reset_selection()
                nuke.delete(n)
                continue

            # replace Input nodes for dots
            elif n.Class() in "Output":
                dot = nuke.createNode("Dot")
                new_name = n.name() + "_DOT"
                dot.setName(new_name)
                dot["label"].setValue(new_name)
                dot.setXYpos(xpos, ypos)
                new_nodes.append(dot)

                # rewire
                dep = next((d for d in n.dependencies()), None)
                if dep:
                    dot.setInput(0, dep)

                # remove Input node
                reset_selection()
                nuke.delete(n)
                continue
            else:
                new_nodes.append(n)

        # reselect nodes with new Dot instead of Inputs and Output
        reset_selection()
        select_nodes(new_nodes)
        # place on backdrop
        bdn = self.set_autobackdrop(xpos, ypos, object_name)
        return containerise(
            node=bdn,
            name=name,
            namespace=namespace,
            context=context,
            loader=self.__class__.__name__,
            data=data_imprint)

set_autobackdrop(xpos, ypos, object_name, bdn_frame=50)

Set auto backdrop around selected nodes

Parameters:

Name Type Description Default
xpos int

x position

required
ypos int

y position

required
object_name str

name of the object

required
bdn_frame int

frame size around the backdrop. Defaults to 50.

50

Returns:

Type Description

nuke.BackdropNode: the created backdrop node

Source code in client/ayon_nuke/plugins/load/load_backdrop.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def set_autobackdrop(self, xpos, ypos, object_name, bdn_frame=50):
    """Set auto backdrop around selected nodes

    Args:
        xpos (int): x position
        ypos (int): y position
        object_name (str): name of the object
        bdn_frame (int, optional): frame size around the backdrop. Defaults to 50.

    Returns:
        nuke.BackdropNode: the created backdrop node
    """
    # place on backdrop
    bdn = nukescripts.autoBackdrop()

    # add frame offset
    xpos = bdn.xpos() - bdn_frame
    ypos = bdn.ypos() - bdn_frame
    bdwidth = bdn["bdwidth"].value() + (bdn_frame*2)
    bdheight = bdn["bdheight"].value() + (bdn_frame*2)

    bdn["xpos"].setValue(xpos)
    bdn["ypos"].setValue(ypos)
    bdn["bdwidth"].setValue(bdwidth)
    bdn["bdheight"].setValue(bdheight)

    bdn["name"].setValue(object_name)
    bdn["label"].setValue("Version tracked frame: \n`{}`\n\nPLEASE DO NOT REMOVE OR MOVE \nANYTHING FROM THIS FRAME!".format(object_name))
    bdn["note_font_size"].setValue(20)

    return bdn

update(container, context)

Update the Loader's path

Nuke automatically tries to reset some variables when changing the loader's path to a new file. These automatic changes are to its inputs:

Source code in client/ayon_nuke/plugins/load/load_backdrop.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def update(self, container, context):
    """Update the Loader's path

    Nuke automatically tries to reset some variables when changing
    the loader's path to a new file. These automatic changes are to its
    inputs:

    """

    # get main variables
    # Get version from io
    project_name = context["project"]["name"]
    version_entity = context["version"]
    repre_entity = context["representation"]

    # get corresponding node
    GN = container["node"]

    file = self.filepath_from_context(context).replace("\\", "/")

    name = container["name"]
    namespace = container["namespace"]
    object_name = "{}_{}".format(name, namespace)

    version_attributes = version_entity["attrib"]
    colorspace = version_attributes.get("colorSpace")

    data_imprint = {
        "representation": repre_entity["id"],
        "version": version_entity["version"],
        "colorspaceInput": colorspace,
    }

    for k in ["source", "fps"]:
        data_imprint[k] = version_attributes[k]

    # adding nodes to node graph
    # just in case we are in group lets jump out of it
    nuke.endGroup()

    xpos = GN.xpos()
    ypos = GN.ypos()
    avalon_data = get_avalon_knob_data(GN)

    # Preserve external connections (to/from outside the backdrop)
    backdrop_nodes = GN.getNodes()
    with restore_node_connections(backdrop_nodes):
        for node in backdrop_nodes:
            # Delete old backdrop nodes
            nuke.delete(node)
        nuke.delete(GN)

        with maintained_selection():
            # add group from nk
            nuke.nodePaste(file)
            # create new backdrop so that the nodes can be
            # filled within it
            GN = self.set_autobackdrop(xpos, ypos, object_name)
            set_avalon_knob_data(GN, avalon_data)

    # get all versions in list
    last_version_entity = ayon_api.get_last_version_by_product_id(
        project_name, version_entity["productId"], fields={"id"}
    )

    # change color of node
    if version_entity["id"] == last_version_entity["id"]:
        color_value = self.node_color
    else:
        color_value = "0xd88467ff"
    GN["tile_color"].setValue(int(color_value, 16))

    self.log.info(
        "updated to version: {}".format(version_entity["version"])
    )

    return update_container(GN, data_imprint)

restore_node_connections(backdrop_nodes)

Context manager to capture and restore node connections.

Captures all incoming and outgoing connections before backdrop nodes are deleted, then restores them after new nodes are pasted. Uses serialized node names to avoid "PythonObject not attached" errors.

Parameters:

Name Type Description Default
backdrop_nodes list

List of nodes whose connections to preserve.

required

Yields:

Type Description

None

Source code in client/ayon_nuke/plugins/load/load_backdrop.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
@contextlib.contextmanager
def restore_node_connections(backdrop_nodes):
    """Context manager to capture and restore node connections.

    Captures all incoming and outgoing connections before backdrop nodes
    are deleted, then restores them after new nodes are pasted.
    Uses serialized node names to avoid "PythonObject not attached" errors.

    Args:
        backdrop_nodes (list): List of nodes whose connections to preserve.

    Yields:
        None
    """
    original_connections = _capture_node_connections(backdrop_nodes)
    try:
        yield
    finally:
        # Build node map by name from current nodes
        node_map = {
            node.name(): node
            for node in nuke.allNodes()
        }
        # Restore connections using the node map
        for conn in original_connections:
            _restore_connection(conn, node_map)