Skip to content

pipeline

NukeHost

Bases: HostBase, IWorkfileHost, ILoadHost, IPublishHost

Source code in client/ayon_nuke/api/pipeline.py
 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
class NukeHost(
    HostBase, IWorkfileHost, ILoadHost, IPublishHost
):
    name = "nuke"
    about_to_save = False

    def get_app_information(self):
        return ApplicationInformation(
            app_name="Nuke",
            app_version=nuke.NUKE_VERSION_STRING,
        )

    def open_workfile(self, filepath):
        return open_file(filepath)

    def save_workfile(self, filepath=None):
        return save_file(filepath)

    def work_root(self, session):
        return work_root(session)

    def get_current_workfile(self):
        return current_file()

    def workfile_has_unsaved_changes(self):
        return has_unsaved_changes()

    def get_workfile_extensions(self):
        return file_extensions()

    def get_containers(self):
        return ls()

    def install(self):
        """Installing all requirements for Nuke host"""

        pyblish.api.register_host("nuke")

        self.log.info("Registering Nuke plug-ins..")
        pyblish.api.register_plugin_path(PUBLISH_PATH)
        register_loader_plugin_path(LOAD_PATH)
        register_creator_plugin_path(CREATE_PATH)
        register_inventory_action_path(INVENTORY_PATH)
        register_workfile_build_plugin_path(WORKFILE_BUILD_PATH)

    def setup_ui_callbacks_and_menu(self):
        """Setup AYON menus."""
        if not nuke.GUI:
            raise RuntimeError("Cannot set up in non-GUI mode.")

        project_settings = get_current_project_settings()
        add_nuke_callbacks(project_settings)

        _install_menu(project_settings)

        add_scripts_menu()
        add_scripts_gizmo()
        launch_workfiles_app()

    def get_context_data(self):
        root_node = nuke.root()
        return get_node_data(root_node, ROOT_DATA_KNOB)

    def update_context_data(self, data, changes):
        root_node = nuke.root()
        set_node_data(root_node, ROOT_DATA_KNOB, data)

    def _before_workfile_save(
        self, save_workfile_context: SaveWorkfileContext
    ) -> None:
        """Before workfile is saved.

        This method is called before the workfile is saved in the host.

        Args:
            save_workfile_context (SaveWorkfileContext): Workfile path with
                target folder and task context.

        """
        super()._before_workfile_save(save_workfile_context)
        self.about_to_save = True

    def _after_workfile_save(
        self, save_workfile_context: SaveWorkfileContext
    ) -> None:
        """After workfile is saved.

        This method is called after the workfile is saved in the host.

        Args:
            save_workfile_context (SaveWorkfileContext): Workfile path with
                target folder and task context.

        """
        super()._after_workfile_save(save_workfile_context)
        self.about_to_save = False

    def _after_context_change(self, context_change_data: ContextChangeData):
        """After context is changed.

        This method is called after the context is changed.

        Args:
            context_change_data (ContextChangeData): Object with information
                about context change.

        """
        super()._after_context_change(context_change_data)

        if not nuke.GUI:
            return

        change_context_label()

        if self.about_to_save:
            # Let's prompt the user to update the context settings or not
            prompt_reset_context()

install()

Installing all requirements for Nuke host

Source code in client/ayon_nuke/api/pipeline.py
131
132
133
134
135
136
137
138
139
140
141
def install(self):
    """Installing all requirements for Nuke host"""

    pyblish.api.register_host("nuke")

    self.log.info("Registering Nuke plug-ins..")
    pyblish.api.register_plugin_path(PUBLISH_PATH)
    register_loader_plugin_path(LOAD_PATH)
    register_creator_plugin_path(CREATE_PATH)
    register_inventory_action_path(INVENTORY_PATH)
    register_workfile_build_plugin_path(WORKFILE_BUILD_PATH)

setup_ui_callbacks_and_menu()

Setup AYON menus.

