Skip to content

usd_chunks.chunk_core

The base classes every chunk object derives from.

These classes are not meant to be instantiated; use the implementations in usd_chunks.chunk.

The attrs library gives every chunk class dataclass-like attributes. The attributes and methods attrs generates are inherited through the MRO, so a subclass only declares its fields and attrs builds init and the rest. Instead of @attrs.define, every chunk object uses AttributesMetaclass, which wraps each class in attrs.define with the right settings and adds custom validation and conversion.

All chunk objects inherit from ChunkCommon, which declares the fields every chunk object has, such as name. Every field that can change has an AttributeSender, and since AttributeSender is a ChunkNoticePropagator, attribute changes propagate up the hierarchy and send notices.

Checkbox ⚓︎

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

Bases: ChunkParamBase[bool]

A checkbox param holding a bool.

Here rather than in chunk.py, which re-exports it, because the framework adds one itself: ChunkModule.create gives every chunk of a cache_cook module its cache_result toggle, and chunk_registry cannot import chunk.py, which imports it.

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

ChunkBase ⚓︎

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

Bases: ChunkGroupBase

Base class for Chunks. Similar to a group but meant to be the top level owner of other params.

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
0
widget_factory ChunkWidgetFactoryBase | None
None
prim_path str | None
None

Attributes:

Name Type Description
children NameSyncedContainer[ChunkCommon]

The container owning the child params

__enter__ ⚓︎

__enter__()

with chunk: -- where chunks created inside the block go is the scene's to say (see SceneSender.enter_chunk).

Source code in usd_chunks/chunk_core.py
def __enter__(self) -> Self:
    """`with chunk:` -- where chunks created inside the block go is the scene's to say
    (see SceneSender.enter_chunk)."""
    self.get_scene().enter_chunk(self)
    return self

can_cook ⚓︎

can_cook()

Whether this chunk's module defines execute(), i.e. whether cook() has anything to run.

A chunk without one (a chunkgroup) holds other chunks and authors nothing itself.

Source code in usd_chunks/chunk_core.py
def can_cook(self) -> bool:
    """Whether this chunk's module defines execute(), i.e. whether cook() has anything to run.

    A chunk without one (a chunkgroup) holds other chunks and authors nothing itself.
    """
    return self._module_hook("execute") is not None

disable ⚓︎

disable(notice=None, sender=None)

Set the DISABLED state; usable as a callback.

Source code in usd_chunks/chunk_core.py
def disable(self, notice=None, sender=None):
    """Set the DISABLED state; usable as a callback."""
    self.set_state(ChunkFlags.State.DISABLED)

enable ⚓︎

enable(notice=None, sender=None)

Clear the DISABLED state; usable as a callback.

Source code in usd_chunks/chunk_core.py
def enable(self, notice=None, sender=None):
    """Clear the DISABLED state; usable as a callback."""
    self.unset_state(ChunkFlags.State.DISABLED)

get_chunk_module ⚓︎

get_chunk_module()

The registered module this chunk's type names, or None.

Looked up in the registry by config.module -- the same name a saved file records as info:chunkType -- rather than held on the chunk. A chunk can therefore only ever run what a registered module defines, which is exactly what reopening the file will run: a saved file is the whole description of what the network does.

The registry's module is the copy chunks are built from. A chunk module can exist twice in sys.modules under different keys (its bare name, and a package path when its folder is importable), so it is found by the registry's name, never by import.

A dict lookup (ChunkRegistry.get_chunk_module does no discovery), so it is cheap enough for the gizmo hooks, which are asked per draw and per drag tick.

Returns:

Type Description
ChunkModule | None

The ChunkModule, or None for a chunk no module made (a plain Chunk built in the

ChunkModule | None

interpreter, a tab context) or whose module is not registered.

Source code in usd_chunks/chunk_core.py
@override
def get_chunk_module(self) -> chunk_registry.ChunkModule | None:
    """The registered module this chunk's type names, or None.

    Looked up in the registry by config.module -- the same name a saved file records as
    info:chunkType -- rather than held on the chunk. A chunk can therefore only ever run
    what a registered module defines, which is exactly what reopening the file will run:
    a saved file is the whole description of what the network does.

    The registry's module is the copy chunks are built from. A chunk module can exist
    twice in sys.modules under different keys (its bare name, and a package path when
    its folder is importable), so it is found by the registry's name, never by import.

    A dict lookup (ChunkRegistry.get_chunk_module does no discovery), so it is cheap
    enough for the gizmo hooks, which are asked per draw and per drag tick.

    Returns:
        The ChunkModule, or None for a chunk no module made (a plain Chunk built in the
        interpreter, a tab context) or whose module is not registered.
    """
    if not (cfg := self._config) or not cfg.module:
        return None
    return chunk_registry.ChunkRegistry().get_chunk_module(cfg.module)

get_config ⚓︎

get_config()

The config this chunk's module declared, or None.

Source code in usd_chunks/chunk_core.py
def get_config(self) -> ChunkConfig | None:
    """The config this chunk's module declared, or None."""
    return self._config

get_context ⚓︎

get_context()

The nearest CONTEXT chunk at or above this one, or None.

Source code in usd_chunks/chunk_core.py
def get_context(self) -> ChunkBase | None:
    """The nearest CONTEXT chunk at or above this one, or None."""
    owner = self
    while owner:
        if isinstance(owner, ChunkBase) and owner.has_flag(ChunkFlags.GroupFlags.CONTEXT):
            return owner
        owner = owner.get_owner()
    return None

reauthor_driven_attrs ⚓︎

reauthor_driven_attrs()

Author again the connection and value of every param of this chunk that drives a real prim attribute (connect_usd_attr).

Those live in the chunk's layer, but they are the params' state rather than what a cook produced: a param is bound once -- by the module, by show_attribute, or on being edited away from its default -- and stays bound whether or not the next cook binds it again. The framework clears the layer before every cook, so it puts them back after one. Only this chunk's own params: a chunk nested inside keeps its own.

Source code in usd_chunks/chunk_core.py
def reauthor_driven_attrs(self) -> None:
    """Author again the connection and value of every param of this chunk that drives a
    real prim attribute (connect_usd_attr).

    Those live in the chunk's layer, but they are the params' state rather than what a
    cook produced: a param is bound once -- by the module, by show_attribute, or on
    being edited away from its default -- and stays bound whether or not the next cook
    binds it again. The framework clears the layer before every cook, so it puts them
    back after one. Only this chunk's own params: a chunk nested inside keeps its own.
    """
    for _, param in self.iter_hierarchy():
        if getattr(param, "_driven_attr_paths", None) and param.get_chunk() is self:
            param._author_driven_connections()

remove ⚓︎

remove(notice=None, sender=None)

Delete this chunk; usable as a callback.

Source code in usd_chunks/chunk_core.py
def remove(self, notice=None, sender=None):
    """Delete this chunk; usable as a callback."""
    self.request_delete()

start_gizmo ⚓︎

start_gizmo(notice=None, sender=None)

Send GIZMO_START; a callback for when a host starts a drag.

Source code in usd_chunks/chunk_core.py
def start_gizmo(self, notice=None, sender=None):
    """Send GIZMO_START; a callback for when a host starts a drag."""
    _DRAGGING[id(self)] = weakref.ref(self)
    for hook in GIZMO_START_HOOKS:
        hook(self)
    self.send_self(chunk_notice.ChunkNoticeAlias.GIZMO_START)

stop_gizmo ⚓︎

stop_gizmo(notice=None, sender=None)

Send GIZMO_STOP; a callback for when a host ends a drag.

The drag's last write cooks first (GIZMO_STOP_HOOKS), so the chunk holds where the handle was let go by the time STOP goes out. Closed before that write, so it cooks what is below in full; a chunk that previewed and was not reached by it cooks in full after (preview_cook).

Source code in usd_chunks/chunk_core.py
def stop_gizmo(self, notice=None, sender=None):
    """Send GIZMO_STOP; a callback for when a host ends a drag.

    The drag's last write cooks first (GIZMO_STOP_HOOKS), so the chunk holds where the
    handle was let go by the time STOP goes out. Closed before that write, so it cooks
    what is below in full; a chunk that previewed and was not reached by it cooks in full
    after (preview_cook).
    """
    _DRAGGING.pop(id(self), None)
    for hook in GIZMO_STOP_HOOKS:
        hook(self)
    _cook_previewed()
    self.send_self(chunk_notice.ChunkNoticeAlias.GIZMO_STOP)

trigger_on_create_callbacks ⚓︎

trigger_on_create_callbacks(notice=None, sender=None)

Trigger every on-create callback in this chunk's hierarchy.

Runs once the chunk is loaded and added to the scene, as a callback on CHUNK_LOADED. Outside the chunk's edit context: each callback triggered runs in its own owner's.

Parameters:

Name Type Description Default
notice

The notice, when called as a callback.

None
sender

The sender, when called as a callback.

None
Source code in usd_chunks/chunk_core.py
@chunk_notice.without_edit_context
def trigger_on_create_callbacks(self, notice=None, sender=None):
    """Trigger every on-create callback in this chunk's hierarchy.

    Runs once the chunk is loaded and added to the scene, as a callback on CHUNK_LOADED.
    Outside the chunk's edit context: each callback triggered runs in its own owner's.

    Args:
        notice: The notice, when called as a callback.
        sender: The sender, when called as a callback.
    """
    for _, child in self.iter_hierarchy():
        for cb in child.get_on_create_callbacks():
            if cb.alias == chunk_notice.ChunkNoticeAlias.CHUNK_LOADED:
                continue
            cb.trigger()

ChunkCommon ⚓︎

ChunkCommon(name='', label='', tooltip='', icon='', user_data={}, layout=1, state=0, flags=0)

Bases: AttributesBase

Base class for all chunk objects, holding the attributes every one of them supports.

Not instantiated directly; concrete classes inherit from it.

Attributes:

Name Type Description

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
0

can_delete ⚓︎

can_delete()

Whether nothing depends on this object, so it can be deleted.

Source code in usd_chunks/chunk_core.py
def can_delete(self):
    """Whether nothing depends on this object, so it can be deleted."""
    return not bool(list(self.get_dag_node().get_outputs()))

get_chunk ⚓︎

get_chunk()

Get the owning Chunk if it exists.

Returns:

Type Description
ChunkBase | None

ChunkBase | None: The chunk that owns this object

Source code in usd_chunks/chunk_core.py
def get_chunk(self) -> ChunkBase | None:
    """Get the owning Chunk if it exists.

    Returns:
        ChunkBase | None: The chunk that owns this object
    """
    if self._chunk_parent is None or self._chunk_parent() is None:
        owner = self.get_owner()
        while owner and not isinstance(owner, ChunkBase):
            owner = owner.get_owner()

        if not owner:
            return None
        self._chunk_parent = weakref.ref(owner)

    return self._chunk_parent()

get_edit_context ⚓︎

get_edit_context()

The layer to author this object's stage edits in: its chunk's layer.

Every param uses the layer of the nearest ChunkBase above it, rather than a layer of its own::

with Usd.EditContext(stage, param.get_edit_context()):
    ...  # modify the stage

Returns:

Type Description
Layer | None

Sdf.Layer | None: The layer, or None when the layer manager is not initialized or

Layer | None

the layer is muted

Source code in usd_chunks/chunk_core.py
def get_edit_context(self) -> Sdf.Layer | None:
    """The layer to author this object's stage edits in: its chunk's layer.

    Every param uses the layer of the nearest ChunkBase above it, rather than a layer of its
    own::

        with Usd.EditContext(stage, param.get_edit_context()):
            ...  # modify the stage

    Returns:
        Sdf.Layer | None: The layer, or None when the layer manager is not initialized or
        the layer is muted
    """
    if not chunk_registry.ChunkLayerManager().initialized:
        return

    if c := self.get_chunk():
        layer = chunk_registry.ChunkLayerManager().get_or_create_layer(c)
        # A diff cook running: its scratch layer, which stands in for the chunk's own.
        # Asked for all the same: asking is what places the layer under its Edit Target.
        if (scratch := chunk_cook.cooking_into(c)) is not None:
            return scratch
        if layer and layer.IsMuted():
            return None
        return layer

get_hash ⚓︎

get_hash()

Get the HashVal of this chunk object.

Useful for storing the object in a hash map without holding a reference to it.

Returns:

Name Type Description
HashVal HashVal

The hash value of this object

Source code in usd_chunks/chunk_core.py
def get_hash(self) -> HashVal:
    """Get the HashVal of this chunk object.

    Useful for storing the object in a hash map without holding a reference to it.

    Returns:
        HashVal: The hash value of this object
    """
    return self._hashable

get_identifier ⚓︎

get_identifier()

A dotted path from the top-most owner to this object, e.g. MyChunk.SomeGroup.MyParam.

Returns:

Name Type Description
str str

The string identifier for this chunk object

Source code in usd_chunks/chunk_core.py
def get_identifier(self) -> str:
    """A dotted path from the top-most owner to this object, e.g. MyChunk.SomeGroup.MyParam.

    Returns:
        str: The string identifier for this chunk object
    """
    names = [self.name]
    owner = self.get_owner()
    while owner:
        if isinstance(owner, ChunkCommon):
            names.append(owner.name)
        owner = owner.get_owner()
    return ".".join(reversed(names))

get_label ⚓︎

get_label()

Get the label of this chunk object, or its name if no label is set.

Returns:

Name Type Description
str str

The label

Source code in usd_chunks/chunk_core.py
def get_label(self) -> str:
    """Get the label of this chunk object, or its name if no label is set.

    Returns:
        str: The label
    """
    return self.name if not self.label else self.label

get_layer_identifier ⚓︎

get_layer_identifier()

Get the layer identifier used by the ChunkLayerManager.

Returns:

Name Type Description
str str

the layer identifier for this param

Source code in usd_chunks/chunk_core.py
def get_layer_identifier(self) -> str:
    """Get the layer identifier used by the ChunkLayerManager.

    Returns:
        str: the layer identifier for this param
    """
    if c := self.get_chunk():
        name = c.name
        val = str(hash(c))
    else:
        name = self.name
        val = str(hash(self))

    return f"{name}_{val}"

get_scene ⚓︎

get_scene()

Easy access to the current chunk scene.

Returns:

Name Type Description
SceneSender SceneSender

The SceneSender of ChunkRegistry

Source code in usd_chunks/chunk_core.py
def get_scene(self) -> SceneSender:
    """Easy access to the current chunk scene.

    Returns:
        SceneSender: The SceneSender of ChunkRegistry
    """
    return chunk_registry.ChunkRegistry().scene

get_scene_stage ⚓︎

get_scene_stage()

The scene's own stage, also inside a cook.

For the framework's work on the scene rather than a module's reading of it: muting a gate's branches, a chunk prim's bookkeeping, a unique name -- all of which a cook stage (get_stage inside a masked cook) would get wrong, holding only the cook's inputs.

