Skip to content

pipeline

BlenderHost

Bases: HostBase, IWorkfileHost, IPublishHost, ILoadHost

Source code in client/ayon_blender/api/pipeline.py
 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
class BlenderHost(HostBase, IWorkfileHost, IPublishHost, ILoadHost):
    name = "blender"

    def install(self):
        """Override install method from HostBase.
        Install Blender host functionality."""
        install()

    def get_containers(self) -> Iterator:
        """List containers from active Blender scene."""
        return ls()

    def get_workfile_extensions(self) -> List[str]:
        """Override get_workfile_extensions method from IWorkfileHost.
        Get workfile possible extensions.

        Returns:
            List[str]: Workfile extensions.
        """
        return file_extensions()

    def save_workfile(self, dst_path: str = None):
        """Override save_workfile method from IWorkfileHost.
        Save currently opened workfile.

        Args:
            dst_path (str): Where the current scene should be saved. Or use
                current path if `None` is passed.
        """
        save_file(dst_path if dst_path else bpy.data.filepath)

    def open_workfile(self, filepath: str):
        """Override open_workfile method from IWorkfileHost.
        Open workfile at specified filepath in the host.

        Args:
            filepath (str): Path to workfile.
        """
        open_file(filepath)

    def get_current_workfile(self) -> str:
        """Override get_current_workfile method from IWorkfileHost.
        Retrieve currently opened workfile path.

        Returns:
            str: Path to currently opened workfile.
        """
        return current_file()

    def workfile_has_unsaved_changes(self) -> bool:
        """Override wokfile_has_unsaved_changes method from IWorkfileHost.
        Returns True if opened workfile has no unsaved changes.

        Returns:
            bool: True if scene is saved and False if it has unsaved
                modifications.
        """
        return has_unsaved_changes()

    def work_root(self, session) -> str:
        """Override work_root method from IWorkfileHost.
        Modify workdir per host.

        Args:
            session (dict): Session context data.

        Returns:
            str: Path to new workdir.
        """
        return work_root(session)

    def get_context_data(self) -> dict:
        """Override abstract method from IPublishHost.
        Get global data related to creation-publishing from workfile.

        Returns:
            dict: Context data stored using 'update_context_data'.
        """
        property = bpy.context.scene.get(AVALON_PROPERTY)
        if property:
            return property.to_dict()
        return {}

    def update_context_data(self, data: dict, changes: dict):
        """Override abstract method from IPublishHost.
        Store global context data to workfile.

        Args:
            data (dict): New data as are.
            changes (dict): Only data that has been changed. Each value has
                tuple with '(<old>, <new>)' value.
        """
        bpy.context.scene[AVALON_PROPERTY] = data

get_containers()

List containers from active Blender scene.

Source code in client/ayon_blender/api/pipeline.py
74
75
76
def get_containers(self) -> Iterator:
    """List containers from active Blender scene."""
    return ls()

get_context_data()

Override abstract method from IPublishHost. Get global data related to creation-publishing from workfile.

Returns:

Name Type Description
dict dict

Context data stored using 'update_context_data'.

Source code in client/ayon_blender/api/pipeline.py
137
138
139
140
141
142
143
144
145
146
147
def get_context_data(self) -> dict:
    """Override abstract method from IPublishHost.
    Get global data related to creation-publishing from workfile.

    Returns:
        dict: Context data stored using 'update_context_data'.
    """
    property = bpy.context.scene.get(AVALON_PROPERTY)
    if property:
        return property.to_dict()
    return {}

get_current_workfile()

Override get_current_workfile method from IWorkfileHost. Retrieve currently opened workfile path.

Returns:

Name Type Description
str str

Path to currently opened workfile.

Source code in client/ayon_blender/api/pipeline.py
106
107
108
109
110
111
112
113
def get_current_workfile(self) -> str:
    """Override get_current_workfile method from IWorkfileHost.
    Retrieve currently opened workfile path.

    Returns:
        str: Path to currently opened workfile.
    """
    return current_file()

get_workfile_extensions()

Override get_workfile_extensions method from IWorkfileHost. Get workfile possible extensions.

Returns:

Type Description
List[str]

List[str]: Workfile extensions.

Source code in client/ayon_blender/api/pipeline.py
78
79
80
81
82
83
84
85
def get_workfile_extensions(self) -> List[str]:
    """Override get_workfile_extensions method from IWorkfileHost.
    Get workfile possible extensions.

    Returns:
        List[str]: Workfile extensions.
    """
    return file_extensions()