Source code in client/ayon_nuke/api/pipeline.py
143
144
145
146
147
148
149
150
151
152
153
154
155
def setup_ui_callbacks_and_menu(self):
    """Setup AYON menus."""
    if not nuke.GUI:
        raise RuntimeError("Cannot set up in non-GUI mode.")

    project_settings = get_current_project_settings()
    add_nuke_callbacks(project_settings)

    _install_menu(project_settings)

    add_scripts_menu()
    add_scripts_gizmo()
    launch_workfiles_app()

add_nuke_callbacks(project_settings=None)

Adding all available nuke callbacks

Source code in client/ayon_nuke/api/pipeline.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def add_nuke_callbacks(project_settings: dict = None):
    """Adding all available nuke callbacks"""
    if project_settings is None:
        project_settings = get_current_project_settings()

    nuke_settings = project_settings["nuke"]

    nuke.addOnCreate(on_root_create, nodeClass="Root")

    nuke.addOnScriptLoad(on_script_load)

    # set checker for last versions on loaded containers
    nuke.addOnScriptSave(check_inventory_versions)

    if nuke_settings["dirmap"]["enabled"]:
        log.info("Added Nuke's dir-mapping callback ...")
        # Add dirmap for file paths.
        nuke.addFilenameFilter(dirmap_file_name_filter)

    log.info("Added Nuke callbacks ...")

containerise(node, name, namespace, context, loader=None, data=None)

Bundle node into an assembly and imprint it with metadata

Containerisation enables a tracking of version, author and origin for loaded assets.

Parameters:

Name Type Description Default
node Node

Nuke's node object to imprint as container

required
name str

Name of resulting assembly

required
namespace str

Namespace under which to host container

required
context dict

Asset information

required
loader str

Name of node used to produce this container.

None

Returns:

Name Type Description
node Node

containerised nuke's node object

Source code in client/ayon_nuke/api/pipeline.py
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
def containerise(node,
                 name,
                 namespace,
                 context,
                 loader=None,
                 data=None):
    """Bundle `node` into an assembly and imprint it with metadata

    Containerisation enables a tracking of version, author and origin
    for loaded assets.

    Arguments:
        node (nuke.Node): Nuke's node object to imprint as container
        name (str): Name of resulting assembly
        namespace (str): Namespace under which to host container
        context (dict): Asset information
        loader (str, optional): Name of node used to produce this container.

    Returns:
        node (nuke.Node): containerised nuke's node object

    """
    data = OrderedDict(
        [
            ("schema", "ayon:container-3.0"),
            ("id", AVALON_CONTAINER_ID),
            ("name", name),
            ("namespace", namespace),
            ("loader", str(loader)),
            ("representation", context["representation"]["id"]),
            ("project_name", context["project"]["name"]),
        ],

        **data or dict()
    )

    set_avalon_knob_data(node, data)

    # set tab to first native
    node.setTab(0)

    return node

list_instances(creator_id=None)

List all created instances to publish from current workfile.

For SubsetManager

Parameters:

Name Type Description Default
creator_id Optional[str]

creator identifier

None

Returns:

Type Description

(list) of dictionaries matching instances format