Returns:

Type Description
Stage | None

Usd.Stage: The stage held by the SceneSender of ChunkRegistry

Source code in usd_chunks/chunk_core.py
def get_scene_stage(self) -> Usd.Stage | None:
    """The scene's own stage, also inside a cook.

    For the framework's work on the scene rather than a module's reading of it: muting
    a gate's branches, a chunk prim's bookkeeping, a unique name -- all of which a cook
    stage (get_stage inside a masked cook) would get wrong, holding only the cook's
    inputs.

    Returns:
        Usd.Stage: The stage held by the SceneSender of ChunkRegistry
    """
    return self.get_scene().get_stage() or chunk_notice._loading_stage

get_stage ⚓︎

get_stage()

Easy access to the current UsdStage.

Inside a cook skip_cook runs on a stage of the chunk's inputs, this is that stage: it is all a module may read. See skip_cook.

Returns:

Type Description
Stage | None

Usd.Stage: The stage held by the SceneSender of ChunkRegistry

Source code in usd_chunks/chunk_core.py
def get_stage(self) -> Usd.Stage | None:
    """Easy access to the current UsdStage.

    Inside a cook skip_cook runs on a stage of the chunk's inputs, this is that stage:
    it is all a module may read. See skip_cook.

    Returns:
        Usd.Stage: The stage held by the SceneSender of ChunkRegistry
    """
    return skip_cook.active_stage() or self.get_scene_stage()

has_flag ⚓︎

has_flag(flag)

Check if a flag is enabled.

Parameters:

Name Type Description Default
flag IntFlag

The flag to check

required

Returns:

Name Type Description
bool bool

If the flag is enabled or not

Source code in usd_chunks/chunk_core.py
def has_flag(self, flag: IntFlag) -> bool:
    """Check if a flag is enabled.

    Args:
        flag (IntFlag): The flag to check

    Returns:
        bool: If the flag is enabled or not
    """
    # Compared as plain ints: IntFlag.__and__ constructs (and caches, and looks up) a
    # whole new flag member just to be thrown away by bool(). This is called millions of
    # times when walking a large graph -- get_chunks() alone asks twice per chunk -- and
    # the enum machinery was measurably the second-largest cost of building one.
    return bool(int(self.flags) & int(flag))

has_state ⚓︎

has_state(state)

Check if state is set.

Parameters:

Name Type Description Default
state State

The state to check

required

Returns:

Name Type Description
bool bool

True if the state is set, otherwise False

Source code in usd_chunks/chunk_core.py
def has_state(self, state: ChunkFlags.State) -> bool:
    """Check if state is set.

    Args:
        state (ChunkFlags.State): The state to check

    Returns:
        bool: True if the state is set, otherwise False
    """
    return bool(self.state & state)

is_deleting ⚓︎

is_deleting()

Whether request_delete has been called on this object.

True from the start of the teardown onwards, and never reset: a deleted object is not reusable. Anything that holds on to a chunk past its own call -- a timer, a file watcher -- should check this before acting on it.

Returns:

Name Type Description
bool bool

True once deletion has started

Source code in usd_chunks/chunk_core.py
def is_deleting(self) -> bool:
    """Whether request_delete has been called on this object.

    True from the start of the teardown onwards, and never reset: a deleted object is
    not reusable. Anything that holds on to a chunk past its own call -- a timer, a
    file watcher -- should check this before acting on it.

    Returns:
        bool: True once deletion has started
    """
    return getattr(self, "_deleting", False)

request_delete ⚓︎

request_delete()

Ask the owners to delete this object; removing their references is their job.

If the object lies within a ChunkContainerBase, the container's remove_param_or_group is called with it. All callbacks are removed from the object and its owner is set to None.

Source code in usd_chunks/chunk_core.py
def request_delete(self):
    """Ask the owners to delete this object; removing their references is their job.

    If the object lies within a ChunkContainerBase, the container's remove_param_or_group is
    called with it. All callbacks are removed from the object and its owner is set to None.
    """
    # Retire the chunk from module execution before anything is dismantled. Teardown
    # detaches params and edits the layer stack, and both cascade as notices that can
    # re-enter the DAG solve and call this chunk's module.execute() again -- against a
    # half-dismantled chunk whose get_param() now returns None, which is an AttributeError
    # in essentially every chunk script (none of them defend against their own params
    # vanishing mid-run, nor should they have to). Never cleared: a chunk is not reusable
    # after request_delete. Read by chunk_notice's execute dispatch.
    self._deleting = True

    # Make sure we're enabled when deleting as being disabled will block necessary notices from being sent
    self.unset_state(ChunkFlags.State.DISABLED)
    # Same for the 'blocked' flag (set by view-driven re-cook on out-of-view chunks): a blocked
    # chunk suppresses its own notices, so CHUNK_DELETED would never fire and the USD prim would
    # be left behind on the stage.
    self.set_blocked(False)

    if not self.can_delete():
        # Debug, not warning: closing a scene deletes every chunk, so a warning here
        # printed one line per wired chunk each time usdview closed or opened a file.
        logger.debug("Deleting %s, which still has wires out; disconnecting them", self.name)
        self.get_dag_node().disconnect()

    owner = self.get_owner()
    if owner and isinstance(owner, ChunkContainerBase):
        # Owner is a group, so delete this param from the group
        owner.remove_param_or_group(self)
    elif owner and isinstance(owner, NameSyncedContainer):
        # Owner is a NameSyncedContainer, pop it from the container. When successfully removed,
        # the container will send PARAM_REMOVED with it's owning ChunkContainerBase as sender.
        owner.pop(self)

    # Disconnected, not only dropped: a connection sits in a reference cycle, so it lives
    # on until the cyclic GC runs -- and a global one kept hearing every stage meanwhile,
    # the next scene's included, on behalf of a chunk deleted with its own.
    for connection in self._callbacks.get(include_private=True):
        connection.disconnect()
    self._callbacks.clear()
    self.set_owner(None)
    self.send_self(chunk_notice.ChunkNoticeAlias.CHUNK_DELETED)

set_flag ⚓︎

set_flag(flag)

Enable a flag.

Parameters:

Name Type Description Default
flag IntFlag

The flag to enable

required
Source code in usd_chunks/chunk_core.py
def set_flag(self, flag: IntFlag):
    """Enable a flag.

    Args:
        flag (IntFlag): The flag to enable
    """
    self.flags |= flag

set_selected ⚓︎

set_selected(val)

Set or clear the SELECTED state.

Source code in usd_chunks/chunk_core.py
def set_selected(self, val: bool):
    """Set or clear the SELECTED state."""
    if val:
        self.set_state(ChunkFlags.State.SELECTED)
    else:
        self.unset_state(ChunkFlags.State.SELECTED)

set_state ⚓︎

set_state(state)

Set a state.

Parameters:

Name Type Description Default
state State

The state to set

required
Source code in usd_chunks/chunk_core.py
def set_state(self, state: ChunkFlags.State):
    """Set a state.

    Args:
        state (ChunkFlags.State): The state to set
    """
    self.state |= state

unset_flag ⚓︎

unset_flag(flag)

Disable a flag.

Parameters:

Name Type Description Default
flag IntFlag

The flag to disable

required
Source code in usd_chunks/chunk_core.py
def unset_flag(self, flag: IntFlag):
    """Disable a flag.

    Args:
        flag (IntFlag): The flag to disable
    """
    self.flags &= ~flag

unset_state ⚓︎

unset_state(state)

Unset a state.

Parameters:

Name Type Description Default
state State

The state to unset

required
Source code in usd_chunks/chunk_core.py
def unset_state(self, state: ChunkFlags.State):
    """Unset a state.

    Args:
        state (ChunkFlags.State): The state to unset
    """
    self.state &= ~state

ChunkConfig ⚓︎

