Skip to content

usd_chunks.chunk

The client-facing chunk API: the concrete chunk, group and param classes.

These classes can be used by themselves, but they also describe common UI information, which makes them easy to implement in any UI framework.

As all chunk classes use chunk_core.AttributesMetaclass, they are all attrs classes (dataclasses). Creating a new param class only takes declaring the class and inheriting from ChunkParamBase or a related base class. The class is wrapped in attrs.define() behind the scenes, so it gets some methods for free, most notably __init__(), built from all the fields of the class, inherited ones included. For this reason, any attribute of a chunk class should be declared with attrs.field().

A class inheriting from ChunkParamBase needs to implement get_type, and evaluate_type too if the type can change at runtime. That is what maps a param to a widget in whatever UI framework is used.

Example

class CustomStrParam(ChunkParamBase[str]):
    some_attrib: str = attrs.field(default="hello")

    @classmethod
    def get_type(cls) -> ChunkFlags.ParamType:
        return ChunkFlags.ParamType.LINEEDIT

In a chunk module, chunk.Chunk() is the top-level container that every param and group is added to. A chunk with a button is as simple as:

Example

from usd_chunks import chunk


def main():
    my_chunk = chunk.Chunk("my_chunk")
    button = chunk.Button("my_button")

    my_chunk.add_param(button)
    return my_chunk

See example for a more extensive example.

Button ⚓︎

Button(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=0, default_value=None, custom_widget=None)

Bases: ChunkParamBase

A button param.

It stores no usable value and is used with callbacks only.

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
0
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

click ⚓︎

click()

Click the button, triggering its connected callbacks.

Source code in usd_chunks/chunk.py
def click(self):
    """Click the button, triggering its connected callbacks."""
    self.get_attribute_sender("value").execute()

Chunk ⚓︎

Chunk(name='', label='', tooltip='', icon='', user_data={}, layout=1, state=0, flags=7, widget_factory=None, prim_path=None, gizmo=None)

Bases: ChunkBase

Chunk is the top level container, holding params and groups which in turn make up the final, displayed chunk.

gizmo="transform" declares a single whole-chunk manipulator -- in effect "host, run your native transform handle and give me the result". It absorbs the gizmo= groups below it into one handle instead of leaving three:

chunk_api = chunk.Chunk("Transform", gizmo="transform")

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.VERTICAL: 1>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.GroupFlags(7)
widget_factory ChunkWidgetFactoryBase | None
None
prim_path str | None
None
gizmo str | None
None

Attributes:

Name Type Description
children NameSyncedContainer[ChunkCommon]

The container owning the child params

ColorPicker ⚓︎

ColorPicker(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=1, default_value=None, custom_widget=None)

Bases: ChunkParamBase[tuple]

A colour param holding an (r, g, b) tuple with values in the 0-1 range.

A UI shows it as a colour swatch that opens a colour dialog.

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.ParamFlags(1)
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

Custom ⚓︎

Custom(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=0, default_value=None, custom_widget=None)

Bases: ChunkParamBase

A param whose widget is supplied by the chunk, through param.custom_widget.

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
0
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

DefaultConfig ⚓︎

DefaultConfig(category='Chunks', icon='', description='Chunk description...', load_for_plugin=None, hosts=[], requirements=[], optional_requirements=[], required_modules=[], module='', interactive=False, cache_cook=False, cache_always=False, cook_on_open=False, new_values={}, cook_on_release=False, hidden=False, terminal=False, exec_inputs=1, dynamic_exec_inputs=False, cooks_when_wired_below=False, outputs=[], variants=[], gizmos=[])

Bases: ChunkConfig

This class is used as a default config.

To use, in the chunk module, add an additional function besides main():

def config():
    return chunk.DefaultConfig(
        load=True, load_for_plugin="chunk_usdview"
    )

Parameters:

Name Type Description Default
category str
'Chunks'
icon str
''
description str
'Chunk description...'
load_for_plugin str | None
None
hosts list[str]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

<dynamic>
requirements list[str]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

<dynamic>
optional_requirements list[str]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

<dynamic>
required_modules list[str]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

<dynamic>
module str
''
interactive bool
False
cache_cook bool
False
cache_always bool
False
cook_on_open bool
False
new_values dict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
cook_on_release bool
False
hidden bool
False
terminal bool
False
exec_inputs int
1
dynamic_exec_inputs bool
False
cooks_when_wired_below bool
False
outputs list[tuple[str, str]]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

<dynamic>
variants list[tuple[str, dict]] | Callable[[], list[tuple[str, dict]]]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

<dynamic>
gizmos list[GizmoBase]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

<dynamic>

FileBrowser ⚓︎

FileBrowser(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=1, default_value=None, custom_widget=None, extensions=[], pattern='*', reads=False)

Bases: ChunkParamBase[str | AssetPath]

A string param with a button that opens a file browser.

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.ParamFlags(1)
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None
extensions list[str]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

<dynamic>
pattern str
'*'
reads bool
False

Gizmo ⚓︎

Gizmo(name=_Nothing.NOTHING, type=_Nothing.NOTHING, label='', anchor='', driver={}, axis=None, space='local', editmode=('onPrimSelection',), offset=None, size=None)

Bases: GizmoBase

A viewport handle driven by this chunk's params.

usd_chunks records; the DCC interprets. Declaring one authors ui:gizmo:* attributes on the chunk prim -- what the handle is, which prim it hangs off, and which params it writes. Drawing, picking and dragging live in the viewport layer.