Source code in client/ayon_nuke/api/pipeline.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
def list_instances(creator_id=None):
    """List all created instances to publish from current workfile.

    For SubsetManager

    Args:
        creator_id (Optional[str]): creator identifier

    Returns:
        (list) of dictionaries matching instances format
    """
    instances_by_order = defaultdict(list)
    product_instances = []
    instance_ids = set()

    for node in nuke.allNodes(recurseGroups=True):

        if node.Class() in ["Viewer", "Dot"]:
            continue

        try:
            if node["disable"].value():
                continue
        except NameError:
            # pass if disable knob doesn't exist
            pass

        # get data from avalon knob
        instance_data = get_node_data(
            node, INSTANCE_DATA_KNOB)

        if not instance_data:
            continue

        if instance_data["id"] not in {
            AYON_INSTANCE_ID, AVALON_INSTANCE_ID
        }:
            continue

        if creator_id and instance_data["creator_identifier"] != creator_id:
            continue

        instance_id = instance_data.get("instance_id")
        if not instance_id:
            pass
        elif instance_id in instance_ids:
            instance_data.pop("instance_id")
        else:
            instance_ids.add(instance_id)

        # node name could change, so update product name data
        _update_product_name_data(instance_data, node)

        if "render_order" not in node.knobs():
            product_instances.append((node, instance_data))
            continue

        order = int(node["render_order"].value())
        instances_by_order[order].append((node, instance_data))

    # Sort instances based on order attribute or product name.
    # TODO: remove in future Publisher enhanced with sorting
    ordered_instances = []
    for key in sorted(instances_by_order.keys()):
        instances_by_product = defaultdict(list)
        for node, data_ in instances_by_order[key]:
            product_name = data_.get("productName")
            if product_name is None:
                product_name = data_.get("subset")
            instances_by_product[product_name].append((node, data_))
        for subkey in sorted(instances_by_product.keys()):
            ordered_instances.extend(instances_by_product[subkey])

    instances_by_product = defaultdict(list)
    for node, data_ in product_instances:
        product_name = data_.get("productName")
        if product_name is None:
            product_name = data_.get("subset")
        instances_by_product[product_name].append((node, data_))
    for key in sorted(instances_by_product.keys()):
        ordered_instances.extend(instances_by_product[key])

    return ordered_instances

ls()

List available containers.

This function is used by the Container Manager in Nuke. You'll need to implement a for-loop that then yields one Container at a time.

Source code in client/ayon_nuke/api/pipeline.py
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
def ls():
    """List available containers.

    This function is used by the Container Manager in Nuke. You'll
    need to implement a for-loop that then *yields* one Container at
    a time.
    """
    all_nodes = nuke.allNodes(recurseGroups=True)

    nodes = [n for n in all_nodes]

    for n in nodes:
        container = parse_container(n)
        if container:
            yield container

on_root_create()

Callback function for on root node create.

Source code in client/ayon_nuke/api/pipeline.py
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
def on_root_create() -> None:
    """Callback function for on root node create."""
    # adding favorites to file browser
    workfile_settings = WorkfileSettings()
    workfile_settings.set_favorites()

    # Root created callback is also triggered on scene load because that also
    # creates a new root node. So we check if current file is None to run
    # logic that we only want to apply on new scene creation.
    if current_file() is None:
        on_script_create_settings = (
            workfile_settings.project_settings
            ["nuke"]
            ["workfile_callbacks"]
            ["on_script_create"]
        )

        if on_script_create_settings["set_resolution"]:
            workfile_settings.reset_resolution()

        if on_script_create_settings["set_frame_range"]:
            workfile_settings.reset_frame_range_handles()

        if on_script_create_settings["set_colorspace"]:
            workfile_settings.set_colorspace()

        start_workfile_template_builder()

on_script_load()

Callback function for on script load.

Source code in client/ayon_nuke/api/pipeline.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def on_script_load() -> None:
    """Callback function for on script load."""
    log.info("On script load...")
    # fix ffmpeg settings on script
    if nuke.env["LINUX"]:
        nuke.tcl('load ffmpegReader')
        nuke.tcl('load ffmpegWriter')
    else:
        nuke.tcl('load movReader')
        nuke.tcl('load movWriter')

    # set apply all workfile settings on script load and save
    workfile_settings = WorkfileSettings()
    on_script_load_settings = (
        workfile_settings.project_settings
        ["nuke"]
        ["workfile_callbacks"]
        ["on_script_open"]
    )

    if on_script_load_settings["set_resolution"]:
        workfile_settings.reset_resolution()

    if on_script_load_settings["set_frame_range"]:
        workfile_settings.reset_frame_range_handles()

    if on_script_load_settings["set_colorspace"]:
        workfile_settings.set_colorspace()

    # set checker for last versions on loaded containers
    check_inventory_versions()

parse_container(node)

Returns containerised data of a node

Reads the imprinted data from containerise.

Parameters:

Name Type Description Default
node Node

Nuke's node object to read imprinted data

required

Returns:

Name Type Description
dict

The container schema data for this container node.