install()

Override install method from HostBase. Install Blender host functionality.

Source code in client/ayon_blender/api/pipeline.py
69
70
71
72
def install(self):
    """Override install method from HostBase.
    Install Blender host functionality."""
    install()

open_workfile(filepath)

Override open_workfile method from IWorkfileHost. Open workfile at specified filepath in the host.

Parameters:

Name Type Description Default
filepath str

Path to workfile.

required
Source code in client/ayon_blender/api/pipeline.py
 97
 98
 99
100
101
102
103
104
def open_workfile(self, filepath: str):
    """Override open_workfile method from IWorkfileHost.
    Open workfile at specified filepath in the host.

    Args:
        filepath (str): Path to workfile.
    """
    open_file(filepath)

save_workfile(dst_path=None)

Override save_workfile method from IWorkfileHost. Save currently opened workfile.

Parameters:

Name Type Description Default
dst_path str

Where the current scene should be saved. Or use current path if None is passed.

None
Source code in client/ayon_blender/api/pipeline.py
87
88
89
90
91
92
93
94
95
def save_workfile(self, dst_path: str = None):
    """Override save_workfile method from IWorkfileHost.
    Save currently opened workfile.

    Args:
        dst_path (str): Where the current scene should be saved. Or use
            current path if `None` is passed.
    """
    save_file(dst_path if dst_path else bpy.data.filepath)

update_context_data(data, changes)

Override abstract method from IPublishHost. Store global context data to workfile.

Parameters:

Name Type Description Default
data dict

New data as are.

required
changes dict

Only data that has been changed. Each value has tuple with '(, )' value.

required
Source code in client/ayon_blender/api/pipeline.py
149
150
151
152
153
154
155
156
157
158
def update_context_data(self, data: dict, changes: dict):
    """Override abstract method from IPublishHost.
    Store global context data to workfile.

    Args:
        data (dict): New data as are.
        changes (dict): Only data that has been changed. Each value has
            tuple with '(<old>, <new>)' value.
    """
    bpy.context.scene[AVALON_PROPERTY] = data

work_root(session)

Override work_root method from IWorkfileHost. Modify workdir per host.

Parameters:

Name Type Description Default
session dict

Session context data.

required

Returns:

Name Type Description
str str

Path to new workdir.

Source code in client/ayon_blender/api/pipeline.py
125
126
127
128
129
130
131
132
133
134
135
def work_root(self, session) -> str:
    """Override work_root method from IWorkfileHost.
    Modify workdir per host.

    Args:
        session (dict): Session context data.

    Returns:
        str: Path to new workdir.
    """
    return work_root(session)

workfile_has_unsaved_changes()

Override wokfile_has_unsaved_changes method from IWorkfileHost. Returns True if opened workfile has no unsaved changes.

Returns:

Name Type Description
bool bool

True if scene is saved and False if it has unsaved modifications.

Source code in client/ayon_blender/api/pipeline.py
115
116
117
118
119
120
121
122
123
def workfile_has_unsaved_changes(self) -> bool:
    """Override wokfile_has_unsaved_changes method from IWorkfileHost.
    Returns True if opened workfile has no unsaved changes.

    Returns:
        bool: True if scene is saved and False if it has unsaved
            modifications.
    """
    return has_unsaved_changes()

add_to_avalon_container(container)

Add the container to the Avalon container.

Source code in client/ayon_blender/api/pipeline.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
def add_to_avalon_container(container: bpy.types.Collection):
    """Add the container to the Avalon container."""

    avalon_container = bpy.data.collections.get(AVALON_CONTAINERS)
    if not avalon_container:
        avalon_container = bpy.data.collections.new(name=AVALON_CONTAINERS)

        # Link the container to the scene so it's easily visible to the artist
        # and can be managed easily. Otherwise it's only found in "Blender
        # File" view and it will be removed by Blenders garbage collection,
        # unless you set a 'fake user'.
        bpy.context.scene.collection.children.link(avalon_container)

    avalon_container.children.link(container)

    # Disable Avalon containers for the view layers.
    for view_layer in bpy.context.scene.view_layers:
        for child in view_layer.layer_collection.children:
            if child.collection == avalon_container:
                child.exclude = True

containerise(name, namespace, nodes, context, loader=None, suffix='CON')

Bundle nodes 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
name str

Name of resulting assembly

required
namespace str