def config():
    return chunk.DefaultConfig(
        gizmos=[
            chunk.Gizmo("body", type="transform", anchor="primpath_location",
                        driver={"translate": ("tx", "ty", "tz")}),
        ],
    )

Write-back goes through params, never through the prim: a chunk like transform.py clears its own layer and re-authors on every cook, so a handle that wrote the prim directly would be clobbered by the next execute.

Parameters:

Name Type Description Default
name str
required
type str
required
label str
''
anchor str
''
driver Any

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
axis str | None
None
space str
'local'
editmode Any
('onPrimSelection',)
offset Any
None
size float | None
None

Group ⚓︎

Group(name='', label='', tooltip='', icon='', user_data={}, layout=1, state=0, flags=5, widget_factory=None, gizmo=None)

Bases: ChunkGroupBase

A container holding child params and groups.

A group can carry a gizmo= type, which is usually the lightest way to declare a handle: the group already is the params the handle drives, so nothing needs listing.

grp = chunk.Group("translate_grp", "Translate", gizmo="translate")

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.VERTICAL: 1>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.GroupFlags(5)
widget_factory ChunkWidgetFactoryBase | None
None
gizmo str | None
None

Attributes:

Name Type Description
children NameSyncedContainer[ChunkCommon]

The container owning the child params

ImageMenu ⚓︎

ImageMenu(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=1, default_value=None, custom_widget=None, menu_items=[], dynamic_items=False, item_images={}, tile_size=96)

Bases: Menu

A Menu whose items have pictures: a material library, a set of presets.

Still a Menu -- the value is the picked item's name, it saves, wires and refreshes (menu_items hook) exactly like one, and a frontend that knows nothing about pictures shows a plain dropdown. Qt draws a searchable grid of tiles; Blender its own thumbnail picker (template_icon_view).

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.ParamFlags(1)
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None
menu_items Sequence[str]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

<dynamic>
dynamic_items bool
False
item_images dict[str, str]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
tile_size int
96

Label ⚓︎

Label(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=0, default_value=None, custom_widget=None)

Bases: ChunkParamBase[str]

A read-only text param.

Its name or label attribute is the text displayed.

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
0
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

LineEdit ⚓︎

LineEdit(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=1, default_value=None, custom_widget=None, prim_types=())

Bases: ChunkParamBase[str]

An editable single-line string param.

Set ParamFlags.PRIM_SELECTION when the param holds Usd.Prim paths.

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

selection_seed int

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.ParamFlags(1)
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None
prim_types Sequence[str]

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

<dynamic>

accepts_prim ⚓︎

accepts_prim(prim)

Whether a prim is one of the types this field takes (see prim_types).

Parameters:

Name Type Description Default
prim Prim

The prim.

required

Returns:

Type Description
bool

True when prim_types is empty, or the prim is one of those types or has one of

bool

those API schemas applied.

Source code in usd_chunks/chunk.py
def accepts_prim(self, prim: Usd.Prim) -> bool:
    """Whether a prim is one of the types this field takes (see prim_types).

    Args:
        prim: The prim.

    Returns:
        True when prim_types is empty, or the prim is one of those types or has one of
        those API schemas applied.
    """
    if not self.prim_types:
        return True
    for name in self.prim_types:
        schema = Usd.SchemaRegistry.GetTypeFromSchemaTypeName(name)
        if schema.isUnknown:
            continue
        if Usd.SchemaRegistry.IsAppliedAPISchema(schema) and prim.HasAPI(schema):
            return True
        if prim.IsA(schema):
            return True
    return False

from_usd_rel classmethod ⚓︎

from_usd_rel(rel, *args, **kwargs)

Create a param that holds a relationship's targets as paths.

Parameters:

Name Type Description Default
rel Relationship

The relationship.

required
*args

Passed to the param constructor.

()
**kwargs

Passed to the param constructor; name defaults to the relationship's base name.

{}

Returns:

Type Description

The new param.

Source code in usd_chunks/chunk.py
@classmethod
def from_usd_rel(cls, rel: Usd.Relationship, *args, **kwargs):
    """Create a param that holds a relationship's targets as paths.

    Args:
        rel: The relationship.
        *args: Passed to the param constructor.
        **kwargs: Passed to the param constructor; `name` defaults to the relationship's
            base name.

    Returns:
        The new param.
    """
    rel_name = rel.GetName()

    if (args and isinstance(args[0], str)) or kwargs.get("name"):
        param = cls(*args, **kwargs)
    else:
        kwargs["name"] = rel_name.split(":")[-1]
        param = cls(*args, **kwargs)
    try:
        if sender := param.get_attribute_sender("value"):
            param.set_usd_prop(str(rel.GetPath()), sender)
    except AttributeError:
        pass
    return param

get_prims ⚓︎

get_prims()

The valid prims on the stage for the paths in the value.

Returns:

Type Description
Sequence[Prim]

Sequence[Usd.Prim]: The prims

Source code in usd_chunks/chunk.py
def get_prims(self) -> Sequence[Usd.Prim]:
    """The valid prims on the stage for the paths in the value.

    Returns:
        Sequence[Usd.Prim]: The prims
    """
    if not (stage := self.get_stage()):
        return []
    return [prm for pp in self.resolve_paths() if (prm := stage.GetPrimAtPath(pp)) and prm.IsValid()]

resolve_paths ⚓︎

resolve_paths()

The prim paths in the value, with globs and collection references expanded.

Supports space/comma separation and Houdini-style glob patterns: * within one path component, ** across any depth, ? a single character. See chunk_utils.resolve_prim_paths.

Returns:

Type Description
list[str]