Source code in client/ayon_nuke/api/pipeline.py
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
def parse_container(node):
    """Returns containerised data of a node

    Reads the imprinted data from `containerise`.

    Arguments:
        node (nuke.Node): Nuke's node object to read imprinted data

    Returns:
        dict: The container schema data for this container node.

    """
    data = read_avalon_data(node)

    # If not all required data return the empty container
    required = ["schema", "id", "name",
                "namespace", "loader", "representation"]
    if not all(key in data for key in required):
        return

    # Store the node's name
    data.update({
        "objectName": node.fullName(),
        "node": node,
    })

    return data

reload_config()

Attempt to reload pipeline at run-time.

CAUTION: This is primarily for development and debugging purposes.

Source code in client/ayon_nuke/api/pipeline.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def reload_config():
    """Attempt to reload pipeline at run-time.

    CAUTION: This is primarily for development and debugging purposes.

    """

    for module in (
        "ayon_nuke.api.actions",
        "ayon_nuke.api.menu",
        "ayon_nuke.api.plugin",
        "ayon_nuke.api.lib",
    ):
        log.info("Reloading module: {}...".format(module))

        module = importlib.import_module(module)

        try:
            importlib.reload(module)
        except AttributeError as e:
            from importlib import reload
            log.warning("Cannot reload module: {}".format(e))
            reload(module)

remove_instance(instance)

Remove instance from current workfile metadata.

For SubsetManager

Parameters:

Name Type Description Default
instance dict

instance representation from subsetmanager model

required
Source code in client/ayon_nuke/api/pipeline.py
776
777
778
779
780
781
782
783
784
785
786
787
def remove_instance(instance):
    """Remove instance from current workfile metadata.

    For SubsetManager

    Args:
        instance (dict): instance representation from subsetmanager model
    """
    instance_node = instance.transient_data["node"]
    instance_knob = instance_node.knobs()[INSTANCE_DATA_KNOB]
    instance_node.removeKnob(instance_knob)
    nuke.delete(instance_node)

select_instance(instance)

Select instance in Node View

Parameters:

Name Type Description Default
instance dict

instance representation from subsetmanager model

required
Source code in client/ayon_nuke/api/pipeline.py
790
791
792
793
794
795
796
797
798
def select_instance(instance):
    """
        Select instance in Node View

        Args:
            instance (dict): instance representation from subsetmanager model
    """
    instance_node = instance.transient_data["node"]
    instance_node["selected"].setValue(True)

start_workfile_template_builder()

Trigger workfile template builder when a new file is created.

Source code in client/ayon_nuke/api/pipeline.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def start_workfile_template_builder() -> None:
    """Trigger workfile template builder when a new file is created."""
    from .workfile_template_builder import (
        trigger_on_app_launch,
        trigger_on_new_file,
    )
    if not os.getenv("AYON_NUKE_INITIALIZED"):
        log.info("Triggering workfile template builder on application launch.")
        trigger_on_app_launch()
        # Track this at process level because the host instance may be
        # recreated or reloaded during Nuke's lifetime.
        # The environment marker persists across those reloads and ensures
        # the application-launch trigger runs only once.
        os.environ["AYON_NUKE_INITIALIZED"] = "True"
    else:
        log.info("Triggering workfile template builder on new file.")
        trigger_on_new_file()

update_container(node, keys=None)

Returns node with updateted containder data

Parameters:

Name Type Description Default
node Node

The node in Nuke to imprint as container,

required
keys dict

data which should be updated

None

Returns:

Name Type Description
node Node

nuke node with updated container data

Source code in client/ayon_nuke/api/pipeline.py
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def update_container(node, keys=None):
    """Returns node with updateted containder data

    Arguments:
        node (nuke.Node): The node in Nuke to imprint as container,
        keys (dict, optional): data which should be updated

    Returns:
        node (nuke.Node): nuke node with updated container data

    Raises:
        TypeError on given an invalid container node

    """
    keys = keys or dict()

    container = parse_container(node)
    if not container:
        raise TypeError("Not a valid container node.")

    container.update(keys)
    node = set_avalon_knob_data(node, container)

    return node