Skip to content

api

Public API

Anything that isn't defined here is INTERNAL and unreliable for external use.

BlenderHost

Bases: HostBase, IWorkfileHost, IPublishHost, ILoadHost

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

    def get_app_information(self):
        from ayon_core.host import ApplicationInformation

        return ApplicationInformation(
            app_name="Blender",
            app_version=bpy.app.version_string,
        )

    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(AYON_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[AYON_PROPERTY] = data

get_containers()

List containers from active Blender scene.

Source code in client/ayon_blender/api/pipeline.py
88
89
90
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
151
152
153
154
155
156
157
158
159
160
161
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(AYON_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
120
121
122
123
124
125
126
127
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
92
93
94
95
96
97
98
99
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
83
84
85
86
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
111
112
113
114
115
116
117
118
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
101
102
103
104
105
106
107
108
109
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
163
164
165
166
167
168
169
170
171
172
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[AYON_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
139
140
141
142
143
144
145
146
147
148
149
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
129
130
131
132
133
134
135
136
137
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()

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
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
656
657
658
659
660
661
662
663
664
665
666
667
668
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 = get_container_name(name, namespace, context, suffix)
    container = bpy.data.collections.new(name=node_name)
    # Link the children nodes
    for obj in nodes:
        if isinstance(obj, bpy.types.Object):
            container.objects.link(obj)
        elif isinstance(obj, bpy.types.Collection):
            container.children.link(obj)
        else:
            raise TypeError(f"Unsupported type {type(obj)} in nodes list.")

    data = {
        "schema": "ayon:container-3.0",
        "id": AYON_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_ayon_container(container)

    return container

current_file()

Return the path of the open scene file.

Source code in client/ayon_blender/api/workio.py
61
62
63
64
65
66
67
def current_file() -> Optional[str]:
    """Return the path of the open scene file."""

    current_filepath = bpy.data.filepath
    if Path(current_filepath).is_file():
        return current_filepath
    return None

file_extensions()

Return the supported file extensions for Blender scene files.

Source code in client/ayon_blender/api/workio.py
76
77
78
79
def file_extensions() -> List[str]:
    """Return the supported file extensions for Blender scene files."""

    return [".blend"]

get_selection(include_collections=False)

Returns a list of selected objects in the current Blender scene.

Parameters:

Name Type Description Default
include_collections bool

Whether to include selected

False

Returns:

Type Description
List[Object]

List[bpy.types.Object]: A list of selected objects.

Source code in client/ayon_blender/api/lib.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def get_selection(include_collections: bool = False) -> List[bpy.types.Object]:
    """
    Returns a list of selected objects in the current Blender scene.

    Args:
        include_collections (bool, optional): Whether to include selected
        collections in the result. Defaults to False.

    Returns:
        List[bpy.types.Object]: A list of selected objects.
    """
    selection = [obj for obj in bpy.context.scene.objects if obj.select_get()]

    if include_collections:
        selection.extend(get_selected_collections())

    return selection

has_unsaved_changes()

Does the open scene file have unsaved changes?

Source code in client/ayon_blender/api/workio.py
70
71
72
73
def has_unsaved_changes() -> bool:
    """Does the open scene file have unsaved changes?"""

    return bpy.data.is_dirty

install()

Install Blender configuration for AYON.

Source code in client/ayon_blender/api/pipeline.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def install():
    """Install Blender configuration for AYON."""
    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_event_callback("before.save", on_before_save)

    _register_callbacks()

    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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
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:
            ayon_prop = node.get(AYON_PROPERTY)
            if not ayon_prop:
                avalon_prop = node.get(AVALON_PROPERTY)
                if not avalon_prop:
                    continue
                else:
                    node[AYON_PROPERTY] = avalon_prop
                    ayon_prop = avalon_prop
                    del node[AVALON_PROPERTY]

            if ayon_prop.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:
            ayon_shader_node = get_ayon_property(shader_node)
            if not ayon_shader_node:
                continue

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

            yield parse_container(shader_node)

lsattr(attr, value=None)

Return nodes matching attr and value

Parameters:

Name Type Description Default
attr str

Name of Blender property

required
value Union[str, int, bool, List, Dict, None]

Value of attribute. If none is provided, return all nodes with this attribute.

None
Example

lsattr("id", "myId") ... [bpy.data.objects["myNode"] lsattr("id") ... [bpy.data.objects["myNode"], bpy.data.objects["myOtherNode"]]

Returns:

Type Description
List

list

Source code in client/ayon_blender/api/lib.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def lsattr(attr: str,
           value: Union[str, int, bool, List, Dict, None] = None) -> List:
    r"""Return nodes matching `attr` and `value`

    Arguments:
        attr: Name of Blender property
        value: Value of attribute. If none
            is provided, return all nodes with this attribute.

    Example:
        >>> lsattr("id", "myId")
        ...   [bpy.data.objects["myNode"]
        >>> lsattr("id")
        ...   [bpy.data.objects["myNode"], bpy.data.objects["myOtherNode"]]

    Returns:
        list
    """

    return lsattrs({attr: value})

lsattrs(attrs)

Return nodes with the given attribute(s).

Parameters:

Name Type Description Default
attrs Dict

Name and value pairs of expected matches

required
Example

lsattrs({"age": 5}) # Return nodes with an age of 5

Return nodes with both age and color of 5 and blue

lsattrs({"age": 5, "color": "blue"})

Returns a list.

Source code in client/ayon_blender/api/lib.py
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
def lsattrs(attrs: Dict) -> List:
    r"""Return nodes with the given attribute(s).

    Arguments:
        attrs: Name and value pairs of expected matches

    Example:
        >>> lsattrs({"age": 5})  # Return nodes with an `age` of 5
        # Return nodes with both `age` and `color` of 5 and blue
        >>> lsattrs({"age": 5, "color": "blue"})

    Returns a list.

    """

    # For now return all objects, not filtered by scene/collection/view_layer.
    matches = set()
    for coll in dir(bpy.data):
        if not isinstance(
                getattr(bpy.data, coll),
                bpy.types.bpy_prop_collection,
        ):
            continue
        for node in getattr(bpy.data, coll):
            ayon_prop = pipeline.get_ayon_property(node)
            if not ayon_prop:
                continue

            for attr, value in attrs.items():
                if (ayon_prop.get(attr)
                        and (value is None or ayon_prop.get(attr) == value)):
                    matches.add(node)
    return list(matches)

maintained_selection()

Maintain selection during context

Example

with maintained_selection(): ... # Modify selection ... bpy.ops.object.select_all(action='DESELECT')

Selection restored

Source code in client/ayon_blender/api/lib.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
@contextlib.contextmanager
def maintained_selection():
    r"""Maintain selection during context

    Example:
        >>> with maintained_selection():
        ...     # Modify selection
        ...     bpy.ops.object.select_all(action='DESELECT')
        >>> # Selection restored
    """

    previous_selection = get_selection()
    previous_active = bpy.context.view_layer.objects.active
    try:
        yield
    finally:
        # Clear the selection
        for node in get_selection():
            node.select_set(state=False)
        if previous_selection:
            for node in previous_selection:
                try:
                    node.select_set(state=True)
                except ReferenceError:
                    # This could happen if a selected node was deleted during
                    # the context.
                    log.exception("Failed to reselect")
                    continue
        try:
            bpy.context.view_layer.objects.active = previous_active
        except ReferenceError:
            # This could happen if the active node was deleted during the
            # context.
            log.exception("Failed to set active object.")

maintained_time()

Maintain current frame during context.

Source code in client/ayon_blender/api/lib.py
374
375
376
377
378
379
380
381
@contextlib.contextmanager
def maintained_time():
    """Maintain current frame during context."""
    current_time = bpy.context.scene.frame_current
    try:
        yield
    finally:
        bpy.context.scene.frame_current = current_time

open_file(filepath)

Open the scene file in Blender.

Source code in client/ayon_blender/api/workio.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def open_file(filepath: str) -> Optional[str]:
    """Open the scene file in Blender."""
    OpenFileCacher.set_opening()

    preferences = bpy.context.preferences
    load_ui = preferences.filepaths.use_load_ui
    use_scripts = preferences.filepaths.use_scripts_auto_execute
    result = bpy.ops.wm.open_mainfile(
        filepath=filepath,
        load_ui=load_ui,
        use_scripts=use_scripts,
    )

    if result == {'FINISHED'}:
        return filepath
    return None

prepare_rendering(variant_name, project_settings=None)

Initialize render setup using render settings from project settings.

Source code in client/ayon_blender/api/render_lib.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
def prepare_rendering(
    variant_name: str, project_settings: Optional[dict] = None
) -> "bpy.types.CompositorNodeOutputFile":
    """Initialize render setup using render settings from project settings."""
    assert bpy.data.filepath, "Workfile not saved. Please save the file first."

    if project_settings is None:
        project_name: str = get_current_project_name()
        project_settings = get_project_settings(project_name)

    ext = get_image_format(project_settings)
    multilayer = get_multilayer(project_settings)
    renderer = get_renderer(project_settings)
    ver_major, ver_minor, _ = lib.get_blender_version()
    if renderer == "BLENDER_EEVEE" and (
        ver_major >= 4 and ver_minor >=2
    ):
        renderer = "BLENDER_EEVEE_NEXT"

    # Set scene render settings
    set_render_format(ext, multilayer)
    bpy.context.scene.render.engine = renderer
    view_layers = bpy.context.scene.view_layers
    set_render_passes(project_settings, renderer, view_layers)

    # Ensure compositor nodes are enabled before accessing node tree
    if not bpy.context.scene.use_nodes:
        bpy.context.scene.use_nodes = True

    # Use selected renderlayer nodes, or assume we want a renderlayer node for
    # each view layer so we retrieve all of them.
    node_tree = bpy.context.scene.node_tree
    selected_renderlayer_nodes = []

    # Check if node_tree is available before accessing nodes
    if node_tree is not None:
        for node in node_tree.nodes:
            if node.bl_idname == "CompositorNodeRLayers" and node.select:
                selected_renderlayer_nodes.append(node)

    if selected_renderlayer_nodes:
        render_layer_nodes = selected_renderlayer_nodes
    else:
        render_layer_nodes = get_or_create_render_layer_nodes(view_layers)

    # Generate Compositing nodes
    output_node = create_render_node_tree(
        variant_name,
        render_layer_nodes,
        project_settings
    )

    set_tmp_scene_render_output_path(project_settings)
    bpy.context.scene.render.use_overwrite = True

    return output_node

publish()

Shorthand to publish from within host.

Source code in client/ayon_blender/api/pipeline.py
789
790
791
792
def publish():
    """Shorthand to publish from within host."""

    return pyblish.util.publish()

read(node)

Return user-defined attributes from node

Source code in client/ayon_blender/api/lib.py
269
270
271
272
273
274
275
276
277
278
279
280
def read(node: bpy.types.bpy_struct_meta_idprop):
    """Return user-defined attributes from `node`"""

    data = dict(node.get(AYON_PROPERTY, {}))

    # Ignore hidden/internal data
    data = {
        key: value
        for key, value in data.items() if not key.startswith("_")
    }

    return data

save_file(filepath, copy=False)

Save the open scene file.

Source code in client/ayon_blender/api/workio.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def save_file(filepath: str, copy: bool = False) -> Optional[str]:
    """Save the open scene file."""

    preferences = bpy.context.preferences
    compress = preferences.filepaths.use_file_compression
    relative_remap = preferences.filepaths.use_relative_paths
    result = bpy.ops.wm.save_as_mainfile(
        filepath=filepath,
        compress=compress,
        relative_remap=relative_remap,
        copy=copy,
    )

    if result == {'FINISHED'}:
        return filepath
    return None

uninstall()

Uninstall Blender configuration for AYON.

Source code in client/ayon_blender/api/pipeline.py
202
203
204
205
206
207
208
209
210
211
212
213
def uninstall():
    """Uninstall Blender configuration for AYON."""
    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()

work_root(session)

Return the default root to browse for work files.

Source code in client/ayon_blender/api/workio.py
82
83
84
85
86
87
88
89
def work_root(session: dict) -> str:
    """Return the default root to browse for work files."""

    work_dir = session["AYON_WORKDIR"]
    scene_dir = session.get("AVALON_SCENEDIR")
    if scene_dir:
        return str(Path(work_dir, scene_dir))
    return work_dir