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
 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()

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

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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
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 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)

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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
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
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):
            for attr, value in attrs.items():
                avalon_prop = node.get(pipeline.AVALON_PROPERTY)
                if not avalon_prop:
                    continue
                if (avalon_prop.get(attr)
                        and (value is None or avalon_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
333
334
335
336
337
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
@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
369
370
371
372
373
374
375
376
@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

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()

read(node)

Return user-defined attributes from node

Source code in client/ayon_blender/api/lib.py
264
265
266
267
268
269
270
271
272
273
274
275
def read(node: bpy.types.bpy_struct_meta_idprop):
    """Return user-defined attributes from `node`"""

    data = dict(node.get(pipeline.AVALON_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 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()

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