Namespace under which to host container

required
nodes List

Long names of nodes to containerise

required
context Dict

Asset information

required
loader Optional[str]

Name of loader used to produce this container.

None
suffix Optional[str]

Suffix of container, defaults to _CON.

'CON'

Returns:

Type Description
Collection

The container assembly

Source code in client/ayon_blender/api/pipeline.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
def containerise(name: str,
                 namespace: str,
                 nodes: List,
                 context: Dict,
                 loader: Optional[str] = None,
                 suffix: Optional[str] = "CON") -> bpy.types.Collection:
    """Bundle `nodes` into an assembly and imprint it with metadata

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

    Arguments:
        name: Name of resulting assembly
        namespace: Namespace under which to host container
        nodes: Long names of nodes to containerise
        context: Asset information
        loader: Name of loader used to produce this container.
        suffix: Suffix of container, defaults to `_CON`.

    Returns:
        The container assembly

    """

    node_name = f"{context['folder']['name']}_{name}"
    if namespace:
        node_name = f"{namespace}:{node_name}"
    if suffix:
        node_name = f"{node_name}_{suffix}"
    container = bpy.data.collections.new(name=node_name)
    # Link the children nodes
    for obj in nodes:
        container.objects.link(obj)

    data = {
        "schema": "openpype:container-2.0",
        "id": AVALON_CONTAINER_ID,
        "name": name,
        "namespace": namespace or '',
        "loader": str(loader),
        "representation": context["representation"]["id"],
    }

    metadata_update(container, data)
    add_to_avalon_container(container)

    return container

containerise_existing(container, name, namespace, context, loader=None, suffix='CON')

Imprint or update container with metadata.

Parameters:

Name Type Description Default
name str

Name of resulting assembly

required
namespace str

Namespace under which to host container

required
context Dict

Asset information

required
loader Optional[str]

Name of loader used to produce this container.

None
suffix Optional[str]

Suffix of container, defaults to _CON.

'CON'

Returns:

Type Description
Collection

The container assembly

Source code in client/ayon_blender/api/pipeline.py
548
549
550
551
552
553
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
def containerise_existing(
        container: bpy.types.Collection,
        name: str,
        namespace: str,
        context: Dict,
        loader: Optional[str] = None,
        suffix: Optional[str] = "CON") -> bpy.types.Collection:
    """Imprint or update container with metadata.

    Arguments:
        name: Name of resulting assembly
        namespace: Namespace under which to host container
        context: Asset information
        loader: Name of loader used to produce this container.
        suffix: Suffix of container, defaults to `_CON`.

    Returns:
        The container assembly
    """

    node_name = container.name
    if suffix:
        node_name = f"{node_name}_{suffix}"
    container.name = node_name
    data = {
        "schema": "openpype:container-2.0",
        "id": AVALON_CONTAINER_ID,
        "name": name,
        "namespace": namespace or '',
        "loader": str(loader),
        "representation": context["representation"]["id"],
        "project_name": context["project"]["name"],
    }

    metadata_update(container, data)
    add_to_avalon_container(container)

    return container

get_frame_range(task_entity=None)

Get the task entity's frame range and handles

Parameters:

Name Type Description Default
task_entity Optional[dict]

Task Entity. When not provided defaults to current context task.

None

Returns:

Type Description
Union[Dict[str, int], None]

Union[Dict[str, int], None]: Dictionary with frame start, frame end, handle start, handle end.

Source code in client/ayon_blender/api/pipeline.py
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
def get_frame_range(task_entity=None) -> Union[Dict[str, int], None]:
    """Get the task entity's frame range and handles

    Args:
        task_entity (Optional[dict]): Task Entity.
            When not provided defaults to current context task.

    Returns:
        Union[Dict[str, int], None]: Dictionary with
            frame start, frame end, handle start, handle end.
    """
    # Set frame start/end
    if task_entity is None:
        task_entity = get_current_task_entity(fields={"attrib"})
    task_attributes = task_entity["attrib"]
    frame_start = int(task_attributes["frameStart"])
    frame_end = int(task_attributes["frameEnd"])
    handle_start = int(task_attributes["handleStart"])
    handle_end = int(task_attributes["handleEnd"])
    frame_start_handle = frame_start - handle_start
    frame_end_handle = frame_end + handle_end

    return {
        "frameStart": frame_start,
        "frameEnd": frame_end,
        "handleStart": handle_start,
        "handleEnd": handle_end,
        "frameStartHandle": frame_start_handle,
        "frameEndHandle": frame_end_handle,
    }