The resolved prim path strings, empty without a stage or a value.

Source code in usd_chunks/chunk.py
def resolve_paths(self) -> list[str]:
    """The prim paths in the value, with globs and collection references expanded.

    Supports space/comma separation and Houdini-style glob patterns: ``*`` within one path
    component, ``**`` across any depth, ``?`` a single character. See
    chunk_utils.resolve_prim_paths.

    Returns:
        The resolved prim path strings, empty without a stage or a value.
    """
    if not (stage := self.get_stage()) or not self.value:
        return []
    return chunk_utils.resolve_prim_paths(stage, self.value)

set_prims ⚓︎

set_prims(prims)

Set the value to a comma-separated list of these prims' paths.

Parameters:

Name Type Description Default
prims Sequence[Prim]

The prims to set

required
Source code in usd_chunks/chunk.py
def set_prims(self, prims: Sequence[Usd.Prim]):
    """Set the value to a comma-separated list of these prims' paths.

    Args:
        prims (Sequence[Usd.Prim]): The prims to set
    """
    self.value = ",".join([str(x.GetPath()) for x in prims])

ListGroup ⚓︎

ListGroup(name='', label='', tooltip='', icon='', user_data={}, layout=1, state=0, flags=13, widget_factory=None, size=0)

Bases: ChunkListGroupBase

A container of params and groups whose size can change.

Params added with add_param are duplicated size times.

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.VERTICAL: 1>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.GroupFlags(13)
widget_factory ChunkWidgetFactoryBase | None
None
size int
0

Attributes:

Name Type Description
children NameSyncedContainer[ChunkCommon]

The container owning the child params

proxy_params list[ChunkGroupBase]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

Matrix ⚓︎

Matrix(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=0, default_value=None, custom_widget=None)

Bases: ChunkParamBase[Matrix4d]

A parameter holding a Gf.Matrix4d, stored in USD as a native matrix4d attribute.

Draws nothing. A matrix is data a chunk keeps -- a camera's placement, a baked transform -- rather than something anyone wants to edit as sixteen numbers, so this exists for values that have to survive a save, not for the UI.

Defaults to the identity, which also means an untransformed param stays at its default and never authors an attribute -- the same "only write what changed" rule every other param follows.

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
0
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

Menu ⚓︎

Menu(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=1, default_value=None, custom_widget=None, menu_items=[], dynamic_items=False)

Bases: ChunkParamBase[str]

A menu param: one choice out of menu_items.

A value is taken as the item it names whatever its case, spaces and underscores ("distant_light" is "DistantLight"). Any other value falls back to the first item, with a warning.

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.ParamFlags(1)
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None
menu_items Sequence[str]

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

<dynamic>
dynamic_items bool
False

get_selected_index ⚓︎

get_selected_index()

The index of the current value in menu_items, 0 if it is not there.

Source code in usd_chunks/chunk.py
def get_selected_index(self):
    """The index of the current value in menu_items, 0 if it is not there."""
    try:
        return self.menu_items.index(self.value)
    except ValueError:
        return 0

refresh_items ⚓︎

refresh_items()

Ask the chunk's module for this menu's items, as the menu is about to open.

A menu of what is on the stage -- the SkelRoots a Skel Pose can pose -- is wanted only when someone looks at it. A chunk opts in with a module-level function::

def menu_items(node, param_name):
    return _skel_roots(node.get_stage()) if param_name == "primpath_location" else None

so it need not listen to the stage to keep a list current that nobody opens, and need not cook to fill it either: a cook is skipped when nothing it reads changed, and a stage walk would be a read of everything. A frontend calls this before it shows the list; None from the hook leaves the items as they are.

A Menu lofted onto a chunkgroup refreshes the inner Menu it stands for, whose items it mirrors (chunk_stage._mirror_menu_items).

Source code in usd_chunks/chunk.py
def refresh_items(self) -> None:
    """Ask the chunk's module for this menu's items, as the menu is about to open.

    A menu of what is on the stage -- the SkelRoots a Skel Pose can pose -- is wanted
    only when someone looks at it. A chunk opts in with a module-level function::

        def menu_items(node, param_name):
            return _skel_roots(node.get_stage()) if param_name == "primpath_location" else None

    so it need not listen to the stage to keep a list current that nobody opens, and
    need not cook to fill it either: a cook is skipped when nothing it reads changed,
    and a stage walk would be a read of everything. A frontend calls this before it
    shows the list; None from the hook leaves the items as they are.

    A Menu lofted onto a chunkgroup refreshes the inner Menu it stands for, whose items
    it mirrors (chunk_stage._mirror_menu_items).
    """
    inner = getattr(self, "_loft_inner_menu", None)
    if inner is not None:
        if (inner_menu := inner()) is not None:
            inner_menu.refresh_items()
        return
    node = self.get_chunk()
    hook = node._module_hook(MENU_ITEMS_HOOK) if node is not None else None
    if hook is None:
        return
    try:
        items = hook(node, self.name)
    except Exception:
        # A failing hook leaves the list as it was: a stale list beats an empty one.
        logger.exception("menu_items hook failed for %r on chunk %r", self.name, node.name)
        return
    if items is not None:
        self.set_items(items)

set_items ⚓︎

set_items(items)

Replace menu_items with items, keeping the current value listed.

The current value stays in the list even when items no longer has it: a saved choice arrives before the upstream chunk that makes it has cooked, and a view-driven recook mutes layers one at a time, so "not there right now" is routinely transient. Dropping it would lose the choice for good.

Only assigned when something changed: menu_items is a plain field, and writing it re-triggers the chunk's execute() whether or not anything differs.