ChunkConfig(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: AttributesBase

Base class for Configs. A config sets some load time configurations for a chunk.

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>

get_variants ⚓︎

get_variants()

The menu entries, building them first if they were declared lazily.

Memoised onto the field, so the callable runs once per process however many menus are drawn. Callers should use this rather than reading .variants, which may still be the callable.

Returns:

Type Description
list

The variants, empty if building them failed.

Source code in usd_chunks/chunk_core.py
def get_variants(self) -> list:
    """The menu entries, building them first if they were declared lazily.

    Memoised onto the field, so the callable runs once per process however many menus
    are drawn. Callers should use this rather than reading .variants, which may still
    be the callable.

    Returns:
        The variants, empty if building them failed.
    """
    variants = self.variants
    if callable(variants):
        try:
            variants = list(variants())
        except Exception as e:  # noqa: BLE001 - a menu must still open
            # Variants are an optional extra on one entry, and this runs while a menu is
            # being drawn for EVERY chunk -- one module that cannot build its list must
            # not take the whole chunk menu with it. Sdr.Registry() can raise, for
            # example, when an installed plugin advertises an invalid version.
            logger.warning("Could not build menu variants for %r: %s", self.module, e)
            return []
        object.__setattr__(self, "variants", variants)
    return variants

ChunkContainerBase ⚓︎

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

Bases: ChunkCommon

Base class for containers: Vectors, Groups and Chunks.

A container holds params (ChunkParamBase) and other containers.

Attributes:

Name Type Description
children NameSyncedContainer[ChunkCommon]

The container owning the child params

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
0
widget_factory ChunkWidgetFactoryBase | None
None

check_hierarchy ⚓︎

check_hierarchy()

A debug function for checking the hierarchy structure of a group.

Raises:

Type Description
TypeError

An owner is not set to a child of this group

TypeError

The owner of a child is not a ChunkNoticePropagator

ValueError

The owner of a child does not itself hold the child

NameError

Duplicate chunk in the hierarchy

NameError

Duplicate name in the hierarchy

Source code in usd_chunks/chunk_core.py
def check_hierarchy(self):
    """A debug function for checking the hierarchy structure of a group.

    Raises:
        TypeError: An owner is not set to a child of this group
        TypeError: The owner of a child is not a ChunkNoticePropagator
        ValueError: The owner of a child does not itself hold the child
        NameError: Duplicate chunk in the hierarchy
        NameError: Duplicate name in the hierarchy
    """
    failed_msg = f"check_hierarchy for {self.name} failed! \n"
    failed_msg += " Reason: {}"

    found_params: set[ChunkCommon] = set()

    # Names are checked among siblings, not across the whole hierarchy: a param is
    # addressed relative to its owner, so two groups may each hold a "General"
    # without either becoming unreachable. Renderer settings are the case that
    # proves it -- every installed renderer gets a group and every one of them ends
    # up with a General for its leftovers.
    #
    # Keyed by id() rather than by the owner itself, so this never depends on how a
    # param defines equality: two distinct groups that happen to compare equal must
    # still be two scopes.
    found_names: dict[int, set[str]] = {}

    for p in self.get_params():
        if isinstance(p, ChunkBase):
            # Chunks (inherit from ChunkAttributes) do not need owners
            continue

        owner = p.get_owner()
        if isinstance(owner, NameSyncedContainer):
            # Get the owner of the container, i.e the group or chunk
            owner = owner.get_owner()

        if not owner:
            raise TypeError(
                failed_msg.format(f"{p.name} does not have an owner. All params except Chunks should have an owner")
            )

        if not isinstance(owner, chunk_notice.ChunkNoticePropagator):
            raise TypeError(failed_msg.format(f"{p.name}'s owner is not a ChunkNoticePropagator object"))

        if isinstance(owner, ChunkContainerBase) and not isinstance(owner, ChunkListGroupBase):
            if p not in [x._param_ref if isinstance(x, ProxyParam) else x for x in owner.get_my_params()]:
                raise ValueError(
                    failed_msg.format(f"{p.name} has owner: {owner.name}. Owner does not hold this param")
                )

        if p in found_params:
            raise NameError(failed_msg.format(f"{p.name} is duplicated in the hierarchy"))
        found_params.add(p)

        direct_owner = p.get_owner()
        if isinstance(direct_owner, NameSyncedContainer):
            direct_owner = direct_owner.get_owner()

        siblings = found_names.setdefault(id(direct_owner), set())
        if p.name in siblings:
            owner_name = getattr(direct_owner, "name", "<no owner>")
            raise NameError(
                failed_msg.format(f"param name: {p.name} is not unique under {owner_name}")
            )
        siblings.add(p.name)

get_my_params ⚓︎

get_my_params() -> tuple[ChunkCommon, ...]
get_my_params(predicate: Predicate[ValueT] | None) -> tuple[ValueT, ...]
get_my_params(predicate=None)

Get the params added directly to this container.

Parameters:

Name Type Description Default
predicate Predicate[ValueT] | None

Only return params matching this. Defaults to None.

None

Returns:

Type Description
tuple[ChunkCommon, ...] | tuple[ValueT, ...]

tuple[ChunkCommon, ...]: The params

Source code in usd_chunks/chunk_core.py
def get_my_params(
    self, predicate: Predicate[ValueT] | None = None
) -> tuple[ChunkCommon, ...] | tuple[ValueT, ...]:
    """Get the params added directly to this container.

    Args:
        predicate (Predicate[ValueT] | None): Only return params matching this. Defaults to None.

    Returns:
        tuple[ChunkCommon, ...]: The params
    """
    return self.children.get_my_params(predicate)

get_param ⚓︎

get_param(param: ChunkCommon | str | HashVal) -> ChunkCommon | None
get_param(param: ChunkCommon | str | HashVal, predicate: Predicate[ValueT] | None) -> ValueT
get_param(param, predicate=None)

Find a param or group inside this container, by object, hash, name or dotted path.

For example::

my_chunk.get_param("groupA.groupB.param")

A bare name returns the first param with that name. A group requires unique names among its own children only, so several params in one hierarchy can share a name.

A predicate narrows and checks the result type::

p = my_chunk.get_param("a_slider", chunk.is_inst(chunk.Slider))
p.value = 10

Parameters:

Name Type Description Default
param ChunkCommon | str | HashVal

The param to find, or its name or path

required
predicate Predicate[ValueT] | None

Only return the param if it matches this

None

Returns:

Type Description
ChunkCommon | None | ValueT

ChunkCommon | None: The param, or None if not found

Source code in usd_chunks/chunk_core.py
def get_param(
    self, param: ChunkCommon | str | HashVal, predicate: Predicate[ValueT] | None = None
) -> ChunkCommon | None | ValueT:
    """Find a param or group inside this container, by object, hash, name or dotted path.

    For example::

        my_chunk.get_param("groupA.groupB.param")

    A bare name returns the first param with that name. A group requires unique names among
    its own children only, so several params in one hierarchy can share a name.

    A predicate narrows and checks the result type::

        p = my_chunk.get_param("a_slider", chunk.is_inst(chunk.Slider))
        p.value = 10

    Args:
        param (ChunkCommon | str | HashVal): The param to find, or its name or path
        predicate (Predicate[ValueT] | None): Only return the param if it matches this

    Returns:
        ChunkCommon | None: The param, or None if not found
    """
    if isinstance(param, (ChunkCommon, HashVal, ProxyParam)):
        return self.children.get_param(param, predicate)
    elif isinstance(param, str):
        return self.children.get_by_name(param, predicate)

get_params ⚓︎

get_params() -> tuple[ChunkCommon, ...]
get_params(predicate: Predicate[ValueT] | None) -> tuple[ValueT, ...]
get_params(predicate=None)

Get every param in this container, nested ones included.

Parameters:

Name Type Description Default
predicate Predicate[ValueT] | None

Only return params matching this. Defaults to None.

None

Returns:

Type Description
tuple[ChunkCommon, ...] | tuple[ValueT, ...]

tuple[ChunkCommon, ...]: The params

Source code in usd_chunks/chunk_core.py
def get_params(self, predicate: Predicate[ValueT] | None = None) -> tuple[ChunkCommon, ...] | tuple[ValueT, ...]:
    """Get every param in this container, nested ones included.

    Args:
        predicate (Predicate[ValueT] | None): Only return params matching this. Defaults to None.

    Returns:
        tuple[ChunkCommon, ...]: The params
    """
    return self.children.get_params(predicate)

iter_hierarchy ⚓︎

iter_hierarchy(level=0)

Walk this container and everything under it, depth first.

Parameters:

Name Type Description Default
level int

The depth of this container. Defaults to 0.

0

Yields:

Type Description
tuple[int, ChunkCommon]

tuple[int, ChunkCommon]: (depth, object), starting with this container

Source code in usd_chunks/chunk_core.py
def iter_hierarchy(self, level=0) -> Generator[tuple[int, ChunkCommon], None, None]:
    """Walk this container and everything under it, depth first.

    Args:
        level (int, optional): The depth of this container. Defaults to 0.

    Yields:
        tuple[int, ChunkCommon]: (depth, object), starting with this container
    """
    yield level, self
    for p in self.get_my_params():
        if isinstance(p, ChunkGroupBase):
            yield from p.iter_hierarchy(level + 1)
        else:
            yield level + 1, p

print_hierarchy ⚓︎

print_hierarchy()

Print the container and its children as a tree, for debugging.

Source code in usd_chunks/chunk_core.py
def print_hierarchy(self):
    """Print the container and its children as a tree, for debugging."""

    def inset(i):
        return "." * i * 4

    max_inset = 15

    msg = f"\n{'-' * max_inset}* {self.name} hierarchy *{'-' * max_inset}\n\n"
    for indent, p in self.iter_hierarchy():
        cls_name = f"[{p.__class__.__name__}]"
        if len(cls_name) > max_inset:
            cls_name = f"[{p.__class__.__name__[0 : max_inset - 1]}]"

        offset = "." * (max_inset - len(cls_name))

        msg += f"{cls_name}{offset}{inset(indent)}{p.name}"
        if isinstance(p, ChunkParamBase):
            msg += f" -> {p.evaluate_type().name}"

        owner = p.get_owner()
        if isinstance(owner, NameSyncedContainer):
            # Get the owner of the container, i.e the group or chunk
            owner = owner.get_owner()

        if owner and isinstance(owner, ChunkContainerBase):
            msg += f". Owner = ({owner.name})"

        msg += f". Id = ({hex(id(p))})"
        msg += "\n"

    self.get_logger().info(msg)

remove_param_or_group ⚓︎

remove_param_or_group(param)

Remove a direct child of this container.

Parameters:

Name Type Description Default
param ChunkCommon

The child to remove

required
Source code in usd_chunks/chunk_core.py
def remove_param_or_group(self, param: ChunkCommon):
    """Remove a direct child of this container.

    Args:
        param (ChunkCommon): The child to remove
    """
    own_p = self.children.pop(param)
    if not own_p:
        return

    own_p.set_owner(None)

request_delete ⚓︎

request_delete()

Delete this container, and with it its children.

Source code in usd_chunks/chunk_core.py
def request_delete(self):
    """Delete this container, and with it its children."""
    # Retire from module execution up here, not in the super() call at the end: the child
    # loop below detaches this container's own params, and its PARAM_REMOVED notices can
    # re-enter the DAG solve long before super().request_delete() would set the flag. See
    # ChunkCommon.request_delete for what the flag protects against.
    self._deleting = True

    # Call request_delete on all children. This will send PARAM_REMOVED on the removed
    # children.
    #
    # get_my_params(), not get_params(): the latter walks the whole nested ChainMap, so a
    # context would delete a grandchild param (a sub-chunk's own Menu/Slider) directly,
    # leaving that sub-chunk alive but gutted -- get_param() returning None on a chunk that
    # was never asked to delete, and so never marked _deleting. Anything the teardown then
    # cascades into (reconcile_edit_targets re-running an Edit Target, a refresh callback)
    # crashes on the missing param. Deleting only direct children keeps the order right:
    # each child container tears down its own subtree, marking itself first.
    for param in self.get_my_params():
        param.request_delete()

    self.children.clear()
    self.children.set_owner(None)

    super().request_delete()

ChunkContainerWidgetBase ⚓︎

ChunkContainerWidgetBase(group, *args, **kwargs)

Bases: Generic[GroupT]

Chunk is a base class for creating UI representation of chunk containers.

Source code in usd_chunks/chunk_core.py
def __init__(self, group: GroupT, *args, **kwargs):
    super().__init__(*args, **kwargs)

    # Hold a weakref to the group. If all other references to the group is killed, then
    # remove it from the UI as well, as the ui should not take ownership of the group
    self._group = weakref.ref(group, self._group_deleted)

    self._callbacks: list[chunk_notice.NoticeConnection] = []

    # Add a parameter to this widget whenever a param was added to the group
    self._callbacks.append(
        chunk_notice.NoticeConnection(
            self._param_added_callback, chunk_notice.ChunkNoticeAlias.PARAM_ADDED, self.group
        )
    )

    # Remove a parameter when the parameter was removed from the group
    self._callbacks.append(
        chunk_notice.NoticeConnection(
            self._param_removed_callback, chunk_notice.ChunkNoticeAlias.PARAM_REMOVED, self.group
        )
    )

    # Calls _delete_self() whenever the chunk sends the CHUNK_DELETED
    self._callbacks.append(
        chunk_notice.NoticeConnection(self._delete_self, chunk_notice.ChunkNoticeAlias.CHUNK_DELETED, self.group)
    )

    # Listen to state changes on the group
    self._callbacks.append(
        chunk_notice.NoticeConnection(
            self._state_changed,
            chunk_notice.ChunkNoticeAlias.STATE_CHANGED,
            self.group.get_attribute_sender("state"),
        )
    )

    self._callbacks.append(
        chunk_notice.NoticeConnection(
            self._name_changed,
            chunk_notice.ChunkNoticeAlias.ATTRIBUTE_CHANGED,
            self.group.get_attribute_sender("name"),
        )
    )

    self._callbacks.append(
        chunk_notice.NoticeConnection(
            self._name_changed,
            chunk_notice.ChunkNoticeAlias.ATTRIBUTE_CHANGED,
            self.group.get_attribute_sender("label"),
        )
    )

    self._callbacks.append(
        chunk_notice.NoticeConnection(
            self._layout_changed,
            chunk_notice.ChunkNoticeAlias.ATTRIBUTE_CHANGED,
            self.group.get_attribute_sender("layout"),
        )
    )

    # Associate ChunkParamGroup objects with group widgets
    self.group_widgets: weakref.WeakValueDictionary[ChunkHash, ChunkContainerWidgetBase] = (
        weakref.WeakValueDictionary()
    )

    # Container for all widgets in this chunk. Dict will map between ChunkParam -> widget
    # for each widget created from the same ChunkParam instance
    self.param_widgets: weakref.WeakValueDictionary[ChunkHash, ChunkParamWidgetBase] = weakref.WeakValueDictionary()

    # Initialize everything
    self.factory = self.get_widget_factory()
    self.build_collapsable()
    self._children_built = not (
        self.defer_collapsed_children
        and self.group.has_flag(ChunkFlags.GroupFlags.COLLAPSABLE)
        and self.group.has_state(ChunkFlags.State.COLLAPSED)
    )
    if self._children_built:
        self._build_param_widgets(self.group)
    self.update_from_layout()
    self.update_from_flags()
    self.update_from_state()

group property ⚓︎

group

The group this widget shows.

Raises:

Type Description
ReferenceError

The group has been garbage collected.

add_widget abstractmethod ⚓︎

add_widget(widget, label=None)

Add a child param's widget to the group's layout. Implemented by a subclass.

Called after the param has been added to the group.

Parameters:

Name Type Description Default
widget ChunkContainerWidgetBase | ChunkParamWidgetBase

The widget to add

required
label str

An optional label of the widget. Defaults to None.

None

Raises:

Type Description
NotImplementedError

A subclass does not implement it.

Source code in usd_chunks/chunk_core.py
@abstractmethod
def add_widget(self, widget: ChunkContainerWidgetBase | ChunkParamWidgetBase, label: str | None = None):
    """Add a child param's widget to the group's layout. Implemented by a subclass.

    Called after the param has been added to the group.

    Args:
        widget (ChunkContainerWidgetBase | ChunkParamWidgetBase): The widget to add
        label (str, optional): An optional label of the widget. Defaults to None.

    Raises:
        NotImplementedError: A subclass does not implement it.
    """
    raise NotImplementedError

build_collapsable abstractmethod ⚓︎

build_collapsable()

Build the group widget.

Raises:

Type Description
NotImplementedError

description

Source code in usd_chunks/chunk_core.py
@abstractmethod
def build_collapsable(self):
    """Build the group widget.

    Raises:
        NotImplementedError: _description_
    """
    raise NotImplementedError

delete_self abstractmethod ⚓︎

delete_self()

Delete this group widget. Implemented by a subclass.

Raises:

Type Description
NotImplementedError

A subclass does not implement it.

Source code in usd_chunks/chunk_core.py
@abstractmethod
def delete_self(self):
    """Delete this group widget. Implemented by a subclass.

    Raises:
        NotImplementedError: A subclass does not implement it.
    """
    raise NotImplementedError

ensure_children_built ⚓︎

ensure_children_built()

Build the child widgets a collapsed group deferred (see defer_collapsed_children).

Built from the group's params as they are now, so rows added while it was folded (a ListGroup grown by a load) arrive with the rest. Does nothing once built.

Source code in usd_chunks/chunk_core.py
def ensure_children_built(self) -> None:
    """Build the child widgets a collapsed group deferred (see defer_collapsed_children).

    Built from the group's params as they are now, so rows added while it was folded
    (a ListGroup grown by a load) arrive with the rest. Does nothing once built.
    """
    if self._children_built:
        return
    self._children_built = True
    self._build_param_widgets(self.group)

get_widget_factory abstractmethod ⚓︎

get_widget_factory()

The widget factory that builds this group's param widgets.

Returns the group's own widget_factory; a UI plugin can override this to return its own.

Raises:

Type Description
AttributeError

The group has no widget factory.

Returns:

Name Type Description
ChunkWidgetFactoryBase ChunkWidgetFactoryBase

The factory that can create the valued parameters from ChunkParamBase objects

Source code in usd_chunks/chunk_core.py
@abstractmethod
def get_widget_factory(self) -> ChunkWidgetFactoryBase:
    """The widget factory that builds this group's param widgets.

    Returns the group's own widget_factory; a UI plugin can override this to return its own.

    Raises:
        AttributeError: The group has no widget factory.

    Returns:
        ChunkWidgetFactoryBase: The factory that can create the valued parameters from ChunkParamBase objects
    """
    factory = self.group.widget_factory
    if factory is None:
        raise AttributeError(
            "No widget factory supplied to ChunkContainerWidgetBase. Implement get_widget_factory()"
        )
    return factory

is_collapsed ⚓︎

is_collapsed()

Whether the group widget should be collapsed, because it or its parent is.

Returns:

Name Type Description
bool bool

True if the group should be collapsed

Source code in usd_chunks/chunk_core.py
def is_collapsed(self) -> bool:
    """Whether the group widget should be collapsed, because it or its parent is.

    Returns:
        bool: True if the group should be collapsed
    """
    val = self.group.has_state(ChunkFlags.State.COLLAPSED)
    parent = self.group.get_owner()
    if parent and isinstance(parent, ChunkContainerBase):
        val |= parent.has_state(ChunkFlags.State.COLLAPSED)
    return val

remove_widget abstractmethod ⚓︎

remove_widget(widget)

Remove a child param widget from this group widget. Implemented by a subclass.

Parameters:

Name Type Description Default
widget Any

The widget to remove from the group widget

required

Raises:

Type Description
NotImplementedError

A subclass does not implement it.

Source code in usd_chunks/chunk_core.py
@abstractmethod
def remove_widget(self, widget: Any):
    """Remove a child param widget from this group widget. Implemented by a subclass.

    Args:
        widget (Any): The widget to remove from the group widget

    Raises:
        NotImplementedError: A subclass does not implement it.
    """
    raise NotImplementedError

set_enabled abstractmethod ⚓︎

set_enabled(val)

Enable or disable the widget. Implemented by a subclass.

Parameters:

Name Type Description Default
val bool

Whether to enable or disable the widget

required

Raises:

Type Description
NotImplementedError

A subclass does not implement it.

Source code in usd_chunks/chunk_core.py
@abstractmethod
def set_enabled(self, val: bool):
    """Enable or disable the widget. Implemented by a subclass.

    Args:
        val (bool): Whether to enable or disable the widget

    Raises:
        NotImplementedError: A subclass does not implement it.
    """
    raise NotImplementedError

set_expanded abstractmethod ⚓︎

set_expanded(checked)

Expand the widget to show its child widgets, or collapse it to hide them.

Implemented by a subclass.

Parameters:

Name Type Description Default
checked bool

Whether the group widget should be expanded or not

required

Raises:

Type Description
NotImplementedError

A subclass does not implement it.

Source code in usd_chunks/chunk_core.py
@abstractmethod
def set_expanded(self, checked: bool):
    """Expand the widget to show its child widgets, or collapse it to hide them.

    Implemented by a subclass.

    Args:
        checked (bool): Whether the group widget should be expanded or not

    Raises:
        NotImplementedError: A subclass does not implement it.
    """
    raise NotImplementedError

set_hidden abstractmethod ⚓︎

set_hidden(val)

Hide or show the widget. Implemented by a subclass.

Parameters:

Name Type Description Default
val bool

Whether to hide or show the widget

required

Raises:

Type Description
NotImplementedError

A subclass does not implement it.

Source code in usd_chunks/chunk_core.py
@abstractmethod
def set_hidden(self, val: bool):
    """Hide or show the widget. Implemented by a subclass.

    Args:
        val (bool): Whether to hide or show the widget

    Raises:
        NotImplementedError: A subclass does not implement it.
    """
    raise NotImplementedError

set_selected abstractmethod ⚓︎

set_selected(val)

Show whether the group is selected. Does nothing by default.

Parameters:

Name Type Description Default
val bool

Whether the group is selected

required
Source code in usd_chunks/chunk_core.py
@abstractmethod
def set_selected(self, val: bool):
    """Show whether the group is selected. Does nothing by default.

    Args:
        val (bool): Whether the group is selected
    """
    pass

supports_widget abstractmethod ⚓︎

supports_widget(widget)

Whether a widget belongs to this UI plugin's toolkit.

A Qt plugin, for example, returns isinstance(widget, QtWidgets.QWidget).

Parameters:

Name Type Description Default
widget Any

The widget to check

required

Raises:

Type Description
NotImplementedError

A subclass does not implement it.

Returns:

Name Type Description
bool bool

True if the widget is supported by the current ui plugin

Source code in usd_chunks/chunk_core.py
@abstractmethod
def supports_widget(self, widget: Any) -> bool:
    """Whether a widget belongs to this UI plugin's toolkit.

    A Qt plugin, for example, returns ``isinstance(widget, QtWidgets.QWidget)``.

    Args:
        widget (Any): The widget to check

    Raises:
        NotImplementedError: A subclass does not implement it.

    Returns:
        bool: True if the widget is supported by the current ui plugin
    """
    raise NotImplementedError

update_from_flags abstractmethod ⚓︎

update_from_flags()

Update the widget from the group's flags. Implemented by a subclass.

Raises:

Type Description
NotImplementedError

A subclass does not implement it.

Source code in usd_chunks/chunk_core.py
@abstractmethod
def update_from_flags(self):
    """Update the widget from the group's flags. Implemented by a subclass.

    Raises:
        NotImplementedError: A subclass does not implement it.
    """
    raise NotImplementedError

update_from_layout abstractmethod ⚓︎

update_from_layout()

Apply the group's layout flags. Does nothing by default.

Source code in usd_chunks/chunk_core.py
@abstractmethod
def update_from_layout(self):
    """Apply the group's layout flags. Does nothing by default."""
    pass

update_from_state abstractmethod ⚓︎

update_from_state()

Apply the group's HIDDEN, DISABLED and SELECTED state to the widget.

A group is disabled only by its own DISABLED state. ParamFlags.OUTPUT means nothing for a group, and it shares a bit with GroupFlags.COLLAPSABLE, so testing it here would disable every collapsible group's children.

Source code in usd_chunks/chunk_core.py
@abstractmethod
def update_from_state(self):
    """Apply the group's HIDDEN, DISABLED and SELECTED state to the widget.

    A group is disabled only by its own DISABLED state. ParamFlags.OUTPUT means nothing for a
    group, and it shares a bit with GroupFlags.COLLAPSABLE, so testing it here would disable
    every collapsible group's children.
    """
    self.set_hidden(self.group.has_state(ChunkFlags.State.HIDDEN))
    # NB: OUTPUT is a ParamFlags value and has no meaning for a group. Checking it
    # here against the group's GroupFlags mis-fires because ParamFlags.OUTPUT and
    # GroupFlags.COLLAPSABLE share the same bit (2), so every collapsible group
    # read as "output" and disabled all its children. A group is only disabled by
    # its own DISABLED state.
    self.set_enabled(not self.group.has_state(ChunkFlags.State.DISABLED))
    self.set_selected(self.group.has_state(ChunkFlags.State.SELECTED))

update_label abstractmethod ⚓︎

update_label(text)

Update the label of this container.

Parameters:

Name Type Description Default
text str

The new label to display

required
Source code in usd_chunks/chunk_core.py
@abstractmethod
def update_label(self, text: str):
    """Update the label of this container.

    Args:
        text (str): The new label to display
    """
    pass

update_param_label abstractmethod ⚓︎

update_param_label(notice, sender)

Correct a child's label in the layout when its name, label or LABELED flag changes.

If LABELED was unset, the label is removed and the widget spans the row; if it was set, the label is added; otherwise only the label text is updated. A UI plugin implements this to get labeled widgets.

Parameters:

Name Type Description Default
notice Notice

The notice that was sent

required
sender AttributeSender

The attribute that changed

required
Source code in usd_chunks/chunk_core.py
@abstractmethod
def update_param_label(self, notice, sender: AttributeSender):
    """Correct a child's label in the layout when its name, label or LABELED flag changes.

    If LABELED was unset, the label is removed and the widget spans the row; if it was set,
    the label is added; otherwise only the label text is updated. A UI plugin implements
    this to get labeled widgets.

    Args:
        notice (Tf.Notice): The notice that was sent
        sender (AttributeSender): The attribute that changed
    """
    pass

ChunkGroupBase ⚓︎

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

Bases: ChunkContainerBase

Base class for dynamic containers, which can hold any number of children of any type.

Chunks and Groups are dynamic in that sense. Vectors are not, and do not subclass this.

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
0
widget_factory ChunkWidgetFactoryBase | None
None

Attributes:

Name Type Description
children NameSyncedContainer[ChunkCommon]

The container owning the child params

add_param ⚓︎

add_param(param, force_unique=True)

Add a param to this group's children.

Changes to the param propagate to this group, since they share the same hierarchy; see ChunkNoticePropagator. To add the same param several times, add clones::

group.add_param(param.clone())
group.add_params([param, param.clone(), param.clone()])

Parameters:

Name Type Description Default
param ChunkT

A parameter to add. May also be another ChunkContainer, which will nest the group

required
force_unique bool

If a param already exists in the hierarchy, we most often do not want a direct duplicate. This enables the check, and if a duplicate exists, raises a ValueError. However, if the hash is unique but the name is a duplicate, this will resolve the name conflict by incrementing a numerical suffix. If set to False, this check is never performed, instead any duplicate will simply replace the old parameter. Defaults to True

True

Returns:

Name Type Description
ChunkT ChunkT

The param

Raises:

Type Description
ValueError

If the param is a direct duplicate (hash exists already)

Source code in usd_chunks/chunk_core.py
def add_param(self, param: ChunkT, force_unique: bool = True) -> ChunkT:
    """Add a param to this group's children.

    Changes to the param propagate to this group, since they share the same hierarchy; see
    ChunkNoticePropagator. To add the same param several times, add clones::

        group.add_param(param.clone())
        group.add_params([param, param.clone(), param.clone()])

    Args:
        param (ChunkT): A parameter to add. May also be another ChunkContainer, which will nest the group
        force_unique (bool): If a param already exists in the hierarchy, we most often do not want a direct duplicate.
            This enables the check, and if a duplicate exists, raises a ValueError. However, if the hash is unique but
            the name is a duplicate, this will resolve the name conflict by incrementing a numerical suffix. If set to False,
            this check is never performed, instead any duplicate will simply replace the old parameter. Defaults to True

    Returns:
        ChunkT: The param

    Raises:
        ValueError: If the param is a direct duplicate (hash exists already)
    """
    new_param = None
    if force_unique:
        new_param = self.resolve_new_param(param)

    if new_param is None or new_param is param:
        new_param = param

    if isinstance(new_param, ChunkCommon):
        # Add the new param to self.children container. The owner/ownee relationship is handled
        # by the container, so should not modify owner here
        self.children.add(new_param)

        if isinstance(new_param, ChunkContainerBase):
            # Also append the children of the group, as this allows for fast lookups across the layers
            self.children.add_nested(new_param.children)

    else:
        raise ValueError("Chunks only support params inherited from ChunkCommon")
    return new_param

add_params ⚓︎

add_params(params, force_unique=True, clone=False)

Add several params, calling add_param on each.

Parameters:

Name Type Description Default
params Iterable[ChunkCommon]

The chunk objects to add

required
force_unique bool

Force unique param names. Defaults to True.

True
clone bool

Add clones instead of the params themselves. Defaults to False.

False

Returns:

Type Description
list[ChunkT]

list[ChunkCommon]: The added params, which differ from the input if clones were made

Source code in usd_chunks/chunk_core.py
def add_params(self, params: Iterable[ChunkT], force_unique: bool = True, clone: bool = False) -> list[ChunkT]:
    """Add several params, calling add_param on each.

    Args:
        params (Iterable[ChunkCommon]): The chunk objects to add
        force_unique (bool, optional): Force unique param names. Defaults to True.
        clone (bool, optional): Add clones instead of the params themselves. Defaults to False.

    Returns:
        list[ChunkCommon]: The added params, which differ from the input if clones were made
    """
    new_params = []
    for param in params:
        if clone:
            p = self.add_param(param.clone(), force_unique)
        else:
            p = self.add_param(param, force_unique)
        new_params.append(p)
    return new_params

get_reserved_names ⚓︎

get_reserved_names()

The names a new child may not take: every direct child's name, and this group's own.

Returns:

Type Description
set[str]

set[str]: The reserved names

Source code in usd_chunks/chunk_core.py
def get_reserved_names(self) -> set[str]:
    """The names a new child may not take: every direct child's name, and this group's own.

    Returns:
        set[str]: The reserved names
    """
    return set(self.children.get_my_names()) | set([self.name])

get_valid_child_name ⚓︎

get_valid_child_name(orig_name, reserved_names)

A unique form of orig_name; see NameSyncedContainer.get_valid_child_name.

Delegated to self.children (the NameSyncedContainer that owns the authoritative name map) rather than implemented here, so the per-prefix "next index to try" cache lives in one place and applies to every path that renames a new or existing child -- this one and ChunkCommon._unique_among_siblings's rename path alike.

Source code in usd_chunks/chunk_core.py
def get_valid_child_name(self, orig_name: str, reserved_names: set[str]) -> str:
    """A unique form of orig_name; see NameSyncedContainer.get_valid_child_name.

    Delegated to `self.children` (the NameSyncedContainer that owns the authoritative
    name map) rather than implemented here, so the per-prefix "next index to try"
    cache lives in one place and applies to every path that renames a new or existing
    child -- this one and ChunkCommon._unique_among_siblings's rename path alike.
    """
    return self.children.get_valid_child_name(orig_name, reserved_names)

resolve_new_param ⚓︎

resolve_new_param(param)

The param, renamed if its name conflicts with another child of this group.

Parameters:

Name Type Description Default
param ChunkParamBase

A param or container

required

Returns:

Name Type Description
ChunkT ChunkT | None

The param, possibly with a new name

Raises:

Type Description
ValueError

The same param (same hash) is already here

Source code in usd_chunks/chunk_core.py
def resolve_new_param(self, param: ChunkT) -> ChunkT | None:
    """The param, renamed if its name conflicts with another child of this group.

    Args:
        param (ChunkParamBase): A param or container

    Returns:
        ChunkT: The param, possibly with a new name

    Raises:
        ValueError: The same param (same hash) is already here
    """
    # A key lookup down the ChainMap, not `param in self.get_params()`: that materialised
    # every param of every nested container (a tuple of ChainMap.values(), each entry a
    # walk of the chain) to answer a membership question, on every add. On a context it
    # is the whole scene, so appending the 50th chunk to a chain cost 5x the first --
    # the one thing about a node graph that must not get slower as the graph grows.
    if param in self.children:
        raise ValueError(f"A duplicate for param {param.name} was found on container {self.name}")

    new_param = param

    if not isinstance(param, ProxyParam):
        reserved_names = self.get_reserved_names()

        new_name = self.get_valid_child_name(param.name, reserved_names)
        new_param.name = new_name

        reserved_names.add(new_name)

        # A chunk entering a scene or chunkgroup keeps its own param names: they are
        # attrs on its own prim, so they can't clash with another chunk. Renamed, a
        # group called "Output" became "Output1" next to a chunk named Output, and its
        # saved values were not read back on reopen.
        entering_context = isinstance(new_param, ChunkBase) and self.has_flag(ChunkFlags.GroupFlags.CONTEXT)
        if isinstance(new_param, ChunkGroupBase) and not entering_context:
            for p in new_param.get_params():
                if not isinstance(p, ProxyParam):
                    new_name = self.get_valid_child_name(p.name, reserved_names)
                    reserved_names.add(new_name)
                    p.name = new_name

    return new_param

ChunkHash ⚓︎

Bases: Protocol

Protocol for a hashable chunk object.

ChunkListGroupBase ⚓︎

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

Bases: ChunkGroupBase

Base class for list containers, whose rows each hold proxies of the children.

Besides the container's children, the group holds one group per row, holding proxies of those children. A UI shows the rows (proxy_params) and hides the children. A proxy is practically identical to the param it references, except for its 'value': renaming the referenced param renames every proxy of it. Proxies are read and set like regular params, but reached through get_indexed_param() rather than get_param().

get_params() and get_my_params() return the proxies; get_param() does not, and returns from the 'children' container the proxies reference. So get_param() changes every row at once, and add_param() adds a param to every row.

Attributes:

Name Type Description
proxy_params list[ChunkGroupBase]

The groups holding each row's proxies. Managed internally, never modified from outside

children NameSyncedContainer[ChunkCommon]

The container owning the child params

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
0
widget_factory ChunkWidgetFactoryBase | None
None
size int
0

get_indexed_param ⚓︎

get_indexed_param(param: ChunkCommon | str | HashVal, index: int) -> ChunkCommon | None
get_indexed_param(param: ChunkCommon | str | HashVal, index: int, predicate: Predicate[ValueT] | None = None) -> ValueT
get_indexed_param(param, index, predicate=None)

The proxy of a param in one row.

Parameters:

Name Type Description Default
param ChunkCommon | str | HashVal

The param to look for, or its name

required
index int

The row, an index into proxy_params

required
predicate Predicate[ValueT] | None

Only return the proxy if it matches this. Defaults to None

None

Returns:

Type Description
ChunkCommon | None | ValueT

ChunkCommon | None: The proxy of param in that row

Raises:

Type Description
IndexError

If the index is out of bounds

Source code in usd_chunks/chunk_core.py
def get_indexed_param(
    self, param: ChunkCommon | str | HashVal, index: int, predicate: Predicate[ValueT] | None = None
) -> ChunkCommon | None | ValueT:
    """The proxy of a param in one row.

    Args:
        param (ChunkCommon | str | HashVal): The param to look for, or its name
        index (int): The row, an index into proxy_params
        predicate (Predicate[ValueT] | None): Only return the proxy if it matches this. Defaults to None

    Returns:
        ChunkCommon | None: The proxy of param in that row

    Raises:
        IndexError: If the index is out of bounds
    """
    if len(self.proxy_params) == 0 and not predicate:
        return

    if index >= len(self.proxy_params):
        raise IndexError("Index out of range")

    res = self.proxy_params[index].get_param(param)
    if not predicate or predicate(res):
        return res

    raise ValueError(f"Predicate {predicate} failed for get_indexed_param with index {index}")

remove_index ⚓︎

remove_index(index)

Remove one row, reducing the size by 1.

The row's group gets request_delete(). An index out of range is logged and ignored.

Parameters:

Name Type Description Default
index int

The row to remove

required
Source code in usd_chunks/chunk_core.py
def remove_index(self, index: int):
    """Remove one row, reducing the size by 1.

    The row's group gets request_delete(). An index out of range is logged and ignored.

    Args:
        index (int): The row to remove
    """
    try:
        self.proxy_params[index].get_dag_node().disconnect()
        self._delete_row(index)
    except IndexError as e:
        self.get_logger().warning("Failed to remove index from list. Index out of range %s", e)
        return

    self.size -= 1
    self._renumber_row_refs([index])

ChunkParamBase ⚓︎

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

Bases: Generic[ValueT], ChunkCommon, ChunkUsdAttributeSupport

Base class for valued params.

Attributes:

Name Type Description
value ValueT

The value of this parameter

driven_scale float

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

raw_value property ⚓︎

raw_value

The stored value before expression evaluation. Use this for display purposes.

add_dependency ⚓︎

add_dependency(input)

Add a DagNode input; refused across a chunk boundary.

A param-level dependency is in-memory only: ChunkStageSync._on_dependency_added authors inputs:chunk for ChunkBase pairs and returns early for anything else, so an edge between two params is never written to USD, draws no wire in the node graph, and is gone after a reload. Within one chunk that is exactly right -- this is the dirty/ordering edge behind set_function, and it can drive attributes (menu_items, a label, visibility) that no expression can reach. Across two chunks it is a connection nobody can see, and the solve no longer tells a chunk what reaches it across one (chunk_notice: chunks speak only through wires), so it would not even update. An expression is the wire that persists; connect_value redirects to one.

Parameters:

Name Type Description Default
input ChunkNoticePropagator

The propagator to depend on.

required

Returns:

Type Description
int

The dependency index.

Raises:

Type Description
ValueError

input is a param of another chunk.

Source code in usd_chunks/chunk_core.py
def add_dependency(self, input: chunk_notice.ChunkNoticePropagator) -> int:
    """Add a DagNode input; refused across a chunk boundary.

    A param-level dependency is in-memory only: ChunkStageSync._on_dependency_added
    authors inputs:chunk for ChunkBase pairs and returns early for anything else, so
    an edge between two params is never written to USD, draws no wire in the node
    graph, and is gone after a reload. Within one chunk that is exactly right -- this
    is the dirty/ordering edge behind set_function, and it can drive attributes
    (menu_items, a label, visibility) that no expression can reach. Across two chunks
    it is a connection nobody can see, and the solve no longer tells a chunk what
    reaches it across one (chunk_notice: chunks speak only through wires), so it would
    not even update. An expression is the wire that persists; connect_value redirects
    to one.

    Args:
        input: The propagator to depend on.

    Returns:
        The dependency index.

    Raises:
        ValueError: input is a param of another chunk.
    """
    if isinstance(input, ChunkParamBase) and (pair := self._cross_chunk_ref(input)):
        mine, theirs = pair
        ref = self._expression_ref_to(input, theirs) or f"@{theirs.name}.<param>@"
        raise ValueError(
            f"Param dependency {mine.name}.{self.name} <- {theirs.name}.{input.name} crosses "
            f"chunks: chunks connect only through wires. Use an expression instead: "
            f"{mine.name}.{self.name} = \"{ref}\" (or connect_value, which authors one)"
        )
    return super().add_dependency(input)

connect_value ⚓︎

connect_value(other)

Make this param's value follow another param's.

Across chunks this authors an expression instead of a DagNode edge, since an expression is written to USD, draws a wire and survives a reload.

Parameters:

Name Type Description Default
other ChunkParamBase[ValueT]

The param to follow.

required

Raises:

Type Description
ValueError

The two params' types are not compatible, or other is in another chunk and no @Node.param@ reaches it -- its name resolves to a different param of that chunk.

Source code in usd_chunks/chunk_core.py
def connect_value(self, other: ChunkParamBase[ValueT]):
    """Make this param's value follow another param's.

    Across chunks this authors an expression instead of a DagNode edge, since an expression
    is written to USD, draws a wire and survives a reload.

    Args:
        other: The param to follow.

    Raises:
        ValueError: The two params' types are not compatible, or other is in another
            chunk and no @Node.param@ reaches it -- its name resolves to a different
            param of that chunk.
    """
    my_t = self.evaluate_type()
    other_t = other.evaluate_type()
    if my_t not in other_t:
        raise ValueError(f"Can't connect {other_t.name} to parameter {my_t}")

    # Across chunks, do what the caller asked for in the form that survives: an
    # expression authors the USD connection, draws the wire, and is patched on rename,
    # where the DagNode edge below would quietly vanish on the next load. The type
    # check above still ran, which the raw expression path skips.
    if pair := self._cross_chunk_ref(other):
        ref = self._expression_ref_to(other, pair[1])
        if ref is None:
            # Chunks connect only through wires, and an expression is the only wire a
            # param can have to another chunk's.
            raise ValueError(
                f"Can't connect {pair[0].name}.{self.name} to {pair[1].name}.{other.name}: "
                f"no @{pair[1].name}.<param>@ reaches it, as its name resolves to another "
                "param of that chunk. Give it a name of its own."
            )
        logger.debug(
            "connect_value across chunks (%s -> %s): authoring %s",
            pair[1].name, pair[0].name, ref,
        )
        self.value = ref
        return

    idx = -1
    # If other already is connected to self, then we can use that index
    for i, node in self.get_dependencies(is_inst(type(other))):
        if node == other:
            idx = i
            break

    if idx == -1:
        # The nodes are not connected, so we add other as dependency
        idx = self.add_dependency(other)
    self.set_function("value", lambda x, _: x.get_dependency(idx, is_inst(type(other))).value)

evaluate_type ⚓︎

evaluate_type()

The ParamType this param has right now.

If get_type() allows several types (FLOAT_SLIDER | INT_SLIDER), this decides which one is in use.

Returns:

Type Description
ParamType

ChunkFlags.ParamType: The runtime type. get_type() by default

Source code in usd_chunks/chunk_core.py
def evaluate_type(self) -> ChunkFlags.ParamType:
    """The ParamType this param has right now.

    If get_type() allows several types (FLOAT_SLIDER | INT_SLIDER), this decides which one
    is in use.

    Returns:
        ChunkFlags.ParamType: The runtime type. get_type() by default
    """
    return self.get_type()

get_type classmethod ⚓︎

get_type()

The ParamType of this param class, which decides the widget a UI builds for it.

Required of every valued param. If this returns a combination of ParamTypes, the subclass also implements evaluate_type() to pick the one in use at runtime.

Returns:

Type Description
ParamType

ChunkFlags.ParamType: The type. NONE by default; subclasses override it

Source code in usd_chunks/chunk_core.py
@classmethod
def get_type(cls) -> ChunkFlags.ParamType:
    """The ParamType of this param class, which decides the widget a UI builds for it.

    Required of every valued param. If this returns a combination of ParamTypes, the
    subclass also implements evaluate_type() to pick the one in use at runtime.

    Returns:
        ChunkFlags.ParamType: The type. NONE by default; subclasses override it
    """
    return ChunkFlags.ParamType.NONE

network_namespace ⚓︎

network_namespace()

The scene root every prim path this param names is relative to.

That is the namespaces of the network hosts enclosing it (chunk_stage.host_networks), outermost first, joined. Empty outside any namespaced host, which is the common case and costs a walk up the owner chain.

Returns:

Type Description
str

The namespace, "" outside any namespaced host.

Source code in usd_chunks/chunk_core.py
def network_namespace(self) -> str:
    """The scene root every prim path this param names is relative to.

    That is the namespaces of the network hosts enclosing it (chunk_stage.host_networks),
    outermost first, joined. Empty outside any namespaced host, which is the common case
    and costs a walk up the owner chain.

    Returns:
        The namespace, "" outside any namespaced host.
    """
    parts = []
    # From the owning chunk's owner, not from the param's: a host's own params are its
    # interface to the graph outside, and its location field IS the namespace -- it
    # must not resolve inside it, or typing /a/b there with /a set reads back as /b.
    chunk = self.get_chunk()
    owner = chunk.get_owner() if chunk is not None else self.get_owner()
    while owner is not None:
        namespace = getattr(owner, "_network_namespace", "")
        if namespace:
            parts.append(namespace)
        owner = getattr(owner, "get_owner", lambda: None)()
    return "".join(reversed(parts))

refresh_expression_value ⚓︎

refresh_expression_value()

Re-announce this param's value because what its expression reads has changed.

The raw text is untouched -- only what it resolves to moved -- so nothing would otherwise fire: widgets keep showing the old number and the USD attrs this param drives keep the old value. Used by an expression ref changing upstream and by a Stage Expression changing a variable.

Source code in usd_chunks/chunk_core.py
def refresh_expression_value(self) -> None:
    """Re-announce this param's value because what its expression reads has changed.

    The raw text is untouched -- only what it resolves to moved -- so nothing would
    otherwise fire: widgets keep showing the old number and the USD attrs this param
    drives keep the old value. Used by an expression ref changing upstream and by a
    Stage Expression changing a variable.
    """
    if self._resolving_ref:
        return
    self._resolving_ref = True
    try:
        attr_sender = self.get_attribute_sender("value")
        attr_sender.old_value = self.__dict__.get("value")
        attr_sender.execute()
    finally:
        self._resolving_ref = False

ChunkUsdAttributeSupport ⚓︎

ChunkUsdAttributeSupport()

Bases: AttributesBase

Mixin that lets a valued param be bound to a USD attribute.

A param can then be built from a Usd.Attribute, with the NoticeConnections that keep the param's value and the attribute in sync.

Attributes:

Name Type Description
driven_scale float

connect_usd_attr ⚓︎

connect_usd_attr(attr, var_selections=())

Drive a real prim attribute from this param's storage attribute via a USD connection.

The storage attr becomes the connection source; the real attr is the target. If the real attr does not exist yet it is created in _author_driven_connections once the storage attr is known. If the storage attr is not yet known the whole operation is deferred until _connect_param_attr is called.

Parameters:

Name Type Description Default
attr Property

The real prim attribute to drive (e.g. /cameras/Cam.focalLength). May be an invalid/non-existent attribute -- the path is stored and the attribute is created on demand.

required
var_selections tuple

The (anchor_prim_path, vs_name, variant) tuples active when attr was resolved, if any -- see _driven_var_selections. chunk_stage._drive_from_storage passes the param's own _var_selections through here when it promotes a direct real-attr binding (show_attribute) into one the storage attr drives.

()
Source code in usd_chunks/chunk_core.py
def connect_usd_attr(self, attr: Usd.Property, var_selections: tuple = ()) -> None:
    """Drive a real prim attribute from this param's storage attribute via a USD connection.

    The storage attr becomes the connection source; the real attr is the target. If the
    real attr does not exist yet it is created in _author_driven_connections once the
    storage attr is known. If the storage attr is not yet known the whole operation is
    deferred until _connect_param_attr is called.

    Args:
        attr (Usd.Property): The real prim attribute to drive (e.g. /cameras/Cam.focalLength).
            May be an invalid/non-existent attribute -- the path is stored and the attribute
            is created on demand.
        var_selections: The (anchor_prim_path, vs_name, variant) tuples active when attr was
            resolved, if any -- see _driven_var_selections. chunk_stage._drive_from_storage
            passes the param's own _var_selections through here when it promotes a direct
            real-attr binding (show_attribute) into one the storage attr drives.
    """
    path = str(attr.GetPath())
    if path not in self._driven_attr_paths:
        self._driven_attr_paths.append(path)
    if var_selections:
        self._driven_var_selections[path] = tuple(var_selections)
    elif path in self._driven_var_selections:
        del self._driven_var_selections[path]
    if self._param_attr_path:
        self._author_driven_connections()

driven_value ⚓︎

driven_value(value)

The value as the driven attributes take it: a number times driven_scale.

Parameters:

Name Type Description Default
value Any

The param's resolved value.

required

Returns:

Type Description
Any

The value scaled, or unchanged when it is not a number or the scale is 1.

Source code in usd_chunks/chunk_core.py
def driven_value(self, value: Any) -> Any:
    """The value as the driven attributes take it: a number times driven_scale.

    Args:
        value: The param's resolved value.

    Returns:
        The value scaled, or unchanged when it is not a number or the scale is 1.
    """
    if self.driven_scale == 1.0 or isinstance(value, bool) or not isinstance(value, (int, float)):
        return value
    return value * self.driven_scale

from_usd_attr classmethod ⚓︎

from_usd_attr(attr, *args, **kwargs)

Create a param from a Usd.Attribute, bound so the param's changes write the attribute.

Parameters:

Name Type Description Default
attr Attribute

The attribute to represent as a param

required
*args

Passed to the param constructor.

()
**kwargs

Passed to the param constructor; name defaults to the attribute's base name. var_selections (see ChunkUsdAttributeSupport._var_selections) is popped out before construction -- it is never a constructor argument, only something _connect_param_attr records afterward.

{}

Returns:

Name Type Description
ChunkUsdAttributeSupport ChunkUsdAttributeSupport

The new param

Source code in usd_chunks/chunk_core.py
@classmethod
def from_usd_attr(cls, attr: Usd.Attribute, *args, **kwargs) -> ChunkUsdAttributeSupport:
    """Create a param from a Usd.Attribute, bound so the param's changes write the attribute.

    Args:
        attr (Usd.Attribute): The attribute to represent as a param
        *args: Passed to the param constructor.
        **kwargs: Passed to the param constructor; `name` defaults to the attribute's base
            name. `var_selections` (see ChunkUsdAttributeSupport._var_selections) is popped
            out before construction -- it is never a constructor argument, only something
            _connect_param_attr records afterward.

    Returns:
        ChunkUsdAttributeSupport: The new param
    """
    var_selections = kwargs.pop("var_selections", ())
    attr_name = attr.GetName()

    if (args and isinstance(args[0], str)) or kwargs.get("name"):
        param = cls(*args, **kwargs)
    else:
        kwargs["name"] = attr_name.split(":")[-1]
        param = cls(*args, **kwargs)

    if hasattr(param, "default_value"):
        if attr.HasFallbackValue():
            default_value = attr.GetMetadata("default")
        else:
            default_value = attr.Get(0)

        param.default_value = default_value  # type: ignore

    param._connect_param_attr(attr, var_selections=var_selections)

    return param

get_usd_prop ⚓︎

get_usd_prop()

Return the storage attribute this param is bound to.

Returns:

Type Description
Property | None

Usd.Property | None: The bound storage USD property, or None.

Source code in usd_chunks/chunk_core.py
def get_usd_prop(self) -> Usd.Property | None:
    """Return the storage attribute this param is bound to.

    Returns:
        Usd.Property | None: The bound storage USD property, or None.
    """
    stage = self.get_scene_stage()
    if stage and self._param_attr_path:
        return stage.GetPropertyAtPath(self._param_attr_path)

release_usd_attr ⚓︎

release_usd_attr(attr)

Stop driving attr (the undo of connect_usd_attr): this param no longer writes its value there. The connection already authored stays in the chunk's layer until its next cook, which starts that layer afresh.

Source code in usd_chunks/chunk_core.py
def release_usd_attr(self, attr: Usd.Property) -> None:
    """Stop driving attr (the undo of connect_usd_attr): this param no longer writes its value
    there. The connection already authored stays in the chunk's layer until its next cook,
    which starts that layer afresh."""
    path = str(attr.GetPath())
    if path in self._driven_attr_paths:
        self._driven_attr_paths.remove(path)
    self._driven_var_selections.pop(path, None)

set_usd_prop ⚓︎

set_usd_prop(prop_path, sender)

Bind this param to a specific USD property with an explicit sender (used for relationships).

Prefer _connect_param_attr for standard attribute binding.

Parameters:

Name Type Description Default
prop_path str | Property

The property, or its path.

required
sender AttributeSender

The AttributeSender whose changes are written to the property.

required
Source code in usd_chunks/chunk_core.py
def set_usd_prop(self, prop_path: str | Usd.Property, sender: AttributeSender):
    """Bind this param to a specific USD property with an explicit sender (used for relationships).

    Prefer _connect_param_attr for standard attribute binding.

    Args:
        prop_path: The property, or its path.
        sender: The AttributeSender whose changes are written to the property.
    """
    path = str(prop_path.GetPath()) if isinstance(prop_path, Usd.Property) else prop_path
    self._param_attr_path = path

    if self._usd_prop_connection:
        self._usd_prop_connection.disconnect()

    self._usd_prop_connection = chunk_notice.NoticeConnection(
        self.update_usd_prop, chunk_notice.ChunkNoticeAlias.ATTRIBUTE_CHANGED, sender, owner=self
    )
    self.usd_prop_changed()

update_usd_prop abstractmethod ⚓︎

update_usd_prop(notice, sender)

Write the param's change to the USD relationship it is bound to, if it is one.

Invoked when the 'value' AttributeSender changes. notice.data is that sender, never the property: an attribute is written by ChunkParamBase.data_changed (and a vector's by ChunkVectorBase.data_changed), so all that is left here is a relationship, which those cannot write -- they look the path up with GetAttributeAtPath.

Parameters:

Name Type Description Default
notice AttributeChangeNotice

The value change

required
sender AttributeSender

The sender of the notice

required
Source code in usd_chunks/chunk_core.py
@abstractmethod
def update_usd_prop(self, notice: chunk_notice.AttributeChangeNotice, sender: AttributeSender):
    """Write the param's change to the USD relationship it is bound to, if it is one.

    Invoked when the 'value' AttributeSender changes. notice.data is that sender, never
    the property: an attribute is written by ChunkParamBase.data_changed (and a vector's
    by ChunkVectorBase.data_changed), so all that is left here is a relationship, which
    those cannot write -- they look the path up with GetAttributeAtPath.

    Args:
        notice (chunk_notice.AttributeChangeNotice): The value change
        sender (AttributeSender): The sender of the notice
    """
    # Looked up, not read off notice.data: testing notice.data for a Relationship never
    # matched, and a param built from a relationship (show_attribute) showed its targets
    # but never wrote them.
    if isinstance(rel := self.get_usd_prop(), Usd.Relationship) and isinstance(sender.value, str):
        # Currently just assume the string is a comma separated list of paths. This will likely
        # be changed in the future for a more robust approach
        paths = [x.strip() for x in sender.value.split(",") if x.strip()]
        if not all([Sdf.Path.IsValidPathString(x) for x in paths]):
            return
        targets = [Sdf.Path(x) for x in paths]
        if rel.GetTargets() == targets:
            return
        stage = rel.GetStage()
        # Into the chunk's own layer (and the variant it was read from), like any other
        # edit a param makes to a real prim.
        with chunk_utils.edit_context_for(stage, self._var_selections,
                                          chunk_utils.chunk_write_layer(stage, self.get_chunk())):
            rel.SetTargets(targets)

usd_prop_changed abstractmethod ⚓︎

usd_prop_changed()

Update the bound AttributeSender's value from the USD attribute after the attribute changes.

Source code in usd_chunks/chunk_core.py
@abstractmethod
def usd_prop_changed(self):
    """Update the bound AttributeSender's value from the USD attribute after the attribute changes."""
    if not self._usd_prop_connection:
        return
    if not isinstance(self._usd_prop_connection.sender, AttributeSender):
        return

    attr = self.get_usd_prop()
    if isinstance(attr, Usd.Attribute):
        self._usd_prop_connection.sender.value = attr.Get(0)
    elif isinstance(attr, Usd.Relationship):
        self._usd_prop_connection.sender.value = ",".join([str(x) for x in attr.GetForwardedTargets()])

ChunkVectorBase ⚓︎

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

Bases: ChunkContainerBase, ChunkUsdAttributeSupport

Base class for vector params: a container with a fixed number of params.

A vector is used like a valued param, with 'value' reading and writing its children::

vec = chunk.Vector("my_vec", param=chunk.Slider(), length=3, suffixes="xyz")

vec[0] = 10
vec.x = 10
vec.value = (0, 1, 2)

Attributes:

Name Type Description
driven_scale float
children NameSyncedContainer[ChunkCommon]

The container owning the child params

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
0
widget_factory ChunkWidgetFactoryBase | None
None
param ChunkParamBase
None
length int
0
suffixes Sequence[str] | str | None
None
is_output bool
False

default_value property writable ⚓︎

default_value

The components' default values as a tuple.

raw_value property ⚓︎

raw_value

The stored expression string, or the tuple of children's raw values.

value property writable ⚓︎

value

The components' values as a tuple, or the resolved expression if one is set.

__getitem__ ⚓︎

__getitem__(key)

A component by index or name, e.g. vec[0] or vec["x"].

Parameters:

Name Type Description Default
key str | int

name or index of the component

required

Raises:

Type Description
KeyError

if key is not accessible

Returns:

Name Type Description
ChunkParamBase ChunkParamBase

The component param

Source code in usd_chunks/chunk_core.py
def __getitem__(self, key: str | int) -> ChunkParamBase:
    """A component by index or name, e.g. vec[0] or vec["x"].

    Args:
        key (str | int): name or index of the component

    Raises:
        KeyError: if key is not accessible

    Returns:
        ChunkParamBase: The component param
    """
    if isinstance(key, str):
        param = self.get_param(key)
    elif isinstance(key, int):
        param = self.get_my_params()[key]
    if not param or not isinstance(param, ChunkParamBase):
        raise KeyError(f"Index {key} does not exist on vector")
    return param

__setitem__ ⚓︎

__setitem__(key, val)

Set a component's value by index or name.

Parameters:

Name Type Description Default
key str | int

The component's index or name.

required
val Any

The new value.

required

Raises:

Type Description
ValueError

The component is a container, not a valued param.

Source code in usd_chunks/chunk_core.py
def __setitem__(self, key: str | int, val: Any) -> ChunkParamBase | None:
    """Set a component's value by index or name.

    Args:
        key: The component's index or name.
        val: The new value.

    Raises:
        ValueError: The component is a container, not a valued param.
    """
    param = self[key]
    if not isinstance(param, ChunkParamBase):
        raise ValueError("ChunkContainers does not support value assignment")

    param.value = val

evaluate_type ⚓︎

evaluate_type()

VECTOR combined with the component param's current type.

Source code in usd_chunks/chunk_core.py
def evaluate_type(self):
    """VECTOR combined with the component param's current type."""
    return ChunkFlags.ParamType.VECTOR | self.param.evaluate_type()

get_type ⚓︎

get_type()

VECTOR combined with the component param's type.

Source code in usd_chunks/chunk_core.py
def get_type(self):
    """VECTOR combined with the component param's type."""
    return ChunkFlags.ParamType.VECTOR | self.param.get_type()

has_flag ⚓︎

has_flag(flag)

Check a flag, reading OUTPUT from is_output rather than from .flags.

A vector's flags are GroupFlags, and ParamFlags.OUTPUT shares a bit with one of them; see the is_output field. Everything else defers to the normal check.

Parameters:

Name Type Description Default
flag IntFlag

The flag to check.

required

Returns:

Type Description
bool

True if the flag is set.

Source code in usd_chunks/chunk_core.py
def has_flag(self, flag: IntFlag) -> bool:
    """Check a flag, reading OUTPUT from is_output rather than from .flags.

    A vector's flags are GroupFlags, and ParamFlags.OUTPUT shares a bit with one of them;
    see the is_output field. Everything else defers to the normal check.

    Args:
        flag: The flag to check.

    Returns:
        True if the flag is set.
    """
    if flag == ChunkFlags.ParamFlags.OUTPUT:
        return self.is_output
    return super().has_flag(flag)

HashVal ⚓︎

HashVal()

The unique identity of a chunk object, created from a uuid4.

Every ChunkCommon holds one.

__copy__ ⚓︎

__copy__()

A new HashVal with a fresh key: a copy of an identity is a different identity.

Source code in usd_chunks/chunk_core.py
def __copy__(self):
    # Should never be called, but just in case...
    # Copying this class should result in a new key
    """A new HashVal with a fresh key: a copy of an identity is a different identity."""
    cls = self.__class__
    c = cls.__new__(cls)
    c.__init__()
    return c

generate_key staticmethod ⚓︎

generate_key()

Generate a new uuid value to hash by. For internal use.

Source code in usd_chunks/chunk_core.py
@staticmethod
def generate_key() -> int:
    """Generate a new uuid value to hash by. For internal use."""
    return uuid.uuid4().int  # type: ignore

NameSyncedContainer ⚓︎

NameSyncedContainer()

Bases: Generic[ChunkT], ChunkNoticePropagator

The container holding a chunk object's children, indexed by hash and by name.

Both maps are ChainMaps that also reach every nested NameSyncedContainer, so a nested child is found without iterating the hierarchy. The get_* methods search nested containers too; the get_my_* methods only this one.

params maps a hash to a ChunkCommon. ChunkCommon objects hash by their uuid, so a param can be looked up by the object itself or by obj._hashable; where a lookup is typed as taking a HashVal (get_param(), get_my_param()), passing the object works the same.

names maps each param's current (mutable) name to its hash, for fast lookup by name. It must be kept up to date whenever a name changes, which is why this class is a ChunkNoticePropagator: it sits in the object hierarchy and updates the mapping when a name changes.

Anything added with add() gets this container as its owner, so a chunk object holding one should own the container and never manage its params' ownership itself. The container sends no notices of its own; it only propagates its children's.

Source code in usd_chunks/chunk_core.py
def __init__(self):
    super().__init__()

    self._last_added: HashVal | None = None
    self._last_removed: HashVal | None = None

    self._params: ChainMap[ChunkHash, ChunkT] = ChainMap()
    self._names: ChainMap[str, ChunkHash] = ChainMap()

    self._reserved_names: dict[str, int] = {}

__contains__ ⚓︎

__contains__(obj)

Whether obj is held here or anywhere nested, by identity (its hash).

The nested hierarchy is not materialised -- see resolve_new_param for why that matters.

Parameters:

Name Type Description Default
obj ChunkCommon | ProxyParam

The chunk object.

required

Returns:

Type Description
bool

True if it is held.

Source code in usd_chunks/chunk_core.py
def __contains__(self, obj: ChunkCommon | ProxyParam) -> bool:
    """Whether obj is held here or anywhere nested, by identity (its hash).

    The nested hierarchy is not materialised -- see resolve_new_param for why that matters.

    Args:
        obj: The chunk object.

    Returns:
        True if it is held.
    """
    return obj.get_hash() in self._params

__copy__ ⚓︎

__copy__()

A new container holding copies of this one's direct children, and its callbacks.

Source code in usd_chunks/chunk_core.py
def __copy__(self):
    """A new container holding copies of this one's direct children, and its callbacks."""
    copied = NameSyncedContainer()

    for param in self._params.maps[0].values():
        copied.add(copy.copy(param))

    copied._copy_callbacks(self)
    return copied

__delitem__ ⚓︎

__delitem__(key)

Remove a child, sending PARAM_REMOVED and releasing its ownership.

Source code in usd_chunks/chunk_core.py
def __delitem__(self, key: ChunkHash):
    """Remove a child, sending PARAM_REMOVED and releasing its ownership."""
    if obj := self.get_param(key):
        # send_removed uses obj.send_self(). For this reason, we need to call send_remove before set_owner(None),
        # as send_self() will propagate the notice to the owners
        self.send_removed(obj)

        # obj.name can drift from the name-map key (a rename or a partially-applied clone can
        # desync the map). Remove the entry by matching value (the key) and fall back to name,
        # popping defensively so delete never crashes with a KeyError.
        names0 = self._names.maps[0]
        if names0.get(obj.name) == key:
            del names0[obj.name]
        else:
            for nm in [n for n, k in list(names0.items()) if k == key]:
                del names0[nm]
        self._params.maps[0].pop(key, None)
        if isinstance(obj, ChunkBase):
            NameSyncedContainer.generation += 1

        if obj.get_owner() == self:
            obj.set_owner(None)

add ⚓︎

add(obj, send=True)

Add a chunk object to this container, which becomes its owner.

The object is stored in params and its name in names, so it can be found with get_param() and get_by_name(). The container maintains the name-to-object relationship, so never add to params or names directly; use this.

If the object is a ChunkContainerBase, its children are chained into this container's maps, which gives fast access to nested params.

Parameters:

Name Type Description Default
obj ChunkCommon | ProxyParam

The object to add. Nothing is done to avoid duplication across layers.

required
send bool

Send PARAM_ADDED for it. Defaults to True.

True
Source code in usd_chunks/chunk_core.py
def add(self, obj: ChunkT | ProxyParam, send=True):
    """Add a chunk object to this container, which becomes its owner.

    The object is stored in params and its name in names, so it can be found with
    get_param() and get_by_name(). The container maintains the name-to-object relationship,
    so never add to params or names directly; use this.

    If the object is a ChunkContainerBase, its children are chained into this container's
    maps, which gives fast access to nested params.

    Args:
        obj (ChunkCommon | ProxyParam): The object to add. Nothing is done to avoid
            duplication across layers.
        send (bool, optional): Send PARAM_ADDED for it. Defaults to True.
    """
    # Append child the object + name to the first layer of the ChainMaps
    self._params.maps[0][obj.get_hash()] = obj  # type: ignore
    self._names.maps[0][obj.name] = obj.get_hash()
    if isinstance(obj, ChunkBase):
        NameSyncedContainer.generation += 1

    # Mark self as the owner of the added obj as we need to be notified when the object changes
    obj.set_owner(self)

    if send:
        self.send_added(obj)

add_nested ⚓︎

add_nested(nested)

Appends nested params to the ChainMap. This allows for fast lookups across the layers.

Parameters:

Name Type Description Default
nested 'NameSyncedContainer[ChunkT]'

The nested params to add

required
Source code in usd_chunks/chunk_core.py
def add_nested(self, nested: NameSyncedContainer[ChunkT]):
    """Appends nested params to the ChainMap. This allows for fast lookups across the layers.

    Args:
        nested ("NameSyncedContainer[ChunkT]"): The nested params to add
    """
    self._params.maps.append(nested._params)
    self._names.maps.append(nested._names)

clear ⚓︎

clear()

Clear all children from this container.

The children are not deleted explicitly, as references to them may be held elsewhere, but in practice they are, because other objects should only hold weakrefs to params.

Source code in usd_chunks/chunk_core.py
def clear(self):
    """Clear all children from this container.

    The children are not deleted explicitly, as references to them may be held elsewhere,
    but in practice they are, because other objects should only hold weakrefs to params.
    """
    self._names.clear()
    self._params.clear()
    NameSyncedContainer.generation += 1

create_proxy staticmethod ⚓︎

create_proxy(source, target)

Fill target with a ProxyParam for each of source's direct children.

Parameters:

Name Type Description Default
source NameSyncedContainer

The container to mirror.

required
target NameSyncedContainer

The container to fill.

required

Returns:

Type Description

target.

Source code in usd_chunks/chunk_core.py
@staticmethod
def create_proxy(source: NameSyncedContainer, target: NameSyncedContainer):
    """Fill `target` with a ProxyParam for each of `source`'s direct children.

    Args:
        source: The container to mirror.
        target: The container to fill.

    Returns:
        `target`.
    """
    for param in source.get_my_params():
        proxy = ProxyParam(param)
        target.add(proxy)
    return target

empty ⚓︎

empty()

Whether the container holds nothing.

Source code in usd_chunks/chunk_core.py
def empty(self):
    """Whether the container holds nothing."""
    return not bool(self._params)

get_by_name ⚓︎

get_by_name(name: str) -> ChunkT | None
get_by_name(name: str, predicate: Predicate[ValueT] | None) -> ValueT
get_by_name(name, predicate=None)

Find a param by name, or by a dotted path through nested groups.

For example::

my_chunk.get_param("groupA.groupB.slider")

Parameters:

Name Type Description Default
name str

The name or dotted path.

required
predicate Predicate[ValueT] | None

Only return the param if it matches this.

None

Returns:

Type Description
ChunkT | None | ValueT

ChunkCommon | None: The param, or None if not found

Source code in usd_chunks/chunk_core.py
def get_by_name(self, name: str, predicate: Predicate[ValueT] | None = None) -> ChunkT | None | ValueT:
    """Find a param by name, or by a dotted path through nested groups.

    For example::

        my_chunk.get_param("groupA.groupB.slider")

    Args:
        name: The name or dotted path.
        predicate: Only return the param if it matches this.

    Returns:
        ChunkCommon | None: The param, or None if not found
    """
    if "." in name:
        hierarchy = name.split(".")
        cm: ChainMap = self._names
        idx = 0
        g = hierarchy[0]

        while idx < len(hierarchy) - 1:
            if g not in cm:
                return None

            if g in cm.maps[0]:
                # Found g in first layer, so can look for next entry in the query
                idx += 1

                # FInd the parameter matching g and update cm to reflected the parameters own children.
                grp = self._params.get(cm.maps[0].get(g))
                if not grp or not isinstance(grp, ChunkContainerBase):
                    raise NameError(f"Could not find param {name}. {g} is not a container type parameter")

                cm = grp.children._names

            g = hierarchy[idx]

        if key := cm.get(g):
            res = self._params.get(key)
            if not predicate or predicate(res):
                return res
            raise ValueError(f"get_by_name predicate {predicate} failed for parameter {key}")

    if key := self._names.get(name):
        res = self.get_param(key)
        if not predicate or predicate(res):
            return res
        raise ValueError(f"get_by_name predicate {predicate} failed for parameter {key}")

get_my_names ⚓︎

get_my_names()

Get the names at this level only.

Returns:

Type Description
tuple[str, ...]

tuple[str, ...]: The param names of this level

Source code in usd_chunks/chunk_core.py
def get_my_names(self) -> tuple[str, ...]:
    """Get the names at this level only.

    Returns:
        tuple[str, ...]: The param names of this level
    """
    return tuple(self._names.maps[0].keys())

get_my_params ⚓︎

get_my_params() -> tuple[ChunkT, ...]
get_my_params(predicate: Predicate[ValueT] | None) -> tuple[ValueT, ...]
get_my_params(predicate=None)

Get the params at this level only.

Parameters:

Name Type Description Default
predicate Predicate[ValueT] | None

Only return params matching this.

None

Returns:

Type Description
tuple[ChunkT, ...] | tuple[ValueT, ...]

tuple[ChunkCommon, ...]: The params

Source code in usd_chunks/chunk_core.py
def get_my_params(self, predicate: Predicate[ValueT] | None = None) -> tuple[ChunkT, ...] | tuple[ValueT, ...]:
    """Get the params at this level only.

    Args:
        predicate: Only return params matching this.

    Returns:
        tuple[ChunkCommon, ...]: The params
    """
    ps = self._params.maps[0].values()
    if not predicate:
        return tuple(ps)
    return tuple(filter(predicate, ps))

get_param ⚓︎

get_param(key: ChunkHash | str) -> ChunkT | None
get_param(key: ChunkHash | str, predicate: Predicate[ValueT] | None) -> ValueT
get_param(key, predicate=None)

Find a param by hash, by object, or by name or dotted path.

A string that is a path to a param, such as aChunk.aGroup.aParam, finds the param at that path; a bare name finds the first param with that name.

Parameters:

Name Type Description Default
key ChunkHash | str

A ChunkCommon (it hashes to its HashVal), a HashVal, or a name or path.

required
predicate Predicate[ValueT] | None

Only return the param if it matches this.

None

Returns:

Type Description
ChunkT | None | ValueT

ChunkCommon | None: The param, or None if not found

Source code in usd_chunks/chunk_core.py
def get_param(
    self, key: ChunkHash | str, predicate: Predicate[ValueT] | None = None
) -> ChunkT | None | ValueT:
    """Find a param by hash, by object, or by name or dotted path.

    A string that is a path to a param, such as aChunk.aGroup.aParam, finds the param at
    that path; a bare name finds the first param with that name.

    Args:
        key: A ChunkCommon (it hashes to its HashVal), a HashVal, or a name or path.
        predicate: Only return the param if it matches this.

    Returns:
        ChunkCommon | None: The param, or None if not found
    """
    if isinstance(key, str):
        res = self.get_by_name(key)
    else:
        res = self._params.get(key)

    if predicate is None:
        return res

    if not predicate(res):
        raise ValueError(f"get_param predicate {predicate} failed for parameter {key}")
    return res

get_params ⚓︎

get_params() -> tuple[ChunkT, ...]
get_params(predicate: Predicate[ValueT] | None) -> tuple[ValueT, ...]
get_params(predicate=None)

Get every param at this level and all nested levels.

Parameters:

Name Type Description Default
predicate Predicate[ValueT] | None

Only return params matching this.

None

Returns:

Type Description
tuple[ChunkT, ...] | tuple[ValueT, ...]

tuple[ChunkCommon, ...]: The params

Source code in usd_chunks/chunk_core.py
def get_params(self, predicate: Predicate[ValueT] | None = None) -> tuple[ChunkT, ...] | tuple[ValueT, ...]:
    """Get every param at this level and all nested levels.

    Args:
        predicate: Only return params matching this.

    Returns:
        tuple[ChunkCommon, ...]: The params
    """
    ps = self._params.values()

    if not predicate:
        return tuple(ps)
    return tuple(filter(predicate, ps))

get_valid_child_name ⚓︎

get_valid_child_name(orig_name, reserved_names)

A unique form of orig_name, numbered so it does not clash with reserved_names.

Parameters:

Name Type Description Default
orig_name str

The name to make valid

required
reserved_names set[str]

The names already taken. The new name is added to it, so a group nested inside an already created group gets a unique name too

required

Returns:

Name Type Description
str str

a unique name

Source code in usd_chunks/chunk_core.py
def get_valid_child_name(self, orig_name: str, reserved_names: set[str]) -> str:
    """A unique form of orig_name, numbered so it does not clash with reserved_names.

    Args:
        orig_name (str): The name to make valid
        reserved_names (set[str]): The names already taken. The new name is added to it, so
            a group nested inside an already created group gets a unique name too

    Returns:
        str: a unique name
    """
    suffix = ""

    if m := re.match("(.*?)([0-9]+)$", orig_name):
        orig_name = m.group(1)
        suffix = m.group(2)
    # Resumed from this prefix's own last try, not always 1: adding the Nth unnamed
    # "Cube" restarted the scan from "Cube1" every time, an O(n) search repeated n
    # times. _reserved_names is only ever a starting guess -- the loop below still
    # checks reserved_names itself, so a gap (an explicit "Cube7" out of order) is
    # still found and never skipped past.
    idx = int(suffix) if suffix else self._reserved_names.get(orig_name, 1)

    max_iter = 1000

    name = orig_name + suffix

    # Capped on tries, not on the number: a name ending in 1000 or more (Cube1000, or a
    # uuid's hex) started past the cap and failed on its first clash.
    for _ in range(max_iter):
        if name not in reserved_names:
            if not suffix:
                # idx is already the next suffix to try: the loop moved past the
                # one just returned (or left it at its start, for the bare name).
                self._reserved_names[orig_name] = idx
            return name
        name = orig_name + str(idx)
        idx += 1
    raise RuntimeError(f"Failed to resolve name, loop exceeded {max_iter} iterations")

name_changed ⚓︎

name_changed(old_name)

Re-key a renamed child in this level's names map.

The entry for old_name is replaced by the object's new name, so the child is found by its new name and no longer by its old one::

c = chunk.Slider("A")
g = chunk.Group("group")
g.add_param(c)
assert g.get_param("A") is not None

c.name = "B"
assert g.get_param("B") is not None and g.get_param("A") is None

Parameters:

Name Type Description Default
old_name str

The name the object was mapped under

required

Raises:

Type Description
ValueError

The old_name was not found

Source code in usd_chunks/chunk_core.py
def name_changed(self, old_name: str):
    """Re-key a renamed child in this level's names map.

    The entry for old_name is replaced by the object's new name, so the child is found by
    its new name and no longer by its old one::

        c = chunk.Slider("A")
        g = chunk.Group("group")
        g.add_param(c)
        assert g.get_param("A") is not None

        c.name = "B"
        assert g.get_param("B") is not None and g.get_param("A") is None

    Args:
        old_name (str): The name the object was mapped under

    Raises:
        ValueError: The old_name was not found
    """
    # Only look for names on the first layer. Groups are responsible for their respective layers
    mapping = self._names.maps[0]

    if old_name in mapping:
        idx = mapping.pop(old_name)
        if obj := self.get_param(idx):
            mapping[obj.name] = idx
    else:
        raise ValueError(f"Failed to update old name {old_name} in container")

pop ⚓︎

pop(key)

Remove and return the child at key.

Parameters:

Name Type Description Default
key ChunkHash

The chunk object to remove

required

Returns:

Type Description
ChunkCommon | None

ChunkCommon | None: The removed object, or None if it is not here

Source code in usd_chunks/chunk_core.py
def pop(self, key: ChunkHash) -> ChunkCommon | None:
    """Remove and return the child at key.

    Args:
        key (ChunkHash): The chunk object to remove

    Returns:
        ChunkCommon | None: The removed object, or None if it is not here
    """
    obj = self.get_param(key)
    if obj:
        del self[obj]
        return obj

send_added ⚓︎

send_added(obj)

Sends a PARAM_ADDED notice with the new obj as notice data and owner as the sender.

Parameters:

Name Type Description Default
obj ChunkCommon | ProxyParam

the new parameter

required
Source code in usd_chunks/chunk_core.py
def send_added(self, obj: ChunkCommon | ProxyParam):
    """Sends a PARAM_ADDED notice with the new obj as notice data and owner as the sender.

    Args:
        obj (ChunkCommon | ProxyParam): the new parameter
    """
    self._last_added = obj._hashable

    if owner := self.get_owner():
        owner.send_self(chunk_notice.ChunkNoticeAlias.PARAM_ADDED, obj)

send_removed ⚓︎

send_removed(obj)

Sends a PARAM_REMOVED notice with the new obj as notice data and owner as the sender.

Parameters:

Name Type Description Default
obj ChunkCommon | ProxyParam

the removed parameter

required
Source code in usd_chunks/chunk_core.py
def send_removed(self, obj: ChunkCommon | ProxyParam):
    """Sends a PARAM_REMOVED notice with the new obj as notice data and owner as the sender.

    Args:
        obj (ChunkCommon | ProxyParam): the removed parameter
    """
    self._last_removed = obj._hashable
    if owner := self.get_owner():
        owner.send_self(chunk_notice.ChunkNoticeAlias.PARAM_REMOVED, obj)

ProxyParam ⚓︎

ProxyParam(param, *args, **kwargs)

Bases: ChunkNoticePropagator

A param that stands in for a concrete one, holding only its own value and children.

The proxy stores a unique value, and unique children if the param is a group. That is what list rows need: one original group dictates the content of every row, and each row holds its own values. Any attribute except 'value' can be changed on the original, and the proxies follow.

The proxy has its own hash; the original is its param_ref. ChunkCommon's _hashable attribute is not overridden, so ProxyParam._hashable evaluates to the referenced HashVal.

Parameters:

Name Type Description Default
param ChunkCommon

The chunk object to stand in for

required
Source code in usd_chunks/chunk_core.py
def __init__(self, param: ChunkCommon, *args, **kwargs):
    super().__init__(*args, **kwargs)

    self.__hashable = HashVal()
    self.__param_ref = weakref.ref(param, self._param_died)
    self._expression_connections: list = []

    if isinstance(param, ChunkParamBase):
        self._value = param.value
        self.__value_sender = AttributeSender(self, "value", param.get_attribute_sender("value").alias)
    else:
        self._value = None
        self.__value_sender = None

    # A ProxyParam mirrors its template's non-value attribute changes via this
    # dependency, but must not be pulled into the template's graph_id: set_graph_id
    # merges the *established* side into whichever DagGraphID it's called with, and a
    # freshly-constructed proxy's root would otherwise become the new root for the
    # whole tab it was just added to, orphaning that tab's graph_XXXX layer.
    self.get_dag_node()._part_of_graph = False
    self.add_dependency(param)

    self._children = NameSyncedContainer()

    if isinstance(param, ChunkContainerBase):
        self._children.set_owner(self)
        self._children = NameSyncedContainer.create_proxy(param.children, self._children)

        self.add_callback(self._ref_child_added, param, notice_alias=chunk_notice.ChunkNoticeAlias.PARAM_ADDED)
        self.add_callback(self._ref_child_removed, param, notice_alias=chunk_notice.ChunkNoticeAlias.PARAM_REMOVED)

PySyntaxHighlightMapping ⚓︎

PySyntaxHighlightMapping()

Bases: SyntaxHighlightMapping

Highlighting for Python source: class and def lines, and comments.

Source code in usd_chunks/chunk_core.py
def __init__(self) -> None:
    super().__init__()

    pattern = r"^\s*class\s+\w+\(.*$"
    self.add_mapping(pattern, SyntaxHighlightStyle(color="#4c6ea3"))

    pattern = r"^\s*def\s+\w+\s*\(.*\)\s*:\s*$"
    self.add_mapping(pattern, SyntaxHighlightStyle(color="#31a56b"))

    pattern = r"^\s*#.*$"
    self.add_mapping(pattern, SyntaxHighlightStyle(color="#3f883f"))

SyntaxHighlightMapping ⚓︎

SyntaxHighlightMapping()

Regex patterns mapped to the style of the text they match, for a code viewer.

Source code in usd_chunks/chunk_core.py
def __init__(self):
    self._mappings: dict[str, SyntaxHighlightStyle] = {}

add_mapping ⚓︎

add_mapping(pattern, style)

Style every match of pattern with style.

Source code in usd_chunks/chunk_core.py
def add_mapping(self, pattern, style: SyntaxHighlightStyle):
    """Style every match of `pattern` with `style`."""
    self._mappings[pattern] = style

match_text ⚓︎

match_text(text)

Every styled span in text.

Parameters:

Name Type Description Default
text str

The text to highlight.

required

Yields:

Type Description
tuple[int, int, SyntaxHighlightStyle]

(start, end, style) for each match of each pattern.

Source code in usd_chunks/chunk_core.py
def match_text(self, text: str) -> Generator[tuple[int, int, SyntaxHighlightStyle], None, None]:
    """Every styled span in `text`.

    Args:
        text: The text to highlight.

    Yields:
        (start, end, style) for each match of each pattern.
    """
    for pattern, fmt in self._mappings.items():
        for m in re.finditer(pattern, text):
            start, end = m.span()
            yield start, end, fmt

SyntaxHighlightStyle ⚓︎

Bases: TypedDict

How highlighted text is drawn: a colour, optionally italic or bold.

Parameters:

Name Type Description Default
color ForwardRef('Required[str]', module='usd_chunks.chunk_core')
required
italic ForwardRef('bool', module='usd_chunks.chunk_core')
required
bold ForwardRef('bool', module='usd_chunks.chunk_core')
required

UnregisteredChunkTypeError ⚓︎

Bases: TypeError

A chunk whose class is defined outside the framework and outside its registered module.

Raised when such a chunk is added to a scene; see check_chunk_type.

UsdSyntaxHighlightMapping ⚓︎

UsdSyntaxHighlightMapping()

Bases: SyntaxHighlightMapping

Highlighting for usda text: class, def and over lines.

Source code in usd_chunks/chunk_core.py
def __init__(self) -> None:
    super().__init__()

    pattern = r"^\s*class\s+\w+\(.*$"
    self.add_mapping(pattern, SyntaxHighlightStyle(color="#4c6ea3"))

    pattern = r"^\s*(def|over)"
    self.add_mapping(pattern, SyntaxHighlightStyle(color="#4a80ec"))

    pattern = r"^\s*#.*$"
    self.add_mapping(pattern, SyntaxHighlightStyle(color="#3f883f"))

    pattern = r"(?<=def )(\w+)"
    self.add_mapping(pattern, SyntaxHighlightStyle(color="#51c765"))

    pattern = r"(\"|\')\w+(\"|\')"
    self.add_mapping(pattern, SyntaxHighlightStyle(color="#e17a3f"))

    pattern = r"(double|float|int|uniform|asset|token|color)\w?.(\[\])?"
    self.add_mapping(pattern, SyntaxHighlightStyle(color="#4aabec"))

all_chunks ⚓︎

all_chunks(chunks)

Every chunk inside the given ones, groups excluded, at any depth.

Source code in usd_chunks/chunk_core.py
def all_chunks(chunks) -> list[ChunkBase]:
    """Every chunk inside the given ones, groups excluded, at any depth."""
    found = []
    for c in chunks:
        sub = [p for p in c.get_my_params() if isinstance(p, ChunkBase)]
        found.extend(all_chunks(sub) if sub else [c])
    return found

check_chunk_type ⚓︎

check_chunk_type(c, fallback=None)

Refuse a chunk whose behaviour a saved file could not bring back.

A chunk can't do anything its module doesn't define, so a saved file is always the whole description of what the network does: behaviour comes only from a registered chunk module, and data lives in USD. The one way round that is a chunk class -- a subclass of Chunk with methods, callbacks wired in init or overrides -- defined somewhere a reopen never runs: a script, the interpreter, a test. It would work for this session and come back from the file as its registered type (or a plain runtime chunk), silently without whatever the class added.

So a chunk entering a scene must be one of:

  • a framework class (Chunk, ChunkBase, a context -- anything in usd_chunks). It has no behaviour of its own: its hooks are looked up in its registered module, and one with no module has none (a chunk built in the interpreter, a tab context). Callbacks a script adds to it are session-only by design, like a script editor's.
  • a class defined in the registered module its config names. That is the module a reopen runs, so the class comes back with it.

Compared by the registry's module name, not by module object: a chunk module can exist twice in sys.modules under different keys (its bare name, and a package path), and both resolve to one registered module. ChunkBase nested inside c are checked too, against their own module or, lacking one, c's -- the module whose main() built them.

Parameters:

Name Type Description Default
c ChunkBase

The chunk being added.

required
fallback ChunkModule | None

The module c answers to when it has none of its own: that of the chunk it is being nested into, when that one is already in a scene.

None

Raises:

Type Description
UnregisteredChunkTypeError

c, or a chunk nested in it, has such a class.

Source code in usd_chunks/chunk_core.py
def check_chunk_type(c: ChunkBase, fallback: chunk_registry.ChunkModule | None = None) -> None:
    """Refuse a chunk whose behaviour a saved file could not bring back.

    A chunk can't do anything its module doesn't define, so a saved file is always the whole
    description of what the network does: behaviour comes only from a registered chunk
    module, and data lives in USD. The one way round that is a chunk *class* -- a subclass
    of Chunk with methods, callbacks wired in __init__ or overrides -- defined somewhere a
    reopen never runs: a script, the interpreter, a test. It would work for this session
    and come back from the file as its registered type (or a plain runtime chunk), silently
    without whatever the class added.

    So a chunk entering a scene must be one of:

    - a framework class (Chunk, ChunkBase, a context -- anything in usd_chunks). It has no
      behaviour of its own: its hooks are looked up in its registered module, and one with
      no module has none (a chunk built in the interpreter, a tab context). Callbacks a
      script adds to it are session-only by design, like a script editor's.
    - a class defined in the registered module its config names. That is the module a
      reopen runs, so the class comes back with it.

    Compared by the registry's module name, not by module object: a chunk module can exist
    twice in sys.modules under different keys (its bare name, and a package path), and both
    resolve to one registered module. ChunkBase nested inside c are checked too, against
    their own module or, lacking one, c's -- the module whose main() built them.

    Args:
        c: The chunk being added.
        fallback: The module c answers to when it has none of its own: that of the chunk it
            is being nested into, when that one is already in a scene.

    Raises:
        UnregisteredChunkTypeError: c, or a chunk nested in it, has such a class.
    """
    registry = chunk_registry.ChunkRegistry()
    outer = c.get_chunk_module() or fallback
    for _, obj in c.iter_hierarchy():
        if not isinstance(obj, ChunkBase) or _is_framework_class(cls := type(obj)):
            continue
        own = obj.get_chunk_module() or outer
        if own is None or registry.get_chunk_module(cls.__module__) is not own:
            where = f"registered module {own.module_name!r}" if own else "no registered module"
            raise UnregisteredChunkTypeError(
                f"Cannot add chunk {obj.name!r}: its class {cls.__qualname__} is defined in "
                f"{cls.__module__!r}, and the chunk has {where}. A chunk type must live in a "
                "registered chunk module (a .py on USD_CHUNK_DIRS with main() and config()): "
                "a saved file records only the module's name, so a class defined anywhere "
                "else would not survive a save and reopen. Move the class into its chunk "
                "module, or build a plain chunk.Chunk and wire session callbacks onto it."
            )

group_parent_path ⚓︎

group_parent_path(group)

The prim path a group sits under: what decides which groups are its siblings.

A restored group knows its own prim path. A group being created does not yet, so it takes its parent group's path, or the /chunks scope for one with no parent.

Source code in usd_chunks/chunk_core.py
def group_parent_path(group) -> str:
    """The prim path a group sits under: what decides which groups are its siblings.

    A restored group knows its own prim path. A group being created does not yet, so it
    takes its parent group's path, or the /chunks scope for one with no parent.
    """
    path = getattr(group, "prim_path", None)
    if path:
        return path.rsplit("/", 1)[0] or "/"
    ref = getattr(group, "_parent_context", None)
    parent = ref() if ref else None
    return (getattr(parent, "prim_path", None) or chunk_naming.CHUNKS_ROOT) if parent else chunk_naming.CHUNKS_ROOT

is_inst ⚓︎

is_inst(cls)

Create a predicate that checks, and narrows the type of, an instance of cls.

Parameters:

Name Type Description Default
cls type[ValueT]

The type to check

required

Returns:

Type Description
Predicate[ValueT]

Predicate[ValueT]: The predicate function

Source code in usd_chunks/chunk_core.py
def is_inst(cls: type[ValueT]) -> Predicate[ValueT]:
    """Create a predicate that checks, and narrows the type of, an instance of `cls`.

    Args:
        cls (type[ValueT]): The type to check

    Returns:
        Predicate[ValueT]: The predicate function
    """

    def _fn(v: Any) -> TypeGuard[ValueT]:
        return isinstance(v, cls)

    return _fn

iter_params_and_rows ⚓︎

iter_params_and_rows(chunk)

chunk.get_params(), plus every list-group row, which get_params leaves out.

Source code in usd_chunks/chunk_core.py
def iter_params_and_rows(chunk: ChunkBase) -> Generator[ChunkCommon, None, None]:
    """chunk.get_params(), plus every list-group row, which get_params leaves out."""
    for param in chunk.get_params():
        yield param
        if isinstance(param, ChunkListGroupBase):
            yield from param.get_params()

list_row_of ⚓︎

list_row_of(template, index)

Row index of a list-group template param, or None if there is no such row.

What an @Node.param[index]@ expression names. A missing row is None rather than an error: rows come and go at runtime, and a ref to one that is gone reads the default the way a ref to a missing param does.

Source code in usd_chunks/chunk_core.py
def list_row_of(template: ChunkCommon | None, index: int) -> ProxyParam | None:
    """Row `index` of a list-group template param, or None if there is no such row.

    What an @Node.param[index]@ expression names. A missing row is None rather than an
    error: rows come and go at runtime, and a ref to one that is gone reads the default the
    way a ref to a missing param does.
    """
    owner = template.get_owner() if template is not None else None
    while owner is not None and not isinstance(owner, (ChunkListGroupBase, ChunkBase)):
        owner = owner.get_owner()
    if not isinstance(owner, ChunkListGroupBase) or not 0 <= index < len(owner.proxy_params):
        return None
    # By the template itself, not its name: a renamed template's rows still answer to it.
    return owner.get_indexed_param(template, index)

list_row_ref ⚓︎

list_row_ref(row)

The name an expression reads row by -- "item[1]" -- or None if it is not a row.

Source code in usd_chunks/chunk_core.py
def list_row_ref(row: ProxyParam) -> str | None:
    """The name an expression reads `row` by -- "item[1]" -- or None if it is not a row."""
    # Ownership chain: ProxyParam -> NameSyncedContainer -> ChunkGroupBase("1") -> ChunkListGroupBase
    container = row.get_owner()
    row_group = container.get_owner() if container is not None else None
    if not (isinstance(row_group, ChunkGroupBase) and row_group.name.isdigit()
            and isinstance(row_group.get_owner(), ChunkListGroupBase)):
        return None
    return f"{row.name}[{row_group.name}]"

params_bound_to ⚓︎

params_bound_to(path)

The params currently bound to this USD property path (see _params_by_attr_path).

Source code in usd_chunks/chunk_core.py
def params_bound_to(path: str) -> list[ChunkUsdAttributeSupport]:
    """The params currently bound to this USD property path (see _params_by_attr_path)."""
    bound = _params_by_attr_path.get(path)
    return list(bound) if bound else []

preview_cook ⚓︎

preview_cook(node)

Whether this cook may be a cheap preview: a handle is being dragged in node's scene.

Asked from a slow chunk's execute(node), downstream of what is dragged -- an IK bake over a hundred frames behind a target's handle. True while the drag is on: the chunk cooks a rougher result that keeps up with the mouse, and the framework cooks it again in full when the last drag ends. False otherwise, and the cook is the real one.

Parameters:

Name Type Description Default
node ChunkBase

The chunk cooking, as handed to execute(node).

required

Returns:

Type Description
bool

True when the chunk may cook a preview.

Source code in usd_chunks/chunk_core.py
def preview_cook(node: ChunkBase) -> bool:
    """Whether this cook may be a cheap preview: a handle is being dragged in node's scene.

    Asked from a slow chunk's execute(node), downstream of what is dragged -- an IK bake
    over a hundred frames behind a target's handle. True while the drag is on: the chunk
    cooks a rougher result that keeps up with the mouse, and the framework cooks it again
    in full when the last drag ends. False otherwise, and the cook is the real one.

    Args:
        node: The chunk cooking, as handed to execute(node).

    Returns:
        True when the chunk may cook a preview.
    """
    scene = node.get_scene()
    dragging = scene is not None and any(c.get_scene() is scene for c in _live(_DRAGGING))
    if dragging:
        _PREVIEWED[id(node)] = weakref.ref(node)
    else:
        _PREVIEWED.pop(id(node), None)
    return dragging