install()

Install Blender configuration for Avalon.

Source code in client/ayon_blender/api/pipeline.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def install():
    """Install Blender configuration for Avalon."""
    sys.excepthook = pype_excepthook_handler

    pyblish.api.register_host("blender")
    pyblish.api.register_plugin_path(str(PUBLISH_PATH))

    register_loader_plugin_path(str(LOAD_PATH))
    register_creator_plugin_path(str(CREATE_PATH))

    lib.append_user_scripts()
    lib.set_app_templates_path()

    register_event_callback("new", on_new)
    register_event_callback("open", on_open)

    _register_callbacks()
    _register_events()

    if not IS_HEADLESS:
        ops.register()

ls()

List containers from active Blender scene.

This is the host-equivalent of api.ls(), but instead of listing assets on disk, it lists assets already loaded in Blender; once loaded they are called containers.

Source code in client/ayon_blender/api/pipeline.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
def ls() -> Iterator:
    """List containers from active Blender scene.

    This is the host-equivalent of api.ls(), but instead of listing assets on
    disk, it lists assets already loaded in Blender; once loaded they are
    called containers.
    """
    container_ids = {
        AYON_CONTAINER_ID,
        # Backwards compatibility
        AVALON_CONTAINER_ID
    }

    for id_type in container_ids:
        for container in lib.lsattr("id", id_type):
            yield parse_container(container)

    # Compositor nodes are not in `bpy.data` that `lib.lsattr` looks in.
    node_tree = bpy.context.scene.node_tree
    if node_tree:
        for node in node_tree.nodes:
            if not node.get(AVALON_PROPERTY):
                continue

            if node.get(AVALON_PROPERTY).get("id") not in container_ids:
                continue

            yield parse_container(node)

    # Shader nodes are not available in a way that `lib.lsattr` can find.
    for material in bpy.data.materials:
        material_node_tree = material.node_tree
        if not material_node_tree:
            continue

        for shader_node in material_node_tree.nodes:
            if not shader_node.get(AVALON_PROPERTY):
                continue

            if shader_node.get(AVALON_PROPERTY).get("id") not in container_ids:
                continue

            yield parse_container(shader_node)

metadata_update(node, data)

Imprint the node with metadata.

Existing metadata will be updated.

Source code in client/ayon_blender/api/pipeline.py
485
486
487
488
489
490
491
492
493
494
495
496
def metadata_update(node: bpy.types.bpy_struct_meta_idprop, data: Dict):
    """Imprint the node with metadata.

    Existing metadata will be updated.
    """

    if not node.get(AVALON_PROPERTY):
        node[AVALON_PROPERTY] = dict()
    for key, value in data.items():
        if value is None:
            continue
        node[AVALON_PROPERTY][key] = value

parse_container(container, validate=True)

Return the container node's full container data.

Parameters:

Name Type Description Default
container Collection

A container node name.

required
validate bool

turn the validation for the container on or off

True

Returns:

Type Description
Dict

The container schema data for this container node.

Source code in client/ayon_blender/api/pipeline.py
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def parse_container(container: bpy.types.Collection,
                    validate: bool = True) -> Dict:
    """Return the container node's full container data.

    Args:
        container: A container node name.
        validate: turn the validation for the container on or off

    Returns:
        The container schema data for this container node.

    """

    data = lib.read(container)

    # Append transient data
    data["objectName"] = container.name
    data["node"] = container  # store parsed object for easy access in loader

    if validate:
        schema.validate(data)

    return data

publish()

Shorthand to publish from within host.

Source code in client/ayon_blender/api/pipeline.py
658
659
660
661
def publish():
    """Shorthand to publish from within host."""

    return pyblish.util.publish()

uninstall()

Uninstall Blender configuration for Avalon.

Source code in client/ayon_blender/api/pipeline.py
188
189
190
191
192
193
194
195
196
197
198
199
def uninstall():
    """Uninstall Blender configuration for Avalon."""
    sys.excepthook = ORIGINAL_EXCEPTHOOK

    pyblish.api.deregister_host("blender")
    pyblish.api.deregister_plugin_path(str(PUBLISH_PATH))

    deregister_loader_plugin_path(str(LOAD_PATH))
    deregister_creator_plugin_path(str(CREATE_PATH))

    if not IS_HEADLESS:
        ops.unregister()