Parameters:

Name Type Description Default
items

The new choices.

required
Source code in usd_chunks/chunk.py
def set_items(self, items) -> None:
    """Replace menu_items with items, keeping the current value listed.

    The current value stays in the list even when items no longer has it: a saved
    choice arrives before the upstream chunk that makes it has cooked, and a view-driven
    recook mutes layers one at a time, so "not there right now" is routinely transient.
    Dropping it would lose the choice for good.

    Only assigned when something changed: menu_items is a plain field, and writing it
    re-triggers the chunk's execute() whether or not anything differs.

    Args:
        items: The new choices.
    """
    current = self.value or ""
    items = list(items)
    if current and current not in items and not chunk_utils.has_expression(current):
        items.append(current)
    if list(self.menu_items or []) != items:
        self.menu_items = items

Separator ⚓︎

Separator(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=0, default_value=None, custom_widget=None)

Bases: ChunkParamBase

A param that only separates others in the UI, and holds no value.

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
0
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

Slider ⚓︎

Slider(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=1, default_value=None, custom_widget=None, min_value=None, max_value=None, is_int=False, gizmo=None)

Bases: ChunkParamBase[int | float]

A slider param holding a float or int value.

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.ParamFlags(1)
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None
min_value float | int | None
None
max_value float | int | None
None
is_int bool
False
gizmo str | None
None

Spinbox ⚓︎

Spinbox(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=1, default_value=None, custom_widget=None, min_value=None, max_value=None, is_int=False)

Bases: ChunkParamBase[float | int]

A spinbox param holding a float or int value.

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.ParamFlags(1)
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None
min_value float | int | None
None
max_value float | int | None
None
is_int bool
False

StandardCategory ⚓︎

Bases: str, Enum

The menu categories the bundled chunks use; a "/" nests a category.

TextEdit ⚓︎

TextEdit(name='', label='', tooltip='', icon='', user_data={}, layout=0, state=0, flags=1, default_value=None, custom_widget=None, rows=None, wrap=False)

Bases: ChunkParamBase[str]

An editable multi-line string param.

Attributes:

Name Type Description
driven_scale float
value ValueT

The value of this parameter

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.HORIZONTAL: 0>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.ParamFlags(1)
default_value ValueT | None
None
custom_widget ChunkParamWidgetBase | None
None
rows int | None
None
wrap bool
False

Vector ⚓︎

Vector(name='', label='', tooltip='', icon='', user_data={}, layout=1, state=0, flags=5, widget_factory=None, param=None, length=0, suffixes=None, _default_value=None, is_output=False, gizmo=None)

Bases: ChunkVectorBase

A group holding a fixed number of params, one per component.

Parameters:

Name Type Description Default
name str
''
label str | None
''
tooltip str | None
''
icon str | None
''
user_data dict[str, Any]

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

<class 'dict'>
layout LayoutFlags
<LayoutFlags.VERTICAL: 1>
state State
usd_chunks.chunk_flags.ChunkFlags.State(0)
flags IntFlag
usd_chunks.chunk_flags.ChunkFlags.GroupFlags(5)
widget_factory ChunkWidgetFactoryBase | None
None
param ChunkParamBase
None
length int
0
suffixes Sequence[str] | str | None
None
is_output bool
False
gizmo str | None
None

Attributes:

Name Type Description
driven_scale float
children NameSyncedContainer[ChunkCommon]

The container owning the child params

anchor_file ⚓︎

anchor_file(node, path)

path as a chunk should author it, for USD to resolve: a ./ or ../ path anchored to the network's folder.

In a USD file such a path is relative to that file. A param's value is saved in the network file, but a chunk authors it into its own anonymous layer, which would anchor it to the working directory instead. A search path (no ./ or ../) is left as it is: the stage's resolver looks for it in the network's folder already.

Parameters:

Name Type Description Default
node

The chunk, for its stage.

required
path str

The param's value.

required
Source code in usd_chunks/chunk.py
def anchor_file(node, path: str) -> str:
    """path as a chunk should author it, for USD to resolve: a ./ or ../ path anchored to
    the network's folder.

    In a USD file such a path is relative to that file. A param's value is saved in the
    network file, but a chunk authors it into its own anonymous layer, which would anchor
    it to the working directory instead. A search path (no ./ or ../) is left as it is: the
    stage's resolver looks for it in the network's folder already.

    Args:
        node: The chunk, for its stage.
        path: The param's value.
    """
    stage = node.get_stage() if hasattr(node, "get_stage") else None
    return asset_paths.anchor(path, stage)

change_block ⚓︎

change_block()

Make every value set inside the block one change: what it affects cooks once, at the end.

Each value set outside a block cooks everything below it straight away. Setting several cooks them several times, each time against a half-new set of values::

mc = scene.create.mychunk()
with chunk.change_block():
    mc.get_param("param1").value = 1
    mc.get_param("param2").value = 2
# mychunk, and everything below it, cooked once, with both values

Inside the block a value change only marks what it affects; callbacks run, and chunks cook, when the block ends. Blocks nest: an inner one joins the outermost. For a script, and for a module whose execute() sets many params of its own (a Wedge writing a variant's ranges).

The same for a script building a network. Made outside a block, each chunk wired below the last cooks the whole chain above it again: a 336-chunk network took 17-27 minutes to build. Inside one, each chunk a script makes (scene.create) cooks once as it is made, before it is wired -- a Light builds its params in its cook, for the script to set next, and a Layer chunk makes its layer for an Edit Target made after it -- and what changed cooks once at the end, upstream first: about two cooks a chunk in all. Readouts read inside the block are from that first, unwired cook.

Chunks created inside the block are placed in the stage's layer stack when it ends, once their wiring is known (ChunkLayerManager.defer_placement), rather than each one as a graph of its own first and moved when wired. Once it has cooked, the layers are ranked as the next chunk made would rank them, and the stage is looked over once for chunk prims that arrived by USD (chunk_cook.after_batch).

Source code in usd_chunks/chunk.py
@contextmanager
def change_block() -> Iterator[None]:
    """Make every value set inside the block one change: what it affects cooks once, at the end.

    Each value set outside a block cooks everything below it straight away. Setting several
    cooks them several times, each time against a half-new set of values::

        mc = scene.create.mychunk()
        with chunk.change_block():
            mc.get_param("param1").value = 1
            mc.get_param("param2").value = 2
        # mychunk, and everything below it, cooked once, with both values

    Inside the block a value change only marks what it affects; callbacks run, and chunks
    cook, when the block ends. Blocks nest: an inner one joins the outermost. For a script,
    and for a module whose execute() sets many params of its own (a Wedge writing a
    variant's ranges).

    The same for a script building a network. Made outside a block, each chunk wired below
    the last cooks the whole chain above it again: a 336-chunk network took 17-27 minutes to
    build. Inside one, each chunk a script makes (scene.create) cooks once as it is made,
    before it is wired -- a Light builds its params in its cook, for the script to set next,
    and a Layer chunk makes its layer for an Edit Target made after it -- and what changed
    cooks once at the end, upstream first: about two cooks a chunk in all. Readouts read
    inside the block are from that first, unwired cook.

    Chunks created inside the block are placed in the stage's layer stack when it ends,
    once their wiring is known (ChunkLayerManager.defer_placement), rather than each one
    as a graph of its own first and moved when wired. Once it has cooked, the layers are
    ranked as the next chunk made would rank them, and the stage is looked over once for
    chunk prims that arrived by USD (chunk_cook.after_batch).
    """
    with chunk_cook.batched_solve():
        lm = ChunkLayerManager()
        placing = lm.initialized and lm.defer_placement()
        try:
            yield
        finally:
            # Before the solve the block ends with: a cook needs its layer on the stage.
            if placing:
                lm.place_deferred_layers()

create_chunks ⚓︎

create_chunks(module_name, anonymous=False)

Find a ChunkModule in the registry and run it's main() function, then add the resulting chunk(s) to the scene if not anonymous.

To build a network from a script, use scene.create.<module>(...) instead (see docs/scripting.md): it also sets params, wires chunks together and reaches menu variants. This stays for making a chunk without adding it (anonymous=True).

Parameters:

Name Type Description Default
module_name str

The name of the module to load, relative to USD_CHUNK_DIRS

required
anonymous bool

If set to True, the resulting chunks will be added to the scene directly. Defaults to False.

False

Returns:

Type Description
Sequence[Chunk]

Sequence[Chunk]: The created chunks

Source code in usd_chunks/chunk.py
def create_chunks(module_name: str, anonymous=False) -> Sequence[Chunk]:
    """Find a ChunkModule in the registry and run it's main() function, then add the resulting chunk(s) to the scene if not anonymous.

    To build a network from a script, use `scene.create.<module>(...)` instead (see
    docs/scripting.md): it also sets params, wires chunks together and reaches menu
    variants. This stays for making a chunk without adding it (anonymous=True).

    Args:
        module_name (str): The name of the module to load, relative to USD_CHUNK_DIRS
        anonymous (bool, optional): If set to True, the resulting chunks will be added to the scene directly. Defaults to False.

    Returns:
        Sequence[Chunk]: The created chunks
    """
    if not (reg := get_chunk_registry()):
        return []

    if not (mod := reg.get_chunk_module(module_name)):
        return []

    if not mod.loaded:
        chunks = mod.load()
    else:
        chunks = mod.create()

    chunks = cast(list[Chunk], chunks)

    if not anonymous:
        for c in chunks:
            reg.scene.add_chunk(c)

    return chunks

get_chunk ⚓︎

get_chunk(chunk_name)

A simple method to find a chunk in the current scene.

Parameters:

Name Type Description Default
chunk_name str

The name of the chunk to find. Note that this should be the current chunk instance name

required

Returns:

Name Type Description
Chunk

The found chunk, or None if not found

Source code in usd_chunks/chunk.py
def get_chunk(chunk_name: str):
    """A simple method to find a chunk in the current scene.

    Args:
        chunk_name (str): The name of the chunk to find. Note that this should be the current chunk instance name

    Returns:
        Chunk: The found chunk, or None if not found
    """
    if not (reg := get_chunk_registry()):
        return None
    return reg.scene.get_chunk(chunk_name)

get_chunk_registry ⚓︎

get_chunk_registry()

Get the ChunkRegistry instance, which finds and registers chunk modules.

Returns:

Type Description
ChunkRegistry | None

ChunkRegistry | None: The registry if it has been initialized, otherwise None

Source code in usd_chunks/chunk.py
def get_chunk_registry() -> ChunkRegistry | None:
    """Get the ChunkRegistry instance, which finds and registers chunk modules.

    Returns:
        ChunkRegistry | None: The registry if it has been initialized, otherwise None
    """
    res = ChunkRegistry()
    return res if res.initialized else None

get_layer_manager ⚓︎

get_layer_manager()

Return the ChunkLayerManager. This can be used to manage the chunk layers. Useful for layer management such as clearing, muting, removing, etc.

Returns:

Type Description
ChunkLayerManager | None

ChunkLayerManager | None: The ChunkLayerManager if found, otherwise None

Source code in usd_chunks/chunk.py
def get_layer_manager() -> ChunkLayerManager | None:
    """Return the ChunkLayerManager. This can be used to manage the chunk layers. Useful for layer management such as clearing, muting, removing, etc.

    Returns:
        ChunkLayerManager | None: The ChunkLayerManager if found, otherwise None
    """
    res = ChunkLayerManager()
    return res if res.initialized else None

get_scene ⚓︎

get_scene()

Return the current SceneSender, which finds, adds, saves and loads chunks.

Returns:

Type Description
SceneSender | None

SceneSender | None: The current scene, or None if there is no scene

Source code in usd_chunks/chunk.py
def get_scene() -> SceneSender | None:
    """Return the current SceneSender, which finds, adds, saves and loads chunks.

    Returns:
        SceneSender | None: The current scene, or None if there is no scene
    """
    if reg := get_chunk_registry():
        return reg.scene

is_chunk ⚓︎

is_chunk(v)

Check whether v is a ChunkBase.

Parameters:

Name Type Description Default
v Any

The input value to check

required

Returns:

Type Description
TypeGuard[ChunkBase]

TypeGuard[ChunkBase]: The TypeGuard

Source code in usd_chunks/chunk.py
def is_chunk(v: Any) -> TypeGuard[ChunkBase]:
    """Check whether v is a ChunkBase.

    Args:
        v (Any): The input value to check

    Returns:
        TypeGuard[ChunkBase]: The TypeGuard
    """
    return is_inst(ChunkBase)(v)

is_group ⚓︎

is_group(v)

Check whether v is a ChunkGroupBase.

Parameters:

Name Type Description Default
v Any

The input value to check

required

Returns:

Type Description
TypeGuard[ChunkGroupBase]

TypeGuard[ChunkGroupBase]: The TypeGuard

Source code in usd_chunks/chunk.py
def is_group(v: Any) -> TypeGuard[ChunkGroupBase]:
    """Check whether v is a ChunkGroupBase.

    Args:
        v (Any): The input value to check

    Returns:
        TypeGuard[ChunkGroupBase]: The TypeGuard
    """
    return is_inst(ChunkGroupBase)(v)

is_param ⚓︎

is_param(v)

Check whether an object is a ChunkParamBase.

Parameters:

Name Type Description Default
v Any

The value to check

required

Returns:

Type Description
TypeGuard[ChunkParamBase]

TypeGuard[ChunkParamBase]: The TypeGuard

Source code in usd_chunks/chunk.py
def is_param(v: Any) -> TypeGuard[ChunkParamBase]:
    """Check whether an object is a ChunkParamBase.

    Args:
        v (Any): The value to check

    Returns:
        TypeGuard[ChunkParamBase]: The TypeGuard
    """
    return is_inst(ChunkParamBase)(v)

is_param_t ⚓︎

is_param_t(t: ParamType) -> Predicate[ChunkParamBase]
is_param_t(t: type[ValueT]) -> Predicate[ChunkParamBase[ValueT]]
is_param_t(t)

Create a predicate matching params of a value type or a ParamType.

A value type matches a param holding a value of that type; a ChunkFlags.ParamType matches a param whose evaluate_type() includes it.

Parameters:

Name Type Description Default
t ParamType | type

The value type or ParamType to match

required

Returns:

Type Description
Predicate[ChunkParamBase] | Predicate[ChunkParamBase[ValueT]]

Predicate[ChunkParamBase]: The predicate function

Source code in usd_chunks/chunk.py
def is_param_t(t: ChunkFlags.ParamType | type[ValueT]) -> Predicate[ChunkParamBase] | Predicate[ChunkParamBase[ValueT]]:
    """Create a predicate matching params of a value type or a ParamType.

    A value type matches a param holding a value of that type; a ChunkFlags.ParamType
    matches a param whose evaluate_type() includes it.

    Args:
        t (ChunkFlags.ParamType | type): The value type or ParamType to match

    Returns:
        Predicate[ChunkParamBase]: The predicate function
    """
    if isinstance(t, ChunkFlags.ParamType):

        def _fn_e(v) -> TypeGuard[ChunkParamBase]:
            if not is_param(v):
                return False
            return t in v.evaluate_type()

        return _fn_e

    def _fn_t(v) -> TypeGuard[ChunkParamBase]:
        if not is_param(v):
            return False
        return t in ChunkFlags.ParamTypeToTypes(v.evaluate_type())

    return _fn_t

param_from_attr ⚓︎

param_from_attr(attr, *args, **kwargs)

Create a param for a Usd.Attribute, if its type is supported.

Uses the from_usd_attr class method of the matching param type, which connects the ATTRIBUTE_CHANGED notice so the param controls the USD attribute. The result is a ChunkCommon rather than a ChunkParamBase because some params are really groups (Vectors, for example).

Parameters:

Name Type Description Default
attr Attribute

The attribute to create a param for

required
*args

Passed to the param constructor.

()
**kwargs

Passed to the param constructor.

{}

Returns:

Type Description
ChunkCommon | None

ChunkCommon | None: The param, or None if no param type maps the attr's type.

Source code in usd_chunks/chunk.py
def param_from_attr(attr: Usd.Attribute, *args, **kwargs) -> ChunkCommon | None:
    """Create a param for a Usd.Attribute, if its type is supported.

    Uses the from_usd_attr class method of the matching param type, which connects the
    ATTRIBUTE_CHANGED notice so the param controls the USD attribute. The result is a
    ChunkCommon rather than a ChunkParamBase because some params are really groups
    (Vectors, for example).

    Args:
        attr (Usd.Attribute): The attribute to create a param for
        *args: Passed to the param constructor.
        **kwargs: Passed to the param constructor.

    Returns:
        ChunkCommon | None: The param, or None if no param type maps the attr's type.
    """
    type_name = attr.GetTypeName()

    t = usd_type_map.get(str(type_name))
    if not t:
        return None
    if isinstance(t, tuple):
        kwargs.update(t[1])
        return t[0].from_usd_attr(attr, *args, **kwargs)
    else:
        return t.from_usd_attr(attr, *args, **kwargs)

param_from_rel ⚓︎

param_from_rel(attr, *args, **kwargs)

Similar to param_from_attr but for a Usd.Relationship. Will create a LineEdit.

Parameters:

Name Type Description Default
attr Relationship

The relationship to connect with a param

required
*args

Passed to the param constructor.

()
**kwargs

Passed to the param constructor.

{}

Returns:

Type Description
ChunkCommon | None

ChunkCommon | None: The resulting param if created successfully

Source code in usd_chunks/chunk.py
def param_from_rel(attr: Usd.Relationship, *args, **kwargs) -> ChunkCommon | None:
    """Similar to param_from_attr but for a Usd.Relationship. Will create a LineEdit.

    Args:
        attr (Usd.Relationship): The relationship to connect with a param
        *args: Passed to the param constructor.
        **kwargs: Passed to the param constructor.

    Returns:
        ChunkCommon | None: The resulting param if created successfully
    """
    return LineEdit.from_usd_rel(attr, *args, **kwargs)

require_packages ⚓︎

require_packages(node, packages)

Make sure the packages a cook needs now are installed; whether they all are.

For a module's optional_requirements: packages only some cooks need, which are not installed when the chunk loads. Asked for here as requirements are when a chunk loads -- the host's question, or USD_CHUNK_AUTO_INSTALL -- naming the node's module. A host that installs in the background (Blender) answers False now and cooks the chunk again once they are in. A "no" stands until restart.

Only asked from the main thread: a cook on a worker thread would open the host's dialog off it. There it only says whether they are installed.

Parameters:

Name Type Description Default
node

The chunk whose cook needs them.

required
packages Sequence[str]

Requirement strings, as in config(), e.g. "trimesh>=4".

required

Returns:

Type Description
bool

True when every package is installed; then import it in the cook.

Source code in usd_chunks/chunk.py
def require_packages(node, packages: Sequence[str]) -> bool:
    """Make sure the packages a cook needs now are installed; whether they all are.

    For a module's `optional_requirements`: packages only some cooks need, which are not
    installed when the chunk loads. Asked for here as `requirements` are when a chunk
    loads -- the host's question, or USD_CHUNK_AUTO_INSTALL -- naming the node's module. A
    host that installs in the background (Blender) answers False now and cooks the
    chunk again once they are in. A "no" stands until restart.

    Only asked from the main thread: a cook on a worker thread would open the host's
    dialog off it. There it only says whether they are installed.

    Args:
        node: The chunk whose cook needs them.
        packages: Requirement strings, as in config(), e.g. "trimesh>=4".

    Returns:
        True when every package is installed; then import it in the cook.
    """
    packages = list(packages)
    if threading.current_thread() is not threading.main_thread():
        return all(installed_version(split_requirement(p)[0]) is not None for p in packages)
    module = node.get_chunk_module() if node is not None else None
    deps = ChunkDependencyManager()
    if not deps.initialized:
        deps.initialize()
    return not deps.install_packages(packages, module.module_name if module is not None else "")

resolve_file ⚓︎

resolve_file(node, path)

The file a param's path names, found as USD would find it; "" if there is none.

For a chunk that opens its file itself (a CAD or URDF import) rather than handing the path to USD. A relative path is a search path from the network's folder, so the chunk reads the same file whatever the working directory, as a Sublayer or Reference does.

Parameters:

Name Type Description Default
node

The chunk, for its stage's resolver context.

required
path str

The param's value.

required
Source code in usd_chunks/chunk.py
def resolve_file(node, path: str) -> str:
    """The file a param's path names, found as USD would find it; "" if there is none.

    For a chunk that opens its file itself (a CAD or URDF import) rather than handing the
    path to USD. A relative path is a search path from the network's folder, so the chunk
    reads the same file whatever the working directory, as a Sublayer or Reference does.

    Args:
        node: The chunk, for its stage's resolver context.
        path: The param's value.
    """
    path = (path or "").strip()
    if not path:
        return ""
    stage = node.get_stage() if hasattr(node, "get_stage") else None
    return asset_paths.resolve(path, stage)

set_validators_enabled ⚓︎

set_validators_enabled(enabled)

Turn attrs validators on or off globally.

Source code in usd_chunks/chunk.py
def set_validators_enabled(enabled: bool):
    """Turn attrs validators on or off globally."""
    validators.set_disabled(not enabled)

show_attribute ⚓︎

show_attribute(prim, target_group, collapse_non_inputs=True, var_selections=None)

Populate a group with typed editable params for all attributes and relationships on a prim.

This is the shared utility for dynamically building attribute editor UIs. Used by the Dynamic chunk, Light chunk, and any chunk that needs to expose a prim's attributes as interactive widgets.

Parameters:

Name Type Description Default
prim

The Usd.Prim whose attributes to display.

required
target_group

A ChunkGroupBase to populate with params. Existing children are cleared before populating -- unless this group was last populated from the same attributes, in which case they are kept and re-authored.

required
collapse_non_inputs

If True, namespace groups other than 'inputs' start collapsed. Keeps the UI tidy for prims with many attributes.

True
var_selections

The (anchor_prim_path, vs_name, variant) tuples active when prim was resolved (split_variant_path / author_in_variant_context), if any. Recorded on each generated attribute param so a later edit re-enters the same variant (author_in_variant_selections) instead of authoring outside it -- see ChunkUsdAttributeSupport.data_changed. None, the default, takes whichever variant scopes are open around prim right now (chunk_utils.open_variant_selections), so a call inside author_in_variant_contexts' loop records its variant without being told. Pass () to record none.

None
Source code in usd_chunks/chunk.py
def show_attribute(prim, target_group, collapse_non_inputs=True, var_selections=None):
    """Populate a group with typed editable params for all attributes and relationships on a prim.

    This is the shared utility for dynamically building attribute editor UIs.
    Used by the Dynamic chunk, Light chunk, and any chunk that needs to expose
    a prim's attributes as interactive widgets.

    Args:
        prim: The Usd.Prim whose attributes to display.
        target_group: A ChunkGroupBase to populate with params. Existing children
            are cleared before populating -- unless this group was last populated from
            the same attributes, in which case they are kept and re-authored.
        collapse_non_inputs: If True, namespace groups other than 'inputs' start
            collapsed. Keeps the UI tidy for prims with many attributes.
        var_selections: The (anchor_prim_path, vs_name, variant) tuples active when `prim`
            was resolved (split_variant_path / author_in_variant_context), if any. Recorded
            on each generated attribute param so a later edit re-enters the same variant
            (author_in_variant_selections) instead of authoring outside it -- see
            ChunkUsdAttributeSupport.data_changed. None, the default, takes whichever
            variant scopes are open around `prim` right now
            (chunk_utils.open_variant_selections), so a call inside
            author_in_variant_contexts' loop records its variant without being told. Pass
            () to record none.
    """
    if not prim or not prim.IsValid():
        # Clean existing params: no prim means nothing to show.
        for grp in target_group.get_my_params():
            grp.request_delete()
        target_group._shown_signature = None
        return

    if var_selections is None:
        var_selections = chunk_utils.open_variant_selections(prim.GetStage(), prim.GetPath())

    # The same attributes as last time, and every param still bound: keep the params.
    #
    # A chunk that shows its own prim (Light) calls this on every cook, and every edit to
    # one of these params is a cook -- rebuilding here deleted and recreated every param and
    # its widget on each tick of a slider, the one being dragged included. A param binds to
    # its attribute by path, so an unchanged signature means each existing param is already
    # bound to the right place. What the cook's cleared layer lost is only what they
    # authored -- the driven connection and value of a param that was edited -- and the
    # framework authors those again after the cook (ChunkBase.reauthor_driven_attrs). An
    # untouched param authors nothing and reads the schema fallback, the same as before.
    try:
        signature = _shown_signature(prim, var_selections, collapse_non_inputs)
    except RuntimeError:
        logger.debug("show_attribute: %s went away while it was being read; leaving this "
                     "chunk's params alone for the next cook", prim.GetPath())
        return
    if (signature == getattr(target_group, "_shown_signature", None)
            and target_group.get_my_params()
            and _shown_params_bound(target_group, str(prim.GetPath()))):
        return

    # Read the prim FIRST, and build every param, before touching target_group at all.
    #
    # Installing a param fires notices; a cook reached that way can recompose the stage; and
    # a resync EXPIRES this prim handle along with every attribute already read off it, so
    # the next read raises. For example, a Stage Expression Switch writes the record of
    # what it muted, that write cascades into cooking a light on the branch it just
    # suppressed, and the light's own prim is gone by the time this loop reaches its
    # second attribute.
    #
    # Raising there is not a local failure -- the exception would escape into
    # gate_to_branches and leave the gate half done, with the branch it was suppressing
    # still composed. Collecting first turns that into a lost cook rather than a
    # half-emptied chunk: nothing has been deleted yet, the params the chunk already has
    # stay exactly as they were, and the next cook rebuilds them.
    prim_path = prim.GetPath()
    specs = []
    try:
        for attr in prim.GetAttributes():
            specs.append((attr.GetNamespace(),
                          param_from_attr(attr, var_selections=var_selections),
                          collapse_non_inputs))
        for rel in prim.GetRelationships():
            specs.append((rel.GetNamespace(), param_from_rel(rel), False))
    except RuntimeError:
        logger.debug("show_attribute: %s went away while it was being read; leaving this "
                     "chunk's params alone for the next cook", prim_path)
        return

    # Clean existing params, now that there is something to replace them with.
    for grp in target_group.get_my_params():
        grp.request_delete()

    groups = {}
    for ns, param, collapse in specs:
        if not param:
            continue

        if not isinstance(param, ChunkGroupBase):
            param.set_flag(ChunkFlags.ParamFlags.LABELED)

        tgt_grp = target_group if not ns else groups.get(ns)
        if not tgt_grp:
            tgt_grp = Group(
                ns,
                flags=ChunkFlags.GroupFlags.COLLAPSABLE | ChunkFlags.GroupFlags.LABELED,
            )
            if collapse and ns and ns != "inputs":
                tgt_grp.set_state(ChunkFlags.State.COLLAPSED)
            target_group.add_param(tgt_grp)
            groups[ns] = tgt_grp

        tgt_grp.add_param(param)

    target_group._shown_signature